clang 17.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"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Sema.h"
34#include "clang/Sema/Template.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/TimeProfiler.h"
39#include <optional>
40
41using namespace clang;
42using namespace sema;
43
44//===----------------------------------------------------------------------===/
45// Template Instantiation Support
46//===----------------------------------------------------------------------===/
47
48namespace {
50struct Response {
51 const Decl *NextDecl = nullptr;
52 bool IsDone = false;
53 bool ClearRelativeToPrimary = true;
54 static Response Done() {
55 Response R;
56 R.IsDone = true;
57 return R;
58 }
59 static Response ChangeDecl(const Decl *ND) {
60 Response R;
61 R.NextDecl = ND;
62 return R;
63 }
64 static Response ChangeDecl(const DeclContext *Ctx) {
65 Response R;
66 R.NextDecl = Decl::castFromDeclContext(Ctx);
67 return R;
68 }
69
70 static Response UseNextDecl(const Decl *CurDecl) {
71 return ChangeDecl(CurDecl->getDeclContext());
72 }
73
74 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
75 Response R = Response::UseNextDecl(CurDecl);
76 R.ClearRelativeToPrimary = false;
77 return R;
78 }
79};
80// Add template arguments from a variable template instantiation.
81Response
82HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
84 bool SkipForSpecialization) {
85 // For a class-scope explicit specialization, there are no template arguments
86 // at this level, but there may be enclosing template arguments.
87 if (VarTemplSpec->isClassScopeExplicitSpecialization())
88 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
89
90 // We're done when we hit an explicit specialization.
92 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
93 return Response::Done();
94
95 // If this variable template specialization was instantiated from a
96 // specialized member that is a variable template, we're done.
97 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
98 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
99 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
101 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
102 if (!SkipForSpecialization)
103 Result.addOuterTemplateArguments(
104 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
105 /*Final=*/false);
106 if (Partial->isMemberSpecialization())
107 return Response::Done();
108 } else {
109 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
110 if (!SkipForSpecialization)
111 Result.addOuterTemplateArguments(
112 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
113 /*Final=*/false);
114 if (Tmpl->isMemberSpecialization())
115 return Response::Done();
116 }
117 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
118}
119
120// If we have a template template parameter with translation unit context,
121// then we're performing substitution into a default template argument of
122// this template template parameter before we've constructed the template
123// that will own this template template parameter. In this case, we
124// use empty template parameter lists for all of the outer templates
125// to avoid performing any substitutions.
126Response
127HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
129 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
130 Result.addOuterTemplateArguments(std::nullopt);
131 return Response::Done();
132}
133
134// Add template arguments from a class template instantiation.
135Response
136HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
138 bool SkipForSpecialization) {
139 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
140 // We're done when we hit an explicit specialization.
141 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
142 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
143 return Response::Done();
144
145 if (!SkipForSpecialization)
146 Result.addOuterTemplateArguments(
147 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
148 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
149 /*Final=*/false);
150
151 // If this class template specialization was instantiated from a
152 // specialized member that is a class template, we're done.
153 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
154 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
155 return Response::Done();
156 }
157 return Response::UseNextDecl(ClassTemplSpec);
158}
159
160Response HandleFunction(const FunctionDecl *Function,
162 const FunctionDecl *Pattern, bool RelativeToPrimary,
163 bool ForConstraintInstantiation) {
164 // Add template arguments from a function template specialization.
165 if (!RelativeToPrimary &&
166 Function->getTemplateSpecializationKindForInstantiation() ==
168 return Response::Done();
169
170 if (!RelativeToPrimary &&
171 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
172 // This is an implicit instantiation of an explicit specialization. We
173 // don't get any template arguments from this function but might get
174 // some from an enclosing template.
175 return Response::UseNextDecl(Function);
176 } else if (const TemplateArgumentList *TemplateArgs =
177 Function->getTemplateSpecializationArgs()) {
178 // Add the template arguments for this specialization.
179 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
180 TemplateArgs->asArray(),
181 /*Final=*/false);
182
183 // If this function was instantiated from a specialized member that is
184 // a function template, we're done.
185 assert(Function->getPrimaryTemplate() && "No function template?");
186 if (Function->getPrimaryTemplate()->isMemberSpecialization())
187 return Response::Done();
188
189 // If this function is a generic lambda specialization, we are done.
190 if (!ForConstraintInstantiation &&
192 return Response::Done();
193
194 } else if (Function->getDescribedFunctionTemplate()) {
195 assert(
196 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
197 "Outer template not instantiated?");
198 }
199 // If this is a friend or local declaration and it declares an entity at
200 // namespace scope, take arguments from its lexical parent
201 // instead of its semantic parent, unless of course the pattern we're
202 // instantiating actually comes from the file's context!
203 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
204 Function->getNonTransparentDeclContext()->isFileContext() &&
205 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
206 return Response::ChangeDecl(Function->getLexicalDeclContext());
207 }
208 return Response::UseNextDecl(Function);
209}
210
211Response HandleRecordDecl(const CXXRecordDecl *Rec,
213 ASTContext &Context,
214 bool ForConstraintInstantiation) {
215 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
216 assert(
217 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
218 "Outer template not instantiated?");
219 if (ClassTemplate->isMemberSpecialization())
220 return Response::Done();
221 if (ForConstraintInstantiation) {
222 QualType RecordType = Context.getTypeDeclType(Rec);
223 QualType Injected = cast<InjectedClassNameType>(RecordType)
224 ->getInjectedSpecializationType();
225 const auto *InjectedType = cast<TemplateSpecializationType>(Injected);
226 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
227 InjectedType->template_arguments(),
228 /*Final=*/false);
229 }
230 }
231
232 bool IsFriend = Rec->getFriendObjectKind() ||
235 if (ForConstraintInstantiation && IsFriend &&
237 return Response::ChangeDecl(Rec->getLexicalDeclContext());
238 }
239
240 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
241 // lambda is defined inside of.
242 if (Rec->isLambda())
243 if (const Decl *LCD = Rec->getLambdaContextDecl())
244 return Response::ChangeDecl(LCD);
245
246 return Response::UseNextDecl(Rec);
247}
248
249Response HandleImplicitConceptSpecializationDecl(
252 Result.addOuterTemplateArguments(
253 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
255 /*Final=*/false);
256 return Response::UseNextDecl(CSD);
257}
258
259Response HandleGenericDeclContext(const Decl *CurDecl) {
260 return Response::UseNextDecl(CurDecl);
261}
262} // namespace TemplateInstArgsHelpers
263} // namespace
264
265/// Retrieve the template argument list(s) that should be used to
266/// instantiate the definition of the given declaration.
267///
268/// \param ND the declaration for which we are computing template instantiation
269/// arguments.
270///
271/// \param Innermost if non-NULL, specifies a template argument list for the
272/// template declaration passed as ND.
273///
274/// \param RelativeToPrimary true if we should get the template
275/// arguments relative to the primary template, even when we're
276/// dealing with a specialization. This is only relevant for function
277/// template specializations.
278///
279/// \param Pattern If non-NULL, indicates the pattern from which we will be
280/// instantiating the definition of the given declaration, \p ND. This is
281/// used to determine the proper set of template instantiation arguments for
282/// friend function template specializations.
283///
284/// \param ForConstraintInstantiation when collecting arguments,
285/// ForConstraintInstantiation indicates we should continue looking when
286/// encountering a lambda generic call operator, and continue looking for
287/// arguments on an enclosing class template.
288
290 const NamedDecl *ND, bool Final, const TemplateArgumentList *Innermost,
291 bool RelativeToPrimary, const FunctionDecl *Pattern,
292 bool ForConstraintInstantiation, bool SkipForSpecialization) {
293 assert(ND && "Can't find arguments for a decl if one isn't provided");
294 // Accumulate the set of template argument lists in this structure.
296
297 if (Innermost)
298 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND),
299 Innermost->asArray(), Final);
300
301 const Decl *CurDecl = ND;
302
303 while (!CurDecl->isFileContextDecl()) {
304 using namespace TemplateInstArgsHelpers;
305 Response R;
306 if (const auto *VarTemplSpec =
307 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
308 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
309 } else if (const auto *ClassTemplSpec =
310 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
311 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
312 SkipForSpecialization);
313 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
314 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
315 ForConstraintInstantiation);
316 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
317 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
318 } else if (const auto *CSD =
319 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
320 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
321 } else if (!isa<DeclContext>(CurDecl)) {
322 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
323 if (CurDecl->getDeclContext()->isTranslationUnit()) {
324 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
325 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
326 }
327 }
328 } else {
329 R = HandleGenericDeclContext(CurDecl);
330 }
331
332 if (R.IsDone)
333 return Result;
334 if (R.ClearRelativeToPrimary)
335 RelativeToPrimary = false;
336 assert(R.NextDecl);
337 CurDecl = R.NextDecl;
338 }
339
340 return Result;
341}
342
344 switch (Kind) {
352 case ConstraintsCheck:
354 return true;
355
370 return false;
371
372 // This function should never be called when Kind's value is Memoization.
373 case Memoization:
374 break;
375 }
376
377 llvm_unreachable("Invalid SynthesisKind!");
378}
379
382 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
383 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
384 sema::TemplateDeductionInfo *DeductionInfo)
385 : SemaRef(SemaRef) {
386 // Don't allow further instantiation if a fatal error and an uncompilable
387 // error have occurred. Any diagnostics we might have raised will not be
388 // visible, and we do not need to construct a correct AST.
389 if (SemaRef.Diags.hasFatalErrorOccurred() &&
391 Invalid = true;
392 return;
393 }
394 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
395 if (!Invalid) {
397 Inst.Kind = Kind;
398 Inst.PointOfInstantiation = PointOfInstantiation;
399 Inst.Entity = Entity;
400 Inst.Template = Template;
401 Inst.TemplateArgs = TemplateArgs.data();
402 Inst.NumTemplateArgs = TemplateArgs.size();
403 Inst.DeductionInfo = DeductionInfo;
404 Inst.InstantiationRange = InstantiationRange;
405 SemaRef.pushCodeSynthesisContext(Inst);
406
407 AlreadyInstantiating = !Inst.Entity ? false :
409 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
410 .second;
411 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
412 }
413}
414
416 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
417 SourceRange InstantiationRange)
418 : InstantiatingTemplate(SemaRef,
419 CodeSynthesisContext::TemplateInstantiation,
420 PointOfInstantiation, InstantiationRange, Entity) {}
421
423 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
424 ExceptionSpecification, SourceRange InstantiationRange)
426 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
427 PointOfInstantiation, InstantiationRange, Entity) {}
428
430 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
431 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
432 SourceRange InstantiationRange)
434 SemaRef,
435 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
436 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
437 Template, TemplateArgs) {}
438
440 Sema &SemaRef, SourceLocation PointOfInstantiation,
442 ArrayRef<TemplateArgument> TemplateArgs,
444 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
445 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
446 InstantiationRange, FunctionTemplate, nullptr,
447 TemplateArgs, &DeductionInfo) {
448 assert(
451}
452
454 Sema &SemaRef, SourceLocation PointOfInstantiation,
455 TemplateDecl *Template,
456 ArrayRef<TemplateArgument> TemplateArgs,
457 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
459 SemaRef,
460 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
461 PointOfInstantiation, InstantiationRange, Template, nullptr,
462 TemplateArgs, &DeductionInfo) {}
463
465 Sema &SemaRef, SourceLocation PointOfInstantiation,
467 ArrayRef<TemplateArgument> TemplateArgs,
468 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
470 SemaRef,
471 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
472 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
473 TemplateArgs, &DeductionInfo) {}
474
476 Sema &SemaRef, SourceLocation PointOfInstantiation,
478 ArrayRef<TemplateArgument> TemplateArgs,
479 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
481 SemaRef,
482 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
483 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
484 TemplateArgs, &DeductionInfo) {}
485
487 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
488 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
490 SemaRef,
491 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
492 PointOfInstantiation, InstantiationRange, Param, nullptr,
493 TemplateArgs) {}
494
496 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
498 SourceRange InstantiationRange)
500 SemaRef,
501 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
502 PointOfInstantiation, InstantiationRange, Param, Template,
503 TemplateArgs) {}
504
506 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
508 SourceRange InstantiationRange)
510 SemaRef,
511 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
512 PointOfInstantiation, InstantiationRange, Param, Template,
513 TemplateArgs) {}
514
516 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
517 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
518 SourceRange InstantiationRange)
520 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
521 PointOfInstantiation, InstantiationRange, Param, Template,
522 TemplateArgs) {}
523
525 Sema &SemaRef, SourceLocation PointOfInstantiation,
527 SourceRange InstantiationRange)
529 SemaRef, CodeSynthesisContext::RequirementInstantiation,
530 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
531 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
532}
533
535 Sema &SemaRef, SourceLocation PointOfInstantiation,
537 SourceRange InstantiationRange)
539 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
540 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
541 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
542
544 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
545 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
547 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
548 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
549 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
550}
551
553 Sema &SemaRef, SourceLocation PointOfInstantiation,
554 ConstraintsCheck, NamedDecl *Template,
555 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
558 PointOfInstantiation, InstantiationRange, Template, nullptr,
559 TemplateArgs) {}
560
562 Sema &SemaRef, SourceLocation PointOfInstantiation,
564 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
567 PointOfInstantiation, InstantiationRange, Template, nullptr,
568 {}, &DeductionInfo) {}
569
571 Sema &SemaRef, SourceLocation PointOfInstantiation,
573 SourceRange InstantiationRange)
576 PointOfInstantiation, InstantiationRange, Template) {}
577
579 Sema &SemaRef, SourceLocation PointOfInstantiation,
581 SourceRange InstantiationRange)
584 PointOfInstantiation, InstantiationRange, Template) {}
585
586
590
591 CodeSynthesisContexts.push_back(Ctx);
592
593 if (!Ctx.isInstantiationRecord())
595
596 // Check to see if we're low on stack space. We can't do anything about this
597 // from here, but we can at least warn the user.
600}
601
603 auto &Active = CodeSynthesisContexts.back();
604 if (!Active.isInstantiationRecord()) {
605 assert(NonInstantiationEntries > 0);
607 }
608
609 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
610
611 // Name lookup no longer looks in this template's defining module.
612 assert(CodeSynthesisContexts.size() >=
614 "forgot to remove a lookup module for a template instantiation");
615 if (CodeSynthesisContexts.size() ==
618 LookupModulesCache.erase(M);
620 }
621
622 // If we've left the code synthesis context for the current context stack,
623 // stop remembering that we've emitted that stack.
624 if (CodeSynthesisContexts.size() ==
627
628 CodeSynthesisContexts.pop_back();
629}
630
632 if (!Invalid) {
633 if (!AlreadyInstantiating) {
634 auto &Active = SemaRef.CodeSynthesisContexts.back();
635 if (Active.Entity)
636 SemaRef.InstantiatingSpecializations.erase(
637 {Active.Entity->getCanonicalDecl(), Active.Kind});
638 }
639
640 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
641 SemaRef.CodeSynthesisContexts.back());
642
643 SemaRef.popCodeSynthesisContext();
644 Invalid = true;
645 }
646}
647
648static std::string convertCallArgsToString(Sema &S,
650 std::string Result;
651 llvm::raw_string_ostream OS(Result);
652 llvm::ListSeparator Comma;
653 for (const Expr *Arg : Args) {
654 OS << Comma;
655 Arg->IgnoreParens()->printPretty(OS, nullptr,
657 }
658 return Result;
659}
660
661bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
662 SourceLocation PointOfInstantiation,
663 SourceRange InstantiationRange) {
664 assert(SemaRef.NonInstantiationEntries <=
665 SemaRef.CodeSynthesisContexts.size());
666 if ((SemaRef.CodeSynthesisContexts.size() -
668 <= SemaRef.getLangOpts().InstantiationDepth)
669 return false;
670
671 SemaRef.Diag(PointOfInstantiation,
672 diag::err_template_recursion_depth_exceeded)
673 << SemaRef.getLangOpts().InstantiationDepth
674 << InstantiationRange;
675 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
676 << SemaRef.getLangOpts().InstantiationDepth;
677 return true;
678}
679
680/// Prints the current instantiation stack through a series of
681/// notes.
683 // Determine which template instantiations to skip, if any.
684 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
685 unsigned Limit = Diags.getTemplateBacktraceLimit();
686 if (Limit && Limit < CodeSynthesisContexts.size()) {
687 SkipStart = Limit / 2 + Limit % 2;
688 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
689 }
690
691 // FIXME: In all of these cases, we need to show the template arguments
692 unsigned InstantiationIdx = 0;
694 Active = CodeSynthesisContexts.rbegin(),
695 ActiveEnd = CodeSynthesisContexts.rend();
696 Active != ActiveEnd;
697 ++Active, ++InstantiationIdx) {
698 // Skip this instantiation?
699 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
700 if (InstantiationIdx == SkipStart) {
701 // Note that we're skipping instantiations.
702 Diags.Report(Active->PointOfInstantiation,
703 diag::note_instantiation_contexts_suppressed)
704 << unsigned(CodeSynthesisContexts.size() - Limit);
705 }
706 continue;
707 }
708
709 switch (Active->Kind) {
711 Decl *D = Active->Entity;
712 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
713 unsigned DiagID = diag::note_template_member_class_here;
714 if (isa<ClassTemplateSpecializationDecl>(Record))
715 DiagID = diag::note_template_class_instantiation_here;
716 Diags.Report(Active->PointOfInstantiation, DiagID)
717 << Record << Active->InstantiationRange;
718 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
719 unsigned DiagID;
720 if (Function->getPrimaryTemplate())
721 DiagID = diag::note_function_template_spec_here;
722 else
723 DiagID = diag::note_template_member_function_here;
724 Diags.Report(Active->PointOfInstantiation, DiagID)
725 << Function
726 << Active->InstantiationRange;
727 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
728 Diags.Report(Active->PointOfInstantiation,
729 VD->isStaticDataMember()?
730 diag::note_template_static_data_member_def_here
731 : diag::note_template_variable_def_here)
732 << VD
733 << Active->InstantiationRange;
734 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
735 Diags.Report(Active->PointOfInstantiation,
736 diag::note_template_enum_def_here)
737 << ED
738 << Active->InstantiationRange;
739 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
740 Diags.Report(Active->PointOfInstantiation,
741 diag::note_template_nsdmi_here)
742 << FD << Active->InstantiationRange;
743 } else {
744 Diags.Report(Active->PointOfInstantiation,
745 diag::note_template_type_alias_instantiation_here)
746 << cast<TypeAliasTemplateDecl>(D)
747 << Active->InstantiationRange;
748 }
749 break;
750 }
751
753 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
754 SmallString<128> TemplateArgsStr;
755 llvm::raw_svector_ostream OS(TemplateArgsStr);
756 Template->printName(OS, getPrintingPolicy());
757 printTemplateArgumentList(OS, Active->template_arguments(),
759 Diags.Report(Active->PointOfInstantiation,
760 diag::note_default_arg_instantiation_here)
761 << OS.str()
762 << Active->InstantiationRange;
763 break;
764 }
765
767 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
768 Diags.Report(Active->PointOfInstantiation,
769 diag::note_explicit_template_arg_substitution_here)
770 << FnTmpl
772 Active->TemplateArgs,
773 Active->NumTemplateArgs)
774 << Active->InstantiationRange;
775 break;
776 }
777
779 if (FunctionTemplateDecl *FnTmpl =
780 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
781 Diags.Report(Active->PointOfInstantiation,
782 diag::note_function_template_deduction_instantiation_here)
783 << FnTmpl
784 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
785 Active->TemplateArgs,
786 Active->NumTemplateArgs)
787 << Active->InstantiationRange;
788 } else {
789 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
790 isa<VarTemplateSpecializationDecl>(Active->Entity);
791 bool IsTemplate = false;
792 TemplateParameterList *Params;
793 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
794 IsTemplate = true;
795 Params = D->getTemplateParameters();
796 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
797 Active->Entity)) {
798 Params = D->getTemplateParameters();
799 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
800 Active->Entity)) {
801 Params = D->getTemplateParameters();
802 } else {
803 llvm_unreachable("unexpected template kind");
804 }
805
806 Diags.Report(Active->PointOfInstantiation,
807 diag::note_deduced_template_arg_substitution_here)
808 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
809 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
810 Active->NumTemplateArgs)
811 << Active->InstantiationRange;
812 }
813 break;
814 }
815
817 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
818 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
819
820 SmallString<128> TemplateArgsStr;
821 llvm::raw_svector_ostream OS(TemplateArgsStr);
823 printTemplateArgumentList(OS, Active->template_arguments(),
825 Diags.Report(Active->PointOfInstantiation,
826 diag::note_default_function_arg_instantiation_here)
827 << OS.str()
828 << Active->InstantiationRange;
829 break;
830 }
831
833 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
834 std::string Name;
835 if (!Parm->getName().empty())
836 Name = std::string(" '") + Parm->getName().str() + "'";
837
838 TemplateParameterList *TemplateParams = nullptr;
839 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
840 TemplateParams = Template->getTemplateParameters();
841 else
842 TemplateParams =
843 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
844 ->getTemplateParameters();
845 Diags.Report(Active->PointOfInstantiation,
846 diag::note_prior_template_arg_substitution)
847 << isa<TemplateTemplateParmDecl>(Parm)
848 << Name
849 << getTemplateArgumentBindingsText(TemplateParams,
850 Active->TemplateArgs,
851 Active->NumTemplateArgs)
852 << Active->InstantiationRange;
853 break;
854 }
855
857 TemplateParameterList *TemplateParams = nullptr;
858 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
859 TemplateParams = Template->getTemplateParameters();
860 else
861 TemplateParams =
862 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
863 ->getTemplateParameters();
864
865 Diags.Report(Active->PointOfInstantiation,
866 diag::note_template_default_arg_checking)
867 << getTemplateArgumentBindingsText(TemplateParams,
868 Active->TemplateArgs,
869 Active->NumTemplateArgs)
870 << Active->InstantiationRange;
871 break;
872 }
873
875 Diags.Report(Active->PointOfInstantiation,
876 diag::note_evaluating_exception_spec_here)
877 << cast<FunctionDecl>(Active->Entity);
878 break;
879
881 Diags.Report(Active->PointOfInstantiation,
882 diag::note_template_exception_spec_instantiation_here)
883 << cast<FunctionDecl>(Active->Entity)
884 << Active->InstantiationRange;
885 break;
886
888 Diags.Report(Active->PointOfInstantiation,
889 diag::note_template_requirement_instantiation_here)
890 << Active->InstantiationRange;
891 break;
893 Diags.Report(Active->PointOfInstantiation,
894 diag::note_template_requirement_params_instantiation_here)
895 << Active->InstantiationRange;
896 break;
897
899 Diags.Report(Active->PointOfInstantiation,
900 diag::note_nested_requirement_here)
901 << Active->InstantiationRange;
902 break;
903
905 Diags.Report(Active->PointOfInstantiation,
906 diag::note_in_declaration_of_implicit_special_member)
907 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
908 break;
909
911 Diags.Report(Active->Entity->getLocation(),
912 diag::note_in_declaration_of_implicit_equality_comparison);
913 break;
914
916 // FIXME: For synthesized functions that are not defaulted,
917 // produce a note.
918 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
921 if (DFK.isSpecialMember()) {
922 auto *MD = cast<CXXMethodDecl>(FD);
923 Diags.Report(Active->PointOfInstantiation,
924 diag::note_member_synthesized_at)
925 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
926 << Context.getTagDeclType(MD->getParent());
927 } else if (DFK.isComparison()) {
928 Diags.Report(Active->PointOfInstantiation,
929 diag::note_comparison_synthesized_at)
930 << (int)DFK.asComparison()
932 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
933 }
934 break;
935 }
936
938 Diags.Report(Active->Entity->getLocation(),
939 diag::note_rewriting_operator_as_spaceship);
940 break;
941
943 Diags.Report(Active->PointOfInstantiation,
944 diag::note_in_binding_decl_init)
945 << cast<BindingDecl>(Active->Entity);
946 break;
947
949 Diags.Report(Active->PointOfInstantiation,
950 diag::note_due_to_dllexported_class)
951 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
952 break;
953
955 Diags.Report(Active->PointOfInstantiation,
956 diag::note_building_builtin_dump_struct_call)
958 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
959 break;
960
962 break;
963
965 unsigned DiagID = 0;
966 if (!Active->Entity) {
967 Diags.Report(Active->PointOfInstantiation,
968 diag::note_nested_requirement_here)
969 << Active->InstantiationRange;
970 break;
971 }
972 if (isa<ConceptDecl>(Active->Entity))
973 DiagID = diag::note_concept_specialization_here;
974 else if (isa<TemplateDecl>(Active->Entity))
975 DiagID = diag::note_checking_constraints_for_template_id_here;
976 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
977 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
978 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
979 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
980 else {
981 assert(isa<FunctionDecl>(Active->Entity));
982 DiagID = diag::note_checking_constraints_for_function_here;
983 }
984 SmallString<128> TemplateArgsStr;
985 llvm::raw_svector_ostream OS(TemplateArgsStr);
986 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
987 if (!isa<FunctionDecl>(Active->Entity)) {
988 printTemplateArgumentList(OS, Active->template_arguments(),
990 }
991 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
992 << Active->InstantiationRange;
993 break;
994 }
996 Diags.Report(Active->PointOfInstantiation,
997 diag::note_constraint_substitution_here)
998 << Active->InstantiationRange;
999 break;
1001 Diags.Report(Active->PointOfInstantiation,
1002 diag::note_constraint_normalization_here)
1003 << cast<NamedDecl>(Active->Entity)->getName()
1004 << Active->InstantiationRange;
1005 break;
1007 Diags.Report(Active->PointOfInstantiation,
1008 diag::note_parameter_mapping_substitution_here)
1009 << Active->InstantiationRange;
1010 break;
1011 }
1012 }
1013}
1014
1015std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1017 return std::optional<TemplateDeductionInfo *>(nullptr);
1018
1020 Active = CodeSynthesisContexts.rbegin(),
1021 ActiveEnd = CodeSynthesisContexts.rend();
1022 Active != ActiveEnd;
1023 ++Active)
1024 {
1025 switch (Active->Kind) {
1027 // An instantiation of an alias template may or may not be a SFINAE
1028 // context, depending on what else is on the stack.
1029 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1030 break;
1031 [[fallthrough]];
1038 // This is a template instantiation, so there is no SFINAE.
1039 return std::nullopt;
1040
1045 // A default template argument instantiation and substitution into
1046 // template parameters with arguments for prior parameters may or may
1047 // not be a SFINAE context; look further up the stack.
1048 break;
1049
1055 // We're either substituting explicitly-specified template arguments,
1056 // deduced template arguments, a constraint expression or a requirement
1057 // in a requires expression, so SFINAE applies.
1058 assert(Active->DeductionInfo && "Missing deduction info pointer");
1059 return Active->DeductionInfo;
1060
1067 // This happens in a context unrelated to template instantiation, so
1068 // there is no SFINAE.
1069 return std::nullopt;
1070
1072 // FIXME: This should not be treated as a SFINAE context, because
1073 // we will cache an incorrect exception specification. However, clang
1074 // bootstrap relies this! See PR31692.
1075 break;
1076
1078 break;
1079 }
1080
1081 // The inner context was transparent for SFINAE. If it occurred within a
1082 // non-instantiation SFINAE context, then SFINAE applies.
1083 if (Active->SavedInNonInstantiationSFINAEContext)
1084 return std::optional<TemplateDeductionInfo *>(nullptr);
1085 }
1086
1087 return std::nullopt;
1088}
1089
1090//===----------------------------------------------------------------------===/
1091// Template Instantiation for Types
1092//===----------------------------------------------------------------------===/
1093namespace {
1094 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1095 const MultiLevelTemplateArgumentList &TemplateArgs;
1096 SourceLocation Loc;
1097 DeclarationName Entity;
1098 bool EvaluateConstraints = true;
1099
1100 public:
1101 typedef TreeTransform<TemplateInstantiator> inherited;
1102
1103 TemplateInstantiator(Sema &SemaRef,
1104 const MultiLevelTemplateArgumentList &TemplateArgs,
1105 SourceLocation Loc, DeclarationName Entity)
1106 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1107 Entity(Entity) {}
1108
1109 void setEvaluateConstraints(bool B) {
1110 EvaluateConstraints = B;
1111 }
1112 bool getEvaluateConstraints() {
1113 return EvaluateConstraints;
1114 }
1115
1116 /// Determine whether the given type \p T has already been
1117 /// transformed.
1118 ///
1119 /// For the purposes of template instantiation, a type has already been
1120 /// transformed if it is NULL or if it is not dependent.
1121 bool AlreadyTransformed(QualType T);
1122
1123 /// Returns the location of the entity being instantiated, if known.
1124 SourceLocation getBaseLocation() { return Loc; }
1125
1126 /// Returns the name of the entity being instantiated, if any.
1127 DeclarationName getBaseEntity() { return Entity; }
1128
1129 /// Sets the "base" location and entity when that
1130 /// information is known based on another transformation.
1131 void setBase(SourceLocation Loc, DeclarationName Entity) {
1132 this->Loc = Loc;
1133 this->Entity = Entity;
1134 }
1135
1136 unsigned TransformTemplateDepth(unsigned Depth) {
1137 return TemplateArgs.getNewDepth(Depth);
1138 }
1139
1140 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1141 int Index = getSema().ArgumentPackSubstitutionIndex;
1142 if (Index == -1)
1143 return std::nullopt;
1144 return Pack.pack_size() - 1 - Index;
1145 }
1146
1147 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1148 SourceRange PatternRange,
1150 bool &ShouldExpand, bool &RetainExpansion,
1151 std::optional<unsigned> &NumExpansions) {
1152 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1153 PatternRange, Unexpanded,
1154 TemplateArgs,
1155 ShouldExpand,
1156 RetainExpansion,
1157 NumExpansions);
1158 }
1159
1160 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1162 }
1163
1164 TemplateArgument ForgetPartiallySubstitutedPack() {
1165 TemplateArgument Result;
1166 if (NamedDecl *PartialPack
1168 MultiLevelTemplateArgumentList &TemplateArgs
1169 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1170 unsigned Depth, Index;
1171 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1172 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1173 Result = TemplateArgs(Depth, Index);
1174 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1175 }
1176 }
1177
1178 return Result;
1179 }
1180
1181 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1182 if (Arg.isNull())
1183 return;
1184
1185 if (NamedDecl *PartialPack
1187 MultiLevelTemplateArgumentList &TemplateArgs
1188 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1189 unsigned Depth, Index;
1190 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1191 TemplateArgs.setArgument(Depth, Index, Arg);
1192 }
1193 }
1194
1195 /// Transform the given declaration by instantiating a reference to
1196 /// this declaration.
1197 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1198
1199 void transformAttrs(Decl *Old, Decl *New) {
1200 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1201 }
1202
1203 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1204 if (Old->isParameterPack()) {
1206 for (auto *New : NewDecls)
1208 Old, cast<VarDecl>(New));
1209 return;
1210 }
1211
1212 assert(NewDecls.size() == 1 &&
1213 "should only have multiple expansions for a pack");
1214 Decl *New = NewDecls.front();
1215
1216 // If we've instantiated the call operator of a lambda or the call
1217 // operator template of a generic lambda, update the "instantiation of"
1218 // information.
1219 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1220 if (NewMD && isLambdaCallOperator(NewMD)) {
1221 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1222 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1223 NewTD->setInstantiatedFromMemberTemplate(
1224 OldMD->getDescribedFunctionTemplate());
1225 else
1226 NewMD->setInstantiationOfMemberFunction(OldMD,
1228 }
1229
1231
1232 // We recreated a local declaration, but not by instantiating it. There
1233 // may be pending dependent diagnostics to produce.
1234 if (auto *DC = dyn_cast<DeclContext>(Old);
1235 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1236 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1237 }
1238
1239 /// Transform the definition of the given declaration by
1240 /// instantiating it.
1241 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1242
1243 /// Transform the first qualifier within a scope by instantiating the
1244 /// declaration.
1245 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1246
1247 /// Rebuild the exception declaration and register the declaration
1248 /// as an instantiated local.
1249 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1251 SourceLocation StartLoc,
1252 SourceLocation NameLoc,
1253 IdentifierInfo *Name);
1254
1255 /// Rebuild the Objective-C exception declaration and register the
1256 /// declaration as an instantiated local.
1257 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1258 TypeSourceInfo *TSInfo, QualType T);
1259
1260 /// Check for tag mismatches when instantiating an
1261 /// elaborated type.
1262 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1263 ElaboratedTypeKeyword Keyword,
1264 NestedNameSpecifierLoc QualifierLoc,
1265 QualType T);
1266
1268 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1269 SourceLocation NameLoc,
1270 QualType ObjectType = QualType(),
1271 NamedDecl *FirstQualifierInScope = nullptr,
1272 bool AllowInjectedClassName = false);
1273
1274 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1275
1276 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1277 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1278 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1279
1280 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1282 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1284 ExprResult TransformSubstNonTypeTemplateParmExpr(
1286
1287 /// Rebuild a DeclRefExpr for a VarDecl reference.
1288 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1289
1290 /// Transform a reference to a function or init-capture parameter pack.
1291 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1292
1293 /// Transform a FunctionParmPackExpr which was built when we couldn't
1294 /// expand a function parameter pack reference which refers to an expanded
1295 /// pack.
1296 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1297
1298 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1300 // Call the base version; it will forward to our overridden version below.
1301 return inherited::TransformFunctionProtoType(TLB, TL);
1302 }
1303
1304 template<typename Fn>
1305 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1307 CXXRecordDecl *ThisContext,
1308 Qualifiers ThisTypeQuals,
1309 Fn TransformExceptionSpec);
1310
1311 ParmVarDecl *
1312 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1313 std::optional<unsigned> NumExpansions,
1314 bool ExpectParameterPack);
1315
1316 using inherited::TransformTemplateTypeParmType;
1317 /// Transforms a template type parameter type by performing
1318 /// substitution of the corresponding template type argument.
1319 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1321 bool SuppressObjCLifetime);
1322
1323 QualType BuildSubstTemplateTypeParmType(
1324 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1325 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1326 TemplateArgument Arg, SourceLocation NameLoc);
1327
1328 /// Transforms an already-substituted template type parameter pack
1329 /// into either itself (if we aren't substituting into its pack expansion)
1330 /// or the appropriate substituted argument.
1331 using inherited::TransformSubstTemplateTypeParmPackType;
1332 QualType
1333 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1335 bool SuppressObjCLifetime);
1336
1337 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1338 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1340 ExprResult Result = inherited::TransformLambdaExpr(E);
1341 if (Result.isInvalid())
1342 return Result;
1343
1344 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1345 for (ParmVarDecl *PVD : MD->parameters()) {
1346 if (!PVD->hasDefaultArg())
1347 continue;
1348 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1349 // FIXME: Obtain the source location for the '=' token.
1350 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1351 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1352 // If substitution fails, the default argument is set to a
1353 // RecoveryExpr that wraps the uninstantiated default argument so
1354 // that downstream diagnostics are omitted.
1355 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1356 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1357 { UninstExpr }, UninstExpr->getType());
1358 if (ErrorResult.isUsable())
1359 PVD->setDefaultArg(ErrorResult.get());
1360 }
1361 }
1362
1363 return Result;
1364 }
1365
1366 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1367 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1368 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1369 if (TransReq.isInvalid())
1370 return TransReq;
1371 assert(TransReq.get() != E &&
1372 "Do not change value of isSatisfied for the existing expression. "
1373 "Create a new expression instead.");
1374 if (E->getBody()->isDependentContext()) {
1375 Sema::SFINAETrap Trap(SemaRef);
1376 // We recreate the RequiresExpr body, but not by instantiating it.
1377 // Produce pending diagnostics for dependent access check.
1378 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1379 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1380 if (Trap.hasErrorOccurred())
1381 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1382 }
1383 return TransReq;
1384 }
1385
1386 bool TransformRequiresExprRequirements(
1389 bool SatisfactionDetermined = false;
1390 for (concepts::Requirement *Req : Reqs) {
1391 concepts::Requirement *TransReq = nullptr;
1392 if (!SatisfactionDetermined) {
1393 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1394 TransReq = TransformTypeRequirement(TypeReq);
1395 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1396 TransReq = TransformExprRequirement(ExprReq);
1397 else
1398 TransReq = TransformNestedRequirement(
1399 cast<concepts::NestedRequirement>(Req));
1400 if (!TransReq)
1401 return true;
1402 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1403 // [expr.prim.req]p6
1404 // [...] The substitution and semantic constraint checking
1405 // proceeds in lexical order and stops when a condition that
1406 // determines the result of the requires-expression is
1407 // encountered. [..]
1408 SatisfactionDetermined = true;
1409 } else
1410 TransReq = Req;
1411 Transformed.push_back(TransReq);
1412 }
1413 return false;
1414 }
1415
1416 TemplateParameterList *TransformTemplateParameterList(
1417 TemplateParameterList *OrigTPL) {
1418 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1419
1420 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1421 TemplateDeclInstantiator DeclInstantiator(getSema(),
1422 /* DeclContext *Owner */ Owner, TemplateArgs);
1423 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1424 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1425 }
1426
1428 TransformTypeRequirement(concepts::TypeRequirement *Req);
1430 TransformExprRequirement(concepts::ExprRequirement *Req);
1432 TransformNestedRequirement(concepts::NestedRequirement *Req);
1433 ExprResult TransformRequiresTypeParams(
1434 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1437 SmallVectorImpl<ParmVarDecl *> &TransParams,
1439
1440 private:
1442 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1443 const NonTypeTemplateParmDecl *parm,
1445 std::optional<unsigned> PackIndex);
1446 };
1447}
1448
1449bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1450 if (T.isNull())
1451 return true;
1452
1454 return false;
1455
1456 getSema().MarkDeclarationsReferencedInType(Loc, T);
1457 return true;
1458}
1459
1460static TemplateArgument
1462 assert(S.ArgumentPackSubstitutionIndex >= 0);
1463 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1465 if (Arg.isPackExpansion())
1466 Arg = Arg.getPackExpansionPattern();
1467 return Arg;
1468}
1469
1470Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1471 if (!D)
1472 return nullptr;
1473
1474 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1475 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1476 // If the corresponding template argument is NULL or non-existent, it's
1477 // because we are performing instantiation from explicitly-specified
1478 // template arguments in a function template, but there were some
1479 // arguments left unspecified.
1480 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1481 TTP->getPosition()))
1482 return D;
1483
1484 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1485
1486 if (TTP->isParameterPack()) {
1487 assert(Arg.getKind() == TemplateArgument::Pack &&
1488 "Missing argument pack");
1489 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1490 }
1491
1493 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1494 "Wrong kind of template template argument");
1495 return Template.getAsTemplateDecl();
1496 }
1497
1498 // Fall through to find the instantiated declaration for this template
1499 // template parameter.
1500 }
1501
1502 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1503}
1504
1505Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1506 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1507 if (!Inst)
1508 return nullptr;
1509
1510 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1511 return Inst;
1512}
1513
1514NamedDecl *
1515TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1516 SourceLocation Loc) {
1517 // If the first part of the nested-name-specifier was a template type
1518 // parameter, instantiate that type parameter down to a tag type.
1519 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1520 const TemplateTypeParmType *TTP
1521 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1522
1523 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1524 // FIXME: This needs testing w/ member access expressions.
1525 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1526
1527 if (TTP->isParameterPack()) {
1528 assert(Arg.getKind() == TemplateArgument::Pack &&
1529 "Missing argument pack");
1530
1531 if (getSema().ArgumentPackSubstitutionIndex == -1)
1532 return nullptr;
1533
1534 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1535 }
1536
1537 QualType T = Arg.getAsType();
1538 if (T.isNull())
1539 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1540
1541 if (const TagType *Tag = T->getAs<TagType>())
1542 return Tag->getDecl();
1543
1544 // The resulting type is not a tag; complain.
1545 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1546 return nullptr;
1547 }
1548 }
1549
1550 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1551}
1552
1553VarDecl *
1554TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1556 SourceLocation StartLoc,
1557 SourceLocation NameLoc,
1558 IdentifierInfo *Name) {
1559 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1560 StartLoc, NameLoc, Name);
1561 if (Var)
1562 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1563 return Var;
1564}
1565
1566VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1567 TypeSourceInfo *TSInfo,
1568 QualType T) {
1569 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1570 if (Var)
1571 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1572 return Var;
1573}
1574
1576TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1577 ElaboratedTypeKeyword Keyword,
1578 NestedNameSpecifierLoc QualifierLoc,
1579 QualType T) {
1580 if (const TagType *TT = T->getAs<TagType>()) {
1581 TagDecl* TD = TT->getDecl();
1582
1583 SourceLocation TagLocation = KeywordLoc;
1584
1586
1587 // TODO: should we even warn on struct/class mismatches for this? Seems
1588 // like it's likely to produce a lot of spurious errors.
1589 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1591 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1592 TagLocation, Id)) {
1593 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1594 << Id
1596 TD->getKindName());
1597 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1598 }
1599 }
1600 }
1601
1602 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1603}
1604
1605TemplateName TemplateInstantiator::TransformTemplateName(
1606 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1607 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1608 bool AllowInjectedClassName) {
1610 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1611 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1612 // If the corresponding template argument is NULL or non-existent, it's
1613 // because we are performing instantiation from explicitly-specified
1614 // template arguments in a function template, but there were some
1615 // arguments left unspecified.
1616 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1617 TTP->getPosition()))
1618 return Name;
1619
1620 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1621
1622 if (TemplateArgs.isRewrite()) {
1623 // We're rewriting the template parameter as a reference to another
1624 // template parameter.
1625 if (Arg.getKind() == TemplateArgument::Pack) {
1626 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1627 "unexpected pack arguments in template rewrite");
1628 Arg = Arg.pack_begin()->getPackExpansionPattern();
1629 }
1630 assert(Arg.getKind() == TemplateArgument::Template &&
1631 "unexpected nontype template argument kind in template rewrite");
1632 return Arg.getAsTemplate();
1633 }
1634
1635 auto [AssociatedDecl, Final] =
1636 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1637 std::optional<unsigned> PackIndex;
1638 if (TTP->isParameterPack()) {
1639 assert(Arg.getKind() == TemplateArgument::Pack &&
1640 "Missing argument pack");
1641
1642 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1643 // We have the template argument pack to substitute, but we're not
1644 // actually expanding the enclosing pack expansion yet. So, just
1645 // keep the entire argument pack.
1646 return getSema().Context.getSubstTemplateTemplateParmPack(
1647 Arg, AssociatedDecl, TTP->getIndex(), Final);
1648 }
1649
1650 PackIndex = getPackIndex(Arg);
1651 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1652 }
1653
1655 assert(!Template.isNull() && "Null template template argument");
1656 assert(!Template.getAsQualifiedTemplateName() &&
1657 "template decl to substitute is qualified?");
1658
1659 if (Final)
1660 return Template;
1661 return getSema().Context.getSubstTemplateTemplateParm(
1662 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
1663 }
1664 }
1665
1667 = Name.getAsSubstTemplateTemplateParmPack()) {
1668 if (getSema().ArgumentPackSubstitutionIndex == -1)
1669 return Name;
1670
1671 TemplateArgument Pack = SubstPack->getArgumentPack();
1672 TemplateName Template =
1674 if (SubstPack->getFinal())
1675 return Template;
1676 return getSema().Context.getSubstTemplateTemplateParm(
1677 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
1678 SubstPack->getIndex(), getPackIndex(Pack));
1679 }
1680
1681 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1682 FirstQualifierInScope,
1683 AllowInjectedClassName);
1684}
1685
1687TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1688 if (!E->isTypeDependent())
1689 return E;
1690
1691 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1692}
1693
1695TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1697 // If the corresponding template argument is NULL or non-existent, it's
1698 // because we are performing instantiation from explicitly-specified
1699 // template arguments in a function template, but there were some
1700 // arguments left unspecified.
1701 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1702 NTTP->getPosition()))
1703 return E;
1704
1705 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1706
1707 if (TemplateArgs.isRewrite()) {
1708 // We're rewriting the template parameter as a reference to another
1709 // template parameter.
1710 if (Arg.getKind() == TemplateArgument::Pack) {
1711 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1712 "unexpected pack arguments in template rewrite");
1713 Arg = Arg.pack_begin()->getPackExpansionPattern();
1714 }
1715 assert(Arg.getKind() == TemplateArgument::Expression &&
1716 "unexpected nontype template argument kind in template rewrite");
1717 // FIXME: This can lead to the same subexpression appearing multiple times
1718 // in a complete expression.
1719 return Arg.getAsExpr();
1720 }
1721
1722 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
1723 std::optional<unsigned> PackIndex;
1724 if (NTTP->isParameterPack()) {
1725 assert(Arg.getKind() == TemplateArgument::Pack &&
1726 "Missing argument pack");
1727
1728 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1729 // We have an argument pack, but we can't select a particular argument
1730 // out of it yet. Therefore, we'll build an expression to hold on to that
1731 // argument pack.
1732 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1733 E->getLocation(),
1734 NTTP->getDeclName());
1735 if (TargetType.isNull())
1736 return ExprError();
1737
1738 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1739 if (TargetType->isRecordType())
1740 ExprType.addConst();
1741 // FIXME: Pass in Final.
1742 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1743 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
1744 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
1745 }
1746 PackIndex = getPackIndex(Arg);
1747 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1748 }
1749 // FIXME: Don't put subst node on Final replacement.
1750 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
1751 Arg, PackIndex);
1752}
1753
1754const LoopHintAttr *
1755TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1756 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1757
1758 if (TransformedExpr == LH->getValue())
1759 return LH;
1760
1761 // Generate error if there is a problem with the value.
1762 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1763 return LH;
1764
1765 // Create new LoopHintValueAttr with integral expression in place of the
1766 // non-type template parameter.
1767 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1768 LH->getState(), TransformedExpr, *LH);
1769}
1770
1771ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1772 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
1774 std::optional<unsigned> PackIndex) {
1775 ExprResult result;
1776
1777 // Determine the substituted parameter type. We can usually infer this from
1778 // the template argument, but not always.
1779 auto SubstParamType = [&] {
1780 QualType T;
1781 if (parm->isExpandedParameterPack())
1783 else
1784 T = parm->getType();
1785 if (parm->isParameterPack() && isa<PackExpansionType>(T))
1786 T = cast<PackExpansionType>(T)->getPattern();
1787 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1788 };
1789
1790 bool refParam = false;
1791
1792 // The template argument itself might be an expression, in which case we just
1793 // return that expression. This happens when substituting into an alias
1794 // template.
1795 if (arg.getKind() == TemplateArgument::Expression) {
1796 Expr *argExpr = arg.getAsExpr();
1797 result = argExpr;
1798 if (argExpr->isLValue()) {
1799 if (argExpr->getType()->isRecordType()) {
1800 // Check whether the parameter was actually a reference.
1801 QualType paramType = SubstParamType();
1802 if (paramType.isNull())
1803 return ExprError();
1804 refParam = paramType->isReferenceType();
1805 } else {
1806 refParam = true;
1807 }
1808 }
1809 } else if (arg.getKind() == TemplateArgument::Declaration ||
1810 arg.getKind() == TemplateArgument::NullPtr) {
1811 ValueDecl *VD;
1812 if (arg.getKind() == TemplateArgument::Declaration) {
1813 VD = arg.getAsDecl();
1814
1815 // Find the instantiation of the template argument. This is
1816 // required for nested templates.
1817 VD = cast_or_null<ValueDecl>(
1818 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1819 if (!VD)
1820 return ExprError();
1821 } else {
1822 // Propagate NULL template argument.
1823 VD = nullptr;
1824 }
1825
1826 QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType();
1827 assert(!paramType.isNull() && "type substitution failed for param type");
1828 assert(!paramType->isDependentType() && "param type still dependent");
1829 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
1830 refParam = paramType->isReferenceType();
1831 } else {
1832 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1833 assert(result.isInvalid() ||
1834 SemaRef.Context.hasSameType(result.get()->getType(),
1835 arg.getIntegralType()));
1836 }
1837
1838 if (result.isInvalid())
1839 return ExprError();
1840
1841 Expr *resultExpr = result.get();
1842 // FIXME: Don't put subst node on final replacement.
1843 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1844 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
1845 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
1846}
1847
1849TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1851 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1852 // We aren't expanding the parameter pack, so just return ourselves.
1853 return E;
1854 }
1855
1858 // FIXME: Don't put subst node on final replacement.
1859 return transformNonTypeTemplateParmRef(
1861 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
1862}
1863
1865TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1867 ExprResult SubstReplacement = E->getReplacement();
1868 if (!isa<ConstantExpr>(SubstReplacement.get()))
1869 SubstReplacement = TransformExpr(E->getReplacement());
1870 if (SubstReplacement.isInvalid())
1871 return true;
1872 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
1873 if (SubstType.isNull())
1874 return true;
1875 // The type may have been previously dependent and not now, which means we
1876 // might have to implicit cast the argument to the new type, for example:
1877 // template<auto T, decltype(T) U>
1878 // concept C = sizeof(U) == 4;
1879 // void foo() requires C<2, 'a'> { }
1880 // When normalizing foo(), we first form the normalized constraints of C:
1881 // AtomicExpr(sizeof(U) == 4,
1882 // U=SubstNonTypeTemplateParmExpr(Param=U,
1883 // Expr=DeclRef(U),
1884 // Type=decltype(T)))
1885 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1886 // produce:
1887 // AtomicExpr(sizeof(U) == 4,
1888 // U=SubstNonTypeTemplateParmExpr(Param=U,
1889 // Expr=ImpCast(
1890 // decltype(2),
1891 // SubstNTTPE(Param=U, Expr='a',
1892 // Type=char)),
1893 // Type=decltype(2)))
1894 // The call to CheckTemplateArgument here produces the ImpCast.
1895 TemplateArgument SugaredConverted, CanonicalConverted;
1896 if (SemaRef
1898 SubstReplacement.get(), SugaredConverted,
1899 CanonicalConverted, Sema::CTAK_Specified)
1900 .isInvalid())
1901 return true;
1902 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
1903 E->getParameter(), E->getExprLoc(),
1904 SugaredConverted, E->getPackIndex());
1905}
1906
1907ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1908 SourceLocation Loc) {
1909 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1910 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1911}
1912
1914TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1915 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1916 // We can expand this parameter pack now.
1918 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1919 if (!VD)
1920 return ExprError();
1921 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1922 }
1923
1924 QualType T = TransformType(E->getType());
1925 if (T.isNull())
1926 return ExprError();
1927
1928 // Transform each of the parameter expansions into the corresponding
1929 // parameters in the instantiation of the function decl.
1931 Vars.reserve(E->getNumExpansions());
1932 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1933 I != End; ++I) {
1934 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1935 if (!D)
1936 return ExprError();
1937 Vars.push_back(D);
1938 }
1939
1940 auto *PackExpr =
1942 E->getParameterPackLocation(), Vars);
1943 getSema().MarkFunctionParmPackReferenced(PackExpr);
1944 return PackExpr;
1945}
1946
1948TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1949 VarDecl *PD) {
1950 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1951 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1952 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1953 assert(Found && "no instantiation for parameter pack");
1954
1955 Decl *TransformedDecl;
1956 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1957 // If this is a reference to a function parameter pack which we can
1958 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1959 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1960 QualType T = TransformType(E->getType());
1961 if (T.isNull())
1962 return ExprError();
1963 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1964 E->getExprLoc(), *Pack);
1965 getSema().MarkFunctionParmPackReferenced(PackExpr);
1966 return PackExpr;
1967 }
1968
1969 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1970 } else {
1971 TransformedDecl = Found->get<Decl*>();
1972 }
1973
1974 // We have either an unexpanded pack or a specific expansion.
1975 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1976}
1977
1979TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
1980 NamedDecl *D = E->getDecl();
1981
1982 // Handle references to non-type template parameters and non-type template
1983 // parameter packs.
1984 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
1985 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
1986 return TransformTemplateParmRefExpr(E, NTTP);
1987
1988 // We have a non-type template parameter that isn't fully substituted;
1989 // FindInstantiatedDecl will find it in the local instantiation scope.
1990 }
1991
1992 // Handle references to function parameter packs.
1993 if (VarDecl *PD = dyn_cast<VarDecl>(D))
1994 if (PD->isParameterPack())
1995 return TransformFunctionParmPackRefExpr(E, PD);
1996
1997 return inherited::TransformDeclRefExpr(E);
1998}
1999
2000ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2001 CXXDefaultArgExpr *E) {
2002 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2003 getDescribedFunctionTemplate() &&
2004 "Default arg expressions are never formed in dependent cases.");
2005 return SemaRef.BuildCXXDefaultArgExpr(
2006 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2007 E->getParam());
2008}
2009
2010template<typename Fn>
2011QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2013 CXXRecordDecl *ThisContext,
2014 Qualifiers ThisTypeQuals,
2015 Fn TransformExceptionSpec) {
2016 // We need a local instantiation scope for this function prototype.
2017 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2018 return inherited::TransformFunctionProtoType(
2019 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2020}
2021
2022ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2023 ParmVarDecl *OldParm, int indexAdjustment,
2024 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2025 auto NewParm = SemaRef.SubstParmVarDecl(
2026 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2027 ExpectParameterPack, EvaluateConstraints);
2028 if (NewParm && SemaRef.getLangOpts().OpenCL)
2029 SemaRef.deduceOpenCLAddressSpace(NewParm);
2030 return NewParm;
2031}
2032
2033QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2034 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2035 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2036 TemplateArgument Arg, SourceLocation NameLoc) {
2037 QualType Replacement = Arg.getAsType();
2038
2039 // If the template parameter had ObjC lifetime qualifiers,
2040 // then any such qualifiers on the replacement type are ignored.
2041 if (SuppressObjCLifetime) {
2042 Qualifiers RQs;
2043 RQs = Replacement.getQualifiers();
2044 RQs.removeObjCLifetime();
2045 Replacement =
2046 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2047 }
2048
2049 if (Final) {
2050 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2051 return Replacement;
2052 }
2053 // TODO: only do this uniquing once, at the start of instantiation.
2054 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2055 Replacement, AssociatedDecl, Index, PackIndex);
2058 NewTL.setNameLoc(NameLoc);
2059 return Result;
2060}
2061
2063TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2065 bool SuppressObjCLifetime) {
2066 const TemplateTypeParmType *T = TL.getTypePtr();
2067 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2068 // Replace the template type parameter with its corresponding
2069 // template argument.
2070
2071 // If the corresponding template argument is NULL or doesn't exist, it's
2072 // because we are performing instantiation from explicitly-specified
2073 // template arguments in a function template class, but there were some
2074 // arguments left unspecified.
2075 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2078 NewTL.setNameLoc(TL.getNameLoc());
2079 return TL.getType();
2080 }
2081
2082 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2083
2084 if (TemplateArgs.isRewrite()) {
2085 // We're rewriting the template parameter as a reference to another
2086 // template parameter.
2087 if (Arg.getKind() == TemplateArgument::Pack) {
2088 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2089 "unexpected pack arguments in template rewrite");
2090 Arg = Arg.pack_begin()->getPackExpansionPattern();
2091 }
2092 assert(Arg.getKind() == TemplateArgument::Type &&
2093 "unexpected nontype template argument kind in template rewrite");
2094 QualType NewT = Arg.getAsType();
2095 assert(isa<TemplateTypeParmType>(NewT) &&
2096 "type parm not rewritten to type parm");
2097 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
2098 NewTL.setNameLoc(TL.getNameLoc());
2099 return NewT;
2100 }
2101
2102 auto [AssociatedDecl, Final] =
2103 TemplateArgs.getAssociatedDecl(T->getDepth());
2104 std::optional<unsigned> PackIndex;
2105 if (T->isParameterPack()) {
2106 assert(Arg.getKind() == TemplateArgument::Pack &&
2107 "Missing argument pack");
2108
2109 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2110 // We have the template argument pack, but we're not expanding the
2111 // enclosing pack expansion yet. Just save the template argument
2112 // pack for later substitution.
2113 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2114 AssociatedDecl, T->getIndex(), Final, Arg);
2117 NewTL.setNameLoc(TL.getNameLoc());
2118 return Result;
2119 }
2120
2121 // PackIndex starts from last element.
2122 PackIndex = getPackIndex(Arg);
2123 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2124 }
2125
2126 assert(Arg.getKind() == TemplateArgument::Type &&
2127 "Template argument kind mismatch");
2128
2129 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2130 AssociatedDecl, T->getIndex(),
2131 PackIndex, Arg, TL.getNameLoc());
2132 }
2133
2134 // The template type parameter comes from an inner template (e.g.,
2135 // the template parameter list of a member template inside the
2136 // template we are instantiating). Create a new template type
2137 // parameter with the template "level" reduced by one.
2138 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2139 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2140 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2141 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2142 QualType Result = getSema().Context.getTemplateTypeParmType(
2143 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2144 T->isParameterPack(), NewTTPDecl);
2146 NewTL.setNameLoc(TL.getNameLoc());
2147 return Result;
2148}
2149
2150QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2152 bool SuppressObjCLifetime) {
2154
2155 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2156
2157 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2158 // We aren't expanding the parameter pack, so just return ourselves.
2159 QualType Result = TL.getType();
2160 if (NewReplaced != T->getAssociatedDecl())
2161 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2162 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2165 NewTL.setNameLoc(TL.getNameLoc());
2166 return Result;
2167 }
2168
2171 return BuildSubstTemplateTypeParmType(
2172 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2173 getPackIndex(Pack), Arg, TL.getNameLoc());
2174}
2175
2176template<typename EntityPrinter>
2178createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
2179 SmallString<128> Message;
2180 SourceLocation ErrorLoc;
2181 if (Info.hasSFINAEDiagnostic()) {
2184 Info.takeSFINAEDiagnostic(PDA);
2185 PDA.second.EmitToString(S.getDiagnostics(), Message);
2186 ErrorLoc = PDA.first;
2187 } else {
2188 ErrorLoc = Info.getLocation();
2189 }
2190 char *MessageBuf = new (S.Context) char[Message.size()];
2191 std::copy(Message.begin(), Message.end(), MessageBuf);
2192 SmallString<128> Entity;
2193 llvm::raw_svector_ostream OS(Entity);
2194 Printer(OS);
2195 char *EntityBuf = new (S.Context) char[Entity.size()];
2196 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2198 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2199 StringRef(MessageBuf, Message.size())};
2200}
2201
2202ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2203 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2206 SmallVectorImpl<ParmVarDecl *> &TransParams,
2208
2209 TemplateDeductionInfo Info(KWLoc);
2210 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2211 RE, Info,
2212 SourceRange{KWLoc, RBraceLoc});
2213 Sema::SFINAETrap Trap(SemaRef);
2214
2215 unsigned ErrorIdx;
2216 if (getDerived().TransformFunctionTypeParams(
2217 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2218 &TransParams, PInfos, &ErrorIdx) ||
2219 Trap.hasErrorOccurred()) {
2221 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2222 // Add a 'failed' Requirement to contain the error that caused the failure
2223 // here.
2224 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2225 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2226 return getDerived().RebuildRequiresExpr(KWLoc, Body, TransParams, TransReqs,
2227 RBraceLoc);
2228 }
2229
2230 return ExprResult{};
2231}
2232
2234TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2235 if (!Req->isDependent() && !AlwaysRebuild())
2236 return Req;
2237 if (Req->isSubstitutionFailure()) {
2238 if (AlwaysRebuild())
2239 return RebuildTypeRequirement(
2241 return Req;
2242 }
2243
2244 Sema::SFINAETrap Trap(SemaRef);
2246 Sema::InstantiatingTemplate TypeInst(SemaRef,
2247 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2248 Req->getType()->getTypeLoc().getSourceRange());
2249 if (TypeInst.isInvalid())
2250 return nullptr;
2251 TypeSourceInfo *TransType = TransformType(Req->getType());
2252 if (!TransType || Trap.hasErrorOccurred())
2253 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2254 [&] (llvm::raw_ostream& OS) {
2255 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2256 }));
2257 return RebuildTypeRequirement(TransType);
2258}
2259
2261TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2262 if (!Req->isDependent() && !AlwaysRebuild())
2263 return Req;
2264
2265 Sema::SFINAETrap Trap(SemaRef);
2266
2267 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2268 TransExpr;
2269 if (Req->isExprSubstitutionFailure())
2270 TransExpr = Req->getExprSubstitutionDiagnostic();
2271 else {
2272 Expr *E = Req->getExpr();
2274 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2275 E->getSourceRange());
2276 if (ExprInst.isInvalid())
2277 return nullptr;
2278 ExprResult TransExprRes = TransformExpr(E);
2279 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2280 TransExprRes.get()->hasPlaceholderType())
2281 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2282 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2283 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2284 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2285 });
2286 else
2287 TransExpr = TransExprRes.get();
2288 }
2289
2290 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2291 const auto &RetReq = Req->getReturnTypeRequirement();
2292 if (RetReq.isEmpty())
2293 TransRetReq.emplace();
2294 else if (RetReq.isSubstitutionFailure())
2295 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2296 else if (RetReq.isTypeConstraint()) {
2297 TemplateParameterList *OrigTPL =
2298 RetReq.getTypeConstraintTemplateParameterList();
2299 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2300 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2301 Req, Info, OrigTPL->getSourceRange());
2302 if (TPLInst.isInvalid())
2303 return nullptr;
2304 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2305 if (!TPL)
2306 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2307 [&] (llvm::raw_ostream& OS) {
2308 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2309 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2310 }));
2311 else {
2312 TPLInst.Clear();
2313 TransRetReq.emplace(TPL);
2314 }
2315 }
2316 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2317 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2318 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2319 std::move(*TransRetReq));
2320 return RebuildExprRequirement(
2322 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2323}
2324
2326TemplateInstantiator::TransformNestedRequirement(
2328 if (!Req->isDependent() && !AlwaysRebuild())
2329 return Req;
2330 if (Req->hasInvalidConstraint()) {
2331 if (AlwaysRebuild())
2332 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2334 return Req;
2335 }
2336 Sema::InstantiatingTemplate ReqInst(SemaRef,
2337 Req->getConstraintExpr()->getBeginLoc(), Req,
2340
2341 ExprResult TransConstraint;
2342 ConstraintSatisfaction Satisfaction;
2344 {
2347 Sema::SFINAETrap Trap(SemaRef);
2348 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2349 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2351 if (ConstrInst.isInvalid())
2352 return nullptr;
2354 if (!SemaRef.CheckConstraintSatisfaction(
2355 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2356 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2357 !Result.empty())
2358 TransConstraint = Result[0];
2359 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2360 "by CheckConstraintSatisfaction.");
2361 }
2362 if (TransConstraint.isUsable() &&
2363 TransConstraint.get()->isInstantiationDependent())
2364 return new (SemaRef.Context)
2365 concepts::NestedRequirement(TransConstraint.get());
2366 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2367 Satisfaction.HasSubstitutionFailure()) {
2368 SmallString<128> Entity;
2369 llvm::raw_svector_ostream OS(Entity);
2370 Req->getConstraintExpr()->printPretty(OS, nullptr,
2371 SemaRef.getPrintingPolicy());
2372 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2373 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2374 return new (SemaRef.Context) concepts::NestedRequirement(
2375 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2376 }
2377 return new (SemaRef.Context) concepts::NestedRequirement(
2378 SemaRef.Context, TransConstraint.get(), Satisfaction);
2379}
2380
2381
2382/// Perform substitution on the type T with a given set of template
2383/// arguments.
2384///
2385/// This routine substitutes the given template arguments into the
2386/// type T and produces the instantiated type.
2387///
2388/// \param T the type into which the template arguments will be
2389/// substituted. If this type is not dependent, it will be returned
2390/// immediately.
2391///
2392/// \param Args the template arguments that will be
2393/// substituted for the top-level template parameters within T.
2394///
2395/// \param Loc the location in the source code where this substitution
2396/// is being performed. It will typically be the location of the
2397/// declarator (if we're instantiating the type of some declaration)
2398/// or the location of the type in the source code (if, e.g., we're
2399/// instantiating the type of a cast expression).
2400///
2401/// \param Entity the name of the entity associated with a declaration
2402/// being instantiated (if any). May be empty to indicate that there
2403/// is no such entity (if, e.g., this is a type that occurs as part of
2404/// a cast expression) or that the entity has no name (e.g., an
2405/// unnamed function parameter).
2406///
2407/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2408/// acceptable as the top level type of the result.
2409///
2410/// \returns If the instantiation succeeds, the instantiated
2411/// type. Otherwise, produces diagnostics and returns a NULL type.
2414 SourceLocation Loc,
2415 DeclarationName Entity,
2416 bool AllowDeducedTST) {
2417 assert(!CodeSynthesisContexts.empty() &&
2418 "Cannot perform an instantiation without some context on the "
2419 "instantiation stack");
2420
2423 return T;
2424
2425 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2426 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2427 : Instantiator.TransformType(T);
2428}
2429
2432 SourceLocation Loc,
2433 DeclarationName Entity) {
2434 assert(!CodeSynthesisContexts.empty() &&
2435 "Cannot perform an instantiation without some context on the "
2436 "instantiation stack");
2437
2438 if (TL.getType().isNull())
2439 return nullptr;
2440
2443 // FIXME: Make a copy of the TypeLoc data here, so that we can
2444 // return a new TypeSourceInfo. Inefficient!
2445 TypeLocBuilder TLB;
2446 TLB.pushFullCopy(TL);
2447 return TLB.getTypeSourceInfo(Context, TL.getType());
2448 }
2449
2450 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2451 TypeLocBuilder TLB;
2452 TLB.reserve(TL.getFullDataSize());
2453 QualType Result = Instantiator.TransformType(TLB, TL);
2454 if (Result.isNull())
2455 return nullptr;
2456
2457 return TLB.getTypeSourceInfo(Context, Result);
2458}
2459
2460/// Deprecated form of the above.
2462 const MultiLevelTemplateArgumentList &TemplateArgs,
2463 SourceLocation Loc, DeclarationName Entity) {
2464 assert(!CodeSynthesisContexts.empty() &&
2465 "Cannot perform an instantiation without some context on the "
2466 "instantiation stack");
2467
2468 // If T is not a dependent type or a variably-modified type, there
2469 // is nothing to do.
2471 return T;
2472
2473 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2474 return Instantiator.TransformType(T);
2475}
2476
2480 return true;
2481
2482 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2483 if (!TL.getAs<FunctionProtoTypeLoc>())
2484 return false;
2485
2487 for (ParmVarDecl *P : FP.getParams()) {
2488 // This must be synthesized from a typedef.
2489 if (!P) continue;
2490
2491 // If there are any parameters, a new TypeSourceInfo that refers to the
2492 // instantiated parameters must be built.
2493 return true;
2494 }
2495
2496 return false;
2497}
2498
2499/// A form of SubstType intended specifically for instantiating the
2500/// type of a FunctionDecl. Its purpose is solely to force the
2501/// instantiation of default-argument expressions and to avoid
2502/// instantiating an exception-specification.
2505 SourceLocation Loc,
2506 DeclarationName Entity,
2507 CXXRecordDecl *ThisContext,
2508 Qualifiers ThisTypeQuals,
2509 bool EvaluateConstraints) {
2510 assert(!CodeSynthesisContexts.empty() &&
2511 "Cannot perform an instantiation without some context on the "
2512 "instantiation stack");
2513
2515 return T;
2516
2517 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2518 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2519
2520 TypeLocBuilder TLB;
2521
2522 TypeLoc TL = T->getTypeLoc();
2523 TLB.reserve(TL.getFullDataSize());
2524
2526
2527 if (FunctionProtoTypeLoc Proto =
2529 // Instantiate the type, other than its exception specification. The
2530 // exception specification is instantiated in InitFunctionInstantiation
2531 // once we've built the FunctionDecl.
2532 // FIXME: Set the exception specification to EST_Uninstantiated here,
2533 // instead of rebuilding the function type again later.
2534 Result = Instantiator.TransformFunctionProtoType(
2535 TLB, Proto, ThisContext, ThisTypeQuals,
2537 bool &Changed) { return false; });
2538 } else {
2539 Result = Instantiator.TransformType(TLB, TL);
2540 }
2541 if (Result.isNull())
2542 return nullptr;
2543
2544 return TLB.getTypeSourceInfo(Context, Result);
2545}
2546
2549 SmallVectorImpl<QualType> &ExceptionStorage,
2550 const MultiLevelTemplateArgumentList &Args) {
2551 assert(ESI.Type != EST_Uninstantiated);
2552
2553 bool Changed = false;
2554 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2555 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2556 Changed);
2557}
2558
2560 const MultiLevelTemplateArgumentList &Args) {
2563
2564 SmallVector<QualType, 4> ExceptionStorage;
2566 ESI, ExceptionStorage, Args))
2567 // On error, recover by dropping the exception specification.
2568 ESI.Type = EST_None;
2569
2570 UpdateExceptionSpec(New, ESI);
2571}
2572
2573namespace {
2574
2575 struct GetContainedInventedTypeParmVisitor :
2576 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2577 TemplateTypeParmDecl *> {
2578 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2579 TemplateTypeParmDecl *>::Visit;
2580
2581 TemplateTypeParmDecl *Visit(QualType T) {
2582 if (T.isNull())
2583 return nullptr;
2584 return Visit(T.getTypePtr());
2585 }
2586 // The deduced type itself.
2587 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2588 const TemplateTypeParmType *T) {
2589 if (!T->getDecl() || !T->getDecl()->isImplicit())
2590 return nullptr;
2591 return T->getDecl();
2592 }
2593
2594 // Only these types can contain 'auto' types, and subsequently be replaced
2595 // by references to invented parameters.
2596
2597 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2598 return Visit(T->getNamedType());
2599 }
2600
2601 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2602 return Visit(T->getPointeeType());
2603 }
2604
2605 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2606 return Visit(T->getPointeeType());
2607 }
2608
2609 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2610 return Visit(T->getPointeeTypeAsWritten());
2611 }
2612
2613 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2614 return Visit(T->getPointeeType());
2615 }
2616
2617 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2618 return Visit(T->getElementType());
2619 }
2620
2621 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2622 const DependentSizedExtVectorType *T) {
2623 return Visit(T->getElementType());
2624 }
2625
2626 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2627 return Visit(T->getElementType());
2628 }
2629
2630 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2631 return VisitFunctionType(T);
2632 }
2633
2634 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2635 return Visit(T->getReturnType());
2636 }
2637
2638 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2639 return Visit(T->getInnerType());
2640 }
2641
2642 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2643 return Visit(T->getModifiedType());
2644 }
2645
2646 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2647 return Visit(T->getUnderlyingType());
2648 }
2649
2650 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2651 return Visit(T->getOriginalType());
2652 }
2653
2654 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2655 return Visit(T->getPattern());
2656 }
2657 };
2658
2659} // namespace
2660
2662 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2663 const MultiLevelTemplateArgumentList &TemplateArgs,
2664 bool EvaluateConstraints) {
2665 const ASTTemplateArgumentListInfo *TemplArgInfo =
2667
2668 if (!EvaluateConstraints) {
2671 TC->getNamedConcept(), TemplArgInfo,
2673 return false;
2674 }
2675
2676 TemplateArgumentListInfo InstArgs;
2677
2678 if (TemplArgInfo) {
2679 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2680 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2681 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2682 InstArgs))
2683 return true;
2684 }
2685 return AttachTypeConstraint(
2687 TC->getNamedConcept(), &InstArgs, Inst,
2688 Inst->isParameterPack()
2689 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2690 ->getEllipsisLoc()
2691 : SourceLocation());
2692}
2693
2695 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
2696 int indexAdjustment, std::optional<unsigned> NumExpansions,
2697 bool ExpectParameterPack, bool EvaluateConstraint) {
2698 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2699 TypeSourceInfo *NewDI = nullptr;
2700
2701 TypeLoc OldTL = OldDI->getTypeLoc();
2702 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2703
2704 // We have a function parameter pack. Substitute into the pattern of the
2705 // expansion.
2706 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2707 OldParm->getLocation(), OldParm->getDeclName());
2708 if (!NewDI)
2709 return nullptr;
2710
2711 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2712 // We still have unexpanded parameter packs, which means that
2713 // our function parameter is still a function parameter pack.
2714 // Therefore, make its type a pack expansion type.
2715 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2716 NumExpansions);
2717 } else if (ExpectParameterPack) {
2718 // We expected to get a parameter pack but didn't (because the type
2719 // itself is not a pack expansion type), so complain. This can occur when
2720 // the substitution goes through an alias template that "loses" the
2721 // pack expansion.
2722 Diag(OldParm->getLocation(),
2723 diag::err_function_parameter_pack_without_parameter_packs)
2724 << NewDI->getType();
2725 return nullptr;
2726 }
2727 } else {
2728 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2729 OldParm->getDeclName());
2730 }
2731
2732 if (!NewDI)
2733 return nullptr;
2734
2735 if (NewDI->getType()->isVoidType()) {
2736 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2737 return nullptr;
2738 }
2739
2740 // In abbreviated templates, TemplateTypeParmDecls with possible
2741 // TypeConstraints are created when the parameter list is originally parsed.
2742 // The TypeConstraints can therefore reference other functions parameters in
2743 // the abbreviated function template, which is why we must instantiate them
2744 // here, when the instantiated versions of those referenced parameters are in
2745 // scope.
2746 if (TemplateTypeParmDecl *TTP =
2747 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2748 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2749 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2750 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2751 // We will first get here when instantiating the abbreviated function
2752 // template's described function, but we might also get here later.
2753 // Make sure we do not instantiate the TypeConstraint more than once.
2754 if (Inst && !Inst->getTypeConstraint()) {
2755 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
2756 return nullptr;
2757 }
2758 }
2759 }
2760
2762 OldParm->getInnerLocStart(),
2763 OldParm->getLocation(),
2764 OldParm->getIdentifier(),
2765 NewDI->getType(), NewDI,
2766 OldParm->getStorageClass());
2767 if (!NewParm)
2768 return nullptr;
2769
2770 // Mark the (new) default argument as uninstantiated (if any).
2771 if (OldParm->hasUninstantiatedDefaultArg()) {
2772 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2773 NewParm->setUninstantiatedDefaultArg(Arg);
2774 } else if (OldParm->hasUnparsedDefaultArg()) {
2775 NewParm->setUnparsedDefaultArg();
2776 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2777 } else if (Expr *Arg = OldParm->getDefaultArg()) {
2778 // Default arguments cannot be substituted until the declaration context
2779 // for the associated function or lambda capture class is available.
2780 // This is necessary for cases like the following where construction of
2781 // the lambda capture class for the outer lambda is dependent on the
2782 // parameter types but where the default argument is dependent on the
2783 // outer lambda's declaration context.
2784 // template <typename T>
2785 // auto f() {
2786 // return [](T = []{ return T{}; }()) { return 0; };
2787 // }
2788 NewParm->setUninstantiatedDefaultArg(Arg);
2789 }
2790
2792
2793 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2794 // Add the new parameter to the instantiated parameter pack.
2796 } else {
2797 // Introduce an Old -> New mapping
2799 }
2800
2801 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2802 // can be anything, is this right ?
2803 NewParm->setDeclContext(CurContext);
2804
2805 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2806 OldParm->getFunctionScopeIndex() + indexAdjustment);
2807
2808 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2809
2810 return NewParm;
2811}
2812
2813/// Substitute the given template arguments into the given set of
2814/// parameters, producing the set of parameter types that would be generated
2815/// from such a substitution.
2818 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2819 const MultiLevelTemplateArgumentList &TemplateArgs,
2820 SmallVectorImpl<QualType> &ParamTypes,
2822 ExtParameterInfoBuilder &ParamInfos) {
2823 assert(!CodeSynthesisContexts.empty() &&
2824 "Cannot perform an instantiation without some context on the "
2825 "instantiation stack");
2826
2827 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2828 DeclarationName());
2829 return Instantiator.TransformFunctionTypeParams(
2830 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2831}
2832
2833/// Substitute the given template arguments into the default argument.
2835 SourceLocation Loc,
2836 ParmVarDecl *Param,
2837 const MultiLevelTemplateArgumentList &TemplateArgs,
2838 bool ForCallExpr) {
2839 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
2840 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
2841
2844
2845 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
2846 if (Inst.isInvalid())
2847 return true;
2848 if (Inst.isAlreadyInstantiating()) {
2849 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
2850 Param->setInvalidDecl();
2851 return true;
2852 }
2853
2855 {
2856 // C++ [dcl.fct.default]p5:
2857 // The names in the [default argument] expression are bound, and
2858 // the semantic constraints are checked, at the point where the
2859 // default argument expression appears.
2860 ContextRAII SavedContext(*this, FD);
2861 std::unique_ptr<LocalInstantiationScope> LIS;
2862
2863 if (ForCallExpr) {
2864 // When instantiating a default argument due to use in a call expression,
2865 // an instantiation scope that includes the parameters of the callee is
2866 // required to satisfy references from the default argument. For example:
2867 // template<typename T> void f(T a, int = decltype(a)());
2868 // void g() { f(0); }
2869 LIS = std::make_unique<LocalInstantiationScope>(*this);
2871 /*ForDefinition*/ false);
2872 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
2873 return true;
2874 }
2875
2877 Result = SubstInitializer(PatternExpr, TemplateArgs,
2878 /*DirectInit*/false);
2879 });
2880 }
2881 if (Result.isInvalid())
2882 return true;
2883
2884 if (ForCallExpr) {
2885 // Check the expression as an initializer for the parameter.
2886 InitializedEntity Entity
2889 Param->getLocation(),
2890 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
2891 Expr *ResultE = Result.getAs<Expr>();
2892
2893 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
2894 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
2895 if (Result.isInvalid())
2896 return true;
2897
2898 Result =
2900 /*DiscardedValue*/ false);
2901 } else {
2902 // FIXME: Obtain the source location for the '=' token.
2903 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
2904 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
2905 }
2906 if (Result.isInvalid())
2907 return true;
2908
2909 // Remember the instantiated default argument.
2910 Param->setDefaultArg(Result.getAs<Expr>());
2911
2912 return false;
2913}
2914
2915/// Perform substitution on the base class specifiers of the
2916/// given class template specialization.
2917///
2918/// Produces a diagnostic and returns true on error, returns false and
2919/// attaches the instantiated base classes to the class template
2920/// specialization if successful.
2921bool
2923 CXXRecordDecl *Pattern,
2924 const MultiLevelTemplateArgumentList &TemplateArgs) {
2925 bool Invalid = false;
2926 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2927 for (const auto &Base : Pattern->bases()) {
2928 if (!Base.getType()->isDependentType()) {
2929 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2930 if (RD->isInvalidDecl())
2931 Instantiation->setInvalidDecl();
2932 }
2933 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2934 continue;
2935 }
2936
2937 SourceLocation EllipsisLoc;
2938 TypeSourceInfo *BaseTypeLoc;
2939 if (Base.isPackExpansion()) {
2940 // This is a pack expansion. See whether we should expand it now, or
2941 // wait until later.
2943 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2944 Unexpanded);
2945 bool ShouldExpand = false;
2946 bool RetainExpansion = false;
2947 std::optional<unsigned> NumExpansions;
2948 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2949 Base.getSourceRange(),
2950 Unexpanded,
2951 TemplateArgs, ShouldExpand,
2952 RetainExpansion,
2953 NumExpansions)) {
2954 Invalid = true;
2955 continue;
2956 }
2957
2958 // If we should expand this pack expansion now, do so.
2959 if (ShouldExpand) {
2960 for (unsigned I = 0; I != *NumExpansions; ++I) {
2961 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2962
2963 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2964 TemplateArgs,
2965 Base.getSourceRange().getBegin(),
2966 DeclarationName());
2967 if (!BaseTypeLoc) {
2968 Invalid = true;
2969 continue;
2970 }
2971
2972 if (CXXBaseSpecifier *InstantiatedBase
2973 = CheckBaseSpecifier(Instantiation,
2974 Base.getSourceRange(),
2975 Base.isVirtual(),
2976 Base.getAccessSpecifierAsWritten(),
2977 BaseTypeLoc,
2978 SourceLocation()))
2979 InstantiatedBases.push_back(InstantiatedBase);
2980 else
2981 Invalid = true;
2982 }
2983
2984 continue;
2985 }
2986
2987 // The resulting base specifier will (still) be a pack expansion.
2988 EllipsisLoc = Base.getEllipsisLoc();
2989 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
2990 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2991 TemplateArgs,
2992 Base.getSourceRange().getBegin(),
2993 DeclarationName());
2994 } else {
2995 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2996 TemplateArgs,
2997 Base.getSourceRange().getBegin(),
2998 DeclarationName());
2999 }
3000
3001 if (!BaseTypeLoc) {
3002 Invalid = true;
3003 continue;
3004 }
3005
3006 if (CXXBaseSpecifier *InstantiatedBase
3007 = CheckBaseSpecifier(Instantiation,
3008 Base.getSourceRange(),
3009 Base.isVirtual(),
3010 Base.getAccessSpecifierAsWritten(),
3011 BaseTypeLoc,
3012 EllipsisLoc))
3013 InstantiatedBases.push_back(InstantiatedBase);
3014 else
3015 Invalid = true;
3016 }
3017
3018 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3019 Invalid = true;
3020
3021 return Invalid;
3022}
3023
3024// Defined via #include from SemaTemplateInstantiateDecl.cpp
3025namespace clang {
3026 namespace sema {
3028 const MultiLevelTemplateArgumentList &TemplateArgs);
3030 const Attr *At, ASTContext &C, Sema &S,
3031 const MultiLevelTemplateArgumentList &TemplateArgs);
3032 }
3033}
3034
3035/// Instantiate the definition of a class from a given pattern.
3036///
3037/// \param PointOfInstantiation The point of instantiation within the
3038/// source code.
3039///
3040/// \param Instantiation is the declaration whose definition is being
3041/// instantiated. This will be either a class template specialization
3042/// or a member class of a class template specialization.
3043///
3044/// \param Pattern is the pattern from which the instantiation
3045/// occurs. This will be either the declaration of a class template or
3046/// the declaration of a member class of a class template.
3047///
3048/// \param TemplateArgs The template arguments to be substituted into
3049/// the pattern.
3050///
3051/// \param TSK the kind of implicit or explicit instantiation to perform.
3052///
3053/// \param Complain whether to complain if the class cannot be instantiated due
3054/// to the lack of a definition.
3055///
3056/// \returns true if an error occurred, false otherwise.
3057bool
3059 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3060 const MultiLevelTemplateArgumentList &TemplateArgs,
3062 bool Complain) {
3063 CXXRecordDecl *PatternDef
3064 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3065 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3066 Instantiation->getInstantiatedFromMemberClass(),
3067 Pattern, PatternDef, TSK, Complain))
3068 return true;
3069
3070 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3071 std::string Name;
3072 llvm::raw_string_ostream OS(Name);
3073 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3074 /*Qualified=*/true);
3075 return Name;
3076 });
3077
3078 Pattern = PatternDef;
3079
3080 // Record the point of instantiation.
3081 if (MemberSpecializationInfo *MSInfo
3082 = Instantiation->getMemberSpecializationInfo()) {
3083 MSInfo->setTemplateSpecializationKind(TSK);
3084 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3085 } else if (ClassTemplateSpecializationDecl *Spec
3086 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3087 Spec->setTemplateSpecializationKind(TSK);
3088 Spec->setPointOfInstantiation(PointOfInstantiation);
3089 }
3090
3091 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3092 if (Inst.isInvalid())
3093 return true;
3094 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3095 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3096 "instantiating class definition");
3097
3098 // Enter the scope of this instantiation. We don't use
3099 // PushDeclContext because we don't have a scope.
3100 ContextRAII SavedContext(*this, Instantiation);
3103
3104 // If this is an instantiation of a local class, merge this local
3105 // instantiation scope with the enclosing scope. Otherwise, every
3106 // instantiation of a class has its own local instantiation scope.
3107 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3108 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3109
3110 // Some class state isn't processed immediately but delayed till class
3111 // instantiation completes. We may not be ready to handle any delayed state
3112 // already on the stack as it might correspond to a different class, so save
3113 // it now and put it back later.
3114 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3115
3116 // Pull attributes from the pattern onto the instantiation.
3117 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3118
3119 // Start the definition of this instantiation.
3120 Instantiation->startDefinition();
3121
3122 // The instantiation is visible here, even if it was first declared in an
3123 // unimported module.
3124 Instantiation->setVisibleDespiteOwningModule();
3125
3126 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3127 Instantiation->setTagKind(Pattern->getTagKind());
3128
3129 // Do substitution on the base class specifiers.
3130 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3131 Instantiation->setInvalidDecl();
3132
3133 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3134 Instantiator.setEvaluateConstraints(false);
3135 SmallVector<Decl*, 4> Fields;
3136 // Delay instantiation of late parsed attributes.
3137 LateInstantiatedAttrVec LateAttrs;
3138 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3139
3140 bool MightHaveConstexprVirtualFunctions = false;
3141 for (auto *Member : Pattern->decls()) {
3142 // Don't instantiate members not belonging in this semantic context.
3143 // e.g. for:
3144 // @code
3145 // template <int i> class A {
3146 // class B *g;
3147 // };
3148 // @endcode
3149 // 'class B' has the template as lexical context but semantically it is
3150 // introduced in namespace scope.
3151 if (Member->getDeclContext() != Pattern)
3152 continue;
3153
3154 // BlockDecls can appear in a default-member-initializer. They must be the
3155 // child of a BlockExpr, so we only know how to instantiate them from there.
3156 // Similarly, lambda closure types are recreated when instantiating the
3157 // corresponding LambdaExpr.
3158 if (isa<BlockDecl>(Member) ||
3159 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3160 continue;
3161
3162 if (Member->isInvalidDecl()) {
3163 Instantiation->setInvalidDecl();
3164 continue;
3165 }
3166
3167 Decl *NewMember = Instantiator.Visit(Member);
3168 if (NewMember) {
3169 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3170 Fields.push_back(Field);
3171 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3172 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3173 // specialization causes the implicit instantiation of the definitions
3174 // of unscoped member enumerations.
3175 // Record a point of instantiation for this implicit instantiation.
3176 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3177 Enum->isCompleteDefinition()) {
3178 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3179 assert(MSInfo && "no spec info for member enum specialization");
3181 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3182 }
3183 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3184 if (SA->isFailed()) {
3185 // A static_assert failed. Bail out; instantiating this
3186 // class is probably not meaningful.
3187 Instantiation->setInvalidDecl();
3188 break;
3189 }
3190 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3191 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3192 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3193 MightHaveConstexprVirtualFunctions = true;
3194 }
3195
3196 if (NewMember->isInvalidDecl())
3197 Instantiation->setInvalidDecl();
3198 } else {
3199 // FIXME: Eventually, a NULL return will mean that one of the
3200 // instantiations was a semantic disaster, and we'll want to mark the
3201 // declaration invalid.
3202 // For now, we expect to skip some members that we can't yet handle.
3203 }
3204 }
3205
3206 // Finish checking fields.
3207 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3209 CheckCompletedCXXClass(nullptr, Instantiation);
3210
3211 // Default arguments are parsed, if not instantiated. We can go instantiate
3212 // default arg exprs for default constructors if necessary now. Unless we're
3213 // parsing a class, in which case wait until that's finished.
3214 if (ParsingClassDepth == 0)
3216
3217 // Instantiate late parsed attributes, and attach them to their decls.
3218 // See Sema::InstantiateAttrs
3219 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3220 E = LateAttrs.end(); I != E; ++I) {
3221 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3222 CurrentInstantiationScope = I->Scope;
3223
3224 // Allow 'this' within late-parsed attributes.
3225 auto *ND = cast<NamedDecl>(I->NewDecl);
3226 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3227 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3228 ND->isCXXInstanceMember());
3229
3230 Attr *NewAttr =
3231 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3232 if (NewAttr)
3233 I->NewDecl->addAttr(NewAttr);
3235 Instantiator.getStartingScope());
3236 }
3237 Instantiator.disableLateAttributeInstantiation();
3238 LateAttrs.clear();
3239
3241
3242 // FIXME: We should do something similar for explicit instantiations so they
3243 // end up in the right module.
3244 if (TSK == TSK_ImplicitInstantiation) {
3245 Instantiation->setLocation(Pattern->getLocation());
3246 Instantiation->setLocStart(Pattern->getInnerLocStart());
3247 Instantiation->setBraceRange(Pattern->getBraceRange());
3248 }
3249
3250 if (!Instantiation->isInvalidDecl()) {
3251 // Perform any dependent diagnostics from the pattern.
3252 if (Pattern->isDependentContext())
3253 PerformDependentDiagnostics(Pattern, TemplateArgs);
3254
3255 // Instantiate any out-of-line class template partial
3256 // specializations now.
3258 P = Instantiator.delayed_partial_spec_begin(),
3259 PEnd = Instantiator.delayed_partial_spec_end();
3260 P != PEnd; ++P) {
3262 P->first, P->second)) {
3263 Instantiation->setInvalidDecl();
3264 break;
3265 }
3266 }
3267
3268 // Instantiate any out-of-line variable template partial
3269 // specializations now.
3271 P = Instantiator.delayed_var_partial_spec_begin(),
3272 PEnd = Instantiator.delayed_var_partial_spec_end();
3273 P != PEnd; ++P) {
3275 P->first, P->second)) {
3276 Instantiation->setInvalidDecl();
3277 break;
3278 }
3279 }
3280 }
3281
3282 // Exit the scope of this instantiation.
3283 SavedContext.pop();
3284
3285 if (!Instantiation->isInvalidDecl()) {
3286 // Always emit the vtable for an explicit instantiation definition
3287 // of a polymorphic class template specialization. Otherwise, eagerly
3288 // instantiate only constexpr virtual functions in preparation for their use
3289 // in constant evaluation.
3291 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3292 else if (MightHaveConstexprVirtualFunctions)
3293 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3294 /*ConstexprOnly*/ true);
3295 }
3296
3297 Consumer.HandleTagDeclDefinition(Instantiation);
3298
3299 return Instantiation->isInvalidDecl();
3300}
3301
3302/// Instantiate the definition of an enum from a given pattern.
3303///
3304/// \param PointOfInstantiation The point of instantiation within the
3305/// source code.
3306/// \param Instantiation is the declaration whose definition is being
3307/// instantiated. This will be a member enumeration of a class
3308/// temploid specialization, or a local enumeration within a
3309/// function temploid specialization.
3310/// \param Pattern The templated declaration from which the instantiation
3311/// occurs.
3312/// \param TemplateArgs The template arguments to be substituted into
3313/// the pattern.
3314/// \param TSK The kind of implicit or explicit instantiation to perform.
3315///
3316/// \return \c true if an error occurred, \c false otherwise.
3317bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3318 EnumDecl *Instantiation, EnumDecl *Pattern,
3319 const MultiLevelTemplateArgumentList &TemplateArgs,
3321 EnumDecl *PatternDef = Pattern->getDefinition();
3322 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3323 Instantiation->getInstantiatedFromMemberEnum(),
3324 Pattern, PatternDef, TSK,/*Complain*/true))
3325 return true;
3326 Pattern = PatternDef;
3327
3328 // Record the point of instantiation.
3329 if (MemberSpecializationInfo *MSInfo
3330 = Instantiation->getMemberSpecializationInfo()) {
3331 MSInfo->setTemplateSpecializationKind(TSK);
3332 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3333 }
3334
3335 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3336 if (Inst.isInvalid())
3337 return true;
3338 if (Inst.isAlreadyInstantiating())
3339 return false;
3340 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3341 "instantiating enum definition");
3342
3343 // The instantiation is visible here, even if it was first declared in an
3344 // unimported module.
3345 Instantiation->setVisibleDespiteOwningModule();
3346
3347 // Enter the scope of this instantiation. We don't use
3348 // PushDeclContext because we don't have a scope.
3349 ContextRAII SavedContext(*this, Instantiation);
3352
3353 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3354
3355 // Pull attributes from the pattern onto the instantiation.
3356 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3357
3358 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3359 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3360
3361 // Exit the scope of this instantiation.
3362 SavedContext.pop();
3363
3364 return Instantiation->isInvalidDecl();
3365}
3366
3367
3368/// Instantiate the definition of a field from the given pattern.
3369///
3370/// \param PointOfInstantiation The point of instantiation within the
3371/// source code.
3372/// \param Instantiation is the declaration whose definition is being
3373/// instantiated. This will be a class of a class temploid
3374/// specialization, or a local enumeration within a function temploid
3375/// specialization.
3376/// \param Pattern The templated declaration from which the instantiation
3377/// occurs.
3378/// \param TemplateArgs The template arguments to be substituted into
3379/// the pattern.
3380///
3381/// \return \c true if an error occurred, \c false otherwise.
3383 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3384 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3385 // If there is no initializer, we don't need to do anything.
3386 if (!Pattern->hasInClassInitializer())
3387 return false;
3388
3389 assert(Instantiation->getInClassInitStyle() ==
3390 Pattern->getInClassInitStyle() &&
3391 "pattern and instantiation disagree about init style");
3392
3393 // Error out if we haven't parsed the initializer of the pattern yet because
3394 // we are waiting for the closing brace of the outer class.
3395 Expr *OldInit = Pattern->getInClassInitializer();
3396 if (!OldInit) {
3397 RecordDecl *PatternRD = Pattern->getParent();
3398 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3399 Diag(PointOfInstantiation,
3400 diag::err_default_member_initializer_not_yet_parsed)
3401 << OutermostClass << Pattern;
3402 Diag(Pattern->getEndLoc(),
3403 diag::note_default_member_initializer_not_yet_parsed);
3404 Instantiation->setInvalidDecl();
3405 return true;
3406 }
3407
3408 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3409 if (Inst.isInvalid())
3410 return true;
3411 if (Inst.isAlreadyInstantiating()) {
3412 // Error out if we hit an instantiation cycle for this initializer.
3413 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3414 << Instantiation;
3415 return true;
3416 }
3417 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3418 "instantiating default member init");
3419
3420 // Enter the scope of this instantiation. We don't use PushDeclContext because
3421 // we don't have a scope.
3422 ContextRAII SavedContext(*this, Instantiation->getParent());
3425 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3426 PointOfInstantiation, Instantiation, CurContext};
3427
3428 LocalInstantiationScope Scope(*this, true);
3429
3430 // Instantiate the initializer.
3432 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3433
3434 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3435 /*CXXDirectInit=*/false);
3436 Expr *Init = NewInit.get();
3437 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3439 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3440
3441 if (auto *L = getASTMutationListener())
3442 L->DefaultMemberInitializerInstantiated(Instantiation);
3443
3444 // Return true if the in-class initializer is still missing.
3445 return !Instantiation->getInClassInitializer();
3446}
3447
3448namespace {
3449 /// A partial specialization whose template arguments have matched
3450 /// a given template-id.
3451 struct PartialSpecMatchResult {
3454 };
3455}
3456
3458 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3459 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3461 return true;
3462
3464 ClassTemplateSpec->getSpecializedTemplate()
3465 ->getPartialSpecializations(PartialSpecs);
3466 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3467 TemplateDeductionInfo Info(Loc);
3468 if (!DeduceTemplateArguments(PartialSpecs[I],
3469 ClassTemplateSpec->getTemplateArgs(), Info))
3470 return true;
3471 }
3472
3473 return false;
3474}
3475
3476/// Get the instantiation pattern to use to instantiate the definition of a
3477/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3478/// template or of a partial specialization).
3481 Sema &S, SourceLocation PointOfInstantiation,
3482 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3484 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3485 if (Inst.isInvalid())
3486 return {/*Invalid=*/true};
3487 if (Inst.isAlreadyInstantiating())
3488 return {/*Invalid=*/false};
3489
3490 llvm::PointerUnion<ClassTemplateDecl *,
3492 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3493 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3494 // Find best matching specialization.
3495 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3496
3497 // C++ [temp.class.spec.match]p1:
3498 // When a class template is used in a context that requires an
3499 // instantiation of the class, it is necessary to determine
3500 // whether the instantiation is to be generated using the primary
3501 // template or one of the partial specializations. This is done by
3502 // matching the template arguments of the class template
3503 // specialization with the template argument lists of the partial
3504 // specializations.
3505 typedef PartialSpecMatchResult MatchResult;
3508 Template->getPartialSpecializations(PartialSpecs);
3509 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3510 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3511 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3512 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3514 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
3515 // Store the failed-deduction information for use in diagnostics, later.
3516 // TODO: Actually use the failed-deduction info?
3517 FailedCandidates.addCandidate().set(
3518 DeclAccessPair::make(Template, AS_public), Partial,
3520 (void)Result;
3521 } else {
3522 Matched.push_back(PartialSpecMatchResult());
3523 Matched.back().Partial = Partial;
3524 Matched.back().Args = Info.takeCanonical();
3525 }
3526 }
3527
3528 // If we're dealing with a member template where the template parameters
3529 // have been instantiated, this provides the original template parameters
3530 // from which the member template's parameters were instantiated.
3531
3532 if (Matched.size() >= 1) {
3533 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3534 if (Matched.size() == 1) {
3535 // -- If exactly one matching specialization is found, the
3536 // instantiation is generated from that specialization.
3537 // We don't need to do anything for this.
3538 } else {
3539 // -- If more than one matching specialization is found, the
3540 // partial order rules (14.5.4.2) are used to determine
3541 // whether one of the specializations is more specialized
3542 // than the others. If none of the specializations is more
3543 // specialized than all of the other matching
3544 // specializations, then the use of the class template is
3545 // ambiguous and the program is ill-formed.
3547 PEnd = Matched.end();
3548 P != PEnd; ++P) {
3550 P->Partial, Best->Partial, PointOfInstantiation) ==
3551 P->Partial)
3552 Best = P;
3553 }
3554
3555 // Determine if the best partial specialization is more specialized than
3556 // the others.
3557 bool Ambiguous = false;
3558 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3559 PEnd = Matched.end();
3560 P != PEnd; ++P) {
3562 P->Partial, Best->Partial,
3563 PointOfInstantiation) != Best->Partial) {
3564 Ambiguous = true;
3565 break;
3566 }
3567 }
3568
3569 if (Ambiguous) {
3570 // Partial ordering did not produce a clear winner. Complain.
3571 Inst.Clear();
3572 ClassTemplateSpec->setInvalidDecl();
3573 S.Diag(PointOfInstantiation,
3574 diag::err_partial_spec_ordering_ambiguous)
3575 << ClassTemplateSpec;
3576
3577 // Print the matching partial specializations.
3578 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3579 PEnd = Matched.end();
3580 P != PEnd; ++P)
3581 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3583 P->Partial->getTemplateParameters(), *P->Args);
3584
3585 return {/*Invalid=*/true};
3586 }
3587 }
3588
3589 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3590 } else {
3591 // -- If no matches are found, the instantiation is generated
3592 // from the primary template.
3593 }
3594 }
3595
3596 CXXRecordDecl *Pattern = nullptr;
3597 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3598 if (auto *PartialSpec =
3599 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3600 // Instantiate using the best class template partial specialization.
3601 while (PartialSpec->getInstantiatedFromMember()) {
3602 // If we've found an explicit specialization of this class template,
3603 // stop here and use that as the pattern.
3604 if (PartialSpec->isMemberSpecialization())
3605 break;
3606
3607 PartialSpec = PartialSpec->getInstantiatedFromMember();
3608 }
3609 Pattern = PartialSpec;
3610 } else {
3611 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3612 while (Template->getInstantiatedFromMemberTemplate()) {
3613 // If we've found an explicit specialization of this class template,
3614 // stop here and use that as the pattern.
3615 if (Template->isMemberSpecialization())
3616 break;
3617
3618 Template = Template->getInstantiatedFromMemberTemplate();
3619 }
3620 Pattern = Template->getTemplatedDecl();
3621 }
3622
3623 return Pattern;
3624}
3625
3627 SourceLocation PointOfInstantiation,
3628 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3629 TemplateSpecializationKind TSK, bool Complain) {
3630 // Perform the actual instantiation on the canonical declaration.
3631 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3632 ClassTemplateSpec->getCanonicalDecl());
3633 if (ClassTemplateSpec->isInvalidDecl())
3634 return true;
3635
3637 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3638 ClassTemplateSpec, TSK);
3639 if (!Pattern.isUsable())
3640 return Pattern.isInvalid();
3641
3642 return InstantiateClass(
3643 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3644 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3645}
3646
3647/// Instantiates the definitions of all of the member
3648/// of the given class, which is an instantiation of a class template
3649/// or a member class of a template.
3650void
3652 CXXRecordDecl *Instantiation,
3653 const MultiLevelTemplateArgumentList &TemplateArgs,
3655 // FIXME: We need to notify the ASTMutationListener that we did all of these
3656 // things, in case we have an explicit instantiation definition in a PCM, a
3657 // module, or preamble, and the declaration is in an imported AST.
3658 assert(
3661 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3662 "Unexpected template specialization kind!");
3663 for (auto *D : Instantiation->decls()) {
3664 bool SuppressNew = false;
3665 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3666 if (FunctionDecl *Pattern =
3667 Function->getInstantiatedFromMemberFunction()) {
3668
3669 if (Function->isIneligibleOrNotSelected())
3670 continue;
3671
3672 if (Function->getTrailingRequiresClause()) {
3673 ConstraintSatisfaction Satisfaction;
3674 if (CheckFunctionConstraints(Function, Satisfaction) ||
3675 !Satisfaction.IsSatisfied) {
3676 continue;
3677 }
3678 }
3679
3680 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3681 continue;
3682
3683 MemberSpecializationInfo *MSInfo =
3684 Function->getMemberSpecializationInfo();
3685 assert(MSInfo && "No member specialization information?");
3686 if (MSInfo->getTemplateSpecializationKind()
3688 continue;
3689
3690 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3691 Function,
3693 MSInfo->getPointOfInstantiation(),
3694 SuppressNew) ||
3695 SuppressNew)
3696 continue;
3697
3698 // C++11 [temp.explicit]p8:
3699 // An explicit instantiation definition that names a class template
3700 // specialization explicitly instantiates the class template
3701 // specialization and is only an explicit instantiation definition
3702 // of members whose definition is visible at the point of
3703 // instantiation.
3704 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3705 continue;
3706
3707 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3708
3709 if (Function->isDefined()) {
3710 // Let the ASTConsumer know that this function has been explicitly
3711 // instantiated now, and its linkage might have changed.
3713 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3714 InstantiateFunctionDefinition(PointOfInstantiation, Function);
3715 } else if (TSK == TSK_ImplicitInstantiation) {
3717 std::make_pair(Function, PointOfInstantiation));
3718 }
3719 }
3720 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3721 if (isa<VarTemplateSpecializationDecl>(Var))
3722 continue;
3723
3724 if (Var->isStaticDataMember()) {
3725 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3726 continue;
3727
3729 assert(MSInfo && "No member specialization information?");
3730 if (MSInfo->getTemplateSpecializationKind()
3732 continue;
3733
3734 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3735 Var,
3737 MSInfo->getPointOfInstantiation(),
3738 SuppressNew) ||
3739 SuppressNew)
3740 continue;
3741
3743 // C++0x [temp.explicit]p8:
3744 // An explicit instantiation definition that names a class template
3745 // specialization explicitly instantiates the class template
3746 // specialization and is only an explicit instantiation definition
3747 // of members whose definition is visible at the point of
3748 // instantiation.
3750 continue;
3751
3752 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3753 InstantiateVariableDefinition(PointOfInstantiation, Var);
3754 } else {
3755 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3756 }
3757 }
3758 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3759 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3760 continue;
3761
3762 // Always skip the injected-class-name, along with any
3763 // redeclarations of nested classes, since both would cause us
3764 // to try to instantiate the members of a class twice.
3765 // Skip closure types; they'll get instantiated when we instantiate
3766 // the corresponding lambda-expression.
3767 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3768 Record->isLambda())
3769 continue;
3770
3771 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3772 assert(MSInfo && "No member specialization information?");
3773
3774 if (MSInfo->getTemplateSpecializationKind()
3776 continue;
3777
3778 if (Context.getTargetInfo().getTriple().isOSWindows() &&
3780 // On Windows, explicit instantiation decl of the outer class doesn't
3781 // affect the inner class. Typically extern template declarations are
3782 // used in combination with dll import/export annotations, but those
3783 // are not propagated from the outer class templates to inner classes.
3784 // Therefore, do not instantiate inner classes on this platform, so
3785 // that users don't end up with undefined symbols during linking.
3786 continue;
3787 }
3788
3789 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3790 Record,
3792 MSInfo->getPointOfInstantiation(),
3793 SuppressNew) ||
3794 SuppressNew)
3795 continue;
3796
3797 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3798 assert(Pattern && "Missing instantiated-from-template information");
3799
3800 if (!Record->getDefinition()) {
3801 if (!Pattern->getDefinition()) {
3802 // C++0x [temp.explicit]p8:
3803 // An explicit instantiation definition that names a class template
3804 // specialization explicitly instantiates the class template
3805 // specialization and is only an explicit instantiation definition
3806 // of members whose definition is visible at the point of
3807 // instantiation.
3809 MSInfo->setTemplateSpecializationKind(TSK);
3810 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3811 }
3812
3813 continue;
3814 }
3815
3816 InstantiateClass(PointOfInstantiation, Record, Pattern,
3817 TemplateArgs,
3818 TSK);
3819 } else {
3821 Record->getTemplateSpecializationKind() ==
3823 Record->setTemplateSpecializationKind(TSK);
3824 MarkVTableUsed(PointOfInstantiation, Record, true);
3825 }
3826 }
3827
3828 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3829 if (Pattern)
3830 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3831 TSK);
3832 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3833 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3834 assert(MSInfo && "No member specialization information?");
3835
3836 if (MSInfo->getTemplateSpecializationKind()
3838 continue;
3839
3841 PointOfInstantiation, TSK, Enum,
3843 MSInfo->getPointOfInstantiation(), SuppressNew) ||
3844 SuppressNew)
3845 continue;
3846
3847 if (Enum->getDefinition())
3848 continue;
3849
3850 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3851 assert(Pattern && "Missing instantiated-from-template information");
3852
3854 if (!Pattern->getDefinition())
3855 continue;
3856
3857 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3858 } else {
3859 MSInfo->setTemplateSpecializationKind(TSK);
3860 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3861 }
3862 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3863 // No need to instantiate in-class initializers during explicit
3864 // instantiation.
3865 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3866 CXXRecordDecl *ClassPattern =
3867 Instantiation->getTemplateInstantiationPattern();
3869 ClassPattern->lookup(Field->getDeclName());
3870 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
3871 assert(Pattern);
3872 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3873 TemplateArgs);
3874 }
3875 }
3876 }
3877}
3878
3879/// Instantiate the definitions of all of the members of the
3880/// given class template specialization, which was named as part of an
3881/// explicit instantiation.
3882void
3884 SourceLocation PointOfInstantiation,
3885 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3887 // C++0x [temp.explicit]p7:
3888 // An explicit instantiation that names a class template
3889 // specialization is an explicit instantion of the same kind
3890 // (declaration or definition) of each of its members (not
3891 // including members inherited from base classes) that has not
3892 // been previously explicitly specialized in the translation unit
3893 // containing the explicit instantiation, except as described
3894 // below.
3895 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3896 getTemplateInstantiationArgs(ClassTemplateSpec),
3897 TSK);
3898}
3899
3902 if (!S)
3903 return S;
3904
3905 TemplateInstantiator Instantiator(*this, TemplateArgs,
3907 DeclarationName());
3908 return Instantiator.TransformStmt(S);
3909}
3910
3913 const MultiLevelTemplateArgumentList &TemplateArgs,
3915 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3916 DeclarationName());
3917 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
3918}
3919
3922 if (!E)
3923 return E;
3924
3925 TemplateInstantiator Instantiator(*this, TemplateArgs,
3927 DeclarationName());
3928 return Instantiator.TransformExpr(E);
3929}
3930
3933 const MultiLevelTemplateArgumentList &TemplateArgs) {
3934 if (!E)
3935 return E;
3936
3937 // This is where we need to make sure we 'know' constraint checking needs to
3938 // happen.
3939 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3940 DeclarationName());
3941 return Instantiator.TransformExpr(E);
3942}
3943
3945 const MultiLevelTemplateArgumentList &TemplateArgs,
3946 bool CXXDirectInit) {
3947 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3948 DeclarationName());
3949 return Instantiator.TransformInitializer(Init, CXXDirectInit);
3950}
3951
3952bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3953 const MultiLevelTemplateArgumentList &TemplateArgs,
3954 SmallVectorImpl<Expr *> &Outputs) {
3955 if (Exprs.empty())
3956 return false;
3957
3958 TemplateInstantiator Instantiator(*this, TemplateArgs,
3960 DeclarationName());
3961 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3962 IsCall, Outputs);
3963}
3964
3967 const MultiLevelTemplateArgumentList &TemplateArgs) {
3968 if (!NNS)
3969 return NestedNameSpecifierLoc();
3970
3971 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3972 DeclarationName());
3973 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3974}
3975
3976/// Do template substitution on declaration name info.
3979 const MultiLevelTemplateArgumentList &TemplateArgs) {
3980 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
3981 NameInfo.getName());
3982 return Instantiator.TransformDeclarationNameInfo(NameInfo);
3983}
3984
3987 TemplateName Name, SourceLocation Loc,
3988 const MultiLevelTemplateArgumentList &TemplateArgs) {
3989 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3990 DeclarationName());
3991 CXXScopeSpec SS;
3992 SS.Adopt(QualifierLoc);
3993 return Instantiator.TransformTemplateName(SS, Name, Loc);
3994}
3995
3996static const Decl *getCanonicalParmVarDecl(const Decl *D) {
3997 // When storing ParmVarDecls in the local instantiation scope, we always
3998 // want to use the ParmVarDecl from the canonical function declaration,
3999 // since the map is then valid for any redeclaration or definition of that
4000 // function.
4001 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4002 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4003 unsigned i = PV->getFunctionScopeIndex();
4004 // This parameter might be from a freestanding function type within the
4005 // function and isn't necessarily referring to one of FD's parameters.
4006 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4007 return FD->getCanonicalDecl()->getParamDecl(i);
4008 }
4009 }
4010 return D;
4011}
4012
4013
4014llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4017 for (LocalInstantiationScope *Current = this; Current;
4018 Current = Current->Outer) {
4019
4020 // Check if we found something within this scope.
4021 const Decl *CheckD = D;
4022 do {
4023 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4024 if (Found != Current->LocalDecls.end())
4025 return &Found->second;
4026
4027 // If this is a tag declaration, it's possible that we need to look for
4028 // a previous declaration.
4029 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4030 CheckD = Tag->getPreviousDecl();
4031 else
4032 CheckD = nullptr;
4033 } while (CheckD);
4034
4035 // If we aren't combined with our outer scope, we're done.
4036 if (!Current->CombineWithOuterScope)
4037 break;
4038 }
4039
4040 // If we're performing a partial substitution during template argument
4041 // deduction, we may not have values for template parameters yet.
4042 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4043 isa<TemplateTemplateParmDecl>(D))
4044 return nullptr;
4045
4046 // Local types referenced prior to definition may require instantiation.
4047 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4048 if (RD->isLocalClass())
4049 return nullptr;
4050
4051 // Enumeration types referenced prior to definition may appear as a result of
4052 // error recovery.
4053 if (isa<EnumDecl>(D))
4054 return nullptr;
4055
4056 // Materialized typedefs/type alias for implicit deduction guides may require
4057 // instantiation.
4058 if (isa<TypedefNameDecl>(D) &&
4059 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4060 return nullptr;
4061
4062 // If we didn't find the decl, then we either have a sema bug, or we have a
4063 // forward reference to a label declaration. Return null to indicate that
4064 // we have an uninstantiated label.
4065 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4066 return nullptr;
4067}
4068
4071 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4072 if (Stored.isNull()) {
4073#ifndef NDEBUG
4074 // It should not be present in any surrounding scope either.
4075 LocalInstantiationScope *Current = this;
4076 while (Current->CombineWithOuterScope && Current->Outer) {
4077 Current = Current->Outer;
4078 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
4079 "Instantiated local in inner and outer scopes");
4080 }
4081#endif
4082 Stored = Inst;
4083 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4084 Pack->push_back(cast<VarDecl>(Inst));
4085 } else {
4086 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4087 }
4088}
4089
4091 VarDecl *Inst) {
4093 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4094 Pack->push_back(Inst);
4095}
4096
4098#ifndef NDEBUG
4099 // This should be the first time we've been told about this decl.
4100 for (LocalInstantiationScope *Current = this;
4101 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4102 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&
4103 "Creating local pack after instantiation of local");
4104#endif
4105
4107 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4109 Stored = Pack;
4110 ArgumentPacks.push_back(Pack);
4111}
4112
4114 for (DeclArgumentPack *Pack : ArgumentPacks)
4115 if (llvm::is_contained(*Pack, D))
4116 return true;
4117 return false;
4118}
4119
4121 const TemplateArgument *ExplicitArgs,
4122 unsigned NumExplicitArgs) {
4123 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4124 "Already have a partially-substituted pack");
4125 assert((!PartiallySubstitutedPack
4126 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4127 "Wrong number of arguments in partially-substituted pack");
4128 PartiallySubstitutedPack = Pack;
4129 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4130 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4131}
4132
4134 const TemplateArgument **ExplicitArgs,
4135 unsigned *NumExplicitArgs) const {
4136 if (ExplicitArgs)
4137 *ExplicitArgs = nullptr;
4138 if (NumExplicitArgs)
4139 *NumExplicitArgs = 0;
4140
4141 for (const LocalInstantiationScope *Current = this; Current;
4142 Current = Current->Outer) {
4143 if (Current->PartiallySubstitutedPack) {
4144 if (ExplicitArgs)
4145 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4146 if (NumExplicitArgs)
4147 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4148
4149 return Current->PartiallySubstitutedPack;
4150 }
4151
4152 if (!Current->CombineWithOuterScope)
4153 break;
4154 }
4155
4156 return nullptr;
4157}
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 concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
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:1060
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:2521
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:1559
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2116
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:684
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:744
bool isInvalid() const
Definition: Ownership.h:165
bool isUsable() const
Definition: Ownership.h:166
PtrTy get() const
Definition: Ownership.h:169
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2817
QualType getOriginalType() const
Definition: Type.h:2830
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3031
QualType getElementType() const
Definition: Type.h:3052
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:4890
QualType getModifiedType() const
Definition: Type.h:4912
Pointer to a block type.
Definition: Type.h:2868
QualType getPointeeType() const
Definition: Type.h:2880
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1249
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1323
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1291
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2014
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:1529
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:1832
base_class_range bases()
Definition: DeclCXX.h:602
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1005
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:548
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:596
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:1886
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1861
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1853
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1839
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:507
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:1872
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...
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:149
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:153
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:165
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:169
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:28
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1338
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1393
bool isFileContext() const
Definition: DeclBase.h:2003
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1186
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1705
bool isTranslationUnit() const
Definition: DeclBase.h:2008
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1867
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2188
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1238
ValueDecl * getDecl()
Definition: Expr.h:1306
SourceLocation getLocation() const
Definition: Expr.h:1314
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:1026
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1185
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:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isFileContextDecl() const
Definition: DeclBase.cpp:408
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:931
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1063
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:914
DeclContext * getDeclContext()
Definition: DeclBase.h:441
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:883
bool hasAttr() const
Definition: DeclBase.h:560
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:943
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:835
The name of a declaration.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:808
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:1994
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:817
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:794
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:3337
QualType getElementType() const
Definition: Type.h:3353
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:5659
QualType getNamedType() const
Retrieve the type named by the qualified-id.
Definition: Type.h:5697
RAII object that enters a new expression evaluation context.
Definition: Sema.h:13951
Represents an enum.
Definition: Decl.h:3720
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:3979
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:4626
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4652
EnumDecl * getDefinition() const
Definition: Decl.h:3823
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:2941
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3085
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3078
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.h:3092
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3137
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:1917
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2582
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:3890
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2365
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2246
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4482
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4509
iterator end() const
Definition: ExprCXX.h:4518
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4524
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4516
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4521
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4512
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1692
iterator begin() const
Definition: ExprCXX.h:4517
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4041
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4257
Declaration of a template function.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1449
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:3720
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3694
QualType getReturnType() const
Definition: Type.h:3959
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:502
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:1924
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:334
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:467
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:4590
QualType getUnderlyingType() const
Definition: Type.h:4606
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2979
QualType getPointeeType() const
Definition: Type.h:2995
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:629
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:660
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:651
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:669
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:674
Describes a module or submodule.
Definition: Module.h:98
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:251
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:1788
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1637
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of 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:5858
QualType getPattern() const
Retrieve the pattern of this pack expansion, which is the type that will be repeatedly instantiated w...
Definition: Type.h:5879
Sugar for parentheses used when specifying types.
Definition: Type.h:2762
QualType getInnerType() const
Definition: Type.h:2771
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2915
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1851
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1839
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2940
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1843
bool hasInheritedDefaultArg() const
Definition: Decl.h:1855
Expr * getDefaultArg()
Definition: Decl.cpp:2903
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2945
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1772
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1859
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2788
QualType getPointeeType() const
Definition: Type.h:2798
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1972
SourceLocation getLocation() const
Definition: Expr.h:2022
IdentKind getIdentKind() const
Definition: Expr.h:2018
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:3199
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:912
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:6649
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6689
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6742
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:3998
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4835
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:908
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2899
QualType getPointeeTypeAsWritten() const
Definition: Type.h:2915
Represents the body of a requires-expression.
Definition: DeclCXX.h:1992
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:478
RequiresExprBodyDecl * getBody() const
Definition: ExprConcepts.h:517
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:9449
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6642
A RAII object to temporarily push a declaration context.
Definition: Sema.h:998
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:3394
DefaultedComparisonKind asComparison() const
Definition: Sema.h:3417
CXXSpecialMember asSpecialMember() const
Definition: Sema.h:3416
A helper class for building up ExtParameterInfos.
Definition: Sema.h:9935
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9751
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:9378
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9809
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:9394
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1884
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:9381
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6870
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:8341
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:9410
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:1649
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:3256
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:16438
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:1645
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:7388
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:8972
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:14773
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:9435
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:1476
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:9443
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:9910
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:21035
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:9419
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:5998
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
bool InstantiateClass(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK, bool Complain=true)
Instantiate the definition of a class from a given pattern.
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc)
Definition: SemaExpr.cpp:3725
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTConsumer & Consumer
Definition: Sema.h:408
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1592
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition: Sema.h:9427
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18570
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:1393
DiagnosticsEngine & Diags
Definition: Sema.h:409
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition: Sema.h:9389
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition: Sema.cpp:510
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21261
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:502
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:540
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6872
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
A trivial tuple used to represent a source range.
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:3990
Stmt - This represents one statement.
Definition: Stmt.h:72
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:349
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:325
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:337
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4318
std::optional< unsigned > getPackIndex() const
Definition: ExprCXX.h:4366
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4360
QualType getParameterType(const ASTContext &Ctx) const
Determine the substituted type of the template parameter.
Definition: ExprCXX.cpp:1648
NonTypeTemplateParmDecl * getParameter() const
Definition: ExprCXX.cpp:1643
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4403
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1674
SourceLocation getParameterPackLocation() const
Retrieve the location of the parameter pack name.
Definition: ExprCXX.h:4443
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.cpp:1669
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4433
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:852
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:5175
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: Type.cpp:3758
TemplateArgument getArgumentPack() const
Definition: Type.cpp:3775
unsigned getIndex() const
Returns the index of the replaced parameter in the associated declaration.
Definition: Type.h:5201
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:845
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3440
void setTagKind(TagKind TK)
Definition: Decl.h:3639