clang 19.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
20#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Sema.h"
36#include "clang/Sema/Template.h"
39#include "llvm/ADT/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
466/// Retrieve the template argument list(s) that should be used to
467/// instantiate the definition of the given declaration.
468///
469/// \param ND the declaration for which we are computing template instantiation
470/// arguments.
471///
472/// \param DC In the event we don't HAVE a declaration yet, we instead provide
473/// the decl context where it will be created. In this case, the `Innermost`
474/// should likely be provided. If ND is non-null, this is ignored.
475///
476/// \param Innermost if non-NULL, specifies a template argument list for the
477/// template declaration passed as ND.
478///
479/// \param RelativeToPrimary true if we should get the template
480/// arguments relative to the primary template, even when we're
481/// dealing with a specialization. This is only relevant for function
482/// template specializations.
483///
484/// \param Pattern If non-NULL, indicates the pattern from which we will be
485/// instantiating the definition of the given declaration, \p ND. This is
486/// used to determine the proper set of template instantiation arguments for
487/// friend function template specializations.
488///
489/// \param ForConstraintInstantiation when collecting arguments,
490/// ForConstraintInstantiation indicates we should continue looking when
491/// encountering a lambda generic call operator, and continue looking for
492/// arguments on an enclosing class template.
493
495 const NamedDecl *ND, const DeclContext *DC, bool Final,
496 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
497 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
498 bool SkipForSpecialization) {
499 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
500 // Accumulate the set of template argument lists in this structure.
502
503 using namespace TemplateInstArgsHelpers;
504 const Decl *CurDecl = ND;
505
506 if (!CurDecl)
507 CurDecl = Decl::castFromDeclContext(DC);
508
509 if (Innermost) {
510 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
511 Final);
512 // Populate placeholder template arguments for TemplateTemplateParmDecls.
513 // This is essential for the case e.g.
514 //
515 // template <class> concept Concept = false;
516 // template <template <Concept C> class T> void foo(T<int>)
517 //
518 // where parameter C has a depth of 1 but the substituting argument `int`
519 // has a depth of 0.
520 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
521 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
522 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
523 }
524
525 while (!CurDecl->isFileContextDecl()) {
526 Response R;
527 if (const auto *VarTemplSpec =
528 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
529 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
530 } else if (const auto *PartialClassTemplSpec =
531 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
532 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
533 SkipForSpecialization);
534 } else if (const auto *ClassTemplSpec =
535 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
536 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
537 SkipForSpecialization);
538 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
539 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
540 ForConstraintInstantiation);
541 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
542 R = HandleRecordDecl(*this, Rec, Result, Context,
543 ForConstraintInstantiation);
544 } else if (const auto *CSD =
545 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
546 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
547 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
548 R = HandleFunctionTemplateDecl(FTD, Result);
549 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
550 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
551 } else if (!isa<DeclContext>(CurDecl)) {
552 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
553 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
554 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
555 }
556 } else {
557 R = HandleGenericDeclContext(CurDecl);
558 }
559
560 if (R.IsDone)
561 return Result;
562 if (R.ClearRelativeToPrimary)
563 RelativeToPrimary = false;
564 assert(R.NextDecl);
565 CurDecl = R.NextDecl;
566 }
567
568 return Result;
569}
570
572 switch (Kind) {
580 case ConstraintsCheck:
582 return true;
583
601 return false;
602
603 // This function should never be called when Kind's value is Memoization.
604 case Memoization:
605 break;
606 }
607
608 llvm_unreachable("Invalid SynthesisKind!");
609}
610
613 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
614 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
615 sema::TemplateDeductionInfo *DeductionInfo)
616 : SemaRef(SemaRef) {
617 // Don't allow further instantiation if a fatal error and an uncompilable
618 // error have occurred. Any diagnostics we might have raised will not be
619 // visible, and we do not need to construct a correct AST.
622 Invalid = true;
623 return;
624 }
625 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
626 if (!Invalid) {
628 Inst.Kind = Kind;
629 Inst.PointOfInstantiation = PointOfInstantiation;
630 Inst.Entity = Entity;
631 Inst.Template = Template;
632 Inst.TemplateArgs = TemplateArgs.data();
633 Inst.NumTemplateArgs = TemplateArgs.size();
634 Inst.DeductionInfo = DeductionInfo;
635 Inst.InstantiationRange = InstantiationRange;
637
638 AlreadyInstantiating = !Inst.Entity ? false :
640 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
641 .second;
643 }
644}
645
647 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
648 SourceRange InstantiationRange)
650 CodeSynthesisContext::TemplateInstantiation,
651 PointOfInstantiation, InstantiationRange, Entity) {}
652
654 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
655 ExceptionSpecification, SourceRange InstantiationRange)
657 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
658 PointOfInstantiation, InstantiationRange, Entity) {}
659
661 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
662 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
663 SourceRange InstantiationRange)
665 SemaRef,
666 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
667 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
668 Template, TemplateArgs) {}
669
671 Sema &SemaRef, SourceLocation PointOfInstantiation,
673 ArrayRef<TemplateArgument> TemplateArgs,
675 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
676 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
677 InstantiationRange, FunctionTemplate, nullptr,
678 TemplateArgs, &DeductionInfo) {
682}
683
685 Sema &SemaRef, SourceLocation PointOfInstantiation,
686 TemplateDecl *Template,
687 ArrayRef<TemplateArgument> TemplateArgs,
688 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
690 SemaRef,
691 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
692 PointOfInstantiation, InstantiationRange, Template, nullptr,
693 TemplateArgs, &DeductionInfo) {}
694
696 Sema &SemaRef, SourceLocation PointOfInstantiation,
698 ArrayRef<TemplateArgument> TemplateArgs,
699 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
701 SemaRef,
702 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
703 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
704 TemplateArgs, &DeductionInfo) {}
705
707 Sema &SemaRef, SourceLocation PointOfInstantiation,
709 ArrayRef<TemplateArgument> TemplateArgs,
710 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
712 SemaRef,
713 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
714 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
715 TemplateArgs, &DeductionInfo) {}
716
718 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
719 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
721 SemaRef,
722 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
723 PointOfInstantiation, InstantiationRange, Param, nullptr,
724 TemplateArgs) {}
725
727 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
729 SourceRange InstantiationRange)
731 SemaRef,
732 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
733 PointOfInstantiation, InstantiationRange, Param, Template,
734 TemplateArgs) {}
735
737 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
739 SourceRange InstantiationRange)
741 SemaRef,
742 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
743 PointOfInstantiation, InstantiationRange, Param, Template,
744 TemplateArgs) {}
745
747 Sema &SemaRef, SourceLocation PointOfInstantiation,
749 SourceRange InstantiationRange)
751 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
752 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
753 /*Template=*/nullptr, TemplateArgs) {}
754
756 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
757 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
758 SourceRange InstantiationRange)
760 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
761 PointOfInstantiation, InstantiationRange, Param, Template,
762 TemplateArgs) {}
763
765 Sema &SemaRef, SourceLocation PointOfInstantiation,
767 SourceRange InstantiationRange)
769 SemaRef, CodeSynthesisContext::RequirementInstantiation,
770 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
771 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
772}
773
775 Sema &SemaRef, SourceLocation PointOfInstantiation,
777 SourceRange InstantiationRange)
779 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
780 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
781 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
782
784 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
785 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
787 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
788 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
789 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
790}
791
793 Sema &SemaRef, SourceLocation PointOfInstantiation,
794 ConstraintsCheck, NamedDecl *Template,
795 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
798 PointOfInstantiation, InstantiationRange, Template, nullptr,
799 TemplateArgs) {}
800
802 Sema &SemaRef, SourceLocation PointOfInstantiation,
804 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
807 PointOfInstantiation, InstantiationRange, Template, nullptr,
808 {}, &DeductionInfo) {}
809
811 Sema &SemaRef, SourceLocation PointOfInstantiation,
813 SourceRange InstantiationRange)
816 PointOfInstantiation, InstantiationRange, Template) {}
817
819 Sema &SemaRef, SourceLocation PointOfInstantiation,
821 SourceRange InstantiationRange)
824 PointOfInstantiation, InstantiationRange, Template) {}
825
827 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
828 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
830 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
831 PointOfInstantiation, InstantiationRange, Entity) {}
832
833
837
838 CodeSynthesisContexts.push_back(Ctx);
839
840 if (!Ctx.isInstantiationRecord())
842
843 // Check to see if we're low on stack space. We can't do anything about this
844 // from here, but we can at least warn the user.
847}
848
850 auto &Active = CodeSynthesisContexts.back();
851 if (!Active.isInstantiationRecord()) {
852 assert(NonInstantiationEntries > 0);
854 }
855
856 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
857
858 // Name lookup no longer looks in this template's defining module.
859 assert(CodeSynthesisContexts.size() >=
861 "forgot to remove a lookup module for a template instantiation");
862 if (CodeSynthesisContexts.size() ==
865 LookupModulesCache.erase(M);
867 }
868
869 // If we've left the code synthesis context for the current context stack,
870 // stop remembering that we've emitted that stack.
871 if (CodeSynthesisContexts.size() ==
874
875 CodeSynthesisContexts.pop_back();
876}
877
879 if (!Invalid) {
880 if (!AlreadyInstantiating) {
881 auto &Active = SemaRef.CodeSynthesisContexts.back();
882 if (Active.Entity)
884 {Active.Entity->getCanonicalDecl(), Active.Kind});
885 }
886
889
891 Invalid = true;
892 }
893}
894
895static std::string convertCallArgsToString(Sema &S,
897 std::string Result;
898 llvm::raw_string_ostream OS(Result);
899 llvm::ListSeparator Comma;
900 for (const Expr *Arg : Args) {
901 OS << Comma;
902 Arg->IgnoreParens()->printPretty(OS, nullptr,
904 }
905 return Result;
906}
907
908bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
909 SourceLocation PointOfInstantiation,
910 SourceRange InstantiationRange) {
913 if ((SemaRef.CodeSynthesisContexts.size() -
915 <= SemaRef.getLangOpts().InstantiationDepth)
916 return false;
917
918 SemaRef.Diag(PointOfInstantiation,
919 diag::err_template_recursion_depth_exceeded)
920 << SemaRef.getLangOpts().InstantiationDepth
921 << InstantiationRange;
922 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
923 << SemaRef.getLangOpts().InstantiationDepth;
924 return true;
925}
926
927/// Prints the current instantiation stack through a series of
928/// notes.
930 // Determine which template instantiations to skip, if any.
931 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
932 unsigned Limit = Diags.getTemplateBacktraceLimit();
933 if (Limit && Limit < CodeSynthesisContexts.size()) {
934 SkipStart = Limit / 2 + Limit % 2;
935 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
936 }
937
938 // FIXME: In all of these cases, we need to show the template arguments
939 unsigned InstantiationIdx = 0;
941 Active = CodeSynthesisContexts.rbegin(),
942 ActiveEnd = CodeSynthesisContexts.rend();
943 Active != ActiveEnd;
944 ++Active, ++InstantiationIdx) {
945 // Skip this instantiation?
946 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
947 if (InstantiationIdx == SkipStart) {
948 // Note that we're skipping instantiations.
949 Diags.Report(Active->PointOfInstantiation,
950 diag::note_instantiation_contexts_suppressed)
951 << unsigned(CodeSynthesisContexts.size() - Limit);
952 }
953 continue;
954 }
955
956 switch (Active->Kind) {
958 Decl *D = Active->Entity;
959 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
960 unsigned DiagID = diag::note_template_member_class_here;
961 if (isa<ClassTemplateSpecializationDecl>(Record))
962 DiagID = diag::note_template_class_instantiation_here;
963 Diags.Report(Active->PointOfInstantiation, DiagID)
964 << Record << Active->InstantiationRange;
965 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
966 unsigned DiagID;
967 if (Function->getPrimaryTemplate())
968 DiagID = diag::note_function_template_spec_here;
969 else
970 DiagID = diag::note_template_member_function_here;
971 Diags.Report(Active->PointOfInstantiation, DiagID)
972 << Function
973 << Active->InstantiationRange;
974 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
975 Diags.Report(Active->PointOfInstantiation,
976 VD->isStaticDataMember()?
977 diag::note_template_static_data_member_def_here
978 : diag::note_template_variable_def_here)
979 << VD
980 << Active->InstantiationRange;
981 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
982 Diags.Report(Active->PointOfInstantiation,
983 diag::note_template_enum_def_here)
984 << ED
985 << Active->InstantiationRange;
986 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
987 Diags.Report(Active->PointOfInstantiation,
988 diag::note_template_nsdmi_here)
989 << FD << Active->InstantiationRange;
990 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
991 Diags.Report(Active->PointOfInstantiation,
992 diag::note_template_class_instantiation_here)
993 << CTD << Active->InstantiationRange;
994 }
995 break;
996 }
997
999 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
1000 SmallString<128> TemplateArgsStr;
1001 llvm::raw_svector_ostream OS(TemplateArgsStr);
1002 Template->printName(OS, getPrintingPolicy());
1003 printTemplateArgumentList(OS, Active->template_arguments(),
1005 Diags.Report(Active->PointOfInstantiation,
1006 diag::note_default_arg_instantiation_here)
1007 << OS.str()
1008 << Active->InstantiationRange;
1009 break;
1010 }
1011
1013 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1014 Diags.Report(Active->PointOfInstantiation,
1015 diag::note_explicit_template_arg_substitution_here)
1016 << FnTmpl
1018 Active->TemplateArgs,
1019 Active->NumTemplateArgs)
1020 << Active->InstantiationRange;
1021 break;
1022 }
1023
1025 if (FunctionTemplateDecl *FnTmpl =
1026 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1027 Diags.Report(Active->PointOfInstantiation,
1028 diag::note_function_template_deduction_instantiation_here)
1029 << FnTmpl
1030 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1031 Active->TemplateArgs,
1032 Active->NumTemplateArgs)
1033 << Active->InstantiationRange;
1034 } else {
1035 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1036 isa<VarTemplateSpecializationDecl>(Active->Entity);
1037 bool IsTemplate = false;
1038 TemplateParameterList *Params;
1039 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1040 IsTemplate = true;
1041 Params = D->getTemplateParameters();
1042 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1043 Active->Entity)) {
1044 Params = D->getTemplateParameters();
1045 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1046 Active->Entity)) {
1047 Params = D->getTemplateParameters();
1048 } else {
1049 llvm_unreachable("unexpected template kind");
1050 }
1051
1052 Diags.Report(Active->PointOfInstantiation,
1053 diag::note_deduced_template_arg_substitution_here)
1054 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1055 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1056 Active->NumTemplateArgs)
1057 << Active->InstantiationRange;
1058 }
1059 break;
1060 }
1061
1063 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1064 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1065
1066 SmallString<128> TemplateArgsStr;
1067 llvm::raw_svector_ostream OS(TemplateArgsStr);
1069 printTemplateArgumentList(OS, Active->template_arguments(),
1071 Diags.Report(Active->PointOfInstantiation,
1072 diag::note_default_function_arg_instantiation_here)
1073 << OS.str()
1074 << Active->InstantiationRange;
1075 break;
1076 }
1077
1079 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1080 std::string Name;
1081 if (!Parm->getName().empty())
1082 Name = std::string(" '") + Parm->getName().str() + "'";
1083
1084 TemplateParameterList *TemplateParams = nullptr;
1085 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1086 TemplateParams = Template->getTemplateParameters();
1087 else
1088 TemplateParams =
1089 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1090 ->getTemplateParameters();
1091 Diags.Report(Active->PointOfInstantiation,
1092 diag::note_prior_template_arg_substitution)
1093 << isa<TemplateTemplateParmDecl>(Parm)
1094 << Name
1095 << getTemplateArgumentBindingsText(TemplateParams,
1096 Active->TemplateArgs,
1097 Active->NumTemplateArgs)
1098 << Active->InstantiationRange;
1099 break;
1100 }
1101
1103 TemplateParameterList *TemplateParams = nullptr;
1104 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1105 TemplateParams = Template->getTemplateParameters();
1106 else
1107 TemplateParams =
1108 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1109 ->getTemplateParameters();
1110
1111 Diags.Report(Active->PointOfInstantiation,
1112 diag::note_template_default_arg_checking)
1113 << getTemplateArgumentBindingsText(TemplateParams,
1114 Active->TemplateArgs,
1115 Active->NumTemplateArgs)
1116 << Active->InstantiationRange;
1117 break;
1118 }
1119
1121 Diags.Report(Active->PointOfInstantiation,
1122 diag::note_evaluating_exception_spec_here)
1123 << cast<FunctionDecl>(Active->Entity);
1124 break;
1125
1127 Diags.Report(Active->PointOfInstantiation,
1128 diag::note_template_exception_spec_instantiation_here)
1129 << cast<FunctionDecl>(Active->Entity)
1130 << Active->InstantiationRange;
1131 break;
1132
1134 Diags.Report(Active->PointOfInstantiation,
1135 diag::note_template_requirement_instantiation_here)
1136 << Active->InstantiationRange;
1137 break;
1139 Diags.Report(Active->PointOfInstantiation,
1140 diag::note_template_requirement_params_instantiation_here)
1141 << Active->InstantiationRange;
1142 break;
1143
1145 Diags.Report(Active->PointOfInstantiation,
1146 diag::note_nested_requirement_here)
1147 << Active->InstantiationRange;
1148 break;
1149
1151 Diags.Report(Active->PointOfInstantiation,
1152 diag::note_in_declaration_of_implicit_special_member)
1153 << cast<CXXRecordDecl>(Active->Entity)
1154 << llvm::to_underlying(Active->SpecialMember);
1155 break;
1156
1158 Diags.Report(Active->Entity->getLocation(),
1159 diag::note_in_declaration_of_implicit_equality_comparison);
1160 break;
1161
1163 // FIXME: For synthesized functions that are not defaulted,
1164 // produce a note.
1165 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1168 if (DFK.isSpecialMember()) {
1169 auto *MD = cast<CXXMethodDecl>(FD);
1170 Diags.Report(Active->PointOfInstantiation,
1171 diag::note_member_synthesized_at)
1172 << MD->isExplicitlyDefaulted()
1173 << llvm::to_underlying(DFK.asSpecialMember())
1174 << Context.getTagDeclType(MD->getParent());
1175 } else if (DFK.isComparison()) {
1176 QualType RecordType = FD->getParamDecl(0)
1177 ->getType()
1178 .getNonReferenceType()
1179 .getUnqualifiedType();
1180 Diags.Report(Active->PointOfInstantiation,
1181 diag::note_comparison_synthesized_at)
1182 << (int)DFK.asComparison() << RecordType;
1183 }
1184 break;
1185 }
1186
1188 Diags.Report(Active->Entity->getLocation(),
1189 diag::note_rewriting_operator_as_spaceship);
1190 break;
1191
1193 Diags.Report(Active->PointOfInstantiation,
1194 diag::note_in_binding_decl_init)
1195 << cast<BindingDecl>(Active->Entity);
1196 break;
1197
1199 Diags.Report(Active->PointOfInstantiation,
1200 diag::note_due_to_dllexported_class)
1201 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1202 break;
1203
1205 Diags.Report(Active->PointOfInstantiation,
1206 diag::note_building_builtin_dump_struct_call)
1208 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1209 break;
1210
1212 break;
1213
1215 Diags.Report(Active->PointOfInstantiation,
1216 diag::note_lambda_substitution_here);
1217 break;
1219 unsigned DiagID = 0;
1220 if (!Active->Entity) {
1221 Diags.Report(Active->PointOfInstantiation,
1222 diag::note_nested_requirement_here)
1223 << Active->InstantiationRange;
1224 break;
1225 }
1226 if (isa<ConceptDecl>(Active->Entity))
1227 DiagID = diag::note_concept_specialization_here;
1228 else if (isa<TemplateDecl>(Active->Entity))
1229 DiagID = diag::note_checking_constraints_for_template_id_here;
1230 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1231 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1232 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1233 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1234 else {
1235 assert(isa<FunctionDecl>(Active->Entity));
1236 DiagID = diag::note_checking_constraints_for_function_here;
1237 }
1238 SmallString<128> TemplateArgsStr;
1239 llvm::raw_svector_ostream OS(TemplateArgsStr);
1240 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1241 if (!isa<FunctionDecl>(Active->Entity)) {
1242 printTemplateArgumentList(OS, Active->template_arguments(),
1244 }
1245 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1246 << Active->InstantiationRange;
1247 break;
1248 }
1250 Diags.Report(Active->PointOfInstantiation,
1251 diag::note_constraint_substitution_here)
1252 << Active->InstantiationRange;
1253 break;
1255 Diags.Report(Active->PointOfInstantiation,
1256 diag::note_constraint_normalization_here)
1257 << cast<NamedDecl>(Active->Entity)->getName()
1258 << Active->InstantiationRange;
1259 break;
1261 Diags.Report(Active->PointOfInstantiation,
1262 diag::note_parameter_mapping_substitution_here)
1263 << Active->InstantiationRange;
1264 break;
1266 Diags.Report(Active->PointOfInstantiation,
1267 diag::note_building_deduction_guide_here);
1268 break;
1270 Diags.Report(Active->PointOfInstantiation,
1271 diag::note_template_type_alias_instantiation_here)
1272 << cast<TypeAliasTemplateDecl>(Active->Entity)
1273 << Active->InstantiationRange;
1274 break;
1275 }
1276 }
1277}
1278
1279std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1281 return std::optional<TemplateDeductionInfo *>(nullptr);
1282
1284 Active = CodeSynthesisContexts.rbegin(),
1285 ActiveEnd = CodeSynthesisContexts.rend();
1286 Active != ActiveEnd;
1287 ++Active)
1288 {
1289 switch (Active->Kind) {
1291 // An instantiation of an alias template may or may not be a SFINAE
1292 // context, depending on what else is on the stack.
1293 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1294 break;
1295 [[fallthrough]];
1303 // This is a template instantiation, so there is no SFINAE.
1304 return std::nullopt;
1306 // [temp.deduct]p9
1307 // A lambda-expression appearing in a function type or a template
1308 // parameter is not considered part of the immediate context for the
1309 // purposes of template argument deduction.
1310 // CWG2672: A lambda-expression body is never in the immediate context.
1311 return std::nullopt;
1312
1317 // A default template argument instantiation and substitution into
1318 // template parameters with arguments for prior parameters may or may
1319 // not be a SFINAE context; look further up the stack.
1320 break;
1321
1324 // We're either substituting explicitly-specified template arguments,
1325 // deduced template arguments. SFINAE applies unless we are in a lambda
1326 // body, see [temp.deduct]p9.
1330 // SFINAE always applies in a constraint expression or a requirement
1331 // in a requires expression.
1332 assert(Active->DeductionInfo && "Missing deduction info pointer");
1333 return Active->DeductionInfo;
1334
1342 // This happens in a context unrelated to template instantiation, so
1343 // there is no SFINAE.
1344 return std::nullopt;
1345
1347 // FIXME: This should not be treated as a SFINAE context, because
1348 // we will cache an incorrect exception specification. However, clang
1349 // bootstrap relies this! See PR31692.
1350 break;
1351
1353 break;
1354 }
1355
1356 // The inner context was transparent for SFINAE. If it occurred within a
1357 // non-instantiation SFINAE context, then SFINAE applies.
1358 if (Active->SavedInNonInstantiationSFINAEContext)
1359 return std::optional<TemplateDeductionInfo *>(nullptr);
1360 }
1361
1362 return std::nullopt;
1363}
1364
1365//===----------------------------------------------------------------------===/
1366// Template Instantiation for Types
1367//===----------------------------------------------------------------------===/
1368namespace {
1369 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1370 const MultiLevelTemplateArgumentList &TemplateArgs;
1372 DeclarationName Entity;
1373 // Whether to evaluate the C++20 constraints or simply substitute into them.
1374 bool EvaluateConstraints = true;
1375
1376 public:
1377 typedef TreeTransform<TemplateInstantiator> inherited;
1378
1379 TemplateInstantiator(Sema &SemaRef,
1380 const MultiLevelTemplateArgumentList &TemplateArgs,
1382 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1383 Entity(Entity) {}
1384
1385 void setEvaluateConstraints(bool B) {
1386 EvaluateConstraints = B;
1387 }
1388 bool getEvaluateConstraints() {
1389 return EvaluateConstraints;
1390 }
1391
1392 /// Determine whether the given type \p T has already been
1393 /// transformed.
1394 ///
1395 /// For the purposes of template instantiation, a type has already been
1396 /// transformed if it is NULL or if it is not dependent.
1397 bool AlreadyTransformed(QualType T);
1398
1399 /// Returns the location of the entity being instantiated, if known.
1400 SourceLocation getBaseLocation() { return Loc; }
1401
1402 /// Returns the name of the entity being instantiated, if any.
1403 DeclarationName getBaseEntity() { return Entity; }
1404
1405 /// Sets the "base" location and entity when that
1406 /// information is known based on another transformation.
1407 void setBase(SourceLocation Loc, DeclarationName Entity) {
1408 this->Loc = Loc;
1409 this->Entity = Entity;
1410 }
1411
1412 unsigned TransformTemplateDepth(unsigned Depth) {
1413 return TemplateArgs.getNewDepth(Depth);
1414 }
1415
1416 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1417 int Index = getSema().ArgumentPackSubstitutionIndex;
1418 if (Index == -1)
1419 return std::nullopt;
1420 return Pack.pack_size() - 1 - Index;
1421 }
1422
1423 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1424 SourceRange PatternRange,
1426 bool &ShouldExpand, bool &RetainExpansion,
1427 std::optional<unsigned> &NumExpansions) {
1428 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1429 PatternRange, Unexpanded,
1430 TemplateArgs,
1431 ShouldExpand,
1432 RetainExpansion,
1433 NumExpansions);
1434 }
1435
1436 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1438 }
1439
1440 TemplateArgument ForgetPartiallySubstitutedPack() {
1441 TemplateArgument Result;
1442 if (NamedDecl *PartialPack
1444 MultiLevelTemplateArgumentList &TemplateArgs
1445 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1446 unsigned Depth, Index;
1447 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1448 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1449 Result = TemplateArgs(Depth, Index);
1450 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1451 }
1452 }
1453
1454 return Result;
1455 }
1456
1457 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1458 if (Arg.isNull())
1459 return;
1460
1461 if (NamedDecl *PartialPack
1463 MultiLevelTemplateArgumentList &TemplateArgs
1464 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1465 unsigned Depth, Index;
1466 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1467 TemplateArgs.setArgument(Depth, Index, Arg);
1468 }
1469 }
1470
1471 /// Transform the given declaration by instantiating a reference to
1472 /// this declaration.
1473 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1474
1475 void transformAttrs(Decl *Old, Decl *New) {
1476 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1477 }
1478
1479 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1480 if (Old->isParameterPack()) {
1482 for (auto *New : NewDecls)
1484 Old, cast<VarDecl>(New));
1485 return;
1486 }
1487
1488 assert(NewDecls.size() == 1 &&
1489 "should only have multiple expansions for a pack");
1490 Decl *New = NewDecls.front();
1491
1492 // If we've instantiated the call operator of a lambda or the call
1493 // operator template of a generic lambda, update the "instantiation of"
1494 // information.
1495 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1496 if (NewMD && isLambdaCallOperator(NewMD)) {
1497 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1498 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1499 NewTD->setInstantiatedFromMemberTemplate(
1500 OldMD->getDescribedFunctionTemplate());
1501 else
1502 NewMD->setInstantiationOfMemberFunction(OldMD,
1504 }
1505
1507
1508 // We recreated a local declaration, but not by instantiating it. There
1509 // may be pending dependent diagnostics to produce.
1510 if (auto *DC = dyn_cast<DeclContext>(Old);
1511 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1512 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1513 }
1514
1515 /// Transform the definition of the given declaration by
1516 /// instantiating it.
1517 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1518
1519 /// Transform the first qualifier within a scope by instantiating the
1520 /// declaration.
1521 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1522
1523 bool TransformExceptionSpec(SourceLocation Loc,
1525 SmallVectorImpl<QualType> &Exceptions,
1526 bool &Changed);
1527
1528 /// Rebuild the exception declaration and register the declaration
1529 /// as an instantiated local.
1530 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1532 SourceLocation StartLoc,
1533 SourceLocation NameLoc,
1534 IdentifierInfo *Name);
1535
1536 /// Rebuild the Objective-C exception declaration and register the
1537 /// declaration as an instantiated local.
1538 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1539 TypeSourceInfo *TSInfo, QualType T);
1540
1541 /// Check for tag mismatches when instantiating an
1542 /// elaborated type.
1543 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1544 ElaboratedTypeKeyword Keyword,
1545 NestedNameSpecifierLoc QualifierLoc,
1546 QualType T);
1547
1549 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1550 SourceLocation NameLoc,
1551 QualType ObjectType = QualType(),
1552 NamedDecl *FirstQualifierInScope = nullptr,
1553 bool AllowInjectedClassName = false);
1554
1555 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1556 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1557 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1558 const Stmt *InstS,
1559 const NoInlineAttr *A);
1560 const AlwaysInlineAttr *
1561 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1562 const AlwaysInlineAttr *A);
1563 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1564 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1565 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1566 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1567
1568 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1570 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1572 ExprResult TransformSubstNonTypeTemplateParmExpr(
1574
1575 /// Rebuild a DeclRefExpr for a VarDecl reference.
1576 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1577
1578 /// Transform a reference to a function or init-capture parameter pack.
1579 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1580
1581 /// Transform a FunctionParmPackExpr which was built when we couldn't
1582 /// expand a function parameter pack reference which refers to an expanded
1583 /// pack.
1584 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1585
1586 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1588 // Call the base version; it will forward to our overridden version below.
1589 return inherited::TransformFunctionProtoType(TLB, TL);
1590 }
1591
1592 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1594 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1595 // Special case for transforming a deduction guide, we return a
1596 // transformed TemplateSpecializationType.
1597 if (Type.isNull() &&
1598 SemaRef.CodeSynthesisContexts.back().Kind ==
1600 // Return a TemplateSpecializationType for transforming a deduction
1601 // guide.
1602 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1603 auto Type =
1604 inherited::TransformType(ICT->getInjectedSpecializationType());
1605 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1606 return Type;
1607 }
1608 }
1609 return Type;
1610 }
1611 // Override the default version to handle a rewrite-template-arg-pack case
1612 // for building a deduction guide.
1613 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1614 TemplateArgumentLoc &Output,
1615 bool Uneval = false) {
1616 const TemplateArgument &Arg = Input.getArgument();
1617 std::vector<TemplateArgument> TArgs;
1618 switch (Arg.getKind()) {
1620 // Literally rewrite the template argument pack, instead of unpacking
1621 // it.
1622 assert(
1623 SemaRef.CodeSynthesisContexts.back().Kind ==
1625 "Transforming a template argument pack is only allowed in building "
1626 "deduction guide");
1627 for (auto &pack : Arg.getPackAsArray()) {
1629 pack, QualType(), SourceLocation{});
1630 TemplateArgumentLoc Output;
1631 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1632 return true; // fails
1633 TArgs.push_back(Output.getArgument());
1634 }
1635 Output = SemaRef.getTrivialTemplateArgumentLoc(
1636 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1638 return false;
1639 default:
1640 break;
1641 }
1642 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1643 }
1644
1645 template<typename Fn>
1646 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1648 CXXRecordDecl *ThisContext,
1649 Qualifiers ThisTypeQuals,
1650 Fn TransformExceptionSpec);
1651
1652 ParmVarDecl *
1653 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1654 std::optional<unsigned> NumExpansions,
1655 bool ExpectParameterPack);
1656
1657 using inherited::TransformTemplateTypeParmType;
1658 /// Transforms a template type parameter type by performing
1659 /// substitution of the corresponding template type argument.
1660 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1662 bool SuppressObjCLifetime);
1663
1664 QualType BuildSubstTemplateTypeParmType(
1665 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1666 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1667 TemplateArgument Arg, SourceLocation NameLoc);
1668
1669 /// Transforms an already-substituted template type parameter pack
1670 /// into either itself (if we aren't substituting into its pack expansion)
1671 /// or the appropriate substituted argument.
1672 using inherited::TransformSubstTemplateTypeParmPackType;
1673 QualType
1674 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1676 bool SuppressObjCLifetime);
1677
1679 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1680 auto &CCS = SemaRef.CodeSynthesisContexts.back();
1681 if (CCS.Kind ==
1683 unsigned TypeAliasDeclDepth = CCS.Entity->getTemplateDepth();
1684 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1685 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1686 }
1687 return inherited::ComputeLambdaDependency(LSI);
1688 }
1689
1690 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1691 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1693
1694 ExprResult Result = inherited::TransformLambdaExpr(E);
1695 if (Result.isInvalid())
1696 return Result;
1697
1698 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1699 for (ParmVarDecl *PVD : MD->parameters()) {
1700 assert(PVD && "null in a parameter list");
1701 if (!PVD->hasDefaultArg())
1702 continue;
1703 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1704 // FIXME: Obtain the source location for the '=' token.
1705 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1706 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1707 // If substitution fails, the default argument is set to a
1708 // RecoveryExpr that wraps the uninstantiated default argument so
1709 // that downstream diagnostics are omitted.
1710 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1711 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1712 { UninstExpr }, UninstExpr->getType());
1713 if (ErrorResult.isUsable())
1714 PVD->setDefaultArg(ErrorResult.get());
1715 }
1716 }
1717
1718 return Result;
1719 }
1720
1721 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1722 // Currently, we instantiate the body when instantiating the lambda
1723 // expression. However, `EvaluateConstraints` is disabled during the
1724 // instantiation of the lambda expression, causing the instantiation
1725 // failure of the return type requirement in the body. If p0588r1 is fully
1726 // implemented, the body will be lazily instantiated, and this problem
1727 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1728 // `true` to temporarily fix this issue.
1729 // FIXME: This temporary fix can be removed after fully implementing
1730 // p0588r1.
1731 bool Prev = EvaluateConstraints;
1732 EvaluateConstraints = true;
1733 StmtResult Stmt = inherited::TransformLambdaBody(E, Body);
1734 EvaluateConstraints = Prev;
1735 return Stmt;
1736 }
1737
1738 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1739 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1740 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1741 if (TransReq.isInvalid())
1742 return TransReq;
1743 assert(TransReq.get() != E &&
1744 "Do not change value of isSatisfied for the existing expression. "
1745 "Create a new expression instead.");
1746 if (E->getBody()->isDependentContext()) {
1747 Sema::SFINAETrap Trap(SemaRef);
1748 // We recreate the RequiresExpr body, but not by instantiating it.
1749 // Produce pending diagnostics for dependent access check.
1750 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1751 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1752 if (Trap.hasErrorOccurred())
1753 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1754 }
1755 return TransReq;
1756 }
1757
1758 bool TransformRequiresExprRequirements(
1761 bool SatisfactionDetermined = false;
1762 for (concepts::Requirement *Req : Reqs) {
1763 concepts::Requirement *TransReq = nullptr;
1764 if (!SatisfactionDetermined) {
1765 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1766 TransReq = TransformTypeRequirement(TypeReq);
1767 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1768 TransReq = TransformExprRequirement(ExprReq);
1769 else
1770 TransReq = TransformNestedRequirement(
1771 cast<concepts::NestedRequirement>(Req));
1772 if (!TransReq)
1773 return true;
1774 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1775 // [expr.prim.req]p6
1776 // [...] The substitution and semantic constraint checking
1777 // proceeds in lexical order and stops when a condition that
1778 // determines the result of the requires-expression is
1779 // encountered. [..]
1780 SatisfactionDetermined = true;
1781 } else
1782 TransReq = Req;
1783 Transformed.push_back(TransReq);
1784 }
1785 return false;
1786 }
1787
1788 TemplateParameterList *TransformTemplateParameterList(
1789 TemplateParameterList *OrigTPL) {
1790 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1791
1792 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1793 TemplateDeclInstantiator DeclInstantiator(getSema(),
1794 /* DeclContext *Owner */ Owner, TemplateArgs);
1795 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1796 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1797 }
1798
1800 TransformTypeRequirement(concepts::TypeRequirement *Req);
1802 TransformExprRequirement(concepts::ExprRequirement *Req);
1804 TransformNestedRequirement(concepts::NestedRequirement *Req);
1805 ExprResult TransformRequiresTypeParams(
1806 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1809 SmallVectorImpl<ParmVarDecl *> &TransParams,
1811
1812 private:
1814 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1815 const NonTypeTemplateParmDecl *parm,
1817 std::optional<unsigned> PackIndex);
1818 };
1819}
1820
1821bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1822 if (T.isNull())
1823 return true;
1824
1826 return false;
1827
1828 getSema().MarkDeclarationsReferencedInType(Loc, T);
1829 return true;
1830}
1831
1832static TemplateArgument
1834 assert(S.ArgumentPackSubstitutionIndex >= 0);
1835 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1837 if (Arg.isPackExpansion())
1838 Arg = Arg.getPackExpansionPattern();
1839 return Arg;
1840}
1841
1842Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1843 if (!D)
1844 return nullptr;
1845
1846 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1847 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1848 // If the corresponding template argument is NULL or non-existent, it's
1849 // because we are performing instantiation from explicitly-specified
1850 // template arguments in a function template, but there were some
1851 // arguments left unspecified.
1852 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1853 TTP->getPosition()))
1854 return D;
1855
1856 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1857
1858 if (TTP->isParameterPack()) {
1859 assert(Arg.getKind() == TemplateArgument::Pack &&
1860 "Missing argument pack");
1861 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1862 }
1863
1865 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1866 "Wrong kind of template template argument");
1867 return Template.getAsTemplateDecl();
1868 }
1869
1870 // Fall through to find the instantiated declaration for this template
1871 // template parameter.
1872 }
1873
1874 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1875}
1876
1877Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1878 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1879 if (!Inst)
1880 return nullptr;
1881
1882 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1883 return Inst;
1884}
1885
1886bool TemplateInstantiator::TransformExceptionSpec(
1888 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1889 if (ESI.Type == EST_Uninstantiated) {
1890 ESI.instantiate();
1891 Changed = true;
1892 }
1893 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1894}
1895
1896NamedDecl *
1897TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1899 // If the first part of the nested-name-specifier was a template type
1900 // parameter, instantiate that type parameter down to a tag type.
1901 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1902 const TemplateTypeParmType *TTP
1903 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1904
1905 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1906 // FIXME: This needs testing w/ member access expressions.
1907 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1908
1909 if (TTP->isParameterPack()) {
1910 assert(Arg.getKind() == TemplateArgument::Pack &&
1911 "Missing argument pack");
1912
1913 if (getSema().ArgumentPackSubstitutionIndex == -1)
1914 return nullptr;
1915
1916 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1917 }
1918
1919 QualType T = Arg.getAsType();
1920 if (T.isNull())
1921 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1922
1923 if (const TagType *Tag = T->getAs<TagType>())
1924 return Tag->getDecl();
1925
1926 // The resulting type is not a tag; complain.
1927 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1928 return nullptr;
1929 }
1930 }
1931
1932 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1933}
1934
1935VarDecl *
1936TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1938 SourceLocation StartLoc,
1939 SourceLocation NameLoc,
1940 IdentifierInfo *Name) {
1941 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1942 StartLoc, NameLoc, Name);
1943 if (Var)
1944 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1945 return Var;
1946}
1947
1948VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1949 TypeSourceInfo *TSInfo,
1950 QualType T) {
1951 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1952 if (Var)
1953 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1954 return Var;
1955}
1956
1958TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1959 ElaboratedTypeKeyword Keyword,
1960 NestedNameSpecifierLoc QualifierLoc,
1961 QualType T) {
1962 if (const TagType *TT = T->getAs<TagType>()) {
1963 TagDecl* TD = TT->getDecl();
1964
1965 SourceLocation TagLocation = KeywordLoc;
1966
1968
1969 // TODO: should we even warn on struct/class mismatches for this? Seems
1970 // like it's likely to produce a lot of spurious errors.
1971 if (Id && Keyword != ElaboratedTypeKeyword::None &&
1974 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1975 TagLocation, Id)) {
1976 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1977 << Id
1979 TD->getKindName());
1980 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1981 }
1982 }
1983 }
1984
1985 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1986}
1987
1988TemplateName TemplateInstantiator::TransformTemplateName(
1989 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1990 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1991 bool AllowInjectedClassName) {
1993 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1994 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1995 // If the corresponding template argument is NULL or non-existent, it's
1996 // because we are performing instantiation from explicitly-specified
1997 // template arguments in a function template, but there were some
1998 // arguments left unspecified.
1999 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2000 TTP->getPosition()))
2001 return Name;
2002
2003 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2004
2005 if (TemplateArgs.isRewrite()) {
2006 // We're rewriting the template parameter as a reference to another
2007 // template parameter.
2008 if (Arg.getKind() == TemplateArgument::Pack) {
2009 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2010 "unexpected pack arguments in template rewrite");
2011 Arg = Arg.pack_begin()->getPackExpansionPattern();
2012 }
2013 assert(Arg.getKind() == TemplateArgument::Template &&
2014 "unexpected nontype template argument kind in template rewrite");
2015 return Arg.getAsTemplate();
2016 }
2017
2018 auto [AssociatedDecl, Final] =
2019 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2020 std::optional<unsigned> PackIndex;
2021 if (TTP->isParameterPack()) {
2022 assert(Arg.getKind() == TemplateArgument::Pack &&
2023 "Missing argument pack");
2024
2025 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2026 // We have the template argument pack to substitute, but we're not
2027 // actually expanding the enclosing pack expansion yet. So, just
2028 // keep the entire argument pack.
2029 return getSema().Context.getSubstTemplateTemplateParmPack(
2030 Arg, AssociatedDecl, TTP->getIndex(), Final);
2031 }
2032
2033 PackIndex = getPackIndex(Arg);
2034 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2035 }
2036
2038 assert(!Template.isNull() && "Null template template argument");
2039 assert(!Template.getAsQualifiedTemplateName() &&
2040 "template decl to substitute is qualified?");
2041
2042 if (Final)
2043 return Template;
2044 return getSema().Context.getSubstTemplateTemplateParm(
2045 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2046 }
2047 }
2048
2050 = Name.getAsSubstTemplateTemplateParmPack()) {
2051 if (getSema().ArgumentPackSubstitutionIndex == -1)
2052 return Name;
2053
2054 TemplateArgument Pack = SubstPack->getArgumentPack();
2055 TemplateName Template =
2057 if (SubstPack->getFinal())
2058 return Template;
2059 return getSema().Context.getSubstTemplateTemplateParm(
2060 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
2061 SubstPack->getIndex(), getPackIndex(Pack));
2062 }
2063
2064 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2065 FirstQualifierInScope,
2066 AllowInjectedClassName);
2067}
2068
2070TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2071 if (!E->isTypeDependent())
2072 return E;
2073
2074 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2075}
2076
2078TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2080 // If the corresponding template argument is NULL or non-existent, it's
2081 // because we are performing instantiation from explicitly-specified
2082 // template arguments in a function template, but there were some
2083 // arguments left unspecified.
2084 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2085 NTTP->getPosition()))
2086 return E;
2087
2088 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2089
2090 if (TemplateArgs.isRewrite()) {
2091 // We're rewriting the template parameter as a reference to another
2092 // template parameter.
2093 if (Arg.getKind() == TemplateArgument::Pack) {
2094 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2095 "unexpected pack arguments in template rewrite");
2096 Arg = Arg.pack_begin()->getPackExpansionPattern();
2097 }
2098 assert(Arg.getKind() == TemplateArgument::Expression &&
2099 "unexpected nontype template argument kind in template rewrite");
2100 // FIXME: This can lead to the same subexpression appearing multiple times
2101 // in a complete expression.
2102 return Arg.getAsExpr();
2103 }
2104
2105 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2106 std::optional<unsigned> PackIndex;
2107 if (NTTP->isParameterPack()) {
2108 assert(Arg.getKind() == TemplateArgument::Pack &&
2109 "Missing argument pack");
2110
2111 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2112 // We have an argument pack, but we can't select a particular argument
2113 // out of it yet. Therefore, we'll build an expression to hold on to that
2114 // argument pack.
2115 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2116 E->getLocation(),
2117 NTTP->getDeclName());
2118 if (TargetType.isNull())
2119 return ExprError();
2120
2121 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2122 if (TargetType->isRecordType())
2123 ExprType.addConst();
2124 // FIXME: Pass in Final.
2126 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2127 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2128 }
2129 PackIndex = getPackIndex(Arg);
2130 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2131 }
2132 // FIXME: Don't put subst node on Final replacement.
2133 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2134 Arg, PackIndex);
2135}
2136
2137const CXXAssumeAttr *
2138TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2139 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2140 if (!Res.isUsable())
2141 return AA;
2142
2143 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2144 AA->getRange());
2145 if (!Res.isUsable())
2146 return AA;
2147
2148 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2149 AA->getRange());
2150}
2151
2152const LoopHintAttr *
2153TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2154 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2155
2156 if (TransformedExpr == LH->getValue())
2157 return LH;
2158
2159 // Generate error if there is a problem with the value.
2160 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2161 LH->getSemanticSpelling() ==
2162 LoopHintAttr::Pragma_unroll))
2163 return LH;
2164
2165 LoopHintAttr::OptionType Option = LH->getOption();
2166 LoopHintAttr::LoopHintState State = LH->getState();
2167
2168 llvm::APSInt ValueAPS =
2169 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2170 // The values of 0 and 1 block any unrolling of the loop.
2171 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2172 Option = LoopHintAttr::Unroll;
2173 State = LoopHintAttr::Disable;
2174 }
2175
2176 // Create new LoopHintValueAttr with integral expression in place of the
2177 // non-type template parameter.
2178 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2179 TransformedExpr, *LH);
2180}
2181const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2182 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2183 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2184 return nullptr;
2185
2186 return A;
2187}
2188const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2189 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2190 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2191 return nullptr;
2192
2193 return A;
2194}
2195
2196const CodeAlignAttr *
2197TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2198 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2199 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2200}
2201
2202ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2203 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2205 std::optional<unsigned> PackIndex) {
2206 ExprResult result;
2207
2208 // Determine the substituted parameter type. We can usually infer this from
2209 // the template argument, but not always.
2210 auto SubstParamType = [&] {
2211 QualType T;
2212 if (parm->isExpandedParameterPack())
2214 else
2215 T = parm->getType();
2216 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2217 T = cast<PackExpansionType>(T)->getPattern();
2218 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2219 };
2220
2221 bool refParam = false;
2222
2223 // The template argument itself might be an expression, in which case we just
2224 // return that expression. This happens when substituting into an alias
2225 // template.
2226 if (arg.getKind() == TemplateArgument::Expression) {
2227 Expr *argExpr = arg.getAsExpr();
2228 result = argExpr;
2229 if (argExpr->isLValue()) {
2230 if (argExpr->getType()->isRecordType()) {
2231 // Check whether the parameter was actually a reference.
2232 QualType paramType = SubstParamType();
2233 if (paramType.isNull())
2234 return ExprError();
2235 refParam = paramType->isReferenceType();
2236 } else {
2237 refParam = true;
2238 }
2239 }
2240 } else if (arg.getKind() == TemplateArgument::Declaration ||
2241 arg.getKind() == TemplateArgument::NullPtr) {
2242 if (arg.getKind() == TemplateArgument::Declaration) {
2243 ValueDecl *VD = arg.getAsDecl();
2244
2245 // Find the instantiation of the template argument. This is
2246 // required for nested templates.
2247 VD = cast_or_null<ValueDecl>(
2248 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2249 if (!VD)
2250 return ExprError();
2251 }
2252
2253 QualType paramType = arg.getNonTypeTemplateArgumentType();
2254 assert(!paramType.isNull() && "type substitution failed for param type");
2255 assert(!paramType->isDependentType() && "param type still dependent");
2256 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2257 refParam = paramType->isReferenceType();
2258 } else {
2259 QualType paramType = arg.getNonTypeTemplateArgumentType();
2261 refParam = paramType->isReferenceType();
2262 assert(result.isInvalid() ||
2264 paramType.getNonReferenceType()));
2265 }
2266
2267 if (result.isInvalid())
2268 return ExprError();
2269
2270 Expr *resultExpr = result.get();
2271 // FIXME: Don't put subst node on final replacement.
2273 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2274 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2275}
2276
2278TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2280 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2281 // We aren't expanding the parameter pack, so just return ourselves.
2282 return E;
2283 }
2284
2287 // FIXME: Don't put subst node on final replacement.
2288 return transformNonTypeTemplateParmRef(
2290 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2291}
2292
2294TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2296 ExprResult SubstReplacement = E->getReplacement();
2297 if (!isa<ConstantExpr>(SubstReplacement.get()))
2298 SubstReplacement = TransformExpr(E->getReplacement());
2299 if (SubstReplacement.isInvalid())
2300 return true;
2301 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2302 if (SubstType.isNull())
2303 return true;
2304 // The type may have been previously dependent and not now, which means we
2305 // might have to implicit cast the argument to the new type, for example:
2306 // template<auto T, decltype(T) U>
2307 // concept C = sizeof(U) == 4;
2308 // void foo() requires C<2, 'a'> { }
2309 // When normalizing foo(), we first form the normalized constraints of C:
2310 // AtomicExpr(sizeof(U) == 4,
2311 // U=SubstNonTypeTemplateParmExpr(Param=U,
2312 // Expr=DeclRef(U),
2313 // Type=decltype(T)))
2314 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2315 // produce:
2316 // AtomicExpr(sizeof(U) == 4,
2317 // U=SubstNonTypeTemplateParmExpr(Param=U,
2318 // Expr=ImpCast(
2319 // decltype(2),
2320 // SubstNTTPE(Param=U, Expr='a',
2321 // Type=char)),
2322 // Type=decltype(2)))
2323 // The call to CheckTemplateArgument here produces the ImpCast.
2324 TemplateArgument SugaredConverted, CanonicalConverted;
2325 if (SemaRef
2327 SubstReplacement.get(), SugaredConverted,
2328 CanonicalConverted, Sema::CTAK_Specified)
2329 .isInvalid())
2330 return true;
2331 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2332 E->getParameter(), E->getExprLoc(),
2333 SugaredConverted, E->getPackIndex());
2334}
2335
2336ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2338 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2339 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2340}
2341
2343TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2344 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2345 // We can expand this parameter pack now.
2347 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2348 if (!VD)
2349 return ExprError();
2350 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2351 }
2352
2353 QualType T = TransformType(E->getType());
2354 if (T.isNull())
2355 return ExprError();
2356
2357 // Transform each of the parameter expansions into the corresponding
2358 // parameters in the instantiation of the function decl.
2360 Vars.reserve(E->getNumExpansions());
2361 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2362 I != End; ++I) {
2363 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2364 if (!D)
2365 return ExprError();
2366 Vars.push_back(D);
2367 }
2368
2369 auto *PackExpr =
2371 E->getParameterPackLocation(), Vars);
2372 getSema().MarkFunctionParmPackReferenced(PackExpr);
2373 return PackExpr;
2374}
2375
2377TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2378 VarDecl *PD) {
2379 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2380 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2381 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2382 assert(Found && "no instantiation for parameter pack");
2383
2384 Decl *TransformedDecl;
2385 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2386 // If this is a reference to a function parameter pack which we can
2387 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2388 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2389 QualType T = TransformType(E->getType());
2390 if (T.isNull())
2391 return ExprError();
2392 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2393 E->getExprLoc(), *Pack);
2394 getSema().MarkFunctionParmPackReferenced(PackExpr);
2395 return PackExpr;
2396 }
2397
2398 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2399 } else {
2400 TransformedDecl = Found->get<Decl*>();
2401 }
2402
2403 // We have either an unexpanded pack or a specific expansion.
2404 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2405}
2406
2408TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2409 NamedDecl *D = E->getDecl();
2410
2411 // Handle references to non-type template parameters and non-type template
2412 // parameter packs.
2413 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2414 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2415 return TransformTemplateParmRefExpr(E, NTTP);
2416
2417 // We have a non-type template parameter that isn't fully substituted;
2418 // FindInstantiatedDecl will find it in the local instantiation scope.
2419 }
2420
2421 // Handle references to function parameter packs.
2422 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2423 if (PD->isParameterPack())
2424 return TransformFunctionParmPackRefExpr(E, PD);
2425
2426 return inherited::TransformDeclRefExpr(E);
2427}
2428
2429ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2430 CXXDefaultArgExpr *E) {
2431 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2432 getDescribedFunctionTemplate() &&
2433 "Default arg expressions are never formed in dependent cases.");
2435 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2436 E->getParam());
2437}
2438
2439template<typename Fn>
2440QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2442 CXXRecordDecl *ThisContext,
2443 Qualifiers ThisTypeQuals,
2444 Fn TransformExceptionSpec) {
2445 // We need a local instantiation scope for this function prototype.
2446 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2447 return inherited::TransformFunctionProtoType(
2448 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2449}
2450
2451ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2452 ParmVarDecl *OldParm, int indexAdjustment,
2453 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2454 auto NewParm = SemaRef.SubstParmVarDecl(
2455 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2456 ExpectParameterPack, EvaluateConstraints);
2457 if (NewParm && SemaRef.getLangOpts().OpenCL)
2459 return NewParm;
2460}
2461
2462QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2463 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2464 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2465 TemplateArgument Arg, SourceLocation NameLoc) {
2466 QualType Replacement = Arg.getAsType();
2467
2468 // If the template parameter had ObjC lifetime qualifiers,
2469 // then any such qualifiers on the replacement type are ignored.
2470 if (SuppressObjCLifetime) {
2471 Qualifiers RQs;
2472 RQs = Replacement.getQualifiers();
2473 RQs.removeObjCLifetime();
2474 Replacement =
2475 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2476 }
2477
2478 if (Final) {
2479 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2480 return Replacement;
2481 }
2482 // TODO: only do this uniquing once, at the start of instantiation.
2483 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2484 Replacement, AssociatedDecl, Index, PackIndex);
2487 NewTL.setNameLoc(NameLoc);
2488 return Result;
2489}
2490
2492TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2494 bool SuppressObjCLifetime) {
2495 const TemplateTypeParmType *T = TL.getTypePtr();
2496 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2497 // Replace the template type parameter with its corresponding
2498 // template argument.
2499
2500 // If the corresponding template argument is NULL or doesn't exist, it's
2501 // because we are performing instantiation from explicitly-specified
2502 // template arguments in a function template class, but there were some
2503 // arguments left unspecified.
2504 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2507 NewTL.setNameLoc(TL.getNameLoc());
2508 return TL.getType();
2509 }
2510
2511 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2512
2513 if (TemplateArgs.isRewrite()) {
2514 // We're rewriting the template parameter as a reference to another
2515 // template parameter.
2516 if (Arg.getKind() == TemplateArgument::Pack) {
2517 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2518 "unexpected pack arguments in template rewrite");
2519 Arg = Arg.pack_begin()->getPackExpansionPattern();
2520 }
2521 assert(Arg.getKind() == TemplateArgument::Type &&
2522 "unexpected nontype template argument kind in template rewrite");
2523 QualType NewT = Arg.getAsType();
2524 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2525 return NewT;
2526 }
2527
2528 auto [AssociatedDecl, Final] =
2529 TemplateArgs.getAssociatedDecl(T->getDepth());
2530 std::optional<unsigned> PackIndex;
2531 if (T->isParameterPack()) {
2532 assert(Arg.getKind() == TemplateArgument::Pack &&
2533 "Missing argument pack");
2534
2535 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2536 // We have the template argument pack, but we're not expanding the
2537 // enclosing pack expansion yet. Just save the template argument
2538 // pack for later substitution.
2539 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2540 AssociatedDecl, T->getIndex(), Final, Arg);
2543 NewTL.setNameLoc(TL.getNameLoc());
2544 return Result;
2545 }
2546
2547 // PackIndex starts from last element.
2548 PackIndex = getPackIndex(Arg);
2549 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2550 }
2551
2552 assert(Arg.getKind() == TemplateArgument::Type &&
2553 "Template argument kind mismatch");
2554
2555 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2556 AssociatedDecl, T->getIndex(),
2557 PackIndex, Arg, TL.getNameLoc());
2558 }
2559
2560 // The template type parameter comes from an inner template (e.g.,
2561 // the template parameter list of a member template inside the
2562 // template we are instantiating). Create a new template type
2563 // parameter with the template "level" reduced by one.
2564 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2565 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2566 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2567 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2568 QualType Result = getSema().Context.getTemplateTypeParmType(
2569 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2570 T->isParameterPack(), NewTTPDecl);
2572 NewTL.setNameLoc(TL.getNameLoc());
2573 return Result;
2574}
2575
2576QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2578 bool SuppressObjCLifetime) {
2580
2581 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2582
2583 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2584 // We aren't expanding the parameter pack, so just return ourselves.
2585 QualType Result = TL.getType();
2586 if (NewReplaced != T->getAssociatedDecl())
2587 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2588 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2591 NewTL.setNameLoc(TL.getNameLoc());
2592 return Result;
2593 }
2594
2595 TemplateArgument Pack = T->getArgumentPack();
2597 return BuildSubstTemplateTypeParmType(
2598 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2599 getPackIndex(Pack), Arg, TL.getNameLoc());
2600}
2601
2604 concepts::EntityPrinter Printer) {
2605 SmallString<128> Message;
2606 SourceLocation ErrorLoc;
2607 if (Info.hasSFINAEDiagnostic()) {
2610 Info.takeSFINAEDiagnostic(PDA);
2611 PDA.second.EmitToString(S.getDiagnostics(), Message);
2612 ErrorLoc = PDA.first;
2613 } else {
2614 ErrorLoc = Info.getLocation();
2615 }
2616 char *MessageBuf = new (S.Context) char[Message.size()];
2617 std::copy(Message.begin(), Message.end(), MessageBuf);
2618 SmallString<128> Entity;
2619 llvm::raw_svector_ostream OS(Entity);
2620 Printer(OS);
2621 char *EntityBuf = new (S.Context) char[Entity.size()];
2622 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2624 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2625 StringRef(MessageBuf, Message.size())};
2626}
2627
2630 EntityPrinter Printer) {
2631 SmallString<128> Entity;
2632 llvm::raw_svector_ostream OS(Entity);
2633 Printer(OS);
2634 char *EntityBuf = new (S.Context) char[Entity.size()];
2635 llvm::copy(Entity, EntityBuf);
2637 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
2638 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2639}
2640
2641ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2642 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2645 SmallVectorImpl<ParmVarDecl *> &TransParams,
2647
2648 TemplateDeductionInfo Info(KWLoc);
2649 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2650 RE, Info,
2651 SourceRange{KWLoc, RBraceLoc});
2653
2654 unsigned ErrorIdx;
2655 if (getDerived().TransformFunctionTypeParams(
2656 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2657 &TransParams, PInfos, &ErrorIdx) ||
2658 Trap.hasErrorOccurred()) {
2660 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2661 // Add a 'failed' Requirement to contain the error that caused the failure
2662 // here.
2663 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2664 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2665 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2666 TransParams, RE->getRParenLoc(),
2667 TransReqs, RBraceLoc);
2668 }
2669
2670 return ExprResult{};
2671}
2672
2674TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2675 if (!Req->isDependent() && !AlwaysRebuild())
2676 return Req;
2677 if (Req->isSubstitutionFailure()) {
2678 if (AlwaysRebuild())
2679 return RebuildTypeRequirement(
2681 return Req;
2682 }
2683
2687 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2688 Req->getType()->getTypeLoc().getSourceRange());
2689 if (TypeInst.isInvalid())
2690 return nullptr;
2691 TypeSourceInfo *TransType = TransformType(Req->getType());
2692 if (!TransType || Trap.hasErrorOccurred())
2693 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2694 [&] (llvm::raw_ostream& OS) {
2695 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2696 }));
2697 return RebuildTypeRequirement(TransType);
2698}
2699
2701TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2702 if (!Req->isDependent() && !AlwaysRebuild())
2703 return Req;
2704
2706
2707 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2708 TransExpr;
2709 if (Req->isExprSubstitutionFailure())
2710 TransExpr = Req->getExprSubstitutionDiagnostic();
2711 else {
2712 Expr *E = Req->getExpr();
2714 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2715 E->getSourceRange());
2716 if (ExprInst.isInvalid())
2717 return nullptr;
2718 ExprResult TransExprRes = TransformExpr(E);
2719 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2720 TransExprRes.get()->hasPlaceholderType())
2721 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2722 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2723 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2724 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2725 });
2726 else
2727 TransExpr = TransExprRes.get();
2728 }
2729
2730 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2731 const auto &RetReq = Req->getReturnTypeRequirement();
2732 if (RetReq.isEmpty())
2733 TransRetReq.emplace();
2734 else if (RetReq.isSubstitutionFailure())
2735 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2736 else if (RetReq.isTypeConstraint()) {
2737 TemplateParameterList *OrigTPL =
2738 RetReq.getTypeConstraintTemplateParameterList();
2739 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2741 Req, Info, OrigTPL->getSourceRange());
2742 if (TPLInst.isInvalid())
2743 return nullptr;
2744 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2745 if (!TPL)
2746 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2747 [&] (llvm::raw_ostream& OS) {
2748 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2749 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2750 }));
2751 else {
2752 TPLInst.Clear();
2753 TransRetReq.emplace(TPL);
2754 }
2755 }
2756 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2757 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2758 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2759 std::move(*TransRetReq));
2760 return RebuildExprRequirement(
2762 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2763}
2764
2766TemplateInstantiator::TransformNestedRequirement(
2768 if (!Req->isDependent() && !AlwaysRebuild())
2769 return Req;
2770 if (Req->hasInvalidConstraint()) {
2771 if (AlwaysRebuild())
2772 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2774 return Req;
2775 }
2777 Req->getConstraintExpr()->getBeginLoc(), Req,
2780 if (!getEvaluateConstraints()) {
2781 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2782 if (TransConstraint.isInvalid() || !TransConstraint.get())
2783 return nullptr;
2784 if (TransConstraint.get()->isInstantiationDependent())
2785 return new (SemaRef.Context)
2786 concepts::NestedRequirement(TransConstraint.get());
2787 ConstraintSatisfaction Satisfaction;
2789 SemaRef.Context, TransConstraint.get(), Satisfaction);
2790 }
2791
2792 ExprResult TransConstraint;
2793 ConstraintSatisfaction Satisfaction;
2795 {
2800 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2802 if (ConstrInst.isInvalid())
2803 return nullptr;
2806 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2807 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2808 !Result.empty())
2809 TransConstraint = Result[0];
2810 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2811 "by CheckConstraintSatisfaction.");
2812 }
2813 if (TransConstraint.isUsable() &&
2814 TransConstraint.get()->isInstantiationDependent())
2815 return new (SemaRef.Context)
2816 concepts::NestedRequirement(TransConstraint.get());
2817 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2818 Satisfaction.HasSubstitutionFailure()) {
2819 SmallString<128> Entity;
2820 llvm::raw_svector_ostream OS(Entity);
2821 Req->getConstraintExpr()->printPretty(OS, nullptr,
2823 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2824 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2826 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2827 }
2829 SemaRef.Context, TransConstraint.get(), Satisfaction);
2830}
2831
2832
2833/// Perform substitution on the type T with a given set of template
2834/// arguments.
2835///
2836/// This routine substitutes the given template arguments into the
2837/// type T and produces the instantiated type.
2838///
2839/// \param T the type into which the template arguments will be
2840/// substituted. If this type is not dependent, it will be returned
2841/// immediately.
2842///
2843/// \param Args the template arguments that will be
2844/// substituted for the top-level template parameters within T.
2845///
2846/// \param Loc the location in the source code where this substitution
2847/// is being performed. It will typically be the location of the
2848/// declarator (if we're instantiating the type of some declaration)
2849/// or the location of the type in the source code (if, e.g., we're
2850/// instantiating the type of a cast expression).
2851///
2852/// \param Entity the name of the entity associated with a declaration
2853/// being instantiated (if any). May be empty to indicate that there
2854/// is no such entity (if, e.g., this is a type that occurs as part of
2855/// a cast expression) or that the entity has no name (e.g., an
2856/// unnamed function parameter).
2857///
2858/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2859/// acceptable as the top level type of the result.
2860///
2861/// \returns If the instantiation succeeds, the instantiated
2862/// type. Otherwise, produces diagnostics and returns a NULL type.
2866 DeclarationName Entity,
2867 bool AllowDeducedTST) {
2868 assert(!CodeSynthesisContexts.empty() &&
2869 "Cannot perform an instantiation without some context on the "
2870 "instantiation stack");
2871
2872 if (!T->getType()->isInstantiationDependentType() &&
2873 !T->getType()->isVariablyModifiedType())
2874 return T;
2875
2876 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2877 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2878 : Instantiator.TransformType(T);
2879}
2880
2884 DeclarationName Entity) {
2885 assert(!CodeSynthesisContexts.empty() &&
2886 "Cannot perform an instantiation without some context on the "
2887 "instantiation stack");
2888
2889 if (TL.getType().isNull())
2890 return nullptr;
2891
2894 // FIXME: Make a copy of the TypeLoc data here, so that we can
2895 // return a new TypeSourceInfo. Inefficient!
2896 TypeLocBuilder TLB;
2897 TLB.pushFullCopy(TL);
2898 return TLB.getTypeSourceInfo(Context, TL.getType());
2899 }
2900
2901 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2902 TypeLocBuilder TLB;
2903 TLB.reserve(TL.getFullDataSize());
2904 QualType Result = Instantiator.TransformType(TLB, TL);
2905 if (Result.isNull())
2906 return nullptr;
2907
2908 return TLB.getTypeSourceInfo(Context, Result);
2909}
2910
2911/// Deprecated form of the above.
2913 const MultiLevelTemplateArgumentList &TemplateArgs,
2915 assert(!CodeSynthesisContexts.empty() &&
2916 "Cannot perform an instantiation without some context on the "
2917 "instantiation stack");
2918
2919 // If T is not a dependent type or a variably-modified type, there
2920 // is nothing to do.
2922 return T;
2923
2924 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2925 return Instantiator.TransformType(T);
2926}
2927
2929 if (T->getType()->isInstantiationDependentType() ||
2930 T->getType()->isVariablyModifiedType())
2931 return true;
2932
2933 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2934 if (!TL.getAs<FunctionProtoTypeLoc>())
2935 return false;
2936
2938 for (ParmVarDecl *P : FP.getParams()) {
2939 // This must be synthesized from a typedef.
2940 if (!P) continue;
2941
2942 // If there are any parameters, a new TypeSourceInfo that refers to the
2943 // instantiated parameters must be built.
2944 return true;
2945 }
2946
2947 return false;
2948}
2949
2950/// A form of SubstType intended specifically for instantiating the
2951/// type of a FunctionDecl. Its purpose is solely to force the
2952/// instantiation of default-argument expressions and to avoid
2953/// instantiating an exception-specification.
2957 DeclarationName Entity,
2958 CXXRecordDecl *ThisContext,
2959 Qualifiers ThisTypeQuals,
2960 bool EvaluateConstraints) {
2961 assert(!CodeSynthesisContexts.empty() &&
2962 "Cannot perform an instantiation without some context on the "
2963 "instantiation stack");
2964
2966 return T;
2967
2968 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2969 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2970
2971 TypeLocBuilder TLB;
2972
2973 TypeLoc TL = T->getTypeLoc();
2974 TLB.reserve(TL.getFullDataSize());
2975
2977
2978 if (FunctionProtoTypeLoc Proto =
2980 // Instantiate the type, other than its exception specification. The
2981 // exception specification is instantiated in InitFunctionInstantiation
2982 // once we've built the FunctionDecl.
2983 // FIXME: Set the exception specification to EST_Uninstantiated here,
2984 // instead of rebuilding the function type again later.
2985 Result = Instantiator.TransformFunctionProtoType(
2986 TLB, Proto, ThisContext, ThisTypeQuals,
2988 bool &Changed) { return false; });
2989 } else {
2990 Result = Instantiator.TransformType(TLB, TL);
2991 }
2992 // When there are errors resolving types, clang may use IntTy as a fallback,
2993 // breaking our assumption that function declarations have function types.
2994 if (Result.isNull() || !Result->isFunctionType())
2995 return nullptr;
2996
2997 return TLB.getTypeSourceInfo(Context, Result);
2998}
2999
3002 SmallVectorImpl<QualType> &ExceptionStorage,
3003 const MultiLevelTemplateArgumentList &Args) {
3004 bool Changed = false;
3005 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3006 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3007 Changed);
3008}
3009
3011 const MultiLevelTemplateArgumentList &Args) {
3014
3015 SmallVector<QualType, 4> ExceptionStorage;
3017 ESI, ExceptionStorage, Args))
3018 // On error, recover by dropping the exception specification.
3019 ESI.Type = EST_None;
3020
3021 UpdateExceptionSpec(New, ESI);
3022}
3023
3024namespace {
3025
3026 struct GetContainedInventedTypeParmVisitor :
3027 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3028 TemplateTypeParmDecl *> {
3029 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3030 TemplateTypeParmDecl *>::Visit;
3031
3033 if (T.isNull())
3034 return nullptr;
3035 return Visit(T.getTypePtr());
3036 }
3037 // The deduced type itself.
3038 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3039 const TemplateTypeParmType *T) {
3040 if (!T->getDecl() || !T->getDecl()->isImplicit())
3041 return nullptr;
3042 return T->getDecl();
3043 }
3044
3045 // Only these types can contain 'auto' types, and subsequently be replaced
3046 // by references to invented parameters.
3047
3048 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3049 return Visit(T->getNamedType());
3050 }
3051
3052 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3053 return Visit(T->getPointeeType());
3054 }
3055
3056 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3057 return Visit(T->getPointeeType());
3058 }
3059
3060 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3061 return Visit(T->getPointeeTypeAsWritten());
3062 }
3063
3064 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3065 return Visit(T->getPointeeType());
3066 }
3067
3068 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3069 return Visit(T->getElementType());
3070 }
3071
3072 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3074 return Visit(T->getElementType());
3075 }
3076
3077 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3078 return Visit(T->getElementType());
3079 }
3080
3081 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3082 return VisitFunctionType(T);
3083 }
3084
3085 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3086 return Visit(T->getReturnType());
3087 }
3088
3089 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3090 return Visit(T->getInnerType());
3091 }
3092
3093 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3094 return Visit(T->getModifiedType());
3095 }
3096
3097 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3098 return Visit(T->getUnderlyingType());
3099 }
3100
3101 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3102 return Visit(T->getOriginalType());
3103 }
3104
3105 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3106 return Visit(T->getPattern());
3107 }
3108 };
3109
3110} // namespace
3111
3113 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3114 const MultiLevelTemplateArgumentList &TemplateArgs,
3115 bool EvaluateConstraints) {
3116 const ASTTemplateArgumentListInfo *TemplArgInfo =
3118
3119 if (!EvaluateConstraints) {
3122 return false;
3123 }
3124
3125 TemplateArgumentListInfo InstArgs;
3126
3127 if (TemplArgInfo) {
3128 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3129 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3130 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3131 InstArgs))
3132 return true;
3133 }
3134 return AttachTypeConstraint(
3136 TC->getNamedConcept(),
3137 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3138 Inst->isParameterPack()
3139 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3140 ->getEllipsisLoc()
3141 : SourceLocation());
3142}
3143
3145 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3146 int indexAdjustment, std::optional<unsigned> NumExpansions,
3147 bool ExpectParameterPack, bool EvaluateConstraint) {
3148 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3149 TypeSourceInfo *NewDI = nullptr;
3150
3151 TypeLoc OldTL = OldDI->getTypeLoc();
3152 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3153
3154 // We have a function parameter pack. Substitute into the pattern of the
3155 // expansion.
3156 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3157 OldParm->getLocation(), OldParm->getDeclName());
3158 if (!NewDI)
3159 return nullptr;
3160
3161 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3162 // We still have unexpanded parameter packs, which means that
3163 // our function parameter is still a function parameter pack.
3164 // Therefore, make its type a pack expansion type.
3165 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3166 NumExpansions);
3167 } else if (ExpectParameterPack) {
3168 // We expected to get a parameter pack but didn't (because the type
3169 // itself is not a pack expansion type), so complain. This can occur when
3170 // the substitution goes through an alias template that "loses" the
3171 // pack expansion.
3172 Diag(OldParm->getLocation(),
3173 diag::err_function_parameter_pack_without_parameter_packs)
3174 << NewDI->getType();
3175 return nullptr;
3176 }
3177 } else {
3178 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3179 OldParm->getDeclName());
3180 }
3181
3182 if (!NewDI)
3183 return nullptr;
3184
3185 if (NewDI->getType()->isVoidType()) {
3186 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3187 return nullptr;
3188 }
3189
3190 // In abbreviated templates, TemplateTypeParmDecls with possible
3191 // TypeConstraints are created when the parameter list is originally parsed.
3192 // The TypeConstraints can therefore reference other functions parameters in
3193 // the abbreviated function template, which is why we must instantiate them
3194 // here, when the instantiated versions of those referenced parameters are in
3195 // scope.
3196 if (TemplateTypeParmDecl *TTP =
3197 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3198 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3199 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3200 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3201 // We will first get here when instantiating the abbreviated function
3202 // template's described function, but we might also get here later.
3203 // Make sure we do not instantiate the TypeConstraint more than once.
3204 if (Inst && !Inst->getTypeConstraint()) {
3205 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3206 return nullptr;
3207 }
3208 }
3209 }
3210
3212 OldParm->getInnerLocStart(),
3213 OldParm->getLocation(),
3214 OldParm->getIdentifier(),
3215 NewDI->getType(), NewDI,
3216 OldParm->getStorageClass());
3217 if (!NewParm)
3218 return nullptr;
3219
3220 // Mark the (new) default argument as uninstantiated (if any).
3221 if (OldParm->hasUninstantiatedDefaultArg()) {
3222 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3223 NewParm->setUninstantiatedDefaultArg(Arg);
3224 } else if (OldParm->hasUnparsedDefaultArg()) {
3225 NewParm->setUnparsedDefaultArg();
3226 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3227 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3228 // Default arguments cannot be substituted until the declaration context
3229 // for the associated function or lambda capture class is available.
3230 // This is necessary for cases like the following where construction of
3231 // the lambda capture class for the outer lambda is dependent on the
3232 // parameter types but where the default argument is dependent on the
3233 // outer lambda's declaration context.
3234 // template <typename T>
3235 // auto f() {
3236 // return [](T = []{ return T{}; }()) { return 0; };
3237 // }
3238 NewParm->setUninstantiatedDefaultArg(Arg);
3239 }
3240
3244
3245 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3246 // Add the new parameter to the instantiated parameter pack.
3248 } else {
3249 // Introduce an Old -> New mapping
3251 }
3252
3253 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3254 // can be anything, is this right ?
3255 NewParm->setDeclContext(CurContext);
3256
3257 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3258 OldParm->getFunctionScopeIndex() + indexAdjustment);
3259
3260 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3261
3262 return NewParm;
3263}
3264
3265/// Substitute the given template arguments into the given set of
3266/// parameters, producing the set of parameter types that would be generated
3267/// from such a substitution.
3270 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3271 const MultiLevelTemplateArgumentList &TemplateArgs,
3272 SmallVectorImpl<QualType> &ParamTypes,
3274 ExtParameterInfoBuilder &ParamInfos) {
3275 assert(!CodeSynthesisContexts.empty() &&
3276 "Cannot perform an instantiation without some context on the "
3277 "instantiation stack");
3278
3279 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3280 DeclarationName());
3281 return Instantiator.TransformFunctionTypeParams(
3282 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3283}
3284
3285/// Substitute the given template arguments into the default argument.
3288 ParmVarDecl *Param,
3289 const MultiLevelTemplateArgumentList &TemplateArgs,
3290 bool ForCallExpr) {
3291 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3292 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3293
3296
3297 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3298 if (Inst.isInvalid())
3299 return true;
3300 if (Inst.isAlreadyInstantiating()) {
3301 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3302 Param->setInvalidDecl();
3303 return true;
3304 }
3305
3307 {
3308 // C++ [dcl.fct.default]p5:
3309 // The names in the [default argument] expression are bound, and
3310 // the semantic constraints are checked, at the point where the
3311 // default argument expression appears.
3312 ContextRAII SavedContext(*this, FD);
3313 std::unique_ptr<LocalInstantiationScope> LIS;
3314 MultiLevelTemplateArgumentList NewTemplateArgs = TemplateArgs;
3315
3316 if (ForCallExpr) {
3317 // When instantiating a default argument due to use in a call expression,
3318 // an instantiation scope that includes the parameters of the callee is
3319 // required to satisfy references from the default argument. For example:
3320 // template<typename T> void f(T a, int = decltype(a)());
3321 // void g() { f(0); }
3322 LIS = std::make_unique<LocalInstantiationScope>(*this);
3324 /*ForDefinition*/ false);
3325 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3326 return true;
3327 const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
3328 if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
3329 TemplateArgumentList *CurrentTemplateArgumentList =
3331 TemplateArgs.getInnermost());
3332 NewTemplateArgs = getTemplateInstantiationArgs(
3333 FD, FD->getDeclContext(), /*Final=*/false,
3334 CurrentTemplateArgumentList->asArray(), /*RelativeToPrimary=*/true);
3335 }
3336 }
3337
3339 Result = SubstInitializer(PatternExpr, NewTemplateArgs,
3340 /*DirectInit*/ false);
3341 });
3342 }
3343 if (Result.isInvalid())
3344 return true;
3345
3346 if (ForCallExpr) {
3347 // Check the expression as an initializer for the parameter.
3348 InitializedEntity Entity
3351 Param->getLocation(),
3352 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3353 Expr *ResultE = Result.getAs<Expr>();
3354
3355 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3356 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3357 if (Result.isInvalid())
3358 return true;
3359
3360 Result =
3362 /*DiscardedValue*/ false);
3363 } else {
3364 // FIXME: Obtain the source location for the '=' token.
3365 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3366 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3367 }
3368 if (Result.isInvalid())
3369 return true;
3370
3371 // Remember the instantiated default argument.
3372 Param->setDefaultArg(Result.getAs<Expr>());
3373
3374 return false;
3375}
3376
3377/// Perform substitution on the base class specifiers of the
3378/// given class template specialization.
3379///
3380/// Produces a diagnostic and returns true on error, returns false and
3381/// attaches the instantiated base classes to the class template
3382/// specialization if successful.
3383bool
3385 CXXRecordDecl *Pattern,
3386 const MultiLevelTemplateArgumentList &TemplateArgs) {
3387 bool Invalid = false;
3388 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3389 for (const auto &Base : Pattern->bases()) {
3390 if (!Base.getType()->isDependentType()) {
3391 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3392 if (RD->isInvalidDecl())
3393 Instantiation->setInvalidDecl();
3394 }
3395 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3396 continue;
3397 }
3398
3399 SourceLocation EllipsisLoc;
3400 TypeSourceInfo *BaseTypeLoc;
3401 if (Base.isPackExpansion()) {
3402 // This is a pack expansion. See whether we should expand it now, or
3403 // wait until later.
3405 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3406 Unexpanded);
3407 bool ShouldExpand = false;
3408 bool RetainExpansion = false;
3409 std::optional<unsigned> NumExpansions;
3410 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3411 Base.getSourceRange(),
3412 Unexpanded,
3413 TemplateArgs, ShouldExpand,
3414 RetainExpansion,
3415 NumExpansions)) {
3416 Invalid = true;
3417 continue;
3418 }
3419
3420 // If we should expand this pack expansion now, do so.
3421 if (ShouldExpand) {
3422 for (unsigned I = 0; I != *NumExpansions; ++I) {
3423 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3424
3425 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3426 TemplateArgs,
3427 Base.getSourceRange().getBegin(),
3428 DeclarationName());
3429 if (!BaseTypeLoc) {
3430 Invalid = true;
3431 continue;
3432 }
3433
3434 if (CXXBaseSpecifier *InstantiatedBase
3435 = CheckBaseSpecifier(Instantiation,
3436 Base.getSourceRange(),
3437 Base.isVirtual(),
3438 Base.getAccessSpecifierAsWritten(),
3439 BaseTypeLoc,
3440 SourceLocation()))
3441 InstantiatedBases.push_back(InstantiatedBase);
3442 else
3443 Invalid = true;
3444 }
3445
3446 continue;
3447 }
3448
3449 // The resulting base specifier will (still) be a pack expansion.
3450 EllipsisLoc = Base.getEllipsisLoc();
3451 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3452 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3453 TemplateArgs,
3454 Base.getSourceRange().getBegin(),
3455 DeclarationName());
3456 } else {
3457 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3458 TemplateArgs,
3459 Base.getSourceRange().getBegin(),
3460 DeclarationName());
3461 }
3462
3463 if (!BaseTypeLoc) {
3464 Invalid = true;
3465 continue;
3466 }
3467
3468 if (CXXBaseSpecifier *InstantiatedBase
3469 = CheckBaseSpecifier(Instantiation,
3470 Base.getSourceRange(),
3471 Base.isVirtual(),
3472 Base.getAccessSpecifierAsWritten(),
3473 BaseTypeLoc,
3474 EllipsisLoc))
3475 InstantiatedBases.push_back(InstantiatedBase);
3476 else
3477 Invalid = true;
3478 }
3479
3480 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3481 Invalid = true;
3482
3483 return Invalid;
3484}
3485
3486// Defined via #include from SemaTemplateInstantiateDecl.cpp
3487namespace clang {
3488 namespace sema {
3490 const MultiLevelTemplateArgumentList &TemplateArgs);
3492 const Attr *At, ASTContext &C, Sema &S,
3493 const MultiLevelTemplateArgumentList &TemplateArgs);
3494 }
3495}
3496
3497/// Instantiate the definition of a class from a given pattern.
3498///
3499/// \param PointOfInstantiation The point of instantiation within the
3500/// source code.
3501///
3502/// \param Instantiation is the declaration whose definition is being
3503/// instantiated. This will be either a class template specialization
3504/// or a member class of a class template specialization.
3505///
3506/// \param Pattern is the pattern from which the instantiation
3507/// occurs. This will be either the declaration of a class template or
3508/// the declaration of a member class of a class template.
3509///
3510/// \param TemplateArgs The template arguments to be substituted into
3511/// the pattern.
3512///
3513/// \param TSK the kind of implicit or explicit instantiation to perform.
3514///
3515/// \param Complain whether to complain if the class cannot be instantiated due
3516/// to the lack of a definition.
3517///
3518/// \returns true if an error occurred, false otherwise.
3519bool
3521 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3522 const MultiLevelTemplateArgumentList &TemplateArgs,
3524 bool Complain) {
3525 CXXRecordDecl *PatternDef
3526 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3527 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3528 Instantiation->getInstantiatedFromMemberClass(),
3529 Pattern, PatternDef, TSK, Complain))
3530 return true;
3531
3532 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3533 std::string Name;
3534 llvm::raw_string_ostream OS(Name);
3535 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3536 /*Qualified=*/true);
3537 return Name;
3538 });
3539
3540 Pattern = PatternDef;
3541
3542 // Record the point of instantiation.
3543 if (MemberSpecializationInfo *MSInfo
3544 = Instantiation->getMemberSpecializationInfo()) {
3545 MSInfo->setTemplateSpecializationKind(TSK);
3546 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3547 } else if (ClassTemplateSpecializationDecl *Spec
3548 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3549 Spec->setTemplateSpecializationKind(TSK);
3550 Spec->setPointOfInstantiation(PointOfInstantiation);
3551 }
3552
3553 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3554 if (Inst.isInvalid())
3555 return true;
3556 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3557 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3558 "instantiating class definition");
3559
3560 // Enter the scope of this instantiation. We don't use
3561 // PushDeclContext because we don't have a scope.
3562 ContextRAII SavedContext(*this, Instantiation);
3565
3566 // If this is an instantiation of a local class, merge this local
3567 // instantiation scope with the enclosing scope. Otherwise, every
3568 // instantiation of a class has its own local instantiation scope.
3569 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3570 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3571
3572 // Some class state isn't processed immediately but delayed till class
3573 // instantiation completes. We may not be ready to handle any delayed state
3574 // already on the stack as it might correspond to a different class, so save
3575 // it now and put it back later.
3576 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3577
3578 // Pull attributes from the pattern onto the instantiation.
3579 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3580
3581 // Start the definition of this instantiation.
3582 Instantiation->startDefinition();
3583
3584 // The instantiation is visible here, even if it was first declared in an
3585 // unimported module.
3586 Instantiation->setVisibleDespiteOwningModule();
3587
3588 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3589 Instantiation->setTagKind(Pattern->getTagKind());
3590
3591 // Do substitution on the base class specifiers.
3592 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3593 Instantiation->setInvalidDecl();
3594
3595 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3596 Instantiator.setEvaluateConstraints(false);
3597 SmallVector<Decl*, 4> Fields;
3598 // Delay instantiation of late parsed attributes.
3599 LateInstantiatedAttrVec LateAttrs;
3600 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3601
3602 bool MightHaveConstexprVirtualFunctions = false;
3603 for (auto *Member : Pattern->decls()) {
3604 // Don't instantiate members not belonging in this semantic context.
3605 // e.g. for:
3606 // @code
3607 // template <int i> class A {
3608 // class B *g;
3609 // };
3610 // @endcode
3611 // 'class B' has the template as lexical context but semantically it is
3612 // introduced in namespace scope.
3613 if (Member->getDeclContext() != Pattern)
3614 continue;
3615
3616 // BlockDecls can appear in a default-member-initializer. They must be the
3617 // child of a BlockExpr, so we only know how to instantiate them from there.
3618 // Similarly, lambda closure types are recreated when instantiating the
3619 // corresponding LambdaExpr.
3620 if (isa<BlockDecl>(Member) ||
3621 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3622 continue;
3623
3624 if (Member->isInvalidDecl()) {
3625 Instantiation->setInvalidDecl();
3626 continue;
3627 }
3628
3629 Decl *NewMember = Instantiator.Visit(Member);
3630 if (NewMember) {
3631 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3632 Fields.push_back(Field);
3633 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3634 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3635 // specialization causes the implicit instantiation of the definitions
3636 // of unscoped member enumerations.
3637 // Record a point of instantiation for this implicit instantiation.
3638 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3639 Enum->isCompleteDefinition()) {
3640 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3641 assert(MSInfo && "no spec info for member enum specialization");
3643 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3644 }
3645 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3646 if (SA->isFailed()) {
3647 // A static_assert failed. Bail out; instantiating this
3648 // class is probably not meaningful.
3649 Instantiation->setInvalidDecl();
3650 break;
3651 }
3652 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3653 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3654 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3655 MightHaveConstexprVirtualFunctions = true;
3656 }
3657
3658 if (NewMember->isInvalidDecl())
3659 Instantiation->setInvalidDecl();
3660 } else {
3661 // FIXME: Eventually, a NULL return will mean that one of the
3662 // instantiations was a semantic disaster, and we'll want to mark the
3663 // declaration invalid.
3664 // For now, we expect to skip some members that we can't yet handle.
3665 }
3666 }
3667
3668 // Finish checking fields.
3669 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3671 CheckCompletedCXXClass(nullptr, Instantiation);
3672
3673 // Default arguments are parsed, if not instantiated. We can go instantiate
3674 // default arg exprs for default constructors if necessary now. Unless we're
3675 // parsing a class, in which case wait until that's finished.
3676 if (ParsingClassDepth == 0)
3678
3679 // Instantiate late parsed attributes, and attach them to their decls.
3680 // See Sema::InstantiateAttrs
3681 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3682 E = LateAttrs.end(); I != E; ++I) {
3683 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3684 CurrentInstantiationScope = I->Scope;
3685
3686 // Allow 'this' within late-parsed attributes.
3687 auto *ND = cast<NamedDecl>(I->NewDecl);
3688 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3689 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3690 ND->isCXXInstanceMember());
3691
3692 Attr *NewAttr =
3693 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3694 if (NewAttr)
3695 I->NewDecl->addAttr(NewAttr);
3697 Instantiator.getStartingScope());
3698 }
3699 Instantiator.disableLateAttributeInstantiation();
3700 LateAttrs.clear();
3701
3703
3704 // FIXME: We should do something similar for explicit instantiations so they
3705 // end up in the right module.
3706 if (TSK == TSK_ImplicitInstantiation) {
3707 Instantiation->setLocation(Pattern->getLocation());
3708 Instantiation->setLocStart(Pattern->getInnerLocStart());
3709 Instantiation->setBraceRange(Pattern->getBraceRange());
3710 }
3711
3712 if (!Instantiation->isInvalidDecl()) {
3713 // Perform any dependent diagnostics from the pattern.
3714 if (Pattern->isDependentContext())
3715 PerformDependentDiagnostics(Pattern, TemplateArgs);
3716
3717 // Instantiate any out-of-line class template partial
3718 // specializations now.
3720 P = Instantiator.delayed_partial_spec_begin(),
3721 PEnd = Instantiator.delayed_partial_spec_end();
3722 P != PEnd; ++P) {
3724 P->first, P->second)) {
3725 Instantiation->setInvalidDecl();
3726 break;
3727 }
3728 }
3729
3730 // Instantiate any out-of-line variable template partial
3731 // specializations now.
3733 P = Instantiator.delayed_var_partial_spec_begin(),
3734 PEnd = Instantiator.delayed_var_partial_spec_end();
3735 P != PEnd; ++P) {
3737 P->first, P->second)) {
3738 Instantiation->setInvalidDecl();
3739 break;
3740 }
3741 }
3742 }
3743
3744 // Exit the scope of this instantiation.
3745 SavedContext.pop();
3746
3747 if (!Instantiation->isInvalidDecl()) {
3748 // Always emit the vtable for an explicit instantiation definition
3749 // of a polymorphic class template specialization. Otherwise, eagerly
3750 // instantiate only constexpr virtual functions in preparation for their use
3751 // in constant evaluation.
3753 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3754 else if (MightHaveConstexprVirtualFunctions)
3755 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3756 /*ConstexprOnly*/ true);
3757 }
3758
3759 Consumer.HandleTagDeclDefinition(Instantiation);
3760
3761 return Instantiation->isInvalidDecl();
3762}
3763
3764/// Instantiate the definition of an enum from a given pattern.
3765///
3766/// \param PointOfInstantiation The point of instantiation within the
3767/// source code.
3768/// \param Instantiation is the declaration whose definition is being
3769/// instantiated. This will be a member enumeration of a class
3770/// temploid specialization, or a local enumeration within a
3771/// function temploid specialization.
3772/// \param Pattern The templated declaration from which the instantiation
3773/// occurs.
3774/// \param TemplateArgs The template arguments to be substituted into
3775/// the pattern.
3776/// \param TSK The kind of implicit or explicit instantiation to perform.
3777///
3778/// \return \c true if an error occurred, \c false otherwise.
3779bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3780 EnumDecl *Instantiation, EnumDecl *Pattern,
3781 const MultiLevelTemplateArgumentList &TemplateArgs,
3783 EnumDecl *PatternDef = Pattern->getDefinition();
3784 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3785 Instantiation->getInstantiatedFromMemberEnum(),
3786 Pattern, PatternDef, TSK,/*Complain*/true))
3787 return true;
3788 Pattern = PatternDef;
3789
3790 // Record the point of instantiation.
3791 if (MemberSpecializationInfo *MSInfo
3792 = Instantiation->getMemberSpecializationInfo()) {
3793 MSInfo->setTemplateSpecializationKind(TSK);
3794 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3795 }
3796
3797 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3798 if (Inst.isInvalid())
3799 return true;
3800 if (Inst.isAlreadyInstantiating())
3801 return false;
3802 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3803 "instantiating enum definition");
3804
3805 // The instantiation is visible here, even if it was first declared in an
3806 // unimported module.
3807 Instantiation->setVisibleDespiteOwningModule();
3808
3809 // Enter the scope of this instantiation. We don't use
3810 // PushDeclContext because we don't have a scope.
3811 ContextRAII SavedContext(*this, Instantiation);
3814
3815 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3816
3817 // Pull attributes from the pattern onto the instantiation.
3818 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3819
3820 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3821 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3822
3823 // Exit the scope of this instantiation.
3824 SavedContext.pop();
3825
3826 return Instantiation->isInvalidDecl();
3827}
3828
3829
3830/// Instantiate the definition of a field from the given pattern.
3831///
3832/// \param PointOfInstantiation The point of instantiation within the
3833/// source code.
3834/// \param Instantiation is the declaration whose definition is being
3835/// instantiated. This will be a class of a class temploid
3836/// specialization, or a local enumeration within a function temploid
3837/// specialization.
3838/// \param Pattern The templated declaration from which the instantiation
3839/// occurs.
3840/// \param TemplateArgs The template arguments to be substituted into
3841/// the pattern.
3842///
3843/// \return \c true if an error occurred, \c false otherwise.
3845 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3846 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3847 // If there is no initializer, we don't need to do anything.
3848 if (!Pattern->hasInClassInitializer())
3849 return false;
3850
3851 assert(Instantiation->getInClassInitStyle() ==
3852 Pattern->getInClassInitStyle() &&
3853 "pattern and instantiation disagree about init style");
3854
3855 // Error out if we haven't parsed the initializer of the pattern yet because
3856 // we are waiting for the closing brace of the outer class.
3857 Expr *OldInit = Pattern->getInClassInitializer();
3858 if (!OldInit) {
3859 RecordDecl *PatternRD = Pattern->getParent();
3860 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3861 Diag(PointOfInstantiation,
3862 diag::err_default_member_initializer_not_yet_parsed)
3863 << OutermostClass << Pattern;
3864 Diag(Pattern->getEndLoc(),
3865 diag::note_default_member_initializer_not_yet_parsed);
3866 Instantiation->setInvalidDecl();
3867 return true;
3868 }
3869
3870 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3871 if (Inst.isInvalid())
3872 return true;
3873 if (Inst.isAlreadyInstantiating()) {
3874 // Error out if we hit an instantiation cycle for this initializer.
3875 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3876 << Instantiation;
3877 return true;
3878 }
3879 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3880 "instantiating default member init");
3881
3882 // Enter the scope of this instantiation. We don't use PushDeclContext because
3883 // we don't have a scope.
3884 ContextRAII SavedContext(*this, Instantiation->getParent());
3887 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3888 PointOfInstantiation, Instantiation, CurContext};
3889
3890 LocalInstantiationScope Scope(*this, true);
3891
3892 // Instantiate the initializer.
3894 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3895
3896 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3897 /*CXXDirectInit=*/false);
3898 Expr *Init = NewInit.get();
3899 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3901 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3902
3903 if (auto *L = getASTMutationListener())
3904 L->DefaultMemberInitializerInstantiated(Instantiation);
3905
3906 // Return true if the in-class initializer is still missing.
3907 return !Instantiation->getInClassInitializer();
3908}
3909
3910namespace {
3911 /// A partial specialization whose template arguments have matched
3912 /// a given template-id.
3913 struct PartialSpecMatchResult {
3916 };
3917}
3918
3921 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3923 return true;
3924
3926 ClassTemplateSpec->getSpecializedTemplate()
3927 ->getPartialSpecializations(PartialSpecs);
3928 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3930 if (DeduceTemplateArguments(PartialSpecs[I],
3931 ClassTemplateSpec->getTemplateArgs().asArray(),
3933 return true;
3934 }
3935
3936 return false;
3937}
3938
3939/// Get the instantiation pattern to use to instantiate the definition of a
3940/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3941/// template or of a partial specialization).
3944 Sema &S, SourceLocation PointOfInstantiation,
3945 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3947 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3948 if (Inst.isInvalid())
3949 return {/*Invalid=*/true};
3950 if (Inst.isAlreadyInstantiating())
3951 return {/*Invalid=*/false};
3952
3953 llvm::PointerUnion<ClassTemplateDecl *,
3955 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3956 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3957 // Find best matching specialization.
3958 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3959
3960 // C++ [temp.class.spec.match]p1:
3961 // When a class template is used in a context that requires an
3962 // instantiation of the class, it is necessary to determine
3963 // whether the instantiation is to be generated using the primary
3964 // template or one of the partial specializations. This is done by
3965 // matching the template arguments of the class template
3966 // specialization with the template argument lists of the partial
3967 // specializations.
3968 typedef PartialSpecMatchResult MatchResult;
3971 Template->getPartialSpecializations(PartialSpecs);
3972 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3973 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3974 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3975 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3977 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3979 // Store the failed-deduction information for use in diagnostics, later.
3980 // TODO: Actually use the failed-deduction info?
3981 FailedCandidates.addCandidate().set(
3982 DeclAccessPair::make(Template, AS_public), Partial,
3984 (void)Result;
3985 } else {
3986 Matched.push_back(PartialSpecMatchResult());
3987 Matched.back().Partial = Partial;
3988 Matched.back().Args = Info.takeCanonical();
3989 }
3990 }
3991
3992 // If we're dealing with a member template where the template parameters
3993 // have been instantiated, this provides the original template parameters
3994 // from which the member template's parameters were instantiated.
3995
3996 if (Matched.size() >= 1) {
3997 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3998 if (Matched.size() == 1) {
3999 // -- If exactly one matching specialization is found, the
4000 // instantiation is generated from that specialization.
4001 // We don't need to do anything for this.
4002 } else {
4003 // -- If more than one matching specialization is found, the
4004 // partial order rules (14.5.4.2) are used to determine
4005 // whether one of the specializations is more specialized
4006 // than the others. If none of the specializations is more
4007 // specialized than all of the other matching
4008 // specializations, then the use of the class template is
4009 // ambiguous and the program is ill-formed.
4011 PEnd = Matched.end();
4012 P != PEnd; ++P) {
4014 P->Partial, Best->Partial, PointOfInstantiation) ==
4015 P->Partial)
4016 Best = P;
4017 }
4018
4019 // Determine if the best partial specialization is more specialized than
4020 // the others.
4021 bool Ambiguous = false;
4022 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4023 PEnd = Matched.end();
4024 P != PEnd; ++P) {
4026 P->Partial, Best->Partial,
4027 PointOfInstantiation) != Best->Partial) {
4028 Ambiguous = true;
4029 break;
4030 }
4031 }
4032
4033 if (Ambiguous) {
4034 // Partial ordering did not produce a clear winner. Complain.
4035 Inst.Clear();
4036 ClassTemplateSpec->setInvalidDecl();
4037 S.Diag(PointOfInstantiation,
4038 diag::err_partial_spec_ordering_ambiguous)
4039 << ClassTemplateSpec;
4040
4041 // Print the matching partial specializations.
4042 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4043 PEnd = Matched.end();
4044 P != PEnd; ++P)
4045 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4047 P->Partial->getTemplateParameters(), *P->Args);
4048
4049 return {/*Invalid=*/true};
4050 }
4051 }
4052
4053 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4054 } else {
4055 // -- If no matches are found, the instantiation is generated
4056 // from the primary template.
4057 }
4058 }
4059
4060 CXXRecordDecl *Pattern = nullptr;
4061 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4062 if (auto *PartialSpec =
4063 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4064 // Instantiate using the best class template partial specialization.
4065 while (PartialSpec->getInstantiatedFromMember()) {
4066 // If we've found an explicit specialization of this class template,
4067 // stop here and use that as the pattern.
4068 if (PartialSpec->isMemberSpecialization())
4069 break;
4070
4071 PartialSpec = PartialSpec->getInstantiatedFromMember();
4072 }
4073 Pattern = PartialSpec;
4074 } else {
4075 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4076 while (Template->getInstantiatedFromMemberTemplate()) {
4077 // If we've found an explicit specialization of this class template,
4078 // stop here and use that as the pattern.
4079 if (Template->isMemberSpecialization())
4080 break;
4081
4082 Template = Template->getInstantiatedFromMemberTemplate();
4083 }
4084 Pattern = Template->getTemplatedDecl();
4085 }
4086
4087 return Pattern;
4088}
4089
4091 SourceLocation PointOfInstantiation,
4092 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4093 TemplateSpecializationKind TSK, bool Complain) {
4094 // Perform the actual instantiation on the canonical declaration.
4095 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4096 ClassTemplateSpec->getCanonicalDecl());
4097 if (ClassTemplateSpec->isInvalidDecl())
4098 return true;
4099
4101 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4102 ClassTemplateSpec, TSK);
4103 if (!Pattern.isUsable())
4104 return Pattern.isInvalid();
4105
4106 return InstantiateClass(
4107 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4108 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4109}
4110
4111/// Instantiates the definitions of all of the member
4112/// of the given class, which is an instantiation of a class template
4113/// or a member class of a template.
4114void
4116 CXXRecordDecl *Instantiation,
4117 const MultiLevelTemplateArgumentList &TemplateArgs,
4119 // FIXME: We need to notify the ASTMutationListener that we did all of these
4120 // things, in case we have an explicit instantiation definition in a PCM, a
4121 // module, or preamble, and the declaration is in an imported AST.
4122 assert(
4125 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4126 "Unexpected template specialization kind!");
4127 for (auto *D : Instantiation->decls()) {
4128 bool SuppressNew = false;
4129 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4130 if (FunctionDecl *Pattern =
4131 Function->getInstantiatedFromMemberFunction()) {
4132
4133 if (Function->isIneligibleOrNotSelected())
4134 continue;
4135
4136 if (Function->getTrailingRequiresClause()) {
4137 ConstraintSatisfaction Satisfaction;
4138 if (CheckFunctionConstraints(Function, Satisfaction) ||
4139 !Satisfaction.IsSatisfied) {
4140 continue;
4141 }
4142 }
4143
4144 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4145 continue;
4146
4147 MemberSpecializationInfo *MSInfo =
4148 Function->getMemberSpecializationInfo();
4149 assert(MSInfo && "No member specialization information?");
4150 if (MSInfo->getTemplateSpecializationKind()
4152 continue;
4153
4154 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4155 Function,
4157 MSInfo->getPointOfInstantiation(),
4158 SuppressNew) ||
4159 SuppressNew)
4160 continue;
4161
4162 // C++11 [temp.explicit]p8:
4163 // An explicit instantiation definition that names a class template
4164 // specialization explicitly instantiates the class template
4165 // specialization and is only an explicit instantiation definition
4166 // of members whose definition is visible at the point of
4167 // instantiation.
4168 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4169 continue;
4170
4171 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4172
4173 if (Function->isDefined()) {
4174 // Let the ASTConsumer know that this function has been explicitly
4175 // instantiated now, and its linkage might have changed.
4177 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4178 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4179 } else if (TSK == TSK_ImplicitInstantiation) {
4181 std::make_pair(Function, PointOfInstantiation));
4182 }
4183 }
4184 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4185 if (isa<VarTemplateSpecializationDecl>(Var))
4186 continue;
4187
4188 if (Var->isStaticDataMember()) {
4189 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4190 continue;
4191
4193 assert(MSInfo && "No member specialization information?");
4194 if (MSInfo->getTemplateSpecializationKind()
4196 continue;
4197
4198 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4199 Var,
4201 MSInfo->getPointOfInstantiation(),
4202 SuppressNew) ||
4203 SuppressNew)
4204 continue;
4205
4207 // C++0x [temp.explicit]p8:
4208 // An explicit instantiation definition that names a class template
4209 // specialization explicitly instantiates the class template
4210 // specialization and is only an explicit instantiation definition
4211 // of members whose definition is visible at the point of
4212 // instantiation.
4214 continue;
4215
4216 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4217 InstantiateVariableDefinition(PointOfInstantiation, Var);
4218 } else {
4219 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4220 }
4221 }
4222 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4223 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4224 continue;
4225
4226 // Always skip the injected-class-name, along with any
4227 // redeclarations of nested classes, since both would cause us
4228 // to try to instantiate the members of a class twice.
4229 // Skip closure types; they'll get instantiated when we instantiate
4230 // the corresponding lambda-expression.
4231 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4232 Record->isLambda())
4233 continue;
4234
4235 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4236 assert(MSInfo && "No member specialization information?");
4237
4238 if (MSInfo->getTemplateSpecializationKind()
4240 continue;
4241
4242 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4244 // On Windows, explicit instantiation decl of the outer class doesn't
4245 // affect the inner class. Typically extern template declarations are
4246 // used in combination with dll import/export annotations, but those
4247 // are not propagated from the outer class templates to inner classes.
4248 // Therefore, do not instantiate inner classes on this platform, so
4249 // that users don't end up with undefined symbols during linking.
4250 continue;
4251 }
4252
4253 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4254 Record,
4256 MSInfo->getPointOfInstantiation(),
4257 SuppressNew) ||
4258 SuppressNew)
4259 continue;
4260
4262 assert(Pattern && "Missing instantiated-from-template information");
4263
4264 if (!Record->getDefinition()) {
4265 if (!Pattern->getDefinition()) {
4266 // C++0x [temp.explicit]p8:
4267 // An explicit instantiation definition that names a class template
4268 // specialization explicitly instantiates the class template
4269 // specialization and is only an explicit instantiation definition
4270 // of members whose definition is visible at the point of
4271 // instantiation.
4273 MSInfo->setTemplateSpecializationKind(TSK);
4274 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4275 }
4276
4277 continue;
4278 }
4279
4280 InstantiateClass(PointOfInstantiation, Record, Pattern,
4281 TemplateArgs,
4282 TSK);
4283 } else {
4285 Record->getTemplateSpecializationKind() ==
4287 Record->setTemplateSpecializationKind(TSK);
4288 MarkVTableUsed(PointOfInstantiation, Record, true);
4289 }
4290 }
4291
4292 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4293 if (Pattern)
4294 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4295 TSK);
4296 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4297 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4298 assert(MSInfo && "No member specialization information?");
4299
4300 if (MSInfo->getTemplateSpecializationKind()
4302 continue;
4303
4305 PointOfInstantiation, TSK, Enum,
4307 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4308 SuppressNew)
4309 continue;
4310
4311 if (Enum->getDefinition())
4312 continue;
4313
4314 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4315 assert(Pattern && "Missing instantiated-from-template information");
4316
4318 if (!Pattern->getDefinition())
4319 continue;
4320
4321 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4322 } else {
4323 MSInfo->setTemplateSpecializationKind(TSK);
4324 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4325 }
4326 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4327 // No need to instantiate in-class initializers during explicit
4328 // instantiation.
4329 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4330 CXXRecordDecl *ClassPattern =
4331 Instantiation->getTemplateInstantiationPattern();
4333 ClassPattern->lookup(Field->getDeclName());
4334 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4335 assert(Pattern);
4336 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4337 TemplateArgs);
4338 }
4339 }
4340 }
4341}
4342
4343/// Instantiate the definitions of all of the members of the
4344/// given class template specialization, which was named as part of an
4345/// explicit instantiation.
4346void
4348 SourceLocation PointOfInstantiation,
4349 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4351 // C++0x [temp.explicit]p7:
4352 // An explicit instantiation that names a class template
4353 // specialization is an explicit instantion of the same kind
4354 // (declaration or definition) of each of its members (not
4355 // including members inherited from base classes) that has not
4356 // been previously explicitly specialized in the translation unit
4357 // containing the explicit instantiation, except as described
4358 // below.
4359 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4360 getTemplateInstantiationArgs(ClassTemplateSpec),
4361 TSK);
4362}
4363
4366 if (!S)
4367 return S;
4368
4369 TemplateInstantiator Instantiator(*this, TemplateArgs,
4371 DeclarationName());
4372 return Instantiator.TransformStmt(S);
4373}
4374
4376 const TemplateArgumentLoc &Input,
4377 const MultiLevelTemplateArgumentList &TemplateArgs,
4378 TemplateArgumentLoc &Output) {
4379 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4380 DeclarationName());
4381 return Instantiator.TransformTemplateArgument(Input, Output);
4382}
4383
4386 const MultiLevelTemplateArgumentList &TemplateArgs,
4388 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4389 DeclarationName());
4390 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4391}
4392
4395 if (!E)
4396 return E;
4397
4398 TemplateInstantiator Instantiator(*this, TemplateArgs,
4400 DeclarationName());
4401 return Instantiator.TransformExpr(E);
4402}
4403
4406 const MultiLevelTemplateArgumentList &TemplateArgs) {
4407 // FIXME: should call SubstExpr directly if this function is equivalent or
4408 // should it be different?
4409 return SubstExpr(E, TemplateArgs);
4410}
4411
4413 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4414 if (!E)
4415 return E;
4416
4417 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4418 DeclarationName());
4419 Instantiator.setEvaluateConstraints(false);
4420 return Instantiator.TransformExpr(E);
4421}
4422
4424 const MultiLevelTemplateArgumentList &TemplateArgs,
4425 bool CXXDirectInit) {
4426 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4427 DeclarationName());
4428 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4429}
4430
4431bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4432 const MultiLevelTemplateArgumentList &TemplateArgs,
4433 SmallVectorImpl<Expr *> &Outputs) {
4434 if (Exprs.empty())
4435 return false;
4436
4437 TemplateInstantiator Instantiator(*this, TemplateArgs,
4439 DeclarationName());
4440 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4441 IsCall, Outputs);
4442}
4443
4446 const MultiLevelTemplateArgumentList &TemplateArgs) {
4447 if (!NNS)
4448 return NestedNameSpecifierLoc();
4449
4450 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4451 DeclarationName());
4452 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4453}
4454
4455/// Do template substitution on declaration name info.
4458 const MultiLevelTemplateArgumentList &TemplateArgs) {
4459 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4460 NameInfo.getName());
4461 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4462}
4463
4467 const MultiLevelTemplateArgumentList &TemplateArgs) {
4468 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4469 DeclarationName());
4470 CXXScopeSpec SS;
4471 SS.Adopt(QualifierLoc);
4472 return Instantiator.TransformTemplateName(SS, Name, Loc);
4473}
4474
4475static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4476 // When storing ParmVarDecls in the local instantiation scope, we always
4477 // want to use the ParmVarDecl from the canonical function declaration,
4478 // since the map is then valid for any redeclaration or definition of that
4479 // function.
4480 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4481 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4482 unsigned i = PV->getFunctionScopeIndex();
4483 // This parameter might be from a freestanding function type within the
4484 // function and isn't necessarily referring to one of FD's parameters.
4485 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4486 return FD->getCanonicalDecl()->getParamDecl(i);
4487 }
4488 }
4489 return D;
4490}
4491
4492
4493llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4496 for (LocalInstantiationScope *Current = this; Current;
4497 Current = Current->Outer) {
4498
4499 // Check if we found something within this scope.
4500 const Decl *CheckD = D;
4501 do {
4502 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4503 if (Found != Current->LocalDecls.end())
4504 return &Found->second;
4505
4506 // If this is a tag declaration, it's possible that we need to look for
4507 // a previous declaration.
4508 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4509 CheckD = Tag->getPreviousDecl();
4510 else
4511 CheckD = nullptr;
4512 } while (CheckD);
4513
4514 // If we aren't combined with our outer scope, we're done.
4515 if (!Current->CombineWithOuterScope)
4516 break;
4517 }
4518
4519 // If we're performing a partial substitution during template argument
4520 // deduction, we may not have values for template parameters yet.
4521 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4522 isa<TemplateTemplateParmDecl>(D))
4523 return nullptr;
4524
4525 // Local types referenced prior to definition may require instantiation.
4526 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4527 if (RD->isLocalClass())
4528 return nullptr;
4529
4530 // Enumeration types referenced prior to definition may appear as a result of
4531 // error recovery.
4532 if (isa<EnumDecl>(D))
4533 return nullptr;
4534
4535 // Materialized typedefs/type alias for implicit deduction guides may require
4536 // instantiation.
4537 if (isa<TypedefNameDecl>(D) &&
4538 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4539 return nullptr;
4540
4541 // If we didn't find the decl, then we either have a sema bug, or we have a
4542 // forward reference to a label declaration. Return null to indicate that
4543 // we have an uninstantiated label.
4544 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4545 return nullptr;
4546}
4547
4550 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4551 if (Stored.isNull()) {
4552#ifndef NDEBUG
4553 // It should not be present in any surrounding scope either.
4554 LocalInstantiationScope *Current = this;
4555 while (Current->CombineWithOuterScope && Current->Outer) {
4556 Current = Current->Outer;
4557 assert(!Current->LocalDecls.contains(D) &&
4558 "Instantiated local in inner and outer scopes");
4559 }
4560#endif
4561 Stored = Inst;
4562 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4563 Pack->push_back(cast<VarDecl>(Inst));
4564 } else {
4565 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4566 }
4567}
4568
4570 VarDecl *Inst) {
4572 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4573 Pack->push_back(Inst);
4574}
4575
4577#ifndef NDEBUG
4578 // This should be the first time we've been told about this decl.
4579 for (LocalInstantiationScope *Current = this;
4580 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4581 assert(!Current->LocalDecls.contains(D) &&
4582 "Creating local pack after instantiation of local");
4583#endif
4584
4586 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4588 Stored = Pack;
4589 ArgumentPacks.push_back(Pack);
4590}
4591
4593 for (DeclArgumentPack *Pack : ArgumentPacks)
4594 if (llvm::is_contained(*Pack, D))
4595 return true;
4596 return false;
4597}
4598
4600 const TemplateArgument *ExplicitArgs,
4601 unsigned NumExplicitArgs) {
4602 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4603 "Already have a partially-substituted pack");
4604 assert((!PartiallySubstitutedPack
4605 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4606 "Wrong number of arguments in partially-substituted pack");
4607 PartiallySubstitutedPack = Pack;
4608 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4609 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4610}
4611
4613 const TemplateArgument **ExplicitArgs,
4614 unsigned *NumExplicitArgs) const {
4615 if (ExplicitArgs)
4616 *ExplicitArgs = nullptr;
4617 if (NumExplicitArgs)
4618 *NumExplicitArgs = 0;
4619
4620 for (const LocalInstantiationScope *Current = this; Current;
4621 Current = Current->Outer) {
4622 if (Current->PartiallySubstitutedPack) {
4623 if (ExplicitArgs)
4624 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4625 if (NumExplicitArgs)
4626 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4627
4628 return Current->PartiallySubstitutedPack;
4629 }
4630
4631 if (!Current->CombineWithOuterScope)
4632 break;
4633 }
4634
4635 return nullptr;
4636}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &, QualType)
Definition: InterpFrame.cpp:96
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
MatchFinder::MatchResult MatchResult
SourceLocation Loc
Definition: SemaObjC.cpp:755
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, concepts::EntityPrinter Printer)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
Defines utilities for dealing with stack allocation and stack space.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:72
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1073
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:2591
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:1591
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2157
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:697
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:757
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:3298
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3518
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:5604
Pointer to a block type.
Definition: Type.h:3349
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1264
SourceLocation getUsedLocation() const
Retrieve the location where this default argument was actually used.
Definition: ExprCXX.h:1338
const ParmVarDecl * getParam() const
Definition: ExprCXX.h:1306
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:1685
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:1876
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:1930
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1905
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1897
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1883
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1594
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:1916
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:199
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2137
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1282
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1802
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1964
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2322
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1260
ValueDecl * getDecl()
Definition: Expr.h:1328
SourceLocation getLocation() const
Definition: Expr.h:1336
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:1051
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:239
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:100
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:220
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isFileContextDecl() const
Definition: DeclBase.cpp:408
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1019
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:274
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1165
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:939
DeclContext * getDeclContext()
Definition: DeclBase.h:454
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:583
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
The name of a declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:828
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:813
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2047
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:822
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1900
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3899
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:6371
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3867
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4126
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:4912
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4938
EnumDecl * getDefinition() const
Definition: Decl.h:3970
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:3057
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4570
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3218
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3212
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3270
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:1971
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2683
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:4113
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4162
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2432
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2313
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4630
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4657
iterator end() const
Definition: ExprCXX.h:4666
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4672
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4664
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4669
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4660
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1748
iterator begin() const
Definition: ExprCXX.h:4665
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4656
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4900
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:4282
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4256
QualType getReturnType() const
Definition: Type.h:4573
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:6221
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1950
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:5242
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3460
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:1826
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1675
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pack expansion of types.
Definition: Type.h:6569
Sugar for parentheses used when specifying types.
Definition: Type.h:3113
Represents a parameter to a function.
Definition: Decl.h:1761
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1821
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2980
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1857
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1902
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1890
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3005
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1794
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1894
bool hasInheritedDefaultArg() const
Definition: Decl.h:1906
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1853
Expr * getDefaultArg()
Definition: Decl.cpp:2968
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3010
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1811
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1910
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3139
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1986
PredefinedIdentKind getIdentKind() const
Definition: Expr.h:2021
SourceLocation getLocation() const
Definition: Expr.h:2027
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:940
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:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1007
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:7560
The collection of all-type qualifiers we support.
Definition: Type.h:318
void removeObjCLifetime()
Definition: Type.h:537
Represents a struct/union/class.
Definition: Decl.h:4168
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5549
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:3380
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
RequiresExprBodyDecl * getBody() const
Definition: ExprConcepts.h:554
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:56
Sema & SemaRef
Definition: SemaBase.h:40
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:10223
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6478
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2531
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4642
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4674
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4671
A helper class for building up ExtParameterInfos.
Definition: Sema.h:9674
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9410
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:451
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:10173
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:10157
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9703
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:10160
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6947
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:9070
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:848
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:10184
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:514
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:517
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:765
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:17035
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:510
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:11164
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:10209
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:3730
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
ActOnBaseSpecifier - Parsed a base specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:9715
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:10217
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:986
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10448
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15272
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:20849
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:10193
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:5569
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.
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:849
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1622
@ 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:10201
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:19080
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:6364
DiagnosticsEngine & Diags
Definition: Sema.h:850
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:10168
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:520
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:21042
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
bool SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output)
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:512
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:550
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:6652
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
A trivial tuple used to represent a source range.
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h: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:4466
std::optional< unsigned > getPackIndex() const
Definition: ExprCXX.h:4514
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4508
QualType getParameterType(const ASTContext &Ctx) const
Determine the substituted type of the template parameter.
Definition: ExprCXX.cpp:1704
NonTypeTemplateParmDecl * getParameter() const
Definition: ExprCXX.cpp:1663
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4551
TemplateArgument getArgumentPack() const
Retrieve the template argument pack containing the substituted template arguments.
Definition: ExprCXX.cpp:1730
SourceLocation getParameterPackLocation() const
Retrieve the location of the parameter pack name.
Definition: ExprCXX.h:4591
NonTypeTemplateParmDecl * getParameterPack() const
Retrieve the non-type template parameter pack being substituted.
Definition: ExprCXX.cpp:1725
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4581
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:5889
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3584
void setTagKind(TagKind TK)
Definition: Decl.h:3783
SourceRange getBraceRange() const
Definition: Decl.h:3663
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3668
StringRef getKindName() const
Definition: Decl.h:3775
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4737
TagKind getTagKind() const
Definition: Decl.h:3779
void setBraceRange(SourceRange R)
Definition: Decl.h:3664
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:202
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
QualifiedTemplateName * getAsQualifiedTemplateName() const
Retrieve the underlying qualified template name structure, if any.
TemplateName getNameToSubstitute() const
Get the template name to substitute when this template name is used as a template template argument.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
TemplateSpecCandidateSet - A set of generalized overload candidates, used in template specializations...
SourceLocation getLocation() const
TemplateSpecCandidate & addCandidate()
Add a new candidate with NumConversions conversion sequence slots to the overload set.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6089
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:5780
unsigned getIndex() const
Definition: Type.h:5779
unsigned getDepth() const
Definition: Type.h:5778
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:231
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:264
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:254
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:246
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:274
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:278
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:250
void setLocStart(SourceLocation L)
Definition: Decl.h:3418
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:7330
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:7341
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:3169
The base class of the type hierarchy.
Definition: Type.h:1813
bool isVoidType() const
Definition: Type.h:7905
bool isReferenceType() const
Definition: Type.h:7624
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:695
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2661
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2653
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2320
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2671
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8126
bool isRecordType() const
Definition: Type.h:7706
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:706
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1270
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2363
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2749
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For a static data member that was instantiated from a static data member of a class template,...
Definition: Decl.cpp:2876
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1155
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2663
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2867
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
Represents a GCC generic vector type.
Definition: Type.h:3969
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:6299
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition: Ownership.h:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:65
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:132
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:136
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:367
@ Success
Template argument deduction was successful.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:185
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:203
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:199
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:195
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:191
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6274
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ AS_public
Definition: Specifiers.h:121
Definition: Format.h:5428
__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:4707
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4709
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4742
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9720
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:9881
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:9834
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:9850
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:9876
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:9845
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9837
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:9722
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:9814
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:9732
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:9741
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:9760
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:9811
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:9768
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:9775
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:9818
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:9786
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:9824
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:9751
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:9830
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:9827
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:9748
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:9756
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:9764
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:9725
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:9778
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:9782
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:9737
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:9808
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:9771
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9840
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:9905
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10059
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:10063
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)