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