clang 22.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"
21#include "clang/AST/Expr.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/SmallVectorExtras.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/SaveAndRestore.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
108 }
109 return LambdaCallOperator;
110}
111
112struct EnclosingTypeAliasTemplateDetails {
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
116
117 explicit operator bool() noexcept { return Template; }
118};
119
120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121// well as its primary template and instantiating template arguments.
122EnclosingTypeAliasTemplateDetails
123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
135 };
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
139 }
140 return Result;
141 }
142 return {};
143}
144
145// Check if we are currently inside of a lambda expression that is
146// surrounded by a using alias declaration. e.g.
147// template <class> using type = decltype([](auto) { ^ }());
148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149// a DeclContext, nor does it have an associated specialization Decl from which
150// we could collect these template arguments.
151bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
160 CallOperator;
161 }
162 const FunctionDecl *CallOperator;
163 };
164
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
167
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(Underlying);
170}
171
172// Add template arguments from a variable template instantiation.
173Response
174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
181
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
185 return Response::Done();
186
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
193 dyn_cast<VarTemplatePartialSpecializationDecl *>(Specialized)) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
208 }
209 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
210}
211
212// If we have a template template parameter with translation unit context,
213// then we're performing substitution into a default template argument of
214// this template template parameter before we've constructed the template
215// that will own this template template parameter. In this case, we
216// use empty template parameter lists for all of the outer templates
217// to avoid performing any substitutions.
218Response
219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
224}
225
226Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
232}
233
234// Add template arguments from a class template instantiation.
235Response
236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
243 return Response::Done();
244
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
250
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
256
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
264 return Response::ChangeDecl(
265 InstFromPartialTempl->getLexicalDeclContext());
266 }
267 return Response::UseNextDecl(ClassTemplSpec);
268}
269
270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
279 return Response::Done();
280
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
291 TemplateArgs->asArray(),
292 /*Final=*/false);
293
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(Function);
300
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
307
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
311 return Response::Done();
312
313 } else if (auto *Template = Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
317 if (ForConstraintInstantiation) {
318 for (auto &Inst : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
320 Inst.Entity == Template) {
321 // After CWG2369, the outer templates are not instantiated when
322 // checking its associated constraints. So add them back through the
323 // synthesis context; this is useful for e.g. nested constraints
324 // involving lambdas.
325 Result.addOuterTemplateArguments(Template, Inst.template_arguments(),
326 /*Final=*/false);
327 break;
328 }
329 }
330 }
331 }
332 // If this is a friend or local declaration and it declares an entity at
333 // namespace scope, take arguments from its lexical parent
334 // instead of its semantic parent, unless of course the pattern we're
335 // instantiating actually comes from the file's context!
336 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
337 Function->getNonTransparentDeclContext()->isFileContext() &&
338 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
339 return Response::ChangeDecl(Function->getLexicalDeclContext());
340 }
341
342 if (ForConstraintInstantiation && Function->getFriendObjectKind())
343 return Response::ChangeDecl(Function->getLexicalDeclContext());
344 return Response::UseNextDecl(Function);
345}
346
347Response HandleFunctionTemplateDecl(Sema &SemaRef,
348 const FunctionTemplateDecl *FTD,
351 Result.addOuterTemplateArguments(
352 const_cast<FunctionTemplateDecl *>(FTD),
353 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
354 SemaRef.Context),
355 /*Final=*/false);
356
358
359 for (const Type *Ty = NNS.getKind() == NestedNameSpecifier::Kind::Type
360 ? NNS.getAsType()
361 : nullptr,
362 *NextTy = nullptr;
364 Ty = std::exchange(NextTy, nullptr)) {
365 if (NestedNameSpecifier P = Ty->getPrefix();
367 NextTy = P.getAsType();
368 const auto *TSTy = dyn_cast<TemplateSpecializationType>(Ty);
369 if (!TSTy)
370 continue;
371
372 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
373 // Prefer template arguments from the injected-class-type if possible.
374 // For example,
375 // ```cpp
376 // template <class... Pack> struct S {
377 // template <class T> void foo();
378 // };
379 // template <class... Pack> template <class T>
380 // ^^^^^^^^^^^^^ InjectedTemplateArgs
381 // They're of kind TemplateArgument::Pack, not of
382 // TemplateArgument::Type.
383 // void S<Pack...>::foo() {}
384 // ^^^^^^^
385 // TSTy->template_arguments() (which are of PackExpansionType)
386 // ```
387 // This meets the contract in
388 // TreeTransform::TryExpandParameterPacks that the template arguments
389 // for unexpanded parameters should be of a Pack kind.
390 if (TSTy->isCurrentInstantiation()) {
391 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
392 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
393 Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);
394 else if (auto *Specialization =
395 dyn_cast<ClassTemplateSpecializationDecl>(RD))
396 Arguments = Specialization->getTemplateInstantiationArgs().asArray();
397 }
398 Result.addOuterTemplateArguments(
399 TSTy->getTemplateName().getAsTemplateDecl(), Arguments,
400 /*Final=*/false);
401 }
402 }
403
404 return Response::ChangeDecl(FTD->getLexicalDeclContext());
405}
406
407Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
409 ASTContext &Context,
410 bool ForConstraintInstantiation) {
411 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
412 assert(
413 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
414 "Outer template not instantiated?");
415 if (ClassTemplate->isMemberSpecialization())
416 return Response::Done();
417 if (ForConstraintInstantiation)
418 Result.addOuterTemplateArguments(
419 const_cast<CXXRecordDecl *>(Rec),
420 ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),
421 /*Final=*/false);
422 }
423
424 if (const MemberSpecializationInfo *MSInfo =
426 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
427 return Response::Done();
428
429 bool IsFriend = Rec->getFriendObjectKind() ||
432 if (ForConstraintInstantiation && IsFriend &&
434 return Response::ChangeDecl(Rec->getLexicalDeclContext());
435 }
436
437 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
438 // TypeAliasTemplateDecl that this lambda is defined inside of.
439 if (Rec->isLambda()) {
440 if (const Decl *LCD = Rec->getLambdaContextDecl())
441 return Response::ChangeDecl(LCD);
442 // Retrieve the template arguments for a using alias declaration.
443 // This is necessary for constraint checking, since we always keep
444 // constraints relative to the primary template.
445 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
446 ForConstraintInstantiation && TypeAlias) {
447 if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
448 TypeAlias.PrimaryTypeAliasDecl)) {
449 Result.addOuterTemplateArguments(TypeAlias.Template,
450 TypeAlias.AssociatedTemplateArguments,
451 /*Final=*/false);
452 // Visit the parent of the current type alias declaration rather than
453 // the lambda thereof.
454 // E.g., in the following example:
455 // struct S {
456 // template <class> using T = decltype([]<Concept> {} ());
457 // };
458 // void foo() {
459 // S::T var;
460 // }
461 // The instantiated lambda expression (which we're visiting at 'var')
462 // has a function DeclContext 'foo' rather than the Record DeclContext
463 // S. This seems to be an oversight to me that we may want to set a
464 // Sema Context from the CXXScopeSpec before substituting into T.
465 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
466 }
467 }
468 }
469
470 return Response::UseNextDecl(Rec);
471}
472
473Response HandleImplicitConceptSpecializationDecl(
476 Result.addOuterTemplateArguments(
477 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
479 /*Final=*/false);
480 return Response::UseNextDecl(CSD);
481}
482
483Response HandleGenericDeclContext(const Decl *CurDecl) {
484 return Response::UseNextDecl(CurDecl);
485}
486} // namespace TemplateInstArgsHelpers
487} // namespace
488
490 const NamedDecl *ND, const DeclContext *DC, bool Final,
491 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
492 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
493 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
494 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
495 // Accumulate the set of template argument lists in this structure.
497
498 using namespace TemplateInstArgsHelpers;
499 const Decl *CurDecl = ND;
500
501 if (Innermost) {
502 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
503 Final);
504 // Populate placeholder template arguments for TemplateTemplateParmDecls.
505 // This is essential for the case e.g.
506 //
507 // template <class> concept Concept = false;
508 // template <template <Concept C> class T> void foo(T<int>)
509 //
510 // where parameter C has a depth of 1 but the substituting argument `int`
511 // has a depth of 0.
512 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
513 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
514 CurDecl = DC ? Decl::castFromDeclContext(DC)
515 : Response::UseNextDecl(CurDecl).NextDecl;
516 } else if (!CurDecl)
517 CurDecl = Decl::castFromDeclContext(DC);
518
519 while (!CurDecl->isFileContextDecl()) {
520 Response R;
521 if (const auto *VarTemplSpec =
522 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
523 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
524 } else if (const auto *PartialClassTemplSpec =
525 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
526 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
527 SkipForSpecialization);
528 } else if (const auto *ClassTemplSpec =
529 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
530 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
531 SkipForSpecialization);
532 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
533 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
534 ForConstraintInstantiation,
535 ForDefaultArgumentSubstitution);
536 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
537 R = HandleRecordDecl(*this, Rec, Result, Context,
538 ForConstraintInstantiation);
539 } else if (const auto *CSD =
540 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
541 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
542 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
543 R = HandleFunctionTemplateDecl(*this, FTD, Result);
544 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
545 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
546 } else if (!isa<DeclContext>(CurDecl)) {
547 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
548 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
549 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
550 }
551 } else {
552 R = HandleGenericDeclContext(CurDecl);
553 }
554
555 if (R.IsDone)
556 return Result;
557 if (R.ClearRelativeToPrimary)
558 RelativeToPrimary = false;
559 assert(R.NextDecl);
560 CurDecl = R.NextDecl;
561 }
562 return Result;
563}
564
605
608 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
609 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
610 sema::TemplateDeductionInfo *DeductionInfo)
611 : SemaRef(SemaRef) {
612 // Don't allow further instantiation if a fatal error and an uncompilable
613 // error have occurred. Any diagnostics we might have raised will not be
614 // visible, and we do not need to construct a correct AST.
615 if (SemaRef.Diags.hasFatalErrorOccurred() &&
616 SemaRef.hasUncompilableErrorOccurred()) {
617 Invalid = true;
618 return;
619 }
620
622 Inst.Kind = Kind;
623 Inst.PointOfInstantiation = PointOfInstantiation;
624 Inst.Entity = Entity;
625 Inst.Template = Template;
626 Inst.TemplateArgs = TemplateArgs.data();
627 Inst.NumTemplateArgs = TemplateArgs.size();
628 Inst.DeductionInfo = DeductionInfo;
629 Inst.InstantiationRange = InstantiationRange;
630 Inst.InConstraintSubstitution =
632 Inst.InParameterMappingSubstitution =
634 if (!SemaRef.CodeSynthesisContexts.empty()) {
635 Inst.InConstraintSubstitution |=
636 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
637 Inst.InParameterMappingSubstitution |=
638 SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;
639 }
640
641 Invalid = SemaRef.pushCodeSynthesisContext(Inst);
642 if (!Invalid)
643 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
644}
645
647 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
648 SourceRange InstantiationRange)
649 : InstantiatingTemplate(SemaRef,
650 CodeSynthesisContext::TemplateInstantiation,
651 PointOfInstantiation, InstantiationRange, Entity) {}
652
654 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
655 ExceptionSpecification, SourceRange InstantiationRange)
657 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
658 PointOfInstantiation, InstantiationRange, Entity) {}
659
661 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
663 SourceRange InstantiationRange)
665 SemaRef,
666 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
667 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
668 Template, TemplateArgs) {}
669
671 Sema &SemaRef, SourceLocation PointOfInstantiation,
673 ArrayRef<TemplateArgument> TemplateArgs,
675 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
676 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
677 InstantiationRange, FunctionTemplate, nullptr,
678 TemplateArgs, &DeductionInfo) {
682}
683
685 Sema &SemaRef, SourceLocation PointOfInstantiation,
687 ArrayRef<TemplateArgument> TemplateArgs,
688 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
690 SemaRef,
691 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
692 PointOfInstantiation, InstantiationRange, Template, nullptr,
693 TemplateArgs, &DeductionInfo) {}
694
696 Sema &SemaRef, SourceLocation PointOfInstantiation,
698 ArrayRef<TemplateArgument> TemplateArgs,
699 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
701 SemaRef,
702 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
703 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
704 TemplateArgs, &DeductionInfo) {}
705
707 Sema &SemaRef, SourceLocation PointOfInstantiation,
709 ArrayRef<TemplateArgument> TemplateArgs,
710 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
712 SemaRef,
713 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
714 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
715 TemplateArgs, &DeductionInfo) {}
716
718 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
719 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
721 SemaRef,
722 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
723 PointOfInstantiation, InstantiationRange, Param, nullptr,
724 TemplateArgs) {}
725
727 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
729 SourceRange InstantiationRange)
731 SemaRef,
732 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
733 PointOfInstantiation, InstantiationRange, Param, Template,
734 TemplateArgs) {}
735
737 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
739 SourceRange InstantiationRange)
741 SemaRef,
742 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
743 PointOfInstantiation, InstantiationRange, Param, Template,
744 TemplateArgs) {}
745
747 Sema &SemaRef, SourceLocation PointOfInstantiation,
749 SourceRange InstantiationRange)
751 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
752 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
753 /*Template=*/nullptr, TemplateArgs) {}
754
756 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
757 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
758 SourceRange InstantiationRange)
760 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
761 PointOfInstantiation, InstantiationRange, Param, Template,
762 TemplateArgs) {}
763
765 Sema &SemaRef, SourceLocation PointOfInstantiation,
767 SourceRange InstantiationRange)
769 SemaRef, CodeSynthesisContext::RequirementInstantiation,
770 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
771 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
772
774 Sema &SemaRef, SourceLocation PointOfInstantiation,
776 SourceRange InstantiationRange)
778 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
779 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
780 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
781
783 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
784 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
786 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
787 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
788 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
789
791 Sema &SemaRef, SourceLocation PointOfInstantiation,
793 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
796 PointOfInstantiation, InstantiationRange, Template, nullptr,
797 TemplateArgs) {}
798
800 Sema &SemaRef, SourceLocation PointOfInstantiation,
802 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
805 PointOfInstantiation, InstantiationRange, Template, nullptr,
806 {}, &DeductionInfo) {}
807
809 Sema &SemaRef, SourceLocation PointOfInstantiation,
811 SourceRange InstantiationRange)
814 PointOfInstantiation, InstantiationRange, Template) {}
815
817 Sema &SemaRef, SourceLocation PointOfInstantiation,
819 SourceRange InstantiationRange)
822 PointOfInstantiation, InstantiationRange, Template) {}
823
825 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
826 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
828 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
829 PointOfInstantiation, InstantiationRange, Entity) {}
830
832 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
833 TemplateDecl *PArg, SourceRange InstantiationRange)
835 ArgLoc, InstantiationRange, PArg) {}
836
840
841 if (!Ctx.isInstantiationRecord()) {
843 } else {
844 assert(SemaRef.NonInstantiationEntries <=
845 SemaRef.CodeSynthesisContexts.size());
846 if ((SemaRef.CodeSynthesisContexts.size() -
847 SemaRef.NonInstantiationEntries) >
848 SemaRef.getLangOpts().InstantiationDepth) {
850 diag::err_template_recursion_depth_exceeded)
851 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
853 diag::note_template_recursion_depth)
854 << SemaRef.getLangOpts().InstantiationDepth;
855 return true;
856 }
857 }
858
859 CodeSynthesisContexts.push_back(Ctx);
860
861 // Check to see if we're low on stack space. We can't do anything about this
862 // from here, but we can at least warn the user.
863 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
864 return false;
865}
866
868 auto &Active = CodeSynthesisContexts.back();
869 if (!Active.isInstantiationRecord()) {
870 assert(NonInstantiationEntries > 0);
872 }
873
874 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
875
876 // Name lookup no longer looks in this template's defining module.
877 assert(CodeSynthesisContexts.size() >=
879 "forgot to remove a lookup module for a template instantiation");
880 if (CodeSynthesisContexts.size() ==
883 LookupModulesCache.erase(M);
885 }
886
887 // If we've left the code synthesis context for the current context stack,
888 // stop remembering that we've emitted that stack.
889 if (CodeSynthesisContexts.size() ==
892
893 CodeSynthesisContexts.pop_back();
894}
895
897 if (!Invalid) {
898 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
899 SemaRef.CodeSynthesisContexts.back());
900
901 SemaRef.popCodeSynthesisContext();
902 Invalid = true;
903 }
904}
905
906static std::string convertCallArgsToString(Sema &S,
908 std::string Result;
909 llvm::raw_string_ostream OS(Result);
910 llvm::ListSeparator Comma;
911 for (const Expr *Arg : Args) {
912 OS << Comma;
913 Arg->IgnoreParens()->printPretty(OS, nullptr,
915 }
916 return Result;
917}
918
920 // Determine which template instantiations to skip, if any.
921 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
922 unsigned Limit = Diags.getTemplateBacktraceLimit();
923 if (Limit && Limit < CodeSynthesisContexts.size()) {
924 SkipStart = Limit / 2 + Limit % 2;
925 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
926 }
927
928 // FIXME: In all of these cases, we need to show the template arguments
929 unsigned InstantiationIdx = 0;
931 Active = CodeSynthesisContexts.rbegin(),
932 ActiveEnd = CodeSynthesisContexts.rend();
933 Active != ActiveEnd;
934 ++Active, ++InstantiationIdx) {
935 // Skip this instantiation?
936 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
937 if (InstantiationIdx == SkipStart) {
938 // Note that we're skipping instantiations.
939 DiagFunc(Active->PointOfInstantiation,
940 PDiag(diag::note_instantiation_contexts_suppressed)
941 << unsigned(CodeSynthesisContexts.size() - Limit));
942 }
943 continue;
944 }
945
946 switch (Active->Kind) {
948 Decl *D = Active->Entity;
949 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
950 unsigned DiagID = diag::note_template_member_class_here;
952 DiagID = diag::note_template_class_instantiation_here;
953 DiagFunc(Active->PointOfInstantiation,
954 PDiag(DiagID) << Record << Active->InstantiationRange);
955 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
956 unsigned DiagID;
957 if (Function->getPrimaryTemplate())
958 DiagID = diag::note_function_template_spec_here;
959 else
960 DiagID = diag::note_template_member_function_here;
961 DiagFunc(Active->PointOfInstantiation,
962 PDiag(DiagID) << Function << Active->InstantiationRange);
963 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
964 DiagFunc(Active->PointOfInstantiation,
965 PDiag(VD->isStaticDataMember()
966 ? diag::note_template_static_data_member_def_here
967 : diag::note_template_variable_def_here)
968 << VD << Active->InstantiationRange);
969 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
970 DiagFunc(Active->PointOfInstantiation,
971 PDiag(diag::note_template_enum_def_here)
972 << ED << Active->InstantiationRange);
973 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
974 DiagFunc(Active->PointOfInstantiation,
975 PDiag(diag::note_template_nsdmi_here)
976 << FD << Active->InstantiationRange);
977 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
978 DiagFunc(Active->PointOfInstantiation,
979 PDiag(diag::note_template_class_instantiation_here)
980 << CTD << Active->InstantiationRange);
981 }
982 break;
983 }
984
986 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
987 SmallString<128> TemplateArgsStr;
988 llvm::raw_svector_ostream OS(TemplateArgsStr);
989 Template->printName(OS, getPrintingPolicy());
990 printTemplateArgumentList(OS, Active->template_arguments(),
992 DiagFunc(Active->PointOfInstantiation,
993 PDiag(diag::note_default_arg_instantiation_here)
994 << OS.str() << Active->InstantiationRange);
995 break;
996 }
997
999 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1000 DiagFunc(Active->PointOfInstantiation,
1001 PDiag(diag::note_explicit_template_arg_substitution_here)
1002 << FnTmpl
1004 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1005 Active->NumTemplateArgs)
1006 << Active->InstantiationRange);
1007 break;
1008 }
1009
1011 if (FunctionTemplateDecl *FnTmpl =
1012 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1013 DiagFunc(
1014 Active->PointOfInstantiation,
1015 PDiag(diag::note_function_template_deduction_instantiation_here)
1016 << FnTmpl
1018 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1019 Active->NumTemplateArgs)
1020 << Active->InstantiationRange);
1021 } else {
1022 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1023 isa<VarTemplateSpecializationDecl>(Active->Entity);
1024 bool IsTemplate = false;
1025 TemplateParameterList *Params;
1026 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1027 IsTemplate = true;
1028 Params = D->getTemplateParameters();
1029 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1030 Active->Entity)) {
1031 Params = D->getTemplateParameters();
1032 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1033 Active->Entity)) {
1034 Params = D->getTemplateParameters();
1035 } else {
1036 llvm_unreachable("unexpected template kind");
1037 }
1038
1039 DiagFunc(Active->PointOfInstantiation,
1040 PDiag(diag::note_deduced_template_arg_substitution_here)
1041 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1043 Active->TemplateArgs,
1044 Active->NumTemplateArgs)
1045 << Active->InstantiationRange);
1046 }
1047 break;
1048 }
1049
1051 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1052 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1053
1054 SmallString<128> TemplateArgsStr;
1055 llvm::raw_svector_ostream OS(TemplateArgsStr);
1057 printTemplateArgumentList(OS, Active->template_arguments(),
1059 DiagFunc(Active->PointOfInstantiation,
1060 PDiag(diag::note_default_function_arg_instantiation_here)
1061 << OS.str() << Active->InstantiationRange);
1062 break;
1063 }
1064
1066 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1067 std::string Name;
1068 if (!Parm->getName().empty())
1069 Name = std::string(" '") + Parm->getName().str() + "'";
1070
1071 TemplateParameterList *TemplateParams = nullptr;
1072 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1073 TemplateParams = Template->getTemplateParameters();
1074 else
1075 TemplateParams =
1077 ->getTemplateParameters();
1078 DiagFunc(Active->PointOfInstantiation,
1079 PDiag(diag::note_prior_template_arg_substitution)
1080 << isa<TemplateTemplateParmDecl>(Parm) << Name
1081 << getTemplateArgumentBindingsText(TemplateParams,
1082 Active->TemplateArgs,
1083 Active->NumTemplateArgs)
1084 << Active->InstantiationRange);
1085 break;
1086 }
1087
1089 TemplateParameterList *TemplateParams = nullptr;
1090 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1091 TemplateParams = Template->getTemplateParameters();
1092 else
1093 TemplateParams =
1095 ->getTemplateParameters();
1096
1097 DiagFunc(Active->PointOfInstantiation,
1098 PDiag(diag::note_template_default_arg_checking)
1099 << getTemplateArgumentBindingsText(TemplateParams,
1100 Active->TemplateArgs,
1101 Active->NumTemplateArgs)
1102 << Active->InstantiationRange);
1103 break;
1104 }
1105
1107 DiagFunc(Active->PointOfInstantiation,
1108 PDiag(diag::note_evaluating_exception_spec_here)
1109 << cast<FunctionDecl>(Active->Entity));
1110 break;
1111
1113 DiagFunc(Active->PointOfInstantiation,
1114 PDiag(diag::note_template_exception_spec_instantiation_here)
1115 << cast<FunctionDecl>(Active->Entity)
1116 << Active->InstantiationRange);
1117 break;
1118
1120 DiagFunc(Active->PointOfInstantiation,
1121 PDiag(diag::note_template_requirement_instantiation_here)
1122 << Active->InstantiationRange);
1123 break;
1125 DiagFunc(Active->PointOfInstantiation,
1126 PDiag(diag::note_template_requirement_params_instantiation_here)
1127 << Active->InstantiationRange);
1128 break;
1129
1131 DiagFunc(Active->PointOfInstantiation,
1132 PDiag(diag::note_nested_requirement_here)
1133 << Active->InstantiationRange);
1134 break;
1135
1137 DiagFunc(Active->PointOfInstantiation,
1138 PDiag(diag::note_in_declaration_of_implicit_special_member)
1139 << cast<CXXRecordDecl>(Active->Entity)
1140 << Active->SpecialMember);
1141 break;
1142
1144 DiagFunc(
1145 Active->Entity->getLocation(),
1146 PDiag(diag::note_in_declaration_of_implicit_equality_comparison));
1147 break;
1148
1150 // FIXME: For synthesized functions that are not defaulted,
1151 // produce a note.
1152 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1153 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1154 // will ensure that DFK.isComparison() is false. This is important because
1155 // we will uncondtionally dereference FD in the else if.
1158 if (DFK.isSpecialMember()) {
1159 auto *MD = cast<CXXMethodDecl>(FD);
1160 DiagFunc(Active->PointOfInstantiation,
1161 PDiag(diag::note_member_synthesized_at)
1162 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1163 << Context.getCanonicalTagType(MD->getParent()));
1164 } else if (DFK.isComparison()) {
1165 QualType RecordType = FD->getParamDecl(0)
1166 ->getType()
1167 .getNonReferenceType()
1168 .getUnqualifiedType();
1169 DiagFunc(Active->PointOfInstantiation,
1170 PDiag(diag::note_comparison_synthesized_at)
1171 << (int)DFK.asComparison() << RecordType);
1172 }
1173 break;
1174 }
1175
1177 DiagFunc(Active->Entity->getLocation(),
1178 PDiag(diag::note_rewriting_operator_as_spaceship));
1179 break;
1180
1182 DiagFunc(Active->PointOfInstantiation,
1183 PDiag(diag::note_in_binding_decl_init)
1184 << cast<BindingDecl>(Active->Entity));
1185 break;
1186
1188 DiagFunc(Active->PointOfInstantiation,
1189 PDiag(diag::note_due_to_dllexported_class)
1190 << cast<CXXRecordDecl>(Active->Entity)
1191 << !getLangOpts().CPlusPlus11);
1192 break;
1193
1195 DiagFunc(Active->PointOfInstantiation,
1196 PDiag(diag::note_building_builtin_dump_struct_call)
1198 *this, llvm::ArrayRef(Active->CallArgs,
1199 Active->NumCallArgs)));
1200 break;
1201
1203 break;
1204
1206 DiagFunc(Active->PointOfInstantiation,
1207 PDiag(diag::note_lambda_substitution_here));
1208 break;
1210 unsigned DiagID = 0;
1211 if (!Active->Entity) {
1212 DiagFunc(Active->PointOfInstantiation,
1213 PDiag(diag::note_nested_requirement_here)
1214 << Active->InstantiationRange);
1215 break;
1216 }
1217 if (isa<ConceptDecl>(Active->Entity))
1218 DiagID = diag::note_concept_specialization_here;
1219 else if (isa<TemplateDecl>(Active->Entity))
1220 DiagID = diag::note_checking_constraints_for_template_id_here;
1221 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1222 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1223 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1224 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1225 else {
1226 assert(isa<FunctionDecl>(Active->Entity));
1227 DiagID = diag::note_checking_constraints_for_function_here;
1228 }
1229 SmallString<128> TemplateArgsStr;
1230 llvm::raw_svector_ostream OS(TemplateArgsStr);
1231 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1232 if (!isa<FunctionDecl>(Active->Entity)) {
1233 printTemplateArgumentList(OS, Active->template_arguments(),
1235 }
1236 DiagFunc(Active->PointOfInstantiation,
1237 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1238 break;
1239 }
1241 DiagFunc(Active->PointOfInstantiation,
1242 PDiag(diag::note_constraint_substitution_here)
1243 << Active->InstantiationRange);
1244 break;
1246 DiagFunc(Active->PointOfInstantiation,
1247 PDiag(diag::note_constraint_normalization_here)
1248 << cast<NamedDecl>(Active->Entity)
1249 << Active->InstantiationRange);
1250 break;
1252 DiagFunc(Active->PointOfInstantiation,
1253 PDiag(diag::note_parameter_mapping_substitution_here)
1254 << Active->InstantiationRange);
1255 break;
1257 DiagFunc(Active->PointOfInstantiation,
1258 PDiag(diag::note_building_deduction_guide_here));
1259 break;
1261 // Workaround for a workaround: don't produce a note if we are merely
1262 // instantiating some other template which contains this alias template.
1263 // This would be redundant either with the error itself, or some other
1264 // context note attached to it.
1265 if (Active->NumTemplateArgs == 0)
1266 break;
1267 DiagFunc(Active->PointOfInstantiation,
1268 PDiag(diag::note_template_type_alias_instantiation_here)
1269 << cast<TypeAliasTemplateDecl>(Active->Entity)
1270 << Active->InstantiationRange);
1271 break;
1273 DiagFunc(Active->PointOfInstantiation,
1274 PDiag(diag::note_template_arg_template_params_mismatch));
1275 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1276 ParamLoc.isValid())
1277 DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration)
1278 << /*isTemplateTemplateParam=*/true
1279 << Active->InstantiationRange);
1280 break;
1281 }
1282 }
1283}
1284
1285std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1287 return std::optional<TemplateDeductionInfo *>(nullptr);
1288
1290 Active = CodeSynthesisContexts.rbegin(),
1291 ActiveEnd = CodeSynthesisContexts.rend();
1292 Active != ActiveEnd;
1293 ++Active)
1294 {
1295 switch (Active->Kind) {
1297 // An instantiation of an alias template may or may not be a SFINAE
1298 // context, depending on what else is on the stack.
1299 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1300 break;
1301 [[fallthrough]];
1309 // This is a template instantiation, so there is no SFINAE.
1310 return std::nullopt;
1312 // [temp.deduct]p9
1313 // A lambda-expression appearing in a function type or a template
1314 // parameter is not considered part of the immediate context for the
1315 // purposes of template argument deduction.
1316 // CWG2672: A lambda-expression body is never in the immediate context.
1317 return std::nullopt;
1318
1324 // A default template argument instantiation and substitution into
1325 // template parameters with arguments for prior parameters may or may
1326 // not be a SFINAE context; look further up the stack.
1327 break;
1328
1331 // We're either substituting explicitly-specified template arguments,
1332 // deduced template arguments. SFINAE applies unless we are in a lambda
1333 // body, see [temp.deduct]p9.
1337 // SFINAE always applies in a constraint expression or a requirement
1338 // in a requires expression.
1339 assert(Active->DeductionInfo && "Missing deduction info pointer");
1340 return Active->DeductionInfo;
1341
1349 // This happens in a context unrelated to template instantiation, so
1350 // there is no SFINAE.
1351 return std::nullopt;
1352
1354 // FIXME: This should not be treated as a SFINAE context, because
1355 // we will cache an incorrect exception specification. However, clang
1356 // bootstrap relies this! See PR31692.
1357 break;
1358
1360 break;
1361 }
1362
1363 // The inner context was transparent for SFINAE. If it occurred within a
1364 // non-instantiation SFINAE context, then SFINAE applies.
1365 if (Active->SavedInNonInstantiationSFINAEContext)
1366 return std::optional<TemplateDeductionInfo *>(nullptr);
1367 }
1368
1369 return std::nullopt;
1370}
1371
1372//===----------------------------------------------------------------------===/
1373// Template Instantiation for Types
1374//===----------------------------------------------------------------------===/
1375namespace {
1376
1377 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1378 const MultiLevelTemplateArgumentList &TemplateArgs;
1379 SourceLocation Loc;
1380 DeclarationName Entity;
1381 // Whether to evaluate the C++20 constraints or simply substitute into them.
1382 bool EvaluateConstraints = true;
1383 // Whether Substitution was Incomplete, that is, we tried to substitute in
1384 // any user provided template arguments which were null.
1385 bool IsIncomplete = false;
1386 // Whether an incomplete substituion should be treated as an error.
1387 bool BailOutOnIncomplete;
1388
1389 // Whether to rebuild pack expansion types; We don't do that when
1390 // rebuilding the parameter mapping of a fold expression appearing
1391 // in a constraint expression.
1392 bool BuildPackExpansionTypes = true;
1393
1394 // CWG2770: Function parameters should be instantiated when they are
1395 // needed by a satisfaction check of an atomic constraint or
1396 // (recursively) by another function parameter.
1397 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1398
1399 public:
1400 typedef TreeTransform<TemplateInstantiator> inherited;
1401
1402 TemplateInstantiator(Sema &SemaRef,
1403 const MultiLevelTemplateArgumentList &TemplateArgs,
1404 SourceLocation Loc, DeclarationName Entity,
1405 bool BailOutOnIncomplete = false)
1406 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1407 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1408
1409 void setEvaluateConstraints(bool B) {
1410 EvaluateConstraints = B;
1411 }
1412 bool getEvaluateConstraints() {
1413 return EvaluateConstraints;
1414 }
1415
1416 inline static struct ForParameterMappingSubstitution_t {
1417 } ForParameterMappingSubstitution;
1418
1419 TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,
1420 SourceLocation Loc,
1421 const MultiLevelTemplateArgumentList &TemplateArgs,
1422 bool BuildPackExpansionTypes)
1423 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1424 BailOutOnIncomplete(false),
1425 BuildPackExpansionTypes(BuildPackExpansionTypes) {}
1426
1427 /// Determine whether the given type \p T has already been
1428 /// transformed.
1429 ///
1430 /// For the purposes of template instantiation, a type has already been
1431 /// transformed if it is NULL or if it is not dependent.
1432 bool AlreadyTransformed(QualType T);
1433
1434 /// Returns the location of the entity being instantiated, if known.
1435 SourceLocation getBaseLocation() { return Loc; }
1436
1437 /// Returns the name of the entity being instantiated, if any.
1438 DeclarationName getBaseEntity() { return Entity; }
1439
1440 /// Returns whether any substitution so far was incomplete.
1441 bool getIsIncomplete() const { return IsIncomplete; }
1442
1443 /// Sets the "base" location and entity when that
1444 /// information is known based on another transformation.
1445 void setBase(SourceLocation Loc, DeclarationName Entity) {
1446 this->Loc = Loc;
1447 this->Entity = Entity;
1448 }
1449
1450 unsigned TransformTemplateDepth(unsigned Depth) {
1451 return TemplateArgs.getNewDepth(Depth);
1452 }
1453
1454 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1455 SourceRange PatternRange,
1456 ArrayRef<UnexpandedParameterPack> Unexpanded,
1457 bool FailOnPackProducingTemplates,
1458 bool &ShouldExpand, bool &RetainExpansion,
1459 UnsignedOrNone &NumExpansions) {
1460 if (SemaRef.CurrentInstantiationScope &&
1461 (SemaRef.inConstraintSubstitution() ||
1462 SemaRef.inParameterMappingSubstitution())) {
1463 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1464 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1465 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);
1466 PVD && maybeInstantiateFunctionParameterToScope(PVD))
1467 return true;
1468 }
1469 }
1470
1471 return getSema().CheckParameterPacksForExpansion(
1472 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1473 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1474 NumExpansions);
1475 }
1476
1477 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1479 }
1480
1481 TemplateArgument ForgetPartiallySubstitutedPack() {
1482 TemplateArgument Result;
1483 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1485 MultiLevelTemplateArgumentList &TemplateArgs =
1486 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1487 unsigned Depth, Index;
1488 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1489 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1490 Result = TemplateArgs(Depth, Index);
1491 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1492 } else {
1493 IsIncomplete = true;
1494 if (BailOutOnIncomplete)
1495 return TemplateArgument();
1496 }
1497 }
1498
1499 return Result;
1500 }
1501
1502 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1503 if (Arg.isNull())
1504 return;
1505
1506 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1508 MultiLevelTemplateArgumentList &TemplateArgs =
1509 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1510 unsigned Depth, Index;
1511 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1512 TemplateArgs.setArgument(Depth, Index, Arg);
1513 }
1514 }
1515
1516 MultiLevelTemplateArgumentList ForgetSubstitution() {
1517 MultiLevelTemplateArgumentList New;
1518 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1519
1520 MultiLevelTemplateArgumentList Old =
1521 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1522 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1523 std::move(New);
1524 return Old;
1525 }
1526
1527 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1528 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = Old;
1529 }
1530
1531 TemplateArgument
1532 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1533 if (TA.getKind() != TemplateArgument::Pack)
1534 return TA;
1535 if (SemaRef.ArgPackSubstIndex)
1536 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1537 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1538 "unexpected pack arguments in template rewrite");
1539 TemplateArgument Arg = *TA.pack_begin();
1540 if (Arg.isPackExpansion())
1541 Arg = Arg.getPackExpansionPattern();
1542 return Arg;
1543 }
1544
1545 /// Transform the given declaration by instantiating a reference to
1546 /// this declaration.
1547 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1548
1549 void transformAttrs(Decl *Old, Decl *New) {
1550 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1551 }
1552
1553 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1554 if (Old->isParameterPack() &&
1555 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1557 for (auto *New : NewDecls)
1559 Old, cast<VarDecl>(New));
1560 return;
1561 }
1562
1563 assert(NewDecls.size() == 1 &&
1564 "should only have multiple expansions for a pack");
1565 Decl *New = NewDecls.front();
1566
1567 // If we've instantiated the call operator of a lambda or the call
1568 // operator template of a generic lambda, update the "instantiation of"
1569 // information.
1570 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1571 if (NewMD && isLambdaCallOperator(NewMD)) {
1572 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1573 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1574 NewTD->setInstantiatedFromMemberTemplate(
1575 OldMD->getDescribedFunctionTemplate());
1576 else
1577 NewMD->setInstantiationOfMemberFunction(OldMD,
1579 }
1580
1582
1583 // We recreated a local declaration, but not by instantiating it. There
1584 // may be pending dependent diagnostics to produce.
1585 if (auto *DC = dyn_cast<DeclContext>(Old);
1586 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1587 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1588 }
1589
1590 /// Transform the definition of the given declaration by
1591 /// instantiating it.
1592 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1593
1594 /// Transform the first qualifier within a scope by instantiating the
1595 /// declaration.
1596 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1597
1598 bool TransformExceptionSpec(SourceLocation Loc,
1599 FunctionProtoType::ExceptionSpecInfo &ESI,
1600 SmallVectorImpl<QualType> &Exceptions,
1601 bool &Changed);
1602
1603 /// Rebuild the exception declaration and register the declaration
1604 /// as an instantiated local.
1605 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1606 TypeSourceInfo *Declarator,
1607 SourceLocation StartLoc,
1608 SourceLocation NameLoc,
1609 IdentifierInfo *Name);
1610
1611 /// Rebuild the Objective-C exception declaration and register the
1612 /// declaration as an instantiated local.
1613 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1614 TypeSourceInfo *TSInfo, QualType T);
1615
1617 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1618 SourceLocation TemplateKWLoc, TemplateName Name,
1619 SourceLocation NameLoc,
1620 QualType ObjectType = QualType(),
1621 NamedDecl *FirstQualifierInScope = nullptr,
1622 bool AllowInjectedClassName = false);
1623
1624 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1625 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1626 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1627 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1628 const Stmt *InstS,
1629 const NoInlineAttr *A);
1630 const AlwaysInlineAttr *
1631 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1632 const AlwaysInlineAttr *A);
1633 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1634 const OpenACCRoutineDeclAttr *
1635 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1636 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1637 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1638 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1639
1640 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1641 NonTypeTemplateParmDecl *D);
1642
1643 /// Rebuild a DeclRefExpr for a VarDecl reference.
1644 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1645
1646 /// Transform a reference to a function or init-capture parameter pack.
1647 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1648
1649 /// Transform a FunctionParmPackExpr which was built when we couldn't
1650 /// expand a function parameter pack reference which refers to an expanded
1651 /// pack.
1652 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1653
1654 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1655 FunctionProtoTypeLoc TL) {
1656 // Call the base version; it will forward to our overridden version below.
1657 return inherited::TransformFunctionProtoType(TLB, TL);
1658 }
1659
1660 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1661 auto Type = inherited::TransformTagType(TLB, TL);
1662 if (!Type.isNull())
1663 return Type;
1664 // Special case for transforming a deduction guide, we return a
1665 // transformed TemplateSpecializationType.
1666 // FIXME: Why is this hack necessary?
1667 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1668 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1670 Type = inherited::TransformType(
1671 ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1672 SemaRef.Context));
1673 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1674 }
1675 return Type;
1676 }
1677 // Override the default version to handle a rewrite-template-arg-pack case
1678 // for building a deduction guide.
1679 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1680 TemplateArgumentLoc &Output,
1681 bool Uneval = false) {
1682 const TemplateArgument &Arg = Input.getArgument();
1683 std::vector<TemplateArgument> TArgs;
1684 switch (Arg.getKind()) {
1686 assert(SemaRef.CodeSynthesisContexts.empty() ||
1687 SemaRef.CodeSynthesisContexts.back().Kind ==
1689 // Literally rewrite the template argument pack, instead of unpacking
1690 // it.
1691 for (auto &pack : Arg.getPackAsArray()) {
1692 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1693 pack, QualType(), SourceLocation{});
1694 TemplateArgumentLoc Output;
1695 if (TransformTemplateArgument(Input, Output, Uneval))
1696 return true; // fails
1697 TArgs.push_back(Output.getArgument());
1698 }
1699 Output = SemaRef.getTrivialTemplateArgumentLoc(
1700 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1701 QualType(), SourceLocation{});
1702 return false;
1703 default:
1704 break;
1705 }
1706 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1707 }
1708
1709 // This has to be here to allow its overload.
1710 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
1711 UnsignedOrNone NumExpansions) {
1712 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
1713 NumExpansions);
1714 }
1715
1716 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
1717 SourceLocation EllipsisLoc,
1718 UnsignedOrNone NumExpansions) {
1719 // We don't rewrite a PackExpansion type when we want to normalize a
1720 // CXXFoldExpr constraint. We'll expand it when evaluating the constraint.
1721 if (BuildPackExpansionTypes)
1722 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
1723 NumExpansions);
1724 return Pattern;
1725 }
1726
1728 QualType
1729 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1730 TemplateSpecializationTypeLoc TL) {
1731 auto *T = TL.getTypePtr();
1732 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1733 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1735 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1736 // need to substitute into.
1737
1738 // `TransformType` code below will handle picking the element from a pack
1739 // with the index `ArgPackSubstIndex`.
1740 // FIXME: add ability to represent sugarred type for N-th element of a
1741 // builtin pack and produce the sugar here.
1742 QualType R = TransformType(T->desugar());
1743 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1744 return R;
1745 }
1746
1747 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1748 ArrayRef<TemplateArgument> PackArgs) {
1749 // Don't do this when rewriting template parameters for CTAD:
1750 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1751 // expanded size, but this never applies since Subst* nodes are not
1752 // created in rewrite scenarios.
1753 //
1754 // 2) The heuristic substitutes into the pattern with pack expansion
1755 // suppressed, which does not meet the requirements for argument
1756 // rewriting when template arguments include a non-pack matching against
1757 // a pack, particularly when rewriting an alias CTAD.
1758 if (TemplateArgs.isRewrite())
1759 return std::nullopt;
1760
1761 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1762 }
1763
1764 template<typename Fn>
1765 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1766 FunctionProtoTypeLoc TL,
1767 CXXRecordDecl *ThisContext,
1768 Qualifiers ThisTypeQuals,
1769 Fn TransformExceptionSpec);
1770
1771 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1772 int indexAdjustment,
1773 UnsignedOrNone NumExpansions,
1774 bool ExpectParameterPack);
1775
1776 using inherited::TransformTemplateTypeParmType;
1777 /// Transforms a template type parameter type by performing
1778 /// substitution of the corresponding template type argument.
1779 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1780 TemplateTypeParmTypeLoc TL,
1781 bool SuppressObjCLifetime);
1782
1783 QualType BuildSubstTemplateTypeParmType(
1784 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1785 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1786 TemplateArgument Arg, SourceLocation NameLoc);
1787
1788 /// Transforms an already-substituted template type parameter pack
1789 /// into either itself (if we aren't substituting into its pack expansion)
1790 /// or the appropriate substituted argument.
1791 using inherited::TransformSubstTemplateTypeParmPackType;
1792 QualType
1793 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1794 SubstTemplateTypeParmPackTypeLoc TL,
1795 bool SuppressObjCLifetime);
1796 QualType
1797 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1798 SubstBuiltinTemplatePackTypeLoc TL);
1799
1801 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1802 if (auto TypeAlias =
1803 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1804 getSema());
1805 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1806 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1807 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1808 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1809 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1810 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1811 if (TA.isDependent())
1812 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1813 }
1814 return inherited::ComputeLambdaDependency(LSI);
1815 }
1816
1817 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1818 // Do not rebuild lambdas to avoid creating a new type.
1819 // Lambdas have already been processed inside their eval contexts.
1821 return E;
1822 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1823 /*InstantiatingLambdaOrBlock=*/true);
1824 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1825
1826 return inherited::TransformLambdaExpr(E);
1827 }
1828
1829 ExprResult TransformBlockExpr(BlockExpr *E) {
1830 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1831 /*InstantiatingLambdaOrBlock=*/true);
1832 return inherited::TransformBlockExpr(E);
1833 }
1834
1835 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1836 LambdaScopeInfo *LSI) {
1837 CXXMethodDecl *MD = LSI->CallOperator;
1838 for (ParmVarDecl *PVD : MD->parameters()) {
1839 assert(PVD && "null in a parameter list");
1840 if (!PVD->hasDefaultArg())
1841 continue;
1842 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1843 // FIXME: Obtain the source location for the '=' token.
1844 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1845 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1846 // If substitution fails, the default argument is set to a
1847 // RecoveryExpr that wraps the uninstantiated default argument so
1848 // that downstream diagnostics are omitted.
1849 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1850 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1851 UninstExpr->getType());
1852 if (ErrorResult.isUsable())
1853 PVD->setDefaultArg(ErrorResult.get());
1854 }
1855 }
1856 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1857 }
1858
1859 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1860 // Currently, we instantiate the body when instantiating the lambda
1861 // expression. However, `EvaluateConstraints` is disabled during the
1862 // instantiation of the lambda expression, causing the instantiation
1863 // failure of the return type requirement in the body. If p0588r1 is fully
1864 // implemented, the body will be lazily instantiated, and this problem
1865 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1866 // `true` to temporarily fix this issue.
1867 // FIXME: This temporary fix can be removed after fully implementing
1868 // p0588r1.
1869 llvm::SaveAndRestore _(EvaluateConstraints, true);
1870 return inherited::TransformLambdaBody(E, Body);
1871 }
1872
1873 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1874 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1875 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1876 if (TransReq.isInvalid())
1877 return TransReq;
1878 assert(TransReq.get() != E &&
1879 "Do not change value of isSatisfied for the existing expression. "
1880 "Create a new expression instead.");
1881 if (E->getBody()->isDependentContext()) {
1882 Sema::SFINAETrap Trap(SemaRef);
1883 // We recreate the RequiresExpr body, but not by instantiating it.
1884 // Produce pending diagnostics for dependent access check.
1885 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1886 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1887 if (Trap.hasErrorOccurred())
1888 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1889 }
1890 return TransReq;
1891 }
1892
1893 bool TransformRequiresExprRequirements(
1894 ArrayRef<concepts::Requirement *> Reqs,
1895 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1896 bool SatisfactionDetermined = false;
1897 for (concepts::Requirement *Req : Reqs) {
1898 concepts::Requirement *TransReq = nullptr;
1899 if (!SatisfactionDetermined) {
1900 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1901 TransReq = TransformTypeRequirement(TypeReq);
1902 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1903 TransReq = TransformExprRequirement(ExprReq);
1904 else
1905 TransReq = TransformNestedRequirement(
1907 if (!TransReq)
1908 return true;
1909 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1910 // [expr.prim.req]p6
1911 // [...] The substitution and semantic constraint checking
1912 // proceeds in lexical order and stops when a condition that
1913 // determines the result of the requires-expression is
1914 // encountered. [..]
1915 SatisfactionDetermined = true;
1916 } else
1917 TransReq = Req;
1918 Transformed.push_back(TransReq);
1919 }
1920 return false;
1921 }
1922
1923 TemplateParameterList *TransformTemplateParameterList(
1924 TemplateParameterList *OrigTPL) {
1925 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1926
1927 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1928 TemplateDeclInstantiator DeclInstantiator(getSema(),
1929 /* DeclContext *Owner */ Owner, TemplateArgs);
1930 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1931 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1932 }
1933
1934 concepts::TypeRequirement *
1935 TransformTypeRequirement(concepts::TypeRequirement *Req);
1936 concepts::ExprRequirement *
1937 TransformExprRequirement(concepts::ExprRequirement *Req);
1938 concepts::NestedRequirement *
1939 TransformNestedRequirement(concepts::NestedRequirement *Req);
1940 ExprResult TransformRequiresTypeParams(
1941 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1942 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1943 SmallVectorImpl<QualType> &PTypes,
1944 SmallVectorImpl<ParmVarDecl *> &TransParams,
1945 Sema::ExtParameterInfoBuilder &PInfos);
1946 };
1947}
1948
1949bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1950 if (T.isNull())
1951 return true;
1952
1955 return false;
1956
1957 getSema().MarkDeclarationsReferencedInType(Loc, T);
1958 return true;
1959}
1960
1961Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1962 if (!D)
1963 return nullptr;
1964
1965 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1966 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1967 // If the corresponding template argument is NULL or non-existent, it's
1968 // because we are performing instantiation from explicitly-specified
1969 // template arguments in a function template, but there were some
1970 // arguments left unspecified.
1971 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1972 TTP->getPosition())) {
1973 IsIncomplete = true;
1974 return BailOutOnIncomplete ? nullptr : D;
1975 }
1976
1977 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1978
1979 if (TTP->isParameterPack()) {
1980 assert(Arg.getKind() == TemplateArgument::Pack &&
1981 "Missing argument pack");
1982 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1983 }
1984
1986 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1987 "Wrong kind of template template argument");
1988 return Template.getAsTemplateDecl();
1989 }
1990
1991 // Fall through to find the instantiated declaration for this template
1992 // template parameter.
1993 }
1994
1995 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);
1996 PVD && SemaRef.CurrentInstantiationScope &&
1997 (SemaRef.inConstraintSubstitution() ||
1998 SemaRef.inParameterMappingSubstitution()) &&
1999 maybeInstantiateFunctionParameterToScope(PVD))
2000 return nullptr;
2001
2002 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
2003}
2004
2005bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
2006 ParmVarDecl *OldParm) {
2007 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))
2008 return false;
2009
2010 if (!OldParm->isParameterPack())
2011 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2012 /*NumExpansions=*/std::nullopt,
2013 /*ExpectParameterPack=*/false);
2014
2015 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2016
2017 // Find the parameter packs that could be expanded.
2018 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
2019 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
2020 TypeLoc Pattern = ExpansionTL.getPatternLoc();
2021 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2022 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2023
2024 bool ShouldExpand = false;
2025 bool RetainExpansion = false;
2026 UnsignedOrNone OrigNumExpansions =
2027 ExpansionTL.getTypePtr()->getNumExpansions();
2028 UnsignedOrNone NumExpansions = OrigNumExpansions;
2029 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
2030 Pattern.getSourceRange(), Unexpanded,
2031 /*FailOnPackProducingTemplates=*/true,
2032 ShouldExpand, RetainExpansion, NumExpansions))
2033 return true;
2034
2035 assert(ShouldExpand && !RetainExpansion &&
2036 "Shouldn't preserve pack expansion when evaluating constraints");
2037 ExpandingFunctionParameterPack(OldParm);
2038 for (unsigned I = 0; I != *NumExpansions; ++I) {
2039 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2040 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2041 /*NumExpansions=*/OrigNumExpansions,
2042 /*ExpectParameterPack=*/false))
2043 return true;
2044 }
2045 return false;
2046}
2047
2048Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2049 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
2050 if (!Inst)
2051 return nullptr;
2052
2053 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2054 return Inst;
2055}
2056
2057bool TemplateInstantiator::TransformExceptionSpec(
2058 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2059 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2060 if (ESI.Type == EST_Uninstantiated) {
2061 ESI.instantiate();
2062 Changed = true;
2063 }
2064 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2065}
2066
2067NamedDecl *
2068TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2069 SourceLocation Loc) {
2070 // If the first part of the nested-name-specifier was a template type
2071 // parameter, instantiate that type parameter down to a tag type.
2072 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
2073 const TemplateTypeParmType *TTP
2074 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
2075
2076 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2077 // FIXME: This needs testing w/ member access expressions.
2078 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2079
2080 if (TTP->isParameterPack()) {
2081 assert(Arg.getKind() == TemplateArgument::Pack &&
2082 "Missing argument pack");
2083
2084 if (!getSema().ArgPackSubstIndex)
2085 return nullptr;
2086
2087 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2088 }
2089
2090 QualType T = Arg.getAsType();
2091 if (T.isNull())
2092 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2093
2094 if (const TagType *Tag = T->getAs<TagType>())
2095 return Tag->getDecl();
2096
2097 // The resulting type is not a tag; complain.
2098 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2099 return nullptr;
2100 }
2101 }
2102
2103 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2104}
2105
2106VarDecl *
2107TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2108 TypeSourceInfo *Declarator,
2109 SourceLocation StartLoc,
2110 SourceLocation NameLoc,
2111 IdentifierInfo *Name) {
2112 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2113 StartLoc, NameLoc, Name);
2114 if (Var)
2115 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2116 return Var;
2117}
2118
2119VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2120 TypeSourceInfo *TSInfo,
2121 QualType T) {
2122 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2123 if (Var)
2124 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2125 return Var;
2126}
2127
2128TemplateName TemplateInstantiator::TransformTemplateName(
2129 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2130 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2131 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2132 if (Name.getKind() == TemplateName::Template) {
2133 assert(!QualifierLoc && "Unexpected qualifier");
2134 if (auto *TTP =
2135 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2136 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2137 // If the corresponding template argument is NULL or non-existent, it's
2138 // because we are performing instantiation from explicitly-specified
2139 // template arguments in a function template, but there were some
2140 // arguments left unspecified.
2141 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2142 TTP->getPosition())) {
2143 IsIncomplete = true;
2144 return BailOutOnIncomplete ? TemplateName() : Name;
2145 }
2146
2147 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2148
2149 if (TemplateArgs.isRewrite()) {
2150 // We're rewriting the template parameter as a reference to another
2151 // template parameter.
2152 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2153 assert(Arg.getKind() == TemplateArgument::Template &&
2154 "unexpected nontype template argument kind in template rewrite");
2155 return Arg.getAsTemplate();
2156 }
2157
2158 auto [AssociatedDecl, Final] =
2159 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2160 UnsignedOrNone PackIndex = std::nullopt;
2161 if (TTP->isParameterPack()) {
2162 assert(Arg.getKind() == TemplateArgument::Pack &&
2163 "Missing argument pack");
2164
2165 if (!getSema().ArgPackSubstIndex) {
2166 // We have the template argument pack to substitute, but we're not
2167 // actually expanding the enclosing pack expansion yet. So, just
2168 // keep the entire argument pack.
2169 return getSema().Context.getSubstTemplateTemplateParmPack(
2170 Arg, AssociatedDecl, TTP->getIndex(), Final);
2171 }
2172
2173 PackIndex = SemaRef.getPackIndex(Arg);
2174 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2175 }
2176
2178 assert(!Template.isNull() && "Null template template argument");
2179 return getSema().Context.getSubstTemplateTemplateParm(
2180 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2181 }
2182 }
2183
2184 if (SubstTemplateTemplateParmPackStorage *SubstPack
2186 if (!getSema().ArgPackSubstIndex)
2187 return Name;
2188
2189 TemplateArgument Pack = SubstPack->getArgumentPack();
2191 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2192 return getSema().Context.getSubstTemplateTemplateParm(
2193 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2194 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2195 }
2196
2197 return inherited::TransformTemplateName(
2198 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2199 FirstQualifierInScope, AllowInjectedClassName);
2200}
2201
2203TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2204 if (!E->isTypeDependent())
2205 return E;
2206
2207 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2208}
2209
2211TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2212 NonTypeTemplateParmDecl *NTTP) {
2213 // If the corresponding template argument is NULL or non-existent, it's
2214 // because we are performing instantiation from explicitly-specified
2215 // template arguments in a function template, but there were some
2216 // arguments left unspecified.
2217 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2218 NTTP->getPosition())) {
2219 IsIncomplete = true;
2220 return BailOutOnIncomplete ? ExprError() : E;
2221 }
2222
2223 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2224
2225 if (TemplateArgs.isRewrite()) {
2226 // We're rewriting the template parameter as a reference to another
2227 // template parameter.
2228 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2229 assert(Arg.getKind() == TemplateArgument::Expression &&
2230 "unexpected nontype template argument kind in template rewrite");
2231 // FIXME: This can lead to the same subexpression appearing multiple times
2232 // in a complete expression.
2233 return Arg.getAsExpr();
2234 }
2235
2236 auto [AssociatedDecl, Final] =
2237 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2238 UnsignedOrNone PackIndex = std::nullopt;
2239 if (NTTP->isParameterPack()) {
2240 assert(Arg.getKind() == TemplateArgument::Pack &&
2241 "Missing argument pack");
2242
2243 if (!getSema().ArgPackSubstIndex) {
2244 // We have an argument pack, but we can't select a particular argument
2245 // out of it yet. Therefore, we'll build an expression to hold on to that
2246 // argument pack.
2247 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2248 E->getLocation(),
2249 NTTP->getDeclName());
2250 if (TargetType.isNull())
2251 return ExprError();
2252
2253 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2254 if (TargetType->isRecordType())
2255 ExprType.addConst();
2256 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2257 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2258 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2259 }
2260 PackIndex = SemaRef.getPackIndex(Arg);
2261 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2262 }
2263 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2264 AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);
2265}
2266
2267const AnnotateAttr *
2268TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2269 SmallVector<Expr *> Args;
2270 for (Expr *Arg : AA->args()) {
2271 ExprResult Res = getDerived().TransformExpr(Arg);
2272 if (Res.isUsable())
2273 Args.push_back(Res.get());
2274 }
2275 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2276 Args.data(), Args.size(), AA->getRange());
2277}
2278
2279const CXXAssumeAttr *
2280TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2281 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2282 if (!Res.isUsable())
2283 return AA;
2284
2285 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2286 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2287 AA->getRange());
2288 if (!Res.isUsable())
2289 return AA;
2290 }
2291
2292 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2293 AA->getRange());
2294}
2295
2296const LoopHintAttr *
2297TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2298 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2299
2300 if (TransformedExpr == LH->getValue())
2301 return LH;
2302
2303 // Generate error if there is a problem with the value.
2304 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2305 LH->getSemanticSpelling() ==
2306 LoopHintAttr::Pragma_unroll))
2307 return LH;
2308
2309 LoopHintAttr::OptionType Option = LH->getOption();
2310 LoopHintAttr::LoopHintState State = LH->getState();
2311
2312 llvm::APSInt ValueAPS =
2313 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2314 // The values of 0 and 1 block any unrolling of the loop.
2315 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2316 Option = LoopHintAttr::Unroll;
2317 State = LoopHintAttr::Disable;
2318 }
2319
2320 // Create new LoopHintValueAttr with integral expression in place of the
2321 // non-type template parameter.
2322 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2323 TransformedExpr, *LH);
2324}
2325const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2326 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2327 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2328 return nullptr;
2329
2330 return A;
2331}
2332const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2333 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2334 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2335 return nullptr;
2336
2337 return A;
2338}
2339
2340const CodeAlignAttr *
2341TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2342 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2343 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2344}
2345const OpenACCRoutineDeclAttr *
2346TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2347 const OpenACCRoutineDeclAttr *A) {
2348 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2349 "applies to a Function Decl (and a few places for VarDecl)");
2350}
2351
2352ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2353 SourceLocation Loc) {
2354 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2355 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2356}
2357
2359TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2360 if (getSema().ArgPackSubstIndex) {
2361 // We can expand this parameter pack now.
2362 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2363 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2364 if (!VD)
2365 return ExprError();
2366 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2367 }
2368
2369 QualType T = TransformType(E->getType());
2370 if (T.isNull())
2371 return ExprError();
2372
2373 // Transform each of the parameter expansions into the corresponding
2374 // parameters in the instantiation of the function decl.
2375 SmallVector<ValueDecl *, 8> Vars;
2376 Vars.reserve(E->getNumExpansions());
2377 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2378 I != End; ++I) {
2379 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2380 if (!D)
2381 return ExprError();
2382 Vars.push_back(D);
2383 }
2384
2385 auto *PackExpr =
2387 E->getParameterPackLocation(), Vars);
2388 getSema().MarkFunctionParmPackReferenced(PackExpr);
2389 return PackExpr;
2390}
2391
2393TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2394 ValueDecl *PD) {
2395 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2396 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2397 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2398 assert(Found && "no instantiation for parameter pack");
2399
2400 Decl *TransformedDecl;
2401 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2402 // If this is a reference to a function parameter pack which we can
2403 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2404 if (!getSema().ArgPackSubstIndex) {
2405 QualType T = TransformType(E->getType());
2406 if (T.isNull())
2407 return ExprError();
2408 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2409 E->getExprLoc(), *Pack);
2410 getSema().MarkFunctionParmPackReferenced(PackExpr);
2411 return PackExpr;
2412 }
2413
2414 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2415 } else {
2416 TransformedDecl = cast<Decl *>(*Found);
2417 }
2418
2419 // We have either an unexpanded pack or a specific expansion.
2420 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2421 E->getExprLoc());
2422}
2423
2425TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2426 NamedDecl *D = E->getDecl();
2427
2428 // Handle references to non-type template parameters and non-type template
2429 // parameter packs.
2430 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2431 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2432 return TransformTemplateParmRefExpr(E, NTTP);
2433
2434 // We have a non-type template parameter that isn't fully substituted;
2435 // FindInstantiatedDecl will find it in the local instantiation scope.
2436 }
2437
2438 // Handle references to function parameter packs.
2439 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2440 if (PD->isParameterPack())
2441 return TransformFunctionParmPackRefExpr(E, PD);
2442
2443 return inherited::TransformDeclRefExpr(E);
2444}
2445
2446ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2447 CXXDefaultArgExpr *E) {
2448 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2449 getDescribedFunctionTemplate() &&
2450 "Default arg expressions are never formed in dependent cases.");
2451 return SemaRef.BuildCXXDefaultArgExpr(
2453 E->getParam());
2454}
2455
2456template<typename Fn>
2457QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2458 FunctionProtoTypeLoc TL,
2459 CXXRecordDecl *ThisContext,
2460 Qualifiers ThisTypeQuals,
2461 Fn TransformExceptionSpec) {
2462 // If this is a lambda or block, the transformation MUST be done in the
2463 // CurrentInstantiationScope since it introduces a mapping of
2464 // the original to the newly created transformed parameters.
2465 //
2466 // In that case, TemplateInstantiator::TransformLambdaExpr will
2467 // have already pushed a scope for this prototype, so don't create
2468 // a second one.
2469 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2470 std::optional<LocalInstantiationScope> Scope;
2471 if (!Current || !Current->isLambdaOrBlock())
2472 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2473
2474 return inherited::TransformFunctionProtoType(
2475 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2476}
2477
2478ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2479 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2480 bool ExpectParameterPack) {
2481 auto NewParm = SemaRef.SubstParmVarDecl(
2482 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2483 ExpectParameterPack, EvaluateConstraints);
2484 if (NewParm && SemaRef.getLangOpts().OpenCL)
2485 SemaRef.deduceOpenCLAddressSpace(NewParm);
2486 return NewParm;
2487}
2488
2489QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2490 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2491 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2492 TemplateArgument Arg, SourceLocation NameLoc) {
2493 QualType Replacement = Arg.getAsType();
2494
2495 // If the template parameter had ObjC lifetime qualifiers,
2496 // then any such qualifiers on the replacement type are ignored.
2497 if (SuppressObjCLifetime) {
2498 Qualifiers RQs;
2499 RQs = Replacement.getQualifiers();
2500 RQs.removeObjCLifetime();
2501 Replacement =
2502 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2503 }
2504
2505 // TODO: only do this uniquing once, at the start of instantiation.
2506 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2507 Replacement, AssociatedDecl, Index, PackIndex, Final);
2508 SubstTemplateTypeParmTypeLoc NewTL =
2509 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2510 NewTL.setNameLoc(NameLoc);
2511 return Result;
2512}
2513
2514QualType
2515TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2516 TemplateTypeParmTypeLoc TL,
2517 bool SuppressObjCLifetime) {
2518 const TemplateTypeParmType *T = TL.getTypePtr();
2519 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2520 // Replace the template type parameter with its corresponding
2521 // template argument.
2522
2523 // If the corresponding template argument is NULL or doesn't exist, it's
2524 // because we are performing instantiation from explicitly-specified
2525 // template arguments in a function template class, but there were some
2526 // arguments left unspecified.
2527 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2528 IsIncomplete = true;
2529 if (BailOutOnIncomplete)
2530 return QualType();
2531
2532 TemplateTypeParmTypeLoc NewTL
2533 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2534 NewTL.setNameLoc(TL.getNameLoc());
2535 return TL.getType();
2536 }
2537
2538 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2539
2540 if (TemplateArgs.isRewrite()) {
2541 // We're rewriting the template parameter as a reference to another
2542 // template parameter.
2543 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2544 assert(Arg.getKind() == TemplateArgument::Type &&
2545 "unexpected nontype template argument kind in template rewrite");
2546 QualType NewT = Arg.getAsType();
2547 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2548 return NewT;
2549 }
2550
2551 auto [AssociatedDecl, Final] =
2552 TemplateArgs.getAssociatedDecl(T->getDepth());
2553 UnsignedOrNone PackIndex = std::nullopt;
2554 if (T->isParameterPack()) {
2555 assert(Arg.getKind() == TemplateArgument::Pack &&
2556 "Missing argument pack");
2557
2558 if (!getSema().ArgPackSubstIndex) {
2559 // We have the template argument pack, but we're not expanding the
2560 // enclosing pack expansion yet. Just save the template argument
2561 // pack for later substitution.
2562 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2563 AssociatedDecl, T->getIndex(), Final, Arg);
2564 SubstTemplateTypeParmPackTypeLoc NewTL
2565 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2566 NewTL.setNameLoc(TL.getNameLoc());
2567 return Result;
2568 }
2569
2570 // PackIndex starts from last element.
2571 PackIndex = SemaRef.getPackIndex(Arg);
2572 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2573 }
2574
2575 assert(Arg.getKind() == TemplateArgument::Type &&
2576 "Template argument kind mismatch");
2577
2578 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2579 AssociatedDecl, T->getIndex(),
2580 PackIndex, Arg, TL.getNameLoc());
2581 }
2582
2583 // The template type parameter comes from an inner template (e.g.,
2584 // the template parameter list of a member template inside the
2585 // template we are instantiating). Create a new template type
2586 // parameter with the template "level" reduced by one.
2587 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2588 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2589 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2590 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2591 QualType Result = getSema().Context.getTemplateTypeParmType(
2592 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2593 T->isParameterPack(), NewTTPDecl);
2594 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2595 NewTL.setNameLoc(TL.getNameLoc());
2596 return Result;
2597}
2598
2599QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2600 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2601 bool SuppressObjCLifetime) {
2602 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2603
2604 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2605
2606 if (!getSema().ArgPackSubstIndex) {
2607 // We aren't expanding the parameter pack, so just return ourselves.
2608 QualType Result = TL.getType();
2609 if (NewReplaced != T->getAssociatedDecl())
2610 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2611 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2612 SubstTemplateTypeParmPackTypeLoc NewTL =
2613 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2614 NewTL.setNameLoc(TL.getNameLoc());
2615 return Result;
2616 }
2617
2618 TemplateArgument Pack = T->getArgumentPack();
2619 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2620 return BuildSubstTemplateTypeParmType(
2621 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2622 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2623}
2624
2625QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2626 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2627 if (!getSema().ArgPackSubstIndex)
2628 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2629 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2630 TL.getTypePtr()->getArgumentPack());
2631 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2632 TL.getBeginLoc());
2633 return Result.getAsType();
2634}
2635
2636static concepts::Requirement::SubstitutionDiagnostic *
2638 Sema::EntityPrinter Printer) {
2639 SmallString<128> Message;
2640 SourceLocation ErrorLoc;
2641 if (Info.hasSFINAEDiagnostic()) {
2644 Info.takeSFINAEDiagnostic(PDA);
2645 PDA.second.EmitToString(S.getDiagnostics(), Message);
2646 ErrorLoc = PDA.first;
2647 } else {
2648 ErrorLoc = Info.getLocation();
2649 }
2650 SmallString<128> Entity;
2651 llvm::raw_svector_ostream OS(Entity);
2652 Printer(OS);
2653 const ASTContext &C = S.Context;
2655 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2656}
2657
2658concepts::Requirement::SubstitutionDiagnostic *
2660 SmallString<128> Entity;
2661 llvm::raw_svector_ostream OS(Entity);
2662 Printer(OS);
2663 const ASTContext &C = Context;
2665 /*SubstitutedEntity=*/C.backupStr(Entity),
2666 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2667}
2668
2669ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2670 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2673 SmallVectorImpl<ParmVarDecl *> &TransParams,
2675
2676 TemplateDeductionInfo Info(KWLoc);
2677 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2678 RE, Info,
2679 SourceRange{KWLoc, RBraceLoc});
2681
2682 unsigned ErrorIdx;
2683 if (getDerived().TransformFunctionTypeParams(
2684 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2685 &TransParams, PInfos, &ErrorIdx) ||
2686 Trap.hasErrorOccurred()) {
2688 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2689 // Add a 'failed' Requirement to contain the error that caused the failure
2690 // here.
2691 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2692 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2693 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2694 TransParams, RE->getRParenLoc(),
2695 TransReqs, RBraceLoc);
2696 }
2697
2698 return ExprResult{};
2699}
2700
2701concepts::TypeRequirement *
2702TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2703 if (!Req->isDependent() && !AlwaysRebuild())
2704 return Req;
2705 if (Req->isSubstitutionFailure()) {
2706 if (AlwaysRebuild())
2707 return RebuildTypeRequirement(
2709 return Req;
2710 }
2711
2712 Sema::SFINAETrap Trap(SemaRef);
2713 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2714 Sema::InstantiatingTemplate TypeInst(SemaRef,
2715 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2716 Req->getType()->getTypeLoc().getSourceRange());
2717 if (TypeInst.isInvalid())
2718 return nullptr;
2719 TypeSourceInfo *TransType = TransformType(Req->getType());
2720 if (!TransType || Trap.hasErrorOccurred())
2721 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2722 [&] (llvm::raw_ostream& OS) {
2723 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2724 }));
2725 return RebuildTypeRequirement(TransType);
2726}
2727
2728concepts::ExprRequirement *
2729TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2730 if (!Req->isDependent() && !AlwaysRebuild())
2731 return Req;
2732
2733 Sema::SFINAETrap Trap(SemaRef);
2734
2735 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2736 TransExpr;
2737 if (Req->isExprSubstitutionFailure())
2738 TransExpr = Req->getExprSubstitutionDiagnostic();
2739 else {
2740 Expr *E = Req->getExpr();
2741 TemplateDeductionInfo Info(E->getBeginLoc());
2742 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2743 E->getSourceRange());
2744 if (ExprInst.isInvalid())
2745 return nullptr;
2746 ExprResult TransExprRes = TransformExpr(E);
2747 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2748 TransExprRes.get()->hasPlaceholderType())
2749 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2750 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2751 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2752 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2753 });
2754 else
2755 TransExpr = TransExprRes.get();
2756 }
2757
2758 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2759 const auto &RetReq = Req->getReturnTypeRequirement();
2760 if (RetReq.isEmpty())
2761 TransRetReq.emplace();
2762 else if (RetReq.isSubstitutionFailure())
2763 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2764 else if (RetReq.isTypeConstraint()) {
2765 TemplateParameterList *OrigTPL =
2766 RetReq.getTypeConstraintTemplateParameterList();
2767 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2768 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2769 Req, Info, OrigTPL->getSourceRange());
2770 if (TPLInst.isInvalid())
2771 return nullptr;
2772 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2773 if (!TPL || Trap.hasErrorOccurred())
2774 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2775 [&] (llvm::raw_ostream& OS) {
2776 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2777 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2778 }));
2779 else {
2780 TPLInst.Clear();
2781 TransRetReq.emplace(TPL);
2782 }
2783 }
2784 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2785 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2786 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2787 std::move(*TransRetReq));
2788 return RebuildExprRequirement(
2790 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2791}
2792
2793concepts::NestedRequirement *
2794TemplateInstantiator::TransformNestedRequirement(
2795 concepts::NestedRequirement *Req) {
2796
2797 ASTContext &C = SemaRef.Context;
2798
2799 Expr *Constraint = Req->getConstraintExpr();
2800 ConstraintSatisfaction Satisfaction;
2801
2802 auto NestedReqWithDiag = [&C, this](Expr *E,
2803 ConstraintSatisfaction Satisfaction) {
2804 Satisfaction.IsSatisfied = false;
2805 SmallString<128> Entity;
2806 llvm::raw_svector_ostream OS(Entity);
2807 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2808 return new (C) concepts::NestedRequirement(
2809 SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));
2810 };
2811
2812 if (Req->hasInvalidConstraint()) {
2813 if (AlwaysRebuild())
2814 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2816 return Req;
2817 }
2818
2819 if (!getEvaluateConstraints()) {
2820 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2821 if (TransConstraint.isInvalid() || !TransConstraint.get())
2822 return nullptr;
2823 if (TransConstraint.get()->isInstantiationDependent())
2824 return new (SemaRef.Context)
2825 concepts::NestedRequirement(TransConstraint.get());
2826 ConstraintSatisfaction Satisfaction;
2827 return new (SemaRef.Context) concepts::NestedRequirement(
2828 SemaRef.Context, TransConstraint.get(), Satisfaction);
2829 }
2830
2831 bool Success;
2832 Expr *NewConstraint;
2833 TemplateDeductionInfo Info(Constraint->getBeginLoc());
2834 {
2835 EnterExpressionEvaluationContext ContextRAII(
2837
2838 Sema::InstantiatingTemplate ConstrInst(
2839 SemaRef, Constraint->getBeginLoc(), Req,
2840 Sema::InstantiatingTemplate::ConstraintsCheck(),
2841 Constraint->getSourceRange());
2842
2843 if (ConstrInst.isInvalid())
2844 return nullptr;
2845
2846 Sema::SFINAETrap Trap(SemaRef);
2847
2848 Success = !SemaRef.CheckConstraintSatisfaction(
2849 Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),
2850 TemplateArgs, Constraint->getSourceRange(), Satisfaction,
2851 /*TopLevelConceptId=*/nullptr, &NewConstraint);
2852
2853 assert((!Success || !Trap.hasErrorOccurred()) &&
2854 "Substitution failures must be handled "
2855 "by CheckConstraintSatisfaction.");
2856 }
2857
2858 if (!Success || Satisfaction.HasSubstitutionFailure())
2859 return NestedReqWithDiag(Constraint, Satisfaction);
2860
2861 // FIXME: const correctness
2862 // MLTAL might be dependent.
2863 if (!NewConstraint) {
2864 if (!Satisfaction.IsSatisfied)
2865 return NestedReqWithDiag(Constraint, Satisfaction);
2866
2867 NewConstraint = Constraint;
2868 }
2869 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2870}
2871
2874 SourceLocation Loc,
2875 DeclarationName Entity,
2876 bool AllowDeducedTST) {
2877 assert(!CodeSynthesisContexts.empty() &&
2878 "Cannot perform an instantiation without some context on the "
2879 "instantiation stack");
2880
2881 if (!T->getType()->isInstantiationDependentType() &&
2882 !T->getType()->isVariablyModifiedType())
2883 return T;
2884
2885 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2886 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2887 : Instantiator.TransformType(T);
2888}
2889
2892 SourceLocation Loc,
2893 DeclarationName Entity) {
2894 assert(!CodeSynthesisContexts.empty() &&
2895 "Cannot perform an instantiation without some context on the "
2896 "instantiation stack");
2897
2898 if (TL.getType().isNull())
2899 return nullptr;
2900
2903 // FIXME: Make a copy of the TypeLoc data here, so that we can
2904 // return a new TypeSourceInfo. Inefficient!
2905 TypeLocBuilder TLB;
2906 TLB.pushFullCopy(TL);
2907 return TLB.getTypeSourceInfo(Context, TL.getType());
2908 }
2909
2910 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2911 TypeLocBuilder TLB;
2912 TLB.reserve(TL.getFullDataSize());
2913 QualType Result = Instantiator.TransformType(TLB, TL);
2914 if (Result.isNull())
2915 return nullptr;
2916
2917 return TLB.getTypeSourceInfo(Context, Result);
2918}
2919
2920/// Deprecated form of the above.
2922 const MultiLevelTemplateArgumentList &TemplateArgs,
2923 SourceLocation Loc, DeclarationName Entity,
2924 bool *IsIncompleteSubstitution) {
2925 assert(!CodeSynthesisContexts.empty() &&
2926 "Cannot perform an instantiation without some context on the "
2927 "instantiation stack");
2928
2929 // If T is not a dependent type or a variably-modified type, there
2930 // is nothing to do.
2931 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2932 return T;
2933
2934 TemplateInstantiator Instantiator(
2935 *this, TemplateArgs, Loc, Entity,
2936 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2937 QualType QT = Instantiator.TransformType(T);
2938 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2939 *IsIncompleteSubstitution = true;
2940 return QT;
2941}
2942
2944 if (T->getType()->isInstantiationDependentType() ||
2945 T->getType()->isVariablyModifiedType())
2946 return true;
2947
2948 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2949 if (!TL.getAs<FunctionProtoTypeLoc>())
2950 return false;
2951
2953 for (ParmVarDecl *P : FP.getParams()) {
2954 // This must be synthesized from a typedef.
2955 if (!P) continue;
2956
2957 // If there are any parameters, a new TypeSourceInfo that refers to the
2958 // instantiated parameters must be built.
2959 return true;
2960 }
2961
2962 return false;
2963}
2964
2967 SourceLocation Loc,
2968 DeclarationName Entity,
2969 CXXRecordDecl *ThisContext,
2970 Qualifiers ThisTypeQuals,
2971 bool EvaluateConstraints) {
2972 assert(!CodeSynthesisContexts.empty() &&
2973 "Cannot perform an instantiation without some context on the "
2974 "instantiation stack");
2975
2977 return T;
2978
2979 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2980 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2981
2982 TypeLocBuilder TLB;
2983
2984 TypeLoc TL = T->getTypeLoc();
2985 TLB.reserve(TL.getFullDataSize());
2986
2988
2989 if (FunctionProtoTypeLoc Proto =
2991 // Instantiate the type, other than its exception specification. The
2992 // exception specification is instantiated in InitFunctionInstantiation
2993 // once we've built the FunctionDecl.
2994 // FIXME: Set the exception specification to EST_Uninstantiated here,
2995 // instead of rebuilding the function type again later.
2996 Result = Instantiator.TransformFunctionProtoType(
2997 TLB, Proto, ThisContext, ThisTypeQuals,
2999 bool &Changed) { return false; });
3000 } else {
3001 Result = Instantiator.TransformType(TLB, TL);
3002 }
3003 // When there are errors resolving types, clang may use IntTy as a fallback,
3004 // breaking our assumption that function declarations have function types.
3005 if (Result.isNull() || !Result->isFunctionType())
3006 return nullptr;
3007
3008 return TLB.getTypeSourceInfo(Context, Result);
3009}
3010
3013 SmallVectorImpl<QualType> &ExceptionStorage,
3014 const MultiLevelTemplateArgumentList &Args) {
3015 bool Changed = false;
3016 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3017 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3018 Changed);
3019}
3020
3022 const MultiLevelTemplateArgumentList &Args) {
3025
3026 SmallVector<QualType, 4> ExceptionStorage;
3027 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3028 ESI, ExceptionStorage, Args))
3029 // On error, recover by dropping the exception specification.
3030 ESI.Type = EST_None;
3031
3033}
3034
3035namespace {
3036
3037 struct GetContainedInventedTypeParmVisitor :
3038 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3039 TemplateTypeParmDecl *> {
3040 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3041 TemplateTypeParmDecl *>::Visit;
3042
3044 if (T.isNull())
3045 return nullptr;
3046 return Visit(T.getTypePtr());
3047 }
3048 // The deduced type itself.
3049 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3050 const TemplateTypeParmType *T) {
3051 if (!T->getDecl() || !T->getDecl()->isImplicit())
3052 return nullptr;
3053 return T->getDecl();
3054 }
3055
3056 // Only these types can contain 'auto' types, and subsequently be replaced
3057 // by references to invented parameters.
3058
3059 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3060 return Visit(T->getPointeeType());
3061 }
3062
3063 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3064 return Visit(T->getPointeeType());
3065 }
3066
3067 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3068 return Visit(T->getPointeeTypeAsWritten());
3069 }
3070
3071 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3072 return Visit(T->getPointeeType());
3073 }
3074
3075 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3076 return Visit(T->getElementType());
3077 }
3078
3079 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3080 const DependentSizedExtVectorType *T) {
3081 return Visit(T->getElementType());
3082 }
3083
3084 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3085 return Visit(T->getElementType());
3086 }
3087
3088 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3089 return VisitFunctionType(T);
3090 }
3091
3092 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3093 return Visit(T->getReturnType());
3094 }
3095
3096 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3097 return Visit(T->getInnerType());
3098 }
3099
3100 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3101 return Visit(T->getModifiedType());
3102 }
3103
3104 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3105 return Visit(T->getUnderlyingType());
3106 }
3107
3108 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3109 return Visit(T->getOriginalType());
3110 }
3111
3112 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3113 return Visit(T->getPattern());
3114 }
3115 };
3116
3117} // namespace
3118
3120 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3121 const MultiLevelTemplateArgumentList &TemplateArgs,
3122 bool EvaluateConstraints) {
3123 const ASTTemplateArgumentListInfo *TemplArgInfo =
3125
3126 if (!EvaluateConstraints && !inParameterMappingSubstitution()) {
3128 if (!Index)
3129 Index = SemaRef.ArgPackSubstIndex;
3132 return false;
3133 }
3134
3135 TemplateArgumentListInfo InstArgs;
3136
3137 if (TemplArgInfo) {
3138 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3139 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3140 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3141 InstArgs))
3142 return true;
3143 }
3144 return AttachTypeConstraint(
3146 TC->getNamedConcept(),
3147 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3148 Inst->isParameterPack()
3150 ->getEllipsisLoc()
3151 : SourceLocation());
3152}
3153
3156 const MultiLevelTemplateArgumentList &TemplateArgs,
3157 int indexAdjustment, UnsignedOrNone NumExpansions,
3158 bool ExpectParameterPack, bool EvaluateConstraint) {
3159 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3160 TypeSourceInfo *NewDI = nullptr;
3161
3162 TypeLoc OldTL = OldDI->getTypeLoc();
3163 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3164
3165 // We have a function parameter pack. Substitute into the pattern of the
3166 // expansion.
3167 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3168 OldParm->getLocation(), OldParm->getDeclName());
3169 if (!NewDI)
3170 return nullptr;
3171
3172 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3173 // We still have unexpanded parameter packs, which means that
3174 // our function parameter is still a function parameter pack.
3175 // Therefore, make its type a pack expansion type.
3176 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3177 NumExpansions);
3178 } else if (ExpectParameterPack) {
3179 // We expected to get a parameter pack but didn't (because the type
3180 // itself is not a pack expansion type), so complain. This can occur when
3181 // the substitution goes through an alias template that "loses" the
3182 // pack expansion.
3183 Diag(OldParm->getLocation(),
3184 diag::err_function_parameter_pack_without_parameter_packs)
3185 << NewDI->getType();
3186 return nullptr;
3187 }
3188 } else {
3189 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3190 OldParm->getDeclName());
3191 }
3192
3193 if (!NewDI)
3194 return nullptr;
3195
3196 if (NewDI->getType()->isVoidType()) {
3197 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3198 return nullptr;
3199 }
3200
3201 // In abbreviated templates, TemplateTypeParmDecls with possible
3202 // TypeConstraints are created when the parameter list is originally parsed.
3203 // The TypeConstraints can therefore reference other functions parameters in
3204 // the abbreviated function template, which is why we must instantiate them
3205 // here, when the instantiated versions of those referenced parameters are in
3206 // scope.
3207 if (TemplateTypeParmDecl *TTP =
3208 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3209 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3210 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3211 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3212 // We will first get here when instantiating the abbreviated function
3213 // template's described function, but we might also get here later.
3214 // Make sure we do not instantiate the TypeConstraint more than once.
3215 if (Inst && !Inst->getTypeConstraint()) {
3216 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3217 return nullptr;
3218 }
3219 }
3220 }
3221
3222 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
3223 OldParm->getInnerLocStart(),
3224 OldParm->getLocation(),
3225 OldParm->getIdentifier(),
3226 NewDI->getType(), NewDI,
3227 OldParm->getStorageClass());
3228 if (!NewParm)
3229 return nullptr;
3230
3231 // Mark the (new) default argument as uninstantiated (if any).
3232 if (OldParm->hasUninstantiatedDefaultArg()) {
3233 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3234 NewParm->setUninstantiatedDefaultArg(Arg);
3235 } else if (OldParm->hasUnparsedDefaultArg()) {
3236 NewParm->setUnparsedDefaultArg();
3237 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3238 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3239 // Default arguments cannot be substituted until the declaration context
3240 // for the associated function or lambda capture class is available.
3241 // This is necessary for cases like the following where construction of
3242 // the lambda capture class for the outer lambda is dependent on the
3243 // parameter types but where the default argument is dependent on the
3244 // outer lambda's declaration context.
3245 // template <typename T>
3246 // auto f() {
3247 // return [](T = []{ return T{}; }()) { return 0; };
3248 // }
3249 NewParm->setUninstantiatedDefaultArg(Arg);
3250 }
3251
3255
3256 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3257 // Add the new parameter to the instantiated parameter pack.
3258 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3259 } else {
3260 // Introduce an Old -> New mapping
3261 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3262 }
3263
3264 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3265 // can be anything, is this right ?
3266 NewParm->setDeclContext(CurContext);
3267
3268 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3269 OldParm->getFunctionScopeIndex() + indexAdjustment);
3270
3271 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3272
3273 return NewParm;
3274}
3275
3278 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3279 const MultiLevelTemplateArgumentList &TemplateArgs,
3280 SmallVectorImpl<QualType> &ParamTypes,
3282 ExtParameterInfoBuilder &ParamInfos) {
3283 assert(!CodeSynthesisContexts.empty() &&
3284 "Cannot perform an instantiation without some context on the "
3285 "instantiation stack");
3286
3287 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3288 DeclarationName());
3289 return Instantiator.TransformFunctionTypeParams(
3290 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3291}
3292
3294 SourceLocation Loc,
3295 ParmVarDecl *Param,
3296 const MultiLevelTemplateArgumentList &TemplateArgs,
3297 bool ForCallExpr) {
3298 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3299 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3300
3301 RecursiveInstGuard AlreadyInstantiating(
3303 if (AlreadyInstantiating) {
3304 Param->setInvalidDecl();
3305 return Diag(Param->getBeginLoc(), diag::err_recursive_default_argument)
3306 << FD << PatternExpr->getSourceRange();
3307 }
3308
3311
3312 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3313 if (Inst.isInvalid())
3314 return true;
3315
3317 // C++ [dcl.fct.default]p5:
3318 // The names in the [default argument] expression are bound, and
3319 // the semantic constraints are checked, at the point where the
3320 // default argument expression appears.
3321 ContextRAII SavedContext(*this, FD);
3322 {
3323 std::optional<LocalInstantiationScope> LIS;
3324
3325 if (ForCallExpr) {
3326 // When instantiating a default argument due to use in a call expression,
3327 // an instantiation scope that includes the parameters of the callee is
3328 // required to satisfy references from the default argument. For example:
3329 // template<typename T> void f(T a, int = decltype(a)());
3330 // void g() { f(0); }
3331 LIS.emplace(*this);
3333 /*ForDefinition*/ false);
3334 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3335 return true;
3336 }
3337
3339 Result = SubstInitializer(PatternExpr, TemplateArgs,
3340 /*DirectInit*/ false);
3341 });
3342 }
3343 if (Result.isInvalid())
3344 return true;
3345
3346 if (ForCallExpr) {
3347 // Check the expression as an initializer for the parameter.
3348 InitializedEntity Entity
3351 Param->getLocation(),
3352 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3353 Expr *ResultE = Result.getAs<Expr>();
3354
3355 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3356 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3357 if (Result.isInvalid())
3358 return true;
3359
3360 Result =
3361 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3362 /*DiscardedValue*/ false);
3363 } else {
3364 // FIXME: Obtain the source location for the '=' token.
3365 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3366 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3367 }
3368 if (Result.isInvalid())
3369 return true;
3370
3371 // Remember the instantiated default argument.
3372 Param->setDefaultArg(Result.getAs<Expr>());
3373
3374 return false;
3375}
3376
3377// See TreeTransform::PreparePackForExpansion for the relevant comment.
3378// This function implements the same concept for base specifiers.
3379static bool
3381 const MultiLevelTemplateArgumentList &TemplateArgs,
3382 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3383 SourceRange BaseSourceRange = Base.getSourceRange();
3384 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3385 Info.Ellipsis = Base.getEllipsisLoc();
3386 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3387 TypeSourceInfo *BaseTypeInfo,
3388 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3389 // This is a pack expansion. See whether we should expand it now, or
3390 // wait until later.
3392 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3393 if (IsLateExpansionAttempt) {
3394 // Request expansion only when there is an opportunity to expand a pack
3395 // that required a substituion first.
3396 bool SawPackTypes =
3397 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3398 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3399 });
3400 if (!SawPackTypes) {
3401 Info.Expand = false;
3402 return false;
3403 }
3404 }
3405
3406 // Determine whether the set of unexpanded parameter packs can and should be
3407 // expanded.
3408 Info.Expand = false;
3409 Info.RetainExpansion = false;
3410 Info.NumExpansions = std::nullopt;
3412 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3413 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3414 Info.RetainExpansion, Info.NumExpansions);
3415 };
3416
3417 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3418 return true;
3419
3420 if (Info.Expand) {
3421 Out = Base.getTypeSourceInfo();
3422 return false;
3423 }
3424
3425 // The resulting base specifier will (still) be a pack expansion.
3426 {
3427 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3428 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3429 BaseSourceRange.getBegin(), DeclarationName());
3430 }
3431 if (!Out->getType()->containsUnexpandedParameterPack())
3432 return false;
3433
3434 // Some packs will learn their length after substitution.
3435 // We may need to request their expansion.
3436 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3437 return true;
3438 if (Info.Expand)
3439 Info.ExpandUnderForgetSubstitions = true;
3440 return false;
3441}
3442
3443bool
3445 CXXRecordDecl *Pattern,
3446 const MultiLevelTemplateArgumentList &TemplateArgs) {
3447 bool Invalid = false;
3448 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3449 for (const auto &Base : Pattern->bases()) {
3450 if (!Base.getType()->isDependentType()) {
3451 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3452 if (RD->isInvalidDecl())
3453 Instantiation->setInvalidDecl();
3454 }
3455 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3456 continue;
3457 }
3458
3459 SourceLocation EllipsisLoc;
3460 TypeSourceInfo *BaseTypeLoc = nullptr;
3461 if (Base.isPackExpansion()) {
3462 UnexpandedInfo Info;
3463 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3464 Info)) {
3465 Invalid = true;
3466 continue;
3467 }
3468
3469 // If we should expand this pack expansion now, do so.
3471 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3473 ArgsForSubst = &EmptyList;
3474
3475 if (Info.Expand) {
3476 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3477 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3478
3479 TypeSourceInfo *Expanded =
3480 SubstType(BaseTypeLoc, *ArgsForSubst,
3481 Base.getSourceRange().getBegin(), DeclarationName());
3482 if (!Expanded) {
3483 Invalid = true;
3484 continue;
3485 }
3486
3487 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3488 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3489 Base.getAccessSpecifierAsWritten(), Expanded,
3490 SourceLocation()))
3491 InstantiatedBases.push_back(InstantiatedBase);
3492 else
3493 Invalid = true;
3494 }
3495
3496 continue;
3497 }
3498
3499 // The resulting base specifier will (still) be a pack expansion.
3500 EllipsisLoc = Base.getEllipsisLoc();
3501 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3502 BaseTypeLoc =
3503 SubstType(BaseTypeLoc, *ArgsForSubst,
3504 Base.getSourceRange().getBegin(), DeclarationName());
3505 } else {
3506 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3507 TemplateArgs,
3508 Base.getSourceRange().getBegin(),
3509 DeclarationName());
3510 }
3511
3512 if (!BaseTypeLoc) {
3513 Invalid = true;
3514 continue;
3515 }
3516
3517 if (CXXBaseSpecifier *InstantiatedBase
3518 = CheckBaseSpecifier(Instantiation,
3519 Base.getSourceRange(),
3520 Base.isVirtual(),
3521 Base.getAccessSpecifierAsWritten(),
3522 BaseTypeLoc,
3523 EllipsisLoc))
3524 InstantiatedBases.push_back(InstantiatedBase);
3525 else
3526 Invalid = true;
3527 }
3528
3529 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3530 Invalid = true;
3531
3532 return Invalid;
3533}
3534
3535// Defined via #include from SemaTemplateInstantiateDecl.cpp
3536namespace clang {
3537 namespace sema {
3539 const MultiLevelTemplateArgumentList &TemplateArgs);
3541 const Attr *At, ASTContext &C, Sema &S,
3542 const MultiLevelTemplateArgumentList &TemplateArgs);
3543 }
3544}
3545
3546bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3547 CXXRecordDecl *Instantiation,
3548 CXXRecordDecl *Pattern,
3549 const MultiLevelTemplateArgumentList &TemplateArgs,
3550 TemplateSpecializationKind TSK, bool Complain) {
3551#ifndef NDEBUG
3552 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3554 assert(!AlreadyInstantiating && "should have been caught by caller");
3555#endif
3556
3557 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3558 TemplateArgs, TSK, Complain);
3559}
3560
3561bool Sema::InstantiateClassImpl(
3562 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3563 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3564 TemplateSpecializationKind TSK, bool Complain) {
3565
3566 CXXRecordDecl *PatternDef
3567 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3568 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3569 Instantiation->getInstantiatedFromMemberClass(),
3570 Pattern, PatternDef, TSK, Complain))
3571 return true;
3572
3573 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3574 llvm::TimeTraceMetadata M;
3575 llvm::raw_string_ostream OS(M.Detail);
3576 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3577 /*Qualified=*/true);
3578 if (llvm::isTimeTraceVerbose()) {
3579 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3580 M.File = SourceMgr.getFilename(Loc);
3581 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3582 }
3583 return M;
3584 });
3585
3586 Pattern = PatternDef;
3587
3588 // Record the point of instantiation.
3589 if (MemberSpecializationInfo *MSInfo
3590 = Instantiation->getMemberSpecializationInfo()) {
3591 MSInfo->setTemplateSpecializationKind(TSK);
3592 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3593 } else if (ClassTemplateSpecializationDecl *Spec
3594 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3595 Spec->setTemplateSpecializationKind(TSK);
3596 Spec->setPointOfInstantiation(PointOfInstantiation);
3597 }
3598
3599 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3600 if (Inst.isInvalid())
3601 return true;
3602 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3603 "instantiating class definition");
3604
3605 // Enter the scope of this instantiation. We don't use
3606 // PushDeclContext because we don't have a scope.
3607 ContextRAII SavedContext(*this, Instantiation);
3608 EnterExpressionEvaluationContext EvalContext(
3609 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3610
3611 // If this is an instantiation of a local class, merge this local
3612 // instantiation scope with the enclosing scope. Otherwise, every
3613 // instantiation of a class has its own local instantiation scope.
3614 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3615 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3616
3617 // Some class state isn't processed immediately but delayed till class
3618 // instantiation completes. We may not be ready to handle any delayed state
3619 // already on the stack as it might correspond to a different class, so save
3620 // it now and put it back later.
3621 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3622
3623 // Pull attributes from the pattern onto the instantiation.
3624 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3625
3626 // Start the definition of this instantiation.
3627 Instantiation->startDefinition();
3628
3629 // The instantiation is visible here, even if it was first declared in an
3630 // unimported module.
3631 Instantiation->setVisibleDespiteOwningModule();
3632
3633 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3634 Instantiation->setTagKind(Pattern->getTagKind());
3635
3636 // Do substitution on the base class specifiers.
3637 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3638 Instantiation->setInvalidDecl();
3639
3640 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3641 Instantiator.setEvaluateConstraints(false);
3642 SmallVector<Decl*, 4> Fields;
3643 // Delay instantiation of late parsed attributes.
3644 LateInstantiatedAttrVec LateAttrs;
3645 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3646
3647 bool MightHaveConstexprVirtualFunctions = false;
3648 for (auto *Member : Pattern->decls()) {
3649 // Don't instantiate members not belonging in this semantic context.
3650 // e.g. for:
3651 // @code
3652 // template <int i> class A {
3653 // class B *g;
3654 // };
3655 // @endcode
3656 // 'class B' has the template as lexical context but semantically it is
3657 // introduced in namespace scope.
3658 if (Member->getDeclContext() != Pattern)
3659 continue;
3660
3661 // BlockDecls can appear in a default-member-initializer. They must be the
3662 // child of a BlockExpr, so we only know how to instantiate them from there.
3663 // Similarly, lambda closure types are recreated when instantiating the
3664 // corresponding LambdaExpr.
3665 if (isa<BlockDecl>(Member) ||
3667 continue;
3668
3669 if (Member->isInvalidDecl()) {
3670 Instantiation->setInvalidDecl();
3671 continue;
3672 }
3673
3674 Decl *NewMember = Instantiator.Visit(Member);
3675 if (NewMember) {
3676 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3677 Fields.push_back(Field);
3678 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3679 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3680 // specialization causes the implicit instantiation of the definitions
3681 // of unscoped member enumerations.
3682 // Record a point of instantiation for this implicit instantiation.
3683 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3684 Enum->isCompleteDefinition()) {
3685 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3686 assert(MSInfo && "no spec info for member enum specialization");
3688 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3689 }
3690 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3691 if (SA->isFailed()) {
3692 // A static_assert failed. Bail out; instantiating this
3693 // class is probably not meaningful.
3694 Instantiation->setInvalidDecl();
3695 break;
3696 }
3697 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3698 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3699 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3700 MightHaveConstexprVirtualFunctions = true;
3701 }
3702
3703 if (NewMember->isInvalidDecl())
3704 Instantiation->setInvalidDecl();
3705 } else {
3706 // FIXME: Eventually, a NULL return will mean that one of the
3707 // instantiations was a semantic disaster, and we'll want to mark the
3708 // declaration invalid.
3709 // For now, we expect to skip some members that we can't yet handle.
3710 }
3711 }
3712
3713 // Finish checking fields.
3714 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3715 SourceLocation(), SourceLocation(), ParsedAttributesView());
3716 CheckCompletedCXXClass(nullptr, Instantiation);
3717
3718 // Default arguments are parsed, if not instantiated. We can go instantiate
3719 // default arg exprs for default constructors if necessary now. Unless we're
3720 // parsing a class, in which case wait until that's finished.
3721 if (ParsingClassDepth == 0)
3722 ActOnFinishCXXNonNestedClass();
3723
3724 // Instantiate late parsed attributes, and attach them to their decls.
3725 // See Sema::InstantiateAttrs
3726 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3727 E = LateAttrs.end(); I != E; ++I) {
3728 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3729 CurrentInstantiationScope = I->Scope;
3730
3731 // Allow 'this' within late-parsed attributes.
3732 auto *ND = cast<NamedDecl>(I->NewDecl);
3733 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3734 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3735 ND->isCXXInstanceMember());
3736
3737 Attr *NewAttr =
3738 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3739 if (NewAttr)
3740 I->NewDecl->addAttr(NewAttr);
3742 Instantiator.getStartingScope());
3743 }
3744 Instantiator.disableLateAttributeInstantiation();
3745 LateAttrs.clear();
3746
3747 ActOnFinishDelayedMemberInitializers(Instantiation);
3748
3749 // FIXME: We should do something similar for explicit instantiations so they
3750 // end up in the right module.
3751 if (TSK == TSK_ImplicitInstantiation) {
3752 Instantiation->setLocation(Pattern->getLocation());
3753 Instantiation->setLocStart(Pattern->getInnerLocStart());
3754 Instantiation->setBraceRange(Pattern->getBraceRange());
3755 }
3756
3757 if (!Instantiation->isInvalidDecl()) {
3758 // Perform any dependent diagnostics from the pattern.
3759 if (Pattern->isDependentContext())
3760 PerformDependentDiagnostics(Pattern, TemplateArgs);
3761
3762 // Instantiate any out-of-line class template partial
3763 // specializations now.
3765 P = Instantiator.delayed_partial_spec_begin(),
3766 PEnd = Instantiator.delayed_partial_spec_end();
3767 P != PEnd; ++P) {
3768 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3769 P->first, P->second)) {
3770 Instantiation->setInvalidDecl();
3771 break;
3772 }
3773 }
3774
3775 // Instantiate any out-of-line variable template partial
3776 // specializations now.
3778 P = Instantiator.delayed_var_partial_spec_begin(),
3779 PEnd = Instantiator.delayed_var_partial_spec_end();
3780 P != PEnd; ++P) {
3781 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3782 P->first, P->second)) {
3783 Instantiation->setInvalidDecl();
3784 break;
3785 }
3786 }
3787 }
3788
3789 // Exit the scope of this instantiation.
3790 SavedContext.pop();
3791
3792 if (!Instantiation->isInvalidDecl()) {
3793 // Always emit the vtable for an explicit instantiation definition
3794 // of a polymorphic class template specialization. Otherwise, eagerly
3795 // instantiate only constexpr virtual functions in preparation for their use
3796 // in constant evaluation.
3798 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3799 else if (MightHaveConstexprVirtualFunctions)
3800 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3801 /*ConstexprOnly*/ true);
3802 }
3803
3804 Consumer.HandleTagDeclDefinition(Instantiation);
3805
3806 return Instantiation->isInvalidDecl();
3807}
3808
3809bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3810 EnumDecl *Instantiation, EnumDecl *Pattern,
3811 const MultiLevelTemplateArgumentList &TemplateArgs,
3813#ifndef NDEBUG
3814 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3816 assert(!AlreadyInstantiating && "should have been caught by caller");
3817#endif
3818
3819 EnumDecl *PatternDef = Pattern->getDefinition();
3820 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3821 Instantiation->getInstantiatedFromMemberEnum(),
3822 Pattern, PatternDef, TSK,/*Complain*/true))
3823 return true;
3824 Pattern = PatternDef;
3825
3826 // Record the point of instantiation.
3827 if (MemberSpecializationInfo *MSInfo
3828 = Instantiation->getMemberSpecializationInfo()) {
3829 MSInfo->setTemplateSpecializationKind(TSK);
3830 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3831 }
3832
3833 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3834 if (Inst.isInvalid())
3835 return true;
3836 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3837 "instantiating enum definition");
3838
3839 // The instantiation is visible here, even if it was first declared in an
3840 // unimported module.
3841 Instantiation->setVisibleDespiteOwningModule();
3842
3843 // Enter the scope of this instantiation. We don't use
3844 // PushDeclContext because we don't have a scope.
3845 ContextRAII SavedContext(*this, Instantiation);
3848
3849 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3850
3851 // Pull attributes from the pattern onto the instantiation.
3852 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3853
3854 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3855 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3856
3857 // Exit the scope of this instantiation.
3858 SavedContext.pop();
3859
3860 return Instantiation->isInvalidDecl();
3861}
3862
3864 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3865 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3866 // If there is no initializer, we don't need to do anything.
3867 if (!Pattern->hasInClassInitializer())
3868 return false;
3869
3870 assert(Instantiation->getInClassInitStyle() ==
3871 Pattern->getInClassInitStyle() &&
3872 "pattern and instantiation disagree about init style");
3873
3874 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3876 if (AlreadyInstantiating)
3877 // Error out if we hit an instantiation cycle for this initializer.
3878 return Diag(PointOfInstantiation,
3879 diag::err_default_member_initializer_cycle)
3880 << Instantiation;
3881
3882 // Error out if we haven't parsed the initializer of the pattern yet because
3883 // we are waiting for the closing brace of the outer class.
3884 Expr *OldInit = Pattern->getInClassInitializer();
3885 if (!OldInit) {
3886 RecordDecl *PatternRD = Pattern->getParent();
3887 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3888 Diag(PointOfInstantiation,
3889 diag::err_default_member_initializer_not_yet_parsed)
3890 << OutermostClass << Pattern;
3891 Diag(Pattern->getEndLoc(),
3892 diag::note_default_member_initializer_not_yet_parsed);
3893 Instantiation->setInvalidDecl();
3894 return true;
3895 }
3896
3897 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3898 if (Inst.isInvalid())
3899 return true;
3900 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3901 "instantiating default member init");
3902
3903 // Enter the scope of this instantiation. We don't use PushDeclContext because
3904 // we don't have a scope.
3905 ContextRAII SavedContext(*this, Instantiation->getParent());
3908 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3909 PointOfInstantiation, Instantiation, CurContext};
3910
3911 LocalInstantiationScope Scope(*this, true);
3912
3913 // Instantiate the initializer.
3915 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3916
3917 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3918 /*CXXDirectInit=*/false);
3919 Expr *Init = NewInit.get();
3920 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3922 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3923
3924 if (auto *L = getASTMutationListener())
3925 L->DefaultMemberInitializerInstantiated(Instantiation);
3926
3927 // Return true if the in-class initializer is still missing.
3928 return !Instantiation->getInClassInitializer();
3929}
3930
3931namespace {
3932 /// A partial specialization whose template arguments have matched
3933 /// a given template-id.
3934 struct PartialSpecMatchResult {
3937 };
3938}
3939
3941 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3942 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3944 return true;
3945
3947 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3948 CTD->getPartialSpecializations(PartialSpecs);
3949 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3950 // C++ [temp.spec.partial.member]p2:
3951 // If the primary member template is explicitly specialized for a given
3952 // (implicit) specialization of the enclosing class template, the partial
3953 // specializations of the member template are ignored for this
3954 // specialization of the enclosing class template. If a partial
3955 // specialization of the member template is explicitly specialized for a
3956 // given (implicit) specialization of the enclosing class template, the
3957 // primary member template and its other partial specializations are still
3958 // considered for this specialization of the enclosing class template.
3960 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3961 continue;
3962
3963 TemplateDeductionInfo Info(Loc);
3964 if (DeduceTemplateArguments(CTPSD,
3965 ClassTemplateSpec->getTemplateArgs().asArray(),
3967 return true;
3968 }
3969
3970 return false;
3971}
3972
3973/// Get the instantiation pattern to use to instantiate the definition of a
3974/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3975/// template or of a partial specialization).
3977 Sema &S, SourceLocation PointOfInstantiation,
3978 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3979 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3980 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3981 if (Inst.isInvalid())
3982 return {/*Invalid=*/true};
3983
3984 llvm::PointerUnion<ClassTemplateDecl *,
3986 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3988 // Find best matching specialization.
3989 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3990
3991 // C++ [temp.class.spec.match]p1:
3992 // When a class template is used in a context that requires an
3993 // instantiation of the class, it is necessary to determine
3994 // whether the instantiation is to be generated using the primary
3995 // template or one of the partial specializations. This is done by
3996 // matching the template arguments of the class template
3997 // specialization with the template argument lists of the partial
3998 // specializations.
3999 typedef PartialSpecMatchResult MatchResult;
4000 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4002 Template->getPartialSpecializations(PartialSpecs);
4003 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4004 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4005 // C++ [temp.spec.partial.member]p2:
4006 // If the primary member template is explicitly specialized for a given
4007 // (implicit) specialization of the enclosing class template, the
4008 // partial specializations of the member template are ignored for this
4009 // specialization of the enclosing class template. If a partial
4010 // specialization of the member template is explicitly specialized for a
4011 // given (implicit) specialization of the enclosing class template, the
4012 // primary member template and its other partial specializations are
4013 // still considered for this specialization of the enclosing class
4014 // template.
4015 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4016 !Partial->getMostRecentDecl()->isMemberSpecialization())
4017 continue;
4018
4019 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4021 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4023 // Store the failed-deduction information for use in diagnostics, later.
4024 // TODO: Actually use the failed-deduction info?
4025 FailedCandidates.addCandidate().set(
4027 MakeDeductionFailureInfo(S.Context, Result, Info));
4028 (void)Result;
4029 } else {
4030 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
4031 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4032 }
4033 }
4034 if (Matched.empty() && PrimaryStrictPackMatch)
4035 Matched = std::move(ExtraMatched);
4036
4037 // If we're dealing with a member template where the template parameters
4038 // have been instantiated, this provides the original template parameters
4039 // from which the member template's parameters were instantiated.
4040
4041 if (Matched.size() >= 1) {
4042 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4043 if (Matched.size() == 1) {
4044 // -- If exactly one matching specialization is found, the
4045 // instantiation is generated from that specialization.
4046 // We don't need to do anything for this.
4047 } else {
4048 // -- If more than one matching specialization is found, the
4049 // partial order rules (14.5.4.2) are used to determine
4050 // whether one of the specializations is more specialized
4051 // than the others. If none of the specializations is more
4052 // specialized than all of the other matching
4053 // specializations, then the use of the class template is
4054 // ambiguous and the program is ill-formed.
4056 PEnd = Matched.end();
4057 P != PEnd; ++P) {
4059 P->Partial, Best->Partial, PointOfInstantiation) ==
4060 P->Partial)
4061 Best = P;
4062 }
4063
4064 // Determine if the best partial specialization is more specialized than
4065 // the others.
4066 bool Ambiguous = false;
4067 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4068 PEnd = Matched.end();
4069 P != PEnd; ++P) {
4070 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4071 P->Partial, Best->Partial,
4072 PointOfInstantiation) != Best->Partial) {
4073 Ambiguous = true;
4074 break;
4075 }
4076 }
4077
4078 if (Ambiguous) {
4079 // Partial ordering did not produce a clear winner. Complain.
4080 Inst.Clear();
4081 S.Diag(PointOfInstantiation,
4082 diag::err_partial_spec_ordering_ambiguous)
4083 << ClassTemplateSpec;
4084
4085 // Print the matching partial specializations.
4086 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4087 PEnd = Matched.end();
4088 P != PEnd; ++P)
4089 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4091 P->Partial->getTemplateParameters(), *P->Args);
4092
4093 return {/*Invalid=*/true};
4094 }
4095 }
4096
4097 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4098 } else {
4099 // -- If no matches are found, the instantiation is generated
4100 // from the primary template.
4101 }
4102 }
4103
4104 CXXRecordDecl *Pattern = nullptr;
4105 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4106 if (auto *PartialSpec =
4107 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4108 // Instantiate using the best class template partial specialization.
4109 while (PartialSpec->getInstantiatedFromMember()) {
4110 // If we've found an explicit specialization of this class template,
4111 // stop here and use that as the pattern.
4112 if (PartialSpec->isMemberSpecialization())
4113 break;
4114
4115 PartialSpec = PartialSpec->getInstantiatedFromMember();
4116 }
4117 Pattern = PartialSpec;
4118 } else {
4119 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4120 while (Template->getInstantiatedFromMemberTemplate()) {
4121 // If we've found an explicit specialization of this class template,
4122 // stop here and use that as the pattern.
4123 if (Template->isMemberSpecialization())
4124 break;
4125
4126 Template = Template->getInstantiatedFromMemberTemplate();
4127 }
4128 Pattern = Template->getTemplatedDecl();
4129 }
4130
4131 return Pattern;
4132}
4133
4135 SourceLocation PointOfInstantiation,
4136 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4137 TemplateSpecializationKind TSK, bool Complain,
4138 bool PrimaryStrictPackMatch) {
4139 // Perform the actual instantiation on the canonical declaration.
4140 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4141 ClassTemplateSpec->getCanonicalDecl());
4142 if (ClassTemplateSpec->isInvalidDecl())
4143 return true;
4144
4145 Sema::RecursiveInstGuard AlreadyInstantiating(
4146 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4147 if (AlreadyInstantiating)
4148 return false;
4149
4150 bool HadAvaibilityWarning =
4151 ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
4152 .first != AR_Available;
4153
4155 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4156 ClassTemplateSpec, TSK,
4157 PrimaryStrictPackMatch);
4158
4159 if (!Pattern.isUsable())
4160 return Pattern.isInvalid();
4161
4162 bool Err = InstantiateClassImpl(
4163 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4164 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4165
4166 // If we haven't already warn on avaibility, consider the avaibility
4167 // attributes of the partial specialization.
4168 // Note that - because we need to have deduced the partial specialization -
4169 // We can only emit these warnings when the specialization is instantiated.
4170 if (!Err && !HadAvaibilityWarning) {
4171 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4173 DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);
4174 }
4175 return Err;
4176}
4177
4178void
4180 CXXRecordDecl *Instantiation,
4181 const MultiLevelTemplateArgumentList &TemplateArgs,
4183 // FIXME: We need to notify the ASTMutationListener that we did all of these
4184 // things, in case we have an explicit instantiation definition in a PCM, a
4185 // module, or preamble, and the declaration is in an imported AST.
4186 assert(
4189 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4190 "Unexpected template specialization kind!");
4191 for (auto *D : Instantiation->decls()) {
4192 bool SuppressNew = false;
4193 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4194 if (FunctionDecl *Pattern =
4195 Function->getInstantiatedFromMemberFunction()) {
4196
4197 if (Function->getTrailingRequiresClause()) {
4198 ConstraintSatisfaction Satisfaction;
4199 if (CheckFunctionConstraints(Function, Satisfaction) ||
4200 !Satisfaction.IsSatisfied) {
4201 continue;
4202 }
4203 }
4204
4205 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4206 continue;
4207
4209 Function->getTemplateSpecializationKind();
4210 if (PrevTSK == TSK_ExplicitSpecialization)
4211 continue;
4212
4214 PointOfInstantiation, TSK, Function, PrevTSK,
4215 Function->getPointOfInstantiation(), SuppressNew) ||
4216 SuppressNew)
4217 continue;
4218
4219 // C++11 [temp.explicit]p8:
4220 // An explicit instantiation definition that names a class template
4221 // specialization explicitly instantiates the class template
4222 // specialization and is only an explicit instantiation definition
4223 // of members whose definition is visible at the point of
4224 // instantiation.
4225 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4226 continue;
4227
4228 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4229
4230 if (Function->isDefined()) {
4231 // Let the ASTConsumer know that this function has been explicitly
4232 // instantiated now, and its linkage might have changed.
4233 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4234 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4235 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4236 } else if (TSK == TSK_ImplicitInstantiation) {
4238 std::make_pair(Function, PointOfInstantiation));
4239 }
4240 }
4241 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4243 continue;
4244
4245 if (Var->isStaticDataMember()) {
4246 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4247 continue;
4248
4250 assert(MSInfo && "No member specialization information?");
4251 if (MSInfo->getTemplateSpecializationKind()
4253 continue;
4254
4255 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4256 Var,
4258 MSInfo->getPointOfInstantiation(),
4259 SuppressNew) ||
4260 SuppressNew)
4261 continue;
4262
4264 // C++0x [temp.explicit]p8:
4265 // An explicit instantiation definition that names a class template
4266 // specialization explicitly instantiates the class template
4267 // specialization and is only an explicit instantiation definition
4268 // of members whose definition is visible at the point of
4269 // instantiation.
4271 continue;
4272
4273 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4274 InstantiateVariableDefinition(PointOfInstantiation, Var);
4275 } else {
4276 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4277 }
4278 }
4279 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4280 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4281 continue;
4282
4283 // Always skip the injected-class-name, along with any
4284 // redeclarations of nested classes, since both would cause us
4285 // to try to instantiate the members of a class twice.
4286 // Skip closure types; they'll get instantiated when we instantiate
4287 // the corresponding lambda-expression.
4288 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4289 Record->isLambda())
4290 continue;
4291
4292 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4293 assert(MSInfo && "No member specialization information?");
4294
4295 if (MSInfo->getTemplateSpecializationKind()
4297 continue;
4298
4299 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4301 // On Windows, explicit instantiation decl of the outer class doesn't
4302 // affect the inner class. Typically extern template declarations are
4303 // used in combination with dll import/export annotations, but those
4304 // are not propagated from the outer class templates to inner classes.
4305 // Therefore, do not instantiate inner classes on this platform, so
4306 // that users don't end up with undefined symbols during linking.
4307 continue;
4308 }
4309
4310 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4311 Record,
4313 MSInfo->getPointOfInstantiation(),
4314 SuppressNew) ||
4315 SuppressNew)
4316 continue;
4317
4318 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4319 assert(Pattern && "Missing instantiated-from-template information");
4320
4321 if (!Record->getDefinition()) {
4322 if (!Pattern->getDefinition()) {
4323 // C++0x [temp.explicit]p8:
4324 // An explicit instantiation definition that names a class template
4325 // specialization explicitly instantiates the class template
4326 // specialization and is only an explicit instantiation definition
4327 // of members whose definition is visible at the point of
4328 // instantiation.
4330 MSInfo->setTemplateSpecializationKind(TSK);
4331 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4332 }
4333
4334 continue;
4335 }
4336
4337 InstantiateClass(PointOfInstantiation, Record, Pattern,
4338 TemplateArgs,
4339 TSK);
4340 } else {
4342 Record->getTemplateSpecializationKind() ==
4344 Record->setTemplateSpecializationKind(TSK);
4345 MarkVTableUsed(PointOfInstantiation, Record, true);
4346 }
4347 }
4348
4349 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4350 if (Pattern)
4351 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4352 TSK);
4353 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4354 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4355 assert(MSInfo && "No member specialization information?");
4356
4357 if (MSInfo->getTemplateSpecializationKind()
4359 continue;
4360
4362 PointOfInstantiation, TSK, Enum,
4364 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4365 SuppressNew)
4366 continue;
4367
4368 if (Enum->getDefinition())
4369 continue;
4370
4371 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4372 assert(Pattern && "Missing instantiated-from-template information");
4373
4375 if (!Pattern->getDefinition())
4376 continue;
4377
4378 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4379 } else {
4380 MSInfo->setTemplateSpecializationKind(TSK);
4381 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4382 }
4383 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4384 // No need to instantiate in-class initializers during explicit
4385 // instantiation.
4386 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4387 // Handle local classes which could have substituted template params.
4388 CXXRecordDecl *ClassPattern =
4389 Instantiation->isLocalClass()
4390 ? Instantiation->getInstantiatedFromMemberClass()
4391 : Instantiation->getTemplateInstantiationPattern();
4392
4394 ClassPattern->lookup(Field->getDeclName());
4395 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4396 assert(Pattern);
4397 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4398 TemplateArgs);
4399 }
4400 }
4401 }
4402}
4403
4404void
4406 SourceLocation PointOfInstantiation,
4407 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4409 // C++0x [temp.explicit]p7:
4410 // An explicit instantiation that names a class template
4411 // specialization is an explicit instantion of the same kind
4412 // (declaration or definition) of each of its members (not
4413 // including members inherited from base classes) that has not
4414 // been previously explicitly specialized in the translation unit
4415 // containing the explicit instantiation, except as described
4416 // below.
4417 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4418 getTemplateInstantiationArgs(ClassTemplateSpec),
4419 TSK);
4420}
4421
4424 if (!S)
4425 return S;
4426
4427 TemplateInstantiator Instantiator(*this, TemplateArgs,
4429 DeclarationName());
4430 return Instantiator.TransformStmt(S);
4431}
4432
4434 const TemplateArgumentLoc &Input,
4435 const MultiLevelTemplateArgumentList &TemplateArgs,
4437 const DeclarationName &Entity) {
4438 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4439 return Instantiator.TransformTemplateArgument(Input, Output);
4440}
4441
4444 const MultiLevelTemplateArgumentList &TemplateArgs,
4446 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4447 DeclarationName());
4448 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4449}
4450
4453 const MultiLevelTemplateArgumentList &TemplateArgs,
4454 TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes) {
4455 TemplateInstantiator Instantiator(
4456 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4457 TemplateArgs, BuildPackExpansionTypes);
4458 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4459}
4460
4463 if (!E)
4464 return E;
4465
4466 TemplateInstantiator Instantiator(*this, TemplateArgs,
4468 DeclarationName());
4469 return Instantiator.TransformExpr(E);
4470}
4471
4474 const MultiLevelTemplateArgumentList &TemplateArgs) {
4475 if (!E)
4476 return E;
4477
4478 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4479 DeclarationName());
4480 return Instantiator.TransformAddressOfOperand(E);
4481}
4482
4485 const MultiLevelTemplateArgumentList &TemplateArgs) {
4486 // FIXME: should call SubstExpr directly if this function is equivalent or
4487 // should it be different?
4488 return SubstExpr(E, TemplateArgs);
4489}
4490
4492 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4493 if (!E)
4494 return E;
4495
4496 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4497 DeclarationName());
4498 Instantiator.setEvaluateConstraints(false);
4499 return Instantiator.TransformExpr(E);
4500}
4501
4503 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4504 const MultiLevelTemplateArgumentList &MLTAL) {
4505 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4506 DeclarationName());
4507 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4509 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4510 ArgsAsWritten->getRAngleLoc());
4511
4513 *this, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
4515 CSE->getNamedConcept(),
4516 ArgsAsWritten->arguments().front().getSourceRange());
4517
4518 if (Inst.isInvalid())
4519 return ExprError();
4520
4521 if (Instantiator.TransformConceptTemplateArguments(
4522 ArgsAsWritten->getTemplateArgs(),
4523 ArgsAsWritten->getTemplateArgs() +
4524 ArgsAsWritten->getNumTemplateArgs(),
4525 SubstArgs))
4526 return true;
4527
4528 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4529 SubstArgs.arguments(),
4530 [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4531
4532 MultiLevelTemplateArgumentList MLTALForConstraint =
4534 CSE->getNamedConcept(),
4536 /*Final=*/false,
4537 /*Innermost=*/NewArgList,
4538 /*RelativeToPrimary=*/true,
4539 /*Pattern=*/nullptr,
4540 /*ForConstraintInstantiation=*/true);
4541
4542 // Rebuild a constraint, only substituting non-dependent concept names
4543 // and nothing else.
4544 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4545 // only SomeConceptName is substituted, in the constraint expression of C.
4546 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4549
4550 ConstraintExprTransformer(Sema &SemaRef,
4552 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4553
4554 ExprResult TransformExpr(Expr *E) {
4555 if (!E)
4556 return E;
4557 switch (E->getStmtClass()) {
4558 case Stmt::BinaryOperatorClass:
4559 case Stmt::ConceptSpecializationExprClass:
4560 case Stmt::ParenExprClass:
4561 case Stmt::UnresolvedLookupExprClass:
4562 return Base::TransformExpr(E);
4563 default:
4564 break;
4565 }
4566 return E;
4567 }
4568
4569 // Rebuild both branches of a conjunction / disjunction
4570 // even if there is a substitution failure in one of
4571 // the branch.
4572 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4573 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4574 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4575 return E;
4576
4577 ExprResult LHS = TransformExpr(E->getLHS());
4578 ExprResult RHS = TransformExpr(E->getRHS());
4579
4580 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4581 return E;
4582
4583 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
4584 E->getOpcode(), SemaRef.Context.BoolTy,
4587 }
4588
4589 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4590 TemplateArgumentLoc &Output,
4591 bool Uneval = false) {
4593 return Base::TransformTemplateArgument(Input, Output, Uneval);
4594
4595 Output = Input;
4596 return false;
4597 }
4598
4599 ExprResult TransformUnresolvedLookupExpr(UnresolvedLookupExpr *E,
4600 bool IsAddressOfOperand = false) {
4601 if (E->isConceptReference()) {
4602 ExprResult Res = SemaRef.SubstExpr(E, MLTAL);
4603 return Res;
4604 }
4605 return E;
4606 }
4607 };
4608
4609 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4610 ExprResult Res =
4611 Transformer.TransformExpr(const_cast<Expr *>(ConstraintExpr));
4612 return Res;
4613}
4614
4616 const MultiLevelTemplateArgumentList &TemplateArgs,
4617 bool CXXDirectInit) {
4618 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4619 DeclarationName());
4620 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4621}
4622
4623bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4624 const MultiLevelTemplateArgumentList &TemplateArgs,
4625 SmallVectorImpl<Expr *> &Outputs) {
4626 if (Exprs.empty())
4627 return false;
4628
4629 TemplateInstantiator Instantiator(*this, TemplateArgs,
4631 DeclarationName());
4632 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4633 IsCall, Outputs);
4634}
4635
4638 const MultiLevelTemplateArgumentList &TemplateArgs) {
4639 if (!NNS)
4640 return NestedNameSpecifierLoc();
4641
4642 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4643 DeclarationName());
4644 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4645}
4646
4649 const MultiLevelTemplateArgumentList &TemplateArgs) {
4650 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4651 NameInfo.getName());
4652 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4653}
4654
4657 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4658 SourceLocation NameLoc,
4659 const MultiLevelTemplateArgumentList &TemplateArgs) {
4660 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4661 DeclarationName());
4662 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4663 NameLoc);
4664}
4665
4666static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4667 // When storing ParmVarDecls in the local instantiation scope, we always
4668 // want to use the ParmVarDecl from the canonical function declaration,
4669 // since the map is then valid for any redeclaration or definition of that
4670 // function.
4671 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4672 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4673 unsigned i = PV->getFunctionScopeIndex();
4674 // This parameter might be from a freestanding function type within the
4675 // function and isn't necessarily referring to one of FD's parameters.
4676 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4677 return FD->getCanonicalDecl()->getParamDecl(i);
4678 }
4679 }
4680 return D;
4681}
4682
4683llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4686 for (LocalInstantiationScope *Current = this; Current;
4687 Current = Current->Outer) {
4688
4689 // Check if we found something within this scope.
4690 const Decl *CheckD = D;
4691 do {
4692 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4693 if (Found != Current->LocalDecls.end())
4694 return &Found->second;
4695
4696 // If this is a tag declaration, it's possible that we need to look for
4697 // a previous declaration.
4698 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4699 CheckD = Tag->getPreviousDecl();
4700 else
4701 CheckD = nullptr;
4702 } while (CheckD);
4703
4704 // If we aren't combined with our outer scope, we're done.
4705 if (!Current->CombineWithOuterScope)
4706 break;
4707 }
4708
4709 return nullptr;
4710}
4711
4712llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4715 if (Result)
4716 return Result;
4717 // If we're performing a partial substitution during template argument
4718 // deduction, we may not have values for template parameters yet.
4721 return nullptr;
4722
4723 // Local types referenced prior to definition may require instantiation.
4724 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4725 if (RD->isLocalClass())
4726 return nullptr;
4727
4728 // Enumeration types referenced prior to definition may appear as a result of
4729 // error recovery.
4730 if (isa<EnumDecl>(D))
4731 return nullptr;
4732
4733 // Materialized typedefs/type alias for implicit deduction guides may require
4734 // instantiation.
4735 if (isa<TypedefNameDecl>(D) &&
4737 return nullptr;
4738
4739 // If we didn't find the decl, then we either have a sema bug, or we have a
4740 // forward reference to a label declaration. Return null to indicate that
4741 // we have an uninstantiated label.
4742 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4743 return nullptr;
4744}
4745
4748 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4749 if (Stored.isNull()) {
4750#ifndef NDEBUG
4751 // It should not be present in any surrounding scope either.
4752 LocalInstantiationScope *Current = this;
4753 while (Current->CombineWithOuterScope && Current->Outer) {
4754 Current = Current->Outer;
4755 assert(!Current->LocalDecls.contains(D) &&
4756 "Instantiated local in inner and outer scopes");
4757 }
4758#endif
4759 Stored = Inst;
4760 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4761 Pack->push_back(cast<ValueDecl>(Inst));
4762 } else {
4763 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4764 }
4765}
4766
4768 VarDecl *Inst) {
4770 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4771 Pack->push_back(Inst);
4772}
4773
4775#ifndef NDEBUG
4776 // This should be the first time we've been told about this decl.
4777 for (LocalInstantiationScope *Current = this;
4778 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4779 assert(!Current->LocalDecls.contains(D) &&
4780 "Creating local pack after instantiation of local");
4781#endif
4782
4784 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4786 Stored = Pack;
4787 ArgumentPacks.push_back(Pack);
4788}
4789
4791 for (DeclArgumentPack *Pack : ArgumentPacks)
4792 if (llvm::is_contained(*Pack, D))
4793 return true;
4794 return false;
4795}
4796
4798 const TemplateArgument *ExplicitArgs,
4799 unsigned NumExplicitArgs) {
4800 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4801 "Already have a partially-substituted pack");
4802 assert((!PartiallySubstitutedPack
4803 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4804 "Wrong number of arguments in partially-substituted pack");
4805 PartiallySubstitutedPack = Pack;
4806 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4807 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4808}
4809
4811 const TemplateArgument **ExplicitArgs,
4812 unsigned *NumExplicitArgs) const {
4813 if (ExplicitArgs)
4814 *ExplicitArgs = nullptr;
4815 if (NumExplicitArgs)
4816 *NumExplicitArgs = 0;
4817
4818 for (const LocalInstantiationScope *Current = this; Current;
4819 Current = Current->Outer) {
4820 if (Current->PartiallySubstitutedPack) {
4821 if (ExplicitArgs)
4822 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4823 if (NumExplicitArgs)
4824 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4825
4826 return Current->PartiallySubstitutedPack;
4827 }
4828
4829 if (!Current->CombineWithOuterScope)
4830 break;
4831 }
4832
4833 return nullptr;
4834}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::Record Record
Definition MachO.h:31
static TemplateDeductionResult DeduceTemplateArguments(Sema &S, TemplateParameterList *TemplateParams, ArrayRef< TemplateArgument > Ps, ArrayRef< TemplateArgument > As, TemplateDeductionInfo &Info, SmallVectorImpl< DeducedTemplateArgument > &Deduced, bool NumberOfArgumentsMustMatch, bool PartialOrdering, PackFold PackFold, bool *HasDeducedAnyParam)
static bool PreparePackForExpansion(Sema &S, const CXXBaseSpecifier &Base, const MultiLevelTemplateArgumentList &TemplateArgs, TypeSourceInfo *&Out, UnexpandedInfo &Info)
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, Sema::EntityPrinter Printer)
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:220
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
The result of parsing/analyzing an expression, statement etc.
Definition Ownership.h:154
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:45
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:3972
Expr * getLHS() const
Definition Expr.h:4022
SourceLocation getOperatorLoc() const
Definition Expr.h:4014
Expr * getRHS() const
Definition Expr.h:4024
static BinaryOperator * Create(const ASTContext &C, Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy, ExprValueKind VK, ExprObjectKind OK, SourceLocation opLoc, FPOptionsOverride FPFeatures)
Definition Expr.cpp:4977
Opcode getOpcode() const
Definition Expr.h:4017
Represents a base class of a C++ class.
Definition DeclCXX.h:146
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition ExprCXX.h:1345
const ParmVarDecl * getParam() const
Definition ExprCXX.h:1313
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
Decl * getLambdaContextDecl() const
Retrieve the declaration that provides additional context for a lambda, when the normal declaration c...
Definition DeclCXX.cpp:1828
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
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:2020
base_class_range bases()
Definition DeclCXX.h:608
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition DeclCXX.h:1018
CXXRecordDecl * getDefinition() const
Definition DeclCXX.h:548
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:602
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition DeclCXX.cpp:2075
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition DeclCXX.h:522
Declaration of a class template.
ClassTemplateDecl * getMostRecentDecl()
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
NamedDecl * getFoundDecl() const
Definition ASTConcept.h:197
Represents the specialization of a concept - evaluates to a prvalue of type bool.
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
ConceptDecl * getNamedConcept() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:433
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:47
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
bool isFileContext() const
Definition DeclBase.h:2180
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
ValueDecl * getDecl()
Definition Expr.h:1338
SourceLocation getLocation() const
Definition Expr.h:1346
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition DeclBase.h:1061
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition DeclBase.cpp:285
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition DeclBase.h:1226
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition DeclBase.cpp:266
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
bool isFileContextDecl() const
Definition DeclBase.cpp:454
static Decl * castFromDeclContext(const DeclContext *)
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition DeclBase.cpp:320
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
bool isInvalidDecl() const
Definition DeclBase.h:588
SourceLocation getLocation() const
Definition DeclBase.h:439
void setLocation(SourceLocation L)
Definition DeclBase.h:440
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition DeclBase.h:949
DeclContext * getDeclContext()
Definition DeclBase.h:448
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition DeclBase.cpp:382
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition DeclBase.h:918
bool hasAttr() const
Definition DeclBase.h:577
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:870
The name of a declaration.
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition Decl.h:822
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4007
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4270
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5081
EnumDecl * getDefinition() const
Definition Decl.h:4110
This represents one expression.
Definition Expr.h:112
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition Expr.h:194
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition Expr.h:223
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:273
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
ExprDependence getDependence() const
Definition Expr.h:164
Represents difference between two FPOptions values.
Represents a member of a struct/union/class.
Definition Decl.h:3160
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4714
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Represents a function declaration or definition.
Definition Decl.h:2000
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
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:4253
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4302
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1816
ValueDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition ExprCXX.h:4884
ValueDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition ExprCXX.h:4876
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4869
iterator end() const
Definition ExprCXX.h:4878
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4881
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4872
iterator begin() const
Definition ExprCXX.h:4877
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5254
QualType desugar() const
Definition TypeBase.h:5835
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5543
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition TypeLoc.h:1678
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4476
QualType getReturnType() const
Definition TypeBase.h:4790
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:526
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 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:1970
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:369
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope=false, bool InstantiatingLambdaOrBlock=false)
Definition Template.h:437
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.
SmallVector< ValueDecl *, 4 > DeclArgumentPack
A set of declarations.
Definition Template.h:372
llvm::PointerUnion< Decl *, DeclArgumentPack * > * getInstantiationOfIfExists(const Decl *D)
Similar to findInstantiationOf(), but it wouldn't assert if the instantiation was not found within th...
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition Template.h:509
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
bool isLambdaOrBlock() const
Determine whether this scope is for instantiating a lambda or block.
Definition Template.h:575
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Provides information a specialization of a member of a class template, which may be a member function...
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Describes a module or submodule.
Definition Module.h:144
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:269
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:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
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:1834
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:1672
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getDepth() const
Get the nesting depth of the template parameter.
SourceLocation getEllipsisLoc() const
Definition TypeLoc.h:2600
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2616
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
SourceLocation getExplicitObjectParamThisLoc() const
Definition Decl.h:1886
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1931
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1919
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3036
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1923
bool hasInheritedDefaultArg() const
Definition Decl.h:1935
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
Expr * getDefaultArg()
Definition Decl.cpp:2999
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3041
unsigned getFunctionScopeDepth() const
Definition Decl.h:1840
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1939
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2040
SourceLocation getLocation() const
Definition Expr.h:2046
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition TypeBase.h:937
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition Type.cpp:3555
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
The collection of all-type qualifiers we support.
Definition TypeBase.h:331
void removeObjCLifetime()
Definition TypeBase.h:551
Represents a struct/union/class.
Definition Decl.h:4312
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Represents the body of a requires-expression.
Definition DeclCXX.h:2098
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
SourceLocation getLParenLoc() const
SourceLocation getRParenLoc() const
RequiresExprBodyDecl * getBody() const
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13588
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8407
A RAII object to temporarily push a declaration context.
Definition Sema.h:3467
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6327
DefaultedComparisonKind asComparison() const
Definition Sema.h:6359
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6356
A helper class for building up ExtParameterInfos.
Definition Sema.h:12958
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12395
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13538
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:13522
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12987
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
ExprResult SubstConceptTemplateArguments(const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr, const MultiLevelTemplateArgumentList &MLTAL)
Substitute concept template arguments in the constraint expression of a concept-id.
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2281
TemplateName SubstTemplateName(SourceLocation TemplateKWLoc, NestedNameSpecifierLoc &QualifierLoc, TemplateName Name, SourceLocation NameLoc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, UnsignedOrNone NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
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 ...
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition Sema.h:13907
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
bool SubstExprs(ArrayRef< Expr * > Exprs, bool IsCall, const MultiLevelTemplateArgumentList &TemplateArgs, SmallVectorImpl< Expr * > &Outputs)
Substitute the given template arguments into a list of expressions, expanding pack expansions if requ...
StmtResult SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & Context
Definition Sema.h:1283
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition Sema.h:13549
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void PrintInstantiationStack()
Definition Sema.h:13616
ASTContext & getASTContext() const
Definition Sema.h:925
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h:918
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
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 ...
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.
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11727
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
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)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:12999
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...
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1414
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition Sema.h:13956
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
bool CheckFunctionConstraints(const FunctionDecl *FD, ConstraintSatisfaction &Satisfaction, SourceLocation UsageLoc=SourceLocation(), bool ForOverloadResolution=false)
Check whether the given function decl's trailing requires clause is satisfied, if any.
bool CheckSpecializationInstantiationRedecl(SourceLocation NewLoc, TemplateSpecializationKind ActOnExplicitInstantiationNewTSK, NamedDecl *PrevDecl, TemplateSpecializationKind PrevTSK, SourceLocation PrevPtOfInstantiation, bool &SuppressNew)
Diagnose cases where we have an explicit template specialization before/after an explicit template in...
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition Sema.h:13558
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
bool inConstraintSubstitution() const
Determine whether we are currently performing constraint substitution.
Definition Sema.h:13896
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void DiagnoseAvailabilityOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass, bool ObjCPropertyAccess, bool AvoidPartialAvailabilityChecks, ObjCInterfaceDecl *ClassReceiver)
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, TemplateDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
std::pair< AvailabilityResult, const NamedDecl * > ShouldDiagnoseAvailabilityOfDecl(const NamedDecl *D, std::string *Message, ObjCInterfaceDecl *ClassReceiver)
The diagnostic we should emit for D, and the declaration that originated it, or AR_Available.
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
UnsignedOrNone ArgPackSubstIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition Sema.h:13582
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 SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
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:1284
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6702
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6712
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13566
bool inParameterMappingSubstitution() const
Definition Sema.h:13901
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8126
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8276
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true, bool *Unreachable=nullptr)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
DiagnosticsEngine & Diags
Definition Sema.h:1285
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
friend class InitializationSequence
Definition Sema.h:1556
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13533
ExprResult ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *DefaultArg, SourceLocation EqualLoc)
TemplateDeductionResult DeduceTemplateArguments(ClassTemplatePartialSpecializationDecl *Partial, ArrayRef< TemplateArgument > TemplateArgs, sema::TemplateDeductionInfo &Info)
void runWithSufficientStackSpace(SourceLocation Loc, llvm::function_ref< void()> Fn)
Run some code with "sufficient" stack space.
Definition Sema.cpp:626
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes)
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
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)
ExprResult SubstCXXIdExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
Substitute an expression as if it is a address-of-operand, which makes it act like a CXXIdExpression ...
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
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)
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ASTMutationListener * getASTMutationListener() const
Definition Sema.cpp:652
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8615
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.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getBegin() const
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:362
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
StmtClass getStmtClass() const
Definition Stmt.h:1472
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:338
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:350
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3717
void setTagKind(TagKind TK)
Definition Decl.h:3915
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4895
void setBraceRange(SourceRange R)
Definition Decl.h:3789
SourceLocation getNameLoc() const
Definition TypeLoc.h:822
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
ArrayRef< TemplateArgumentLoc > arguments() const
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Location wrapper for a TemplateArgument.
const TemplateArgument & getArgument() const
Represents a template argument.
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Expr * getAsExpr() const
Retrieve the template argument as an expression.
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
bool isConceptOrConceptTemplateParameter() const
QualType getAsType() const
Retrieve the type for a type template argument.
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
TemplateArgument getPackExpansionPattern() const
When the template argument is a pack expansion, returns the pattern of the pack expansion.
bool isNull() const
Determine whether this template argument has no value.
unsigned pack_size() const
The number of template arguments in the given template argument pack.
@ Template
The template argument is a template name that was provided for a template template parameter.
@ Pack
The template argument is actually a parameter pack.
@ Type
The template argument is a type.
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
ArgKind getKind() const
Return the kind of stored template argument.
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition Template.h:684
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition Template.h:687
The base class of all kinds of template declarations (e.g., class, function, etc.).
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Represents a C++ template name within the type system.
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
NameKind getKind() const
@ Template
A single template declaration.
SubstTemplateTemplateParmPackStorage * getAsSubstTemplateTemplateParmPack() const
Retrieve the substituted template template parameter pack, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
NamedDecl * getParam(unsigned Idx)
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation getTemplateLoc() const
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
TemplateTemplateParmDecl - Declares a template template parameter, e.g., "T" in.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Declaration of a template type parameter.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint, UnsignedOrNone ArgPackSubstIndex)
bool isParameterPack() const
Returns whether this is a parameter pack.
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
QualType TransformTemplateSpecializationType(TypeLocBuilder &TLB, TemplateSpecializationTypeLoc TL, QualType ObjectType, NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName)
Declaration of an alias template.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition ASTConcept.h:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:266
UnsignedOrNone getArgPackSubstIndex() const
Definition ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:276
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:280
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
void setLocStart(SourceLocation L)
Definition Decl.h:3548
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h:1408
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition TypeLoc.h:78
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition TypeLoc.h:154
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition TypeLoc.h:165
SourceLocation getBeginLoc() const
Get the begin source location.
Definition TypeLoc.cpp:193
A container of type source information.
Definition TypeBase.h:8249
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8260
SourceLocation getNameLoc() const
Definition TypeLoc.h:547
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8871
bool isReferenceType() const
Definition TypeBase.h:8539
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9091
bool isRecordType() const
Definition TypeBase.h:8642
QualType getUnderlyingType() const
Definition Decl.h:3617
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3392
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5513
Represents a variable declaration or definition.
Definition Decl.h:926
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition Decl.cpp:2907
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
const ReturnTypeRequirement & getReturnTypeRequirement() const
SourceLocation getNoexceptLoc() const
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
A static requirement that can be used in a requires-expression to check properties of types and expre...
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
TypeSourceInfo * getType() const
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
std::variant< struct RequiresDecl, struct HeaderDecl, struct UmbrellaDirDecl, struct ModuleDecl, struct ExcludeDecl, struct ExportDecl, struct ExportAsDecl, struct ExternModuleDecl, struct UseDecl, struct LinkDecl, struct ConfigMacrosDecl, struct ConflictDecl > Decl
All declarations that can appear in a module declaration.
Attr * instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
Attr * instantiateTemplateAttributeForDecl(const Attr *At, ASTContext &C, Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs)
The JSON file list parser is used to communicate input to InstallAPI.
void atTemplateEnd(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus11
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
Definition Template.h:50
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ TemplateName
The identifier is a template name. FIXME: Add an annotation for that.
Definition Parser.h:61
NamedDecl * getAsNamedDecl(TemplateParameter P)
@ OK_Ordinary
An ordinary object is located at an address in memory.
Definition Specifiers.h:151
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:236
bool isPackProducingBuiltinTemplateName(TemplateName N)
@ AS_public
Definition Specifiers.h:124
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition ASTLambda.h:89
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:905
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:562
@ AR_Available
Definition DeclBase.h:73
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
DynamicRecursiveASTVisitorBase< false > DynamicRecursiveASTVisitor
TemplateDeductionResult
Describes the result of template argument deduction.
Definition Sema.h:367
@ Success
Template argument deduction was successful.
Definition Sema.h:369
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5867
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
ActionResult< Stmt * > StmtResult
Definition Ownership.h:250
#define false
Definition stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
const TemplateArgumentLoc * getTemplateArgs() const
Retrieve the template arguments.
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
SourceLocation getLAngleLoc() const
ArrayRef< TemplateArgumentLoc > arguments() const
SourceLocation getRAngleLoc() const
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
DeclarationName getName() const
getName - Returns the embedded declaration name.
Holds information about the various types of exception specification.
Definition TypeBase.h:5311
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5313
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13035
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13205
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition Sema.h:13152
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13174
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition Sema.h:13200
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13161
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13037
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13129
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13047
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13056
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13075
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13126
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13083
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13090
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13133
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13101
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13139
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13066
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13145
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13142
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13148
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13063
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13071
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13079
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13040
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13093
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13097
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13052
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13123
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13086
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13164
bool isInstantiationRecord() const
Determines whether this template is an actual instantiation that should be counted toward the maximum...
A stack object to be created when performing template instantiation.
Definition Sema.h:13231
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13391
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation Ellipsis
UnsignedOrNone NumExpansions