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 this function was instantiated from a specialized member that is
279 // a function template, we're done.
280 assert(Function->getPrimaryTemplate() && "No function template?");
281 if (Function->getPrimaryTemplate()->isMemberSpecialization())
282 return Response::Done();
283
284 // If this function is a generic lambda specialization, we are done.
285 if (!ForConstraintInstantiation &&
287 // TypeAliasTemplateDecls should be taken into account, e.g.
288 // when we're deducing the return type of a lambda.
289 //
290 // template <class> int Value = 0;
291 // template <class T>
292 // using T = decltype([]<int U = 0>() { return Value<T>; }());
293 //
294 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
295 if (isLambdaEnclosedByTypeAliasDecl(
296 /*PrimaryLambdaCallOperator=*/getPrimaryTemplateOfGenericLambda(
297 Function),
298 /*PrimaryTypeAliasDecl=*/TypeAlias.PrimaryTypeAliasDecl))
299 return Response::UseNextDecl(Function);
300 }
301 return Response::Done();
302 }
303
304 } else if (Function->getDescribedFunctionTemplate()) {
305 assert(
306 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
307 "Outer template not instantiated?");
308 }
309 // If this is a friend or local declaration and it declares an entity at
310 // namespace scope, take arguments from its lexical parent
311 // instead of its semantic parent, unless of course the pattern we're
312 // instantiating actually comes from the file's context!
313 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
314 Function->getNonTransparentDeclContext()->isFileContext() &&
315 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
316 return Response::ChangeDecl(Function->getLexicalDeclContext());
317 }
318
319 if (ForConstraintInstantiation && Function->getFriendObjectKind())
320 return Response::ChangeDecl(Function->getLexicalDeclContext());
321 return Response::UseNextDecl(Function);
322}
323
324Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
326 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
327 Result.addOuterTemplateArguments(
328 const_cast<FunctionTemplateDecl *>(FTD),
329 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
330 /*Final=*/false);
331
333
334 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
335 if (NNS->isInstantiationDependent()) {
336 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
337 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
338 // Prefer template arguments from the injected-class-type if possible.
339 // For example,
340 // ```cpp
341 // template <class... Pack> struct S {
342 // template <class T> void foo();
343 // };
344 // template <class... Pack> template <class T>
345 // ^^^^^^^^^^^^^ InjectedTemplateArgs
346 // They're of kind TemplateArgument::Pack, not of
347 // TemplateArgument::Type.
348 // void S<Pack...>::foo() {}
349 // ^^^^^^^
350 // TSTy->template_arguments() (which are of PackExpansionType)
351 // ```
352 // This meets the contract in
353 // TreeTransform::TryExpandParameterPacks that the template arguments
354 // for unexpanded parameters should be of a Pack kind.
355 if (TSTy->isCurrentInstantiation()) {
356 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
357 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
358 Arguments = CTD->getInjectedTemplateArgs();
359 else if (auto *Specialization =
360 dyn_cast<ClassTemplateSpecializationDecl>(RD))
361 Arguments =
362 Specialization->getTemplateInstantiationArgs().asArray();
363 }
364 Result.addOuterTemplateArguments(
365 const_cast<FunctionTemplateDecl *>(FTD), Arguments,
366 /*Final=*/false);
367 }
368 }
369
370 NNS = NNS->getPrefix();
371 }
372 }
373
374 return Response::ChangeDecl(FTD->getLexicalDeclContext());
375}
376
377Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
379 ASTContext &Context,
380 bool ForConstraintInstantiation) {
381 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
382 assert(
383 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
384 "Outer template not instantiated?");
385 if (ClassTemplate->isMemberSpecialization())
386 return Response::Done();
387 if (ForConstraintInstantiation)
388 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
389 ClassTemplate->getInjectedTemplateArgs(),
390 /*Final=*/false);
391 }
392
393 if (const MemberSpecializationInfo *MSInfo =
395 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
396 return Response::Done();
397
398 bool IsFriend = Rec->getFriendObjectKind() ||
401 if (ForConstraintInstantiation && IsFriend &&
403 return Response::ChangeDecl(Rec->getLexicalDeclContext());
404 }
405
406 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
407 // TypeAliasTemplateDecl that this lambda is defined inside of.
408 if (Rec->isLambda()) {
409 if (const Decl *LCD = Rec->getLambdaContextDecl())
410 return Response::ChangeDecl(LCD);
411 // Retrieve the template arguments for a using alias declaration.
412 // This is necessary for constraint checking, since we always keep
413 // constraints relative to the primary template.
414 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
415 const FunctionDecl *PrimaryLambdaCallOperator =
416 getPrimaryTemplateOfGenericLambda(Rec->getLambdaCallOperator());
417 if (isLambdaEnclosedByTypeAliasDecl(PrimaryLambdaCallOperator,
418 TypeAlias.PrimaryTypeAliasDecl)) {
419 Result.addOuterTemplateArguments(TypeAlias.Template,
420 TypeAlias.AssociatedTemplateArguments,
421 /*Final=*/false);
422 // Visit the parent of the current type alias declaration rather than
423 // the lambda thereof.
424 // E.g., in the following example:
425 // struct S {
426 // template <class> using T = decltype([]<Concept> {} ());
427 // };
428 // void foo() {
429 // S::T var;
430 // }
431 // The instantiated lambda expression (which we're visiting at 'var')
432 // has a function DeclContext 'foo' rather than the Record DeclContext
433 // S. This seems to be an oversight to me that we may want to set a
434 // Sema Context from the CXXScopeSpec before substituting into T.
435 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
436 }
437 }
438 }
439
440 return Response::UseNextDecl(Rec);
441}
442
443Response HandleImplicitConceptSpecializationDecl(
446 Result.addOuterTemplateArguments(
447 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
449 /*Final=*/false);
450 return Response::UseNextDecl(CSD);
451}
452
453Response HandleGenericDeclContext(const Decl *CurDecl) {
454 return Response::UseNextDecl(CurDecl);
455}
456} // namespace TemplateInstArgsHelpers
457} // namespace
458
459/// Retrieve the template argument list(s) that should be used to
460/// instantiate the definition of the given declaration.
461///
462/// \param ND the declaration for which we are computing template instantiation
463/// arguments.
464///
465/// \param DC In the event we don't HAVE a declaration yet, we instead provide
466/// the decl context where it will be created. In this case, the `Innermost`
467/// should likely be provided. If ND is non-null, this is ignored.
468///
469/// \param Innermost if non-NULL, specifies a template argument list for the
470/// template declaration passed as ND.
471///
472/// \param RelativeToPrimary true if we should get the template
473/// arguments relative to the primary template, even when we're
474/// dealing with a specialization. This is only relevant for function
475/// template specializations.
476///
477/// \param Pattern If non-NULL, indicates the pattern from which we will be
478/// instantiating the definition of the given declaration, \p ND. This is
479/// used to determine the proper set of template instantiation arguments for
480/// friend function template specializations.
481///
482/// \param ForConstraintInstantiation when collecting arguments,
483/// ForConstraintInstantiation indicates we should continue looking when
484/// encountering a lambda generic call operator, and continue looking for
485/// arguments on an enclosing class template.
486
488 const NamedDecl *ND, const DeclContext *DC, bool Final,
489 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
490 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
491 bool SkipForSpecialization) {
492 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
493 // Accumulate the set of template argument lists in this structure.
495
496 using namespace TemplateInstArgsHelpers;
497 const Decl *CurDecl = ND;
498
499 if (!CurDecl)
500 CurDecl = Decl::castFromDeclContext(DC);
501
502 if (Innermost) {
503 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
504 Final);
505 // Populate placeholder template arguments for TemplateTemplateParmDecls.
506 // This is essential for the case e.g.
507 //
508 // template <class> concept Concept = false;
509 // template <template <Concept C> class T> void foo(T<int>)
510 //
511 // where parameter C has a depth of 1 but the substituting argument `int`
512 // has a depth of 0.
513 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
514 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
515 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
516 }
517
518 while (!CurDecl->isFileContextDecl()) {
519 Response R;
520 if (const auto *VarTemplSpec =
521 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
522 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
523 } else if (const auto *PartialClassTemplSpec =
524 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
525 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
526 SkipForSpecialization);
527 } else if (const auto *ClassTemplSpec =
528 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
529 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
530 SkipForSpecialization);
531 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
532 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
533 ForConstraintInstantiation);
534 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
535 R = HandleRecordDecl(*this, Rec, Result, Context,
536 ForConstraintInstantiation);
537 } else if (const auto *CSD =
538 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
539 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
540 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
541 R = HandleFunctionTemplateDecl(FTD, Result);
542 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
543 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
544 } else if (!isa<DeclContext>(CurDecl)) {
545 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
546 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
547 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
548 }
549 } else {
550 R = HandleGenericDeclContext(CurDecl);
551 }
552
553 if (R.IsDone)
554 return Result;
555 if (R.ClearRelativeToPrimary)
556 RelativeToPrimary = false;
557 assert(R.NextDecl);
558 CurDecl = R.NextDecl;
559 }
560
561 return Result;
562}
563
565 switch (Kind) {
573 case ConstraintsCheck:
575 return true;
576
594 return false;
595
596 // This function should never be called when Kind's value is Memoization.
597 case Memoization:
598 break;
599 }
600
601 llvm_unreachable("Invalid SynthesisKind!");
602}
603
606 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
607 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
608 sema::TemplateDeductionInfo *DeductionInfo)
609 : SemaRef(SemaRef) {
610 // Don't allow further instantiation if a fatal error and an uncompilable
611 // error have occurred. Any diagnostics we might have raised will not be
612 // visible, and we do not need to construct a correct AST.
615 Invalid = true;
616 return;
617 }
618 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
619 if (!Invalid) {
621 Inst.Kind = Kind;
622 Inst.PointOfInstantiation = PointOfInstantiation;
623 Inst.Entity = Entity;
624 Inst.Template = Template;
625 Inst.TemplateArgs = TemplateArgs.data();
626 Inst.NumTemplateArgs = TemplateArgs.size();
627 Inst.DeductionInfo = DeductionInfo;
628 Inst.InstantiationRange = InstantiationRange;
630
631 AlreadyInstantiating = !Inst.Entity ? false :
633 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
634 .second;
636 }
637}
638
640 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
641 SourceRange InstantiationRange)
643 CodeSynthesisContext::TemplateInstantiation,
644 PointOfInstantiation, InstantiationRange, Entity) {}
645
647 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
648 ExceptionSpecification, SourceRange InstantiationRange)
650 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
651 PointOfInstantiation, InstantiationRange, Entity) {}
652
654 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
655 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
656 SourceRange InstantiationRange)
658 SemaRef,
659 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
660 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
661 Template, TemplateArgs) {}
662
664 Sema &SemaRef, SourceLocation PointOfInstantiation,
666 ArrayRef<TemplateArgument> TemplateArgs,
668 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
669 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
670 InstantiationRange, FunctionTemplate, nullptr,
671 TemplateArgs, &DeductionInfo) {
675}
676
678 Sema &SemaRef, SourceLocation PointOfInstantiation,
679 TemplateDecl *Template,
680 ArrayRef<TemplateArgument> TemplateArgs,
681 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
683 SemaRef,
684 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
685 PointOfInstantiation, InstantiationRange, Template, nullptr,
686 TemplateArgs, &DeductionInfo) {}
687
689 Sema &SemaRef, SourceLocation PointOfInstantiation,
691 ArrayRef<TemplateArgument> TemplateArgs,
692 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
694 SemaRef,
695 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
696 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
697 TemplateArgs, &DeductionInfo) {}
698
700 Sema &SemaRef, SourceLocation PointOfInstantiation,
702 ArrayRef<TemplateArgument> TemplateArgs,
703 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
705 SemaRef,
706 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
707 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
708 TemplateArgs, &DeductionInfo) {}
709
711 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
712 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
714 SemaRef,
715 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
716 PointOfInstantiation, InstantiationRange, Param, nullptr,
717 TemplateArgs) {}
718
720 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
722 SourceRange InstantiationRange)
724 SemaRef,
725 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
726 PointOfInstantiation, InstantiationRange, Param, Template,
727 TemplateArgs) {}
728
730 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
732 SourceRange InstantiationRange)
734 SemaRef,
735 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
736 PointOfInstantiation, InstantiationRange, Param, Template,
737 TemplateArgs) {}
738
740 Sema &SemaRef, SourceLocation PointOfInstantiation,
742 SourceRange InstantiationRange)
744 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
745 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
746 /*Template=*/nullptr, TemplateArgs) {}
747
749 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
750 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
751 SourceRange InstantiationRange)
753 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
754 PointOfInstantiation, InstantiationRange, Param, Template,
755 TemplateArgs) {}
756
758 Sema &SemaRef, SourceLocation PointOfInstantiation,
760 SourceRange InstantiationRange)
762 SemaRef, CodeSynthesisContext::RequirementInstantiation,
763 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
764 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
765}
766
768 Sema &SemaRef, SourceLocation PointOfInstantiation,
770 SourceRange InstantiationRange)
772 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
773 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
774 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
775
777 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
778 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
780 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
781 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
782 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
783}
784
786 Sema &SemaRef, SourceLocation PointOfInstantiation,
787 ConstraintsCheck, NamedDecl *Template,
788 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
791 PointOfInstantiation, InstantiationRange, Template, nullptr,
792 TemplateArgs) {}
793
795 Sema &SemaRef, SourceLocation PointOfInstantiation,
797 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
800 PointOfInstantiation, InstantiationRange, Template, nullptr,
801 {}, &DeductionInfo) {}
802
804 Sema &SemaRef, SourceLocation PointOfInstantiation,
806 SourceRange InstantiationRange)
809 PointOfInstantiation, InstantiationRange, Template) {}
810
812 Sema &SemaRef, SourceLocation PointOfInstantiation,
814 SourceRange InstantiationRange)
817 PointOfInstantiation, InstantiationRange, Template) {}
818
820 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
821 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
823 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
824 PointOfInstantiation, InstantiationRange, Entity) {}
825
826
830
831 CodeSynthesisContexts.push_back(Ctx);
832
833 if (!Ctx.isInstantiationRecord())
835
836 // Check to see if we're low on stack space. We can't do anything about this
837 // from here, but we can at least warn the user.
840}
841
843 auto &Active = CodeSynthesisContexts.back();
844 if (!Active.isInstantiationRecord()) {
845 assert(NonInstantiationEntries > 0);
847 }
848
849 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
850
851 // Name lookup no longer looks in this template's defining module.
852 assert(CodeSynthesisContexts.size() >=
854 "forgot to remove a lookup module for a template instantiation");
855 if (CodeSynthesisContexts.size() ==
858 LookupModulesCache.erase(M);
860 }
861
862 // If we've left the code synthesis context for the current context stack,
863 // stop remembering that we've emitted that stack.
864 if (CodeSynthesisContexts.size() ==
867
868 CodeSynthesisContexts.pop_back();
869}
870
872 if (!Invalid) {
873 if (!AlreadyInstantiating) {
874 auto &Active = SemaRef.CodeSynthesisContexts.back();
875 if (Active.Entity)
877 {Active.Entity->getCanonicalDecl(), Active.Kind});
878 }
879
882
884 Invalid = true;
885 }
886}
887
888static std::string convertCallArgsToString(Sema &S,
890 std::string Result;
891 llvm::raw_string_ostream OS(Result);
892 llvm::ListSeparator Comma;
893 for (const Expr *Arg : Args) {
894 OS << Comma;
895 Arg->IgnoreParens()->printPretty(OS, nullptr,
897 }
898 return Result;
899}
900
901bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
902 SourceLocation PointOfInstantiation,
903 SourceRange InstantiationRange) {
906 if ((SemaRef.CodeSynthesisContexts.size() -
908 <= SemaRef.getLangOpts().InstantiationDepth)
909 return false;
910
911 SemaRef.Diag(PointOfInstantiation,
912 diag::err_template_recursion_depth_exceeded)
913 << SemaRef.getLangOpts().InstantiationDepth
914 << InstantiationRange;
915 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
916 << SemaRef.getLangOpts().InstantiationDepth;
917 return true;
918}
919
920/// Prints the current instantiation stack through a series of
921/// notes.
923 // Determine which template instantiations to skip, if any.
924 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
925 unsigned Limit = Diags.getTemplateBacktraceLimit();
926 if (Limit && Limit < CodeSynthesisContexts.size()) {
927 SkipStart = Limit / 2 + Limit % 2;
928 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
929 }
930
931 // FIXME: In all of these cases, we need to show the template arguments
932 unsigned InstantiationIdx = 0;
934 Active = CodeSynthesisContexts.rbegin(),
935 ActiveEnd = CodeSynthesisContexts.rend();
936 Active != ActiveEnd;
937 ++Active, ++InstantiationIdx) {
938 // Skip this instantiation?
939 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
940 if (InstantiationIdx == SkipStart) {
941 // Note that we're skipping instantiations.
942 Diags.Report(Active->PointOfInstantiation,
943 diag::note_instantiation_contexts_suppressed)
944 << unsigned(CodeSynthesisContexts.size() - Limit);
945 }
946 continue;
947 }
948
949 switch (Active->Kind) {
951 Decl *D = Active->Entity;
952 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
953 unsigned DiagID = diag::note_template_member_class_here;
954 if (isa<ClassTemplateSpecializationDecl>(Record))
955 DiagID = diag::note_template_class_instantiation_here;
956 Diags.Report(Active->PointOfInstantiation, DiagID)
957 << Record << Active->InstantiationRange;
958 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
959 unsigned DiagID;
960 if (Function->getPrimaryTemplate())
961 DiagID = diag::note_function_template_spec_here;
962 else
963 DiagID = diag::note_template_member_function_here;
964 Diags.Report(Active->PointOfInstantiation, DiagID)
965 << Function
966 << Active->InstantiationRange;
967 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
968 Diags.Report(Active->PointOfInstantiation,
969 VD->isStaticDataMember()?
970 diag::note_template_static_data_member_def_here
971 : diag::note_template_variable_def_here)
972 << VD
973 << Active->InstantiationRange;
974 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
975 Diags.Report(Active->PointOfInstantiation,
976 diag::note_template_enum_def_here)
977 << ED
978 << Active->InstantiationRange;
979 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
980 Diags.Report(Active->PointOfInstantiation,
981 diag::note_template_nsdmi_here)
982 << FD << Active->InstantiationRange;
983 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
984 Diags.Report(Active->PointOfInstantiation,
985 diag::note_template_class_instantiation_here)
986 << CTD << Active->InstantiationRange;
987 }
988 break;
989 }
990
992 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
993 SmallString<128> TemplateArgsStr;
994 llvm::raw_svector_ostream OS(TemplateArgsStr);
995 Template->printName(OS, getPrintingPolicy());
996 printTemplateArgumentList(OS, Active->template_arguments(),
998 Diags.Report(Active->PointOfInstantiation,
999 diag::note_default_arg_instantiation_here)
1000 << OS.str()
1001 << Active->InstantiationRange;
1002 break;
1003 }
1004
1006 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1007 Diags.Report(Active->PointOfInstantiation,
1008 diag::note_explicit_template_arg_substitution_here)
1009 << FnTmpl
1011 Active->TemplateArgs,
1012 Active->NumTemplateArgs)
1013 << Active->InstantiationRange;
1014 break;
1015 }
1016
1018 if (FunctionTemplateDecl *FnTmpl =
1019 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1020 Diags.Report(Active->PointOfInstantiation,
1021 diag::note_function_template_deduction_instantiation_here)
1022 << FnTmpl
1023 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1024 Active->TemplateArgs,
1025 Active->NumTemplateArgs)
1026 << Active->InstantiationRange;
1027 } else {
1028 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1029 isa<VarTemplateSpecializationDecl>(Active->Entity);
1030 bool IsTemplate = false;
1031 TemplateParameterList *Params;
1032 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1033 IsTemplate = true;
1034 Params = D->getTemplateParameters();
1035 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1036 Active->Entity)) {
1037 Params = D->getTemplateParameters();
1038 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1039 Active->Entity)) {
1040 Params = D->getTemplateParameters();
1041 } else {
1042 llvm_unreachable("unexpected template kind");
1043 }
1044
1045 Diags.Report(Active->PointOfInstantiation,
1046 diag::note_deduced_template_arg_substitution_here)
1047 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1048 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1049 Active->NumTemplateArgs)
1050 << Active->InstantiationRange;
1051 }
1052 break;
1053 }
1054
1056 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1057 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1058
1059 SmallString<128> TemplateArgsStr;
1060 llvm::raw_svector_ostream OS(TemplateArgsStr);
1062 printTemplateArgumentList(OS, Active->template_arguments(),
1064 Diags.Report(Active->PointOfInstantiation,
1065 diag::note_default_function_arg_instantiation_here)
1066 << OS.str()
1067 << Active->InstantiationRange;
1068 break;
1069 }
1070
1072 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1073 std::string Name;
1074 if (!Parm->getName().empty())
1075 Name = std::string(" '") + Parm->getName().str() + "'";
1076
1077 TemplateParameterList *TemplateParams = nullptr;
1078 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1079 TemplateParams = Template->getTemplateParameters();
1080 else
1081 TemplateParams =
1082 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1083 ->getTemplateParameters();
1084 Diags.Report(Active->PointOfInstantiation,
1085 diag::note_prior_template_arg_substitution)
1086 << isa<TemplateTemplateParmDecl>(Parm)
1087 << Name
1088 << getTemplateArgumentBindingsText(TemplateParams,
1089 Active->TemplateArgs,
1090 Active->NumTemplateArgs)
1091 << Active->InstantiationRange;
1092 break;
1093 }
1094
1096 TemplateParameterList *TemplateParams = nullptr;
1097 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1098 TemplateParams = Template->getTemplateParameters();
1099 else
1100 TemplateParams =
1101 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1102 ->getTemplateParameters();
1103
1104 Diags.Report(Active->PointOfInstantiation,
1105 diag::note_template_default_arg_checking)
1106 << getTemplateArgumentBindingsText(TemplateParams,
1107 Active->TemplateArgs,
1108 Active->NumTemplateArgs)
1109 << Active->InstantiationRange;
1110 break;
1111 }
1112
1114 Diags.Report(Active->PointOfInstantiation,
1115 diag::note_evaluating_exception_spec_here)
1116 << cast<FunctionDecl>(Active->Entity);
1117 break;
1118
1120 Diags.Report(Active->PointOfInstantiation,
1121 diag::note_template_exception_spec_instantiation_here)
1122 << cast<FunctionDecl>(Active->Entity)
1123 << Active->InstantiationRange;
1124 break;
1125
1127 Diags.Report(Active->PointOfInstantiation,
1128 diag::note_template_requirement_instantiation_here)
1129 << Active->InstantiationRange;
1130 break;
1132 Diags.Report(Active->PointOfInstantiation,
1133 diag::note_template_requirement_params_instantiation_here)
1134 << Active->InstantiationRange;
1135 break;
1136
1138 Diags.Report(Active->PointOfInstantiation,
1139 diag::note_nested_requirement_here)
1140 << Active->InstantiationRange;
1141 break;
1142
1144 Diags.Report(Active->PointOfInstantiation,
1145 diag::note_in_declaration_of_implicit_special_member)
1146 << cast<CXXRecordDecl>(Active->Entity)
1147 << llvm::to_underlying(Active->SpecialMember);
1148 break;
1149
1151 Diags.Report(Active->Entity->getLocation(),
1152 diag::note_in_declaration_of_implicit_equality_comparison);
1153 break;
1154
1156 // FIXME: For synthesized functions that are not defaulted,
1157 // produce a note.
1158 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1161 if (DFK.isSpecialMember()) {
1162 auto *MD = cast<CXXMethodDecl>(FD);
1163 Diags.Report(Active->PointOfInstantiation,
1164 diag::note_member_synthesized_at)
1165 << MD->isExplicitlyDefaulted()
1166 << llvm::to_underlying(DFK.asSpecialMember())
1167 << Context.getTagDeclType(MD->getParent());
1168 } else if (DFK.isComparison()) {
1169 QualType RecordType = FD->getParamDecl(0)
1170 ->getType()
1171 .getNonReferenceType()
1172 .getUnqualifiedType();
1173 Diags.Report(Active->PointOfInstantiation,
1174 diag::note_comparison_synthesized_at)
1175 << (int)DFK.asComparison() << RecordType;
1176 }
1177 break;
1178 }
1179
1181 Diags.Report(Active->Entity->getLocation(),
1182 diag::note_rewriting_operator_as_spaceship);
1183 break;
1184
1186 Diags.Report(Active->PointOfInstantiation,
1187 diag::note_in_binding_decl_init)
1188 << cast<BindingDecl>(Active->Entity);
1189 break;
1190
1192 Diags.Report(Active->PointOfInstantiation,
1193 diag::note_due_to_dllexported_class)
1194 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1195 break;
1196
1198 Diags.Report(Active->PointOfInstantiation,
1199 diag::note_building_builtin_dump_struct_call)
1201 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1202 break;
1203
1205 break;
1206
1208 Diags.Report(Active->PointOfInstantiation,
1209 diag::note_lambda_substitution_here);
1210 break;
1212 unsigned DiagID = 0;
1213 if (!Active->Entity) {
1214 Diags.Report(Active->PointOfInstantiation,
1215 diag::note_nested_requirement_here)
1216 << Active->InstantiationRange;
1217 break;
1218 }
1219 if (isa<ConceptDecl>(Active->Entity))
1220 DiagID = diag::note_concept_specialization_here;
1221 else if (isa<TemplateDecl>(Active->Entity))
1222 DiagID = diag::note_checking_constraints_for_template_id_here;
1223 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1224 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1225 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1226 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1227 else {
1228 assert(isa<FunctionDecl>(Active->Entity));
1229 DiagID = diag::note_checking_constraints_for_function_here;
1230 }
1231 SmallString<128> TemplateArgsStr;
1232 llvm::raw_svector_ostream OS(TemplateArgsStr);
1233 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1234 if (!isa<FunctionDecl>(Active->Entity)) {
1235 printTemplateArgumentList(OS, Active->template_arguments(),
1237 }
1238 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1239 << Active->InstantiationRange;
1240 break;
1241 }
1243 Diags.Report(Active->PointOfInstantiation,
1244 diag::note_constraint_substitution_here)
1245 << Active->InstantiationRange;
1246 break;
1248 Diags.Report(Active->PointOfInstantiation,
1249 diag::note_constraint_normalization_here)
1250 << cast<NamedDecl>(Active->Entity)->getName()
1251 << Active->InstantiationRange;
1252 break;
1254 Diags.Report(Active->PointOfInstantiation,
1255 diag::note_parameter_mapping_substitution_here)
1256 << Active->InstantiationRange;
1257 break;
1259 Diags.Report(Active->PointOfInstantiation,
1260 diag::note_building_deduction_guide_here);
1261 break;
1263 Diags.Report(Active->PointOfInstantiation,
1264 diag::note_template_type_alias_instantiation_here)
1265 << cast<TypeAliasTemplateDecl>(Active->Entity)
1266 << Active->InstantiationRange;
1267 break;
1268 }
1269 }
1270}
1271
1272std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1274 return std::optional<TemplateDeductionInfo *>(nullptr);
1275
1277 Active = CodeSynthesisContexts.rbegin(),
1278 ActiveEnd = CodeSynthesisContexts.rend();
1279 Active != ActiveEnd;
1280 ++Active)
1281 {
1282 switch (Active->Kind) {
1284 // An instantiation of an alias template may or may not be a SFINAE
1285 // context, depending on what else is on the stack.
1286 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1287 break;
1288 [[fallthrough]];
1296 // This is a template instantiation, so there is no SFINAE.
1297 return std::nullopt;
1299 // [temp.deduct]p9
1300 // A lambda-expression appearing in a function type or a template
1301 // parameter is not considered part of the immediate context for the
1302 // purposes of template argument deduction.
1303 // CWG2672: A lambda-expression body is never in the immediate context.
1304 return std::nullopt;
1305
1310 // A default template argument instantiation and substitution into
1311 // template parameters with arguments for prior parameters may or may
1312 // not be a SFINAE context; look further up the stack.
1313 break;
1314
1317 // We're either substituting explicitly-specified template arguments,
1318 // deduced template arguments. SFINAE applies unless we are in a lambda
1319 // body, see [temp.deduct]p9.
1323 // SFINAE always applies in a constraint expression or a requirement
1324 // in a requires expression.
1325 assert(Active->DeductionInfo && "Missing deduction info pointer");
1326 return Active->DeductionInfo;
1327
1335 // This happens in a context unrelated to template instantiation, so
1336 // there is no SFINAE.
1337 return std::nullopt;
1338
1340 // FIXME: This should not be treated as a SFINAE context, because
1341 // we will cache an incorrect exception specification. However, clang
1342 // bootstrap relies this! See PR31692.
1343 break;
1344
1346 break;
1347 }
1348
1349 // The inner context was transparent for SFINAE. If it occurred within a
1350 // non-instantiation SFINAE context, then SFINAE applies.
1351 if (Active->SavedInNonInstantiationSFINAEContext)
1352 return std::optional<TemplateDeductionInfo *>(nullptr);
1353 }
1354
1355 return std::nullopt;
1356}
1357
1358//===----------------------------------------------------------------------===/
1359// Template Instantiation for Types
1360//===----------------------------------------------------------------------===/
1361namespace {
1362 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1363 const MultiLevelTemplateArgumentList &TemplateArgs;
1364 SourceLocation Loc;
1365 DeclarationName Entity;
1366 // Whether to evaluate the C++20 constraints or simply substitute into them.
1367 bool EvaluateConstraints = true;
1368
1369 public:
1370 typedef TreeTransform<TemplateInstantiator> inherited;
1371
1372 TemplateInstantiator(Sema &SemaRef,
1373 const MultiLevelTemplateArgumentList &TemplateArgs,
1374 SourceLocation Loc, DeclarationName Entity)
1375 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1376 Entity(Entity) {}
1377
1378 void setEvaluateConstraints(bool B) {
1379 EvaluateConstraints = B;
1380 }
1381 bool getEvaluateConstraints() {
1382 return EvaluateConstraints;
1383 }
1384
1385 /// Determine whether the given type \p T has already been
1386 /// transformed.
1387 ///
1388 /// For the purposes of template instantiation, a type has already been
1389 /// transformed if it is NULL or if it is not dependent.
1390 bool AlreadyTransformed(QualType T);
1391
1392 /// Returns the location of the entity being instantiated, if known.
1393 SourceLocation getBaseLocation() { return Loc; }
1394
1395 /// Returns the name of the entity being instantiated, if any.
1396 DeclarationName getBaseEntity() { return Entity; }
1397
1398 /// Sets the "base" location and entity when that
1399 /// information is known based on another transformation.
1400 void setBase(SourceLocation Loc, DeclarationName Entity) {
1401 this->Loc = Loc;
1402 this->Entity = Entity;
1403 }
1404
1405 unsigned TransformTemplateDepth(unsigned Depth) {
1406 return TemplateArgs.getNewDepth(Depth);
1407 }
1408
1409 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1410 int Index = getSema().ArgumentPackSubstitutionIndex;
1411 if (Index == -1)
1412 return std::nullopt;
1413 return Pack.pack_size() - 1 - Index;
1414 }
1415
1416 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1417 SourceRange PatternRange,
1419 bool &ShouldExpand, bool &RetainExpansion,
1420 std::optional<unsigned> &NumExpansions) {
1421 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1422 PatternRange, Unexpanded,
1423 TemplateArgs,
1424 ShouldExpand,
1425 RetainExpansion,
1426 NumExpansions);
1427 }
1428
1429 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1431 }
1432
1433 TemplateArgument ForgetPartiallySubstitutedPack() {
1434 TemplateArgument Result;
1435 if (NamedDecl *PartialPack
1437 MultiLevelTemplateArgumentList &TemplateArgs
1438 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1439 unsigned Depth, Index;
1440 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1441 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1442 Result = TemplateArgs(Depth, Index);
1443 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1444 }
1445 }
1446
1447 return Result;
1448 }
1449
1450 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1451 if (Arg.isNull())
1452 return;
1453
1454 if (NamedDecl *PartialPack
1456 MultiLevelTemplateArgumentList &TemplateArgs
1457 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1458 unsigned Depth, Index;
1459 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1460 TemplateArgs.setArgument(Depth, Index, Arg);
1461 }
1462 }
1463
1464 /// Transform the given declaration by instantiating a reference to
1465 /// this declaration.
1466 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1467
1468 void transformAttrs(Decl *Old, Decl *New) {
1469 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1470 }
1471
1472 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1473 if (Old->isParameterPack()) {
1475 for (auto *New : NewDecls)
1477 Old, cast<VarDecl>(New));
1478 return;
1479 }
1480
1481 assert(NewDecls.size() == 1 &&
1482 "should only have multiple expansions for a pack");
1483 Decl *New = NewDecls.front();
1484
1485 // If we've instantiated the call operator of a lambda or the call
1486 // operator template of a generic lambda, update the "instantiation of"
1487 // information.
1488 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1489 if (NewMD && isLambdaCallOperator(NewMD)) {
1490 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1491 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1492 NewTD->setInstantiatedFromMemberTemplate(
1493 OldMD->getDescribedFunctionTemplate());
1494 else
1495 NewMD->setInstantiationOfMemberFunction(OldMD,
1497 }
1498
1500
1501 // We recreated a local declaration, but not by instantiating it. There
1502 // may be pending dependent diagnostics to produce.
1503 if (auto *DC = dyn_cast<DeclContext>(Old);
1504 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1505 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1506 }
1507
1508 /// Transform the definition of the given declaration by
1509 /// instantiating it.
1510 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1511
1512 /// Transform the first qualifier within a scope by instantiating the
1513 /// declaration.
1514 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1515
1516 bool TransformExceptionSpec(SourceLocation Loc,
1518 SmallVectorImpl<QualType> &Exceptions,
1519 bool &Changed);
1520
1521 /// Rebuild the exception declaration and register the declaration
1522 /// as an instantiated local.
1523 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1525 SourceLocation StartLoc,
1526 SourceLocation NameLoc,
1527 IdentifierInfo *Name);
1528
1529 /// Rebuild the Objective-C exception declaration and register the
1530 /// declaration as an instantiated local.
1531 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1532 TypeSourceInfo *TSInfo, QualType T);
1533
1534 /// Check for tag mismatches when instantiating an
1535 /// elaborated type.
1536 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1537 ElaboratedTypeKeyword Keyword,
1538 NestedNameSpecifierLoc QualifierLoc,
1539 QualType T);
1540
1542 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1543 SourceLocation NameLoc,
1544 QualType ObjectType = QualType(),
1545 NamedDecl *FirstQualifierInScope = nullptr,
1546 bool AllowInjectedClassName = false);
1547
1548 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1549 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1550 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1551 const Stmt *InstS,
1552 const NoInlineAttr *A);
1553 const AlwaysInlineAttr *
1554 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1555 const AlwaysInlineAttr *A);
1556 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1557 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1558 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1559 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1560
1561 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1563 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1565 ExprResult TransformSubstNonTypeTemplateParmExpr(
1567
1568 /// Rebuild a DeclRefExpr for a VarDecl reference.
1569 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1570
1571 /// Transform a reference to a function or init-capture parameter pack.
1572 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1573
1574 /// Transform a FunctionParmPackExpr which was built when we couldn't
1575 /// expand a function parameter pack reference which refers to an expanded
1576 /// pack.
1577 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1578
1579 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1581 // Call the base version; it will forward to our overridden version below.
1582 return inherited::TransformFunctionProtoType(TLB, TL);
1583 }
1584
1585 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1587 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1588 // Special case for transforming a deduction guide, we return a
1589 // transformed TemplateSpecializationType.
1590 if (Type.isNull() &&
1591 SemaRef.CodeSynthesisContexts.back().Kind ==
1593 // Return a TemplateSpecializationType for transforming a deduction
1594 // guide.
1595 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1596 auto Type =
1597 inherited::TransformType(ICT->getInjectedSpecializationType());
1598 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1599 return Type;
1600 }
1601 }
1602 return Type;
1603 }
1604 // Override the default version to handle a rewrite-template-arg-pack case
1605 // for building a deduction guide.
1606 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1607 TemplateArgumentLoc &Output,
1608 bool Uneval = false) {
1609 const TemplateArgument &Arg = Input.getArgument();
1610 std::vector<TemplateArgument> TArgs;
1611 switch (Arg.getKind()) {
1613 // Literally rewrite the template argument pack, instead of unpacking
1614 // it.
1615 assert(
1616 SemaRef.CodeSynthesisContexts.back().Kind ==
1618 "Transforming a template argument pack is only allowed in building "
1619 "deduction guide");
1620 for (auto &pack : Arg.getPackAsArray()) {
1622 pack, QualType(), SourceLocation{});
1623 TemplateArgumentLoc Output;
1624 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1625 return true; // fails
1626 TArgs.push_back(Output.getArgument());
1627 }
1628 Output = SemaRef.getTrivialTemplateArgumentLoc(
1629 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1631 return false;
1632 default:
1633 break;
1634 }
1635 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1636 }
1637
1638 template<typename Fn>
1639 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1641 CXXRecordDecl *ThisContext,
1642 Qualifiers ThisTypeQuals,
1643 Fn TransformExceptionSpec);
1644
1645 ParmVarDecl *
1646 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1647 std::optional<unsigned> NumExpansions,
1648 bool ExpectParameterPack);
1649
1650 using inherited::TransformTemplateTypeParmType;
1651 /// Transforms a template type parameter type by performing
1652 /// substitution of the corresponding template type argument.
1653 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1655 bool SuppressObjCLifetime);
1656
1657 QualType BuildSubstTemplateTypeParmType(
1658 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1659 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1660 TemplateArgument Arg, SourceLocation NameLoc);
1661
1662 /// Transforms an already-substituted template type parameter pack
1663 /// into either itself (if we aren't substituting into its pack expansion)
1664 /// or the appropriate substituted argument.
1665 using inherited::TransformSubstTemplateTypeParmPackType;
1666 QualType
1667 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1669 bool SuppressObjCLifetime);
1670
1672 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1673 auto &CCS = SemaRef.CodeSynthesisContexts.back();
1674 if (CCS.Kind ==
1676 unsigned TypeAliasDeclDepth = CCS.Entity->getTemplateDepth();
1677 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1678 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1679 }
1680 return inherited::ComputeLambdaDependency(LSI);
1681 }
1682
1683 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1684 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1686
1687 ExprResult Result = inherited::TransformLambdaExpr(E);
1688 if (Result.isInvalid())
1689 return Result;
1690
1691 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1692 for (ParmVarDecl *PVD : MD->parameters()) {
1693 assert(PVD && "null in a parameter list");
1694 if (!PVD->hasDefaultArg())
1695 continue;
1696 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1697 // FIXME: Obtain the source location for the '=' token.
1698 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1699 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1700 // If substitution fails, the default argument is set to a
1701 // RecoveryExpr that wraps the uninstantiated default argument so
1702 // that downstream diagnostics are omitted.
1703 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1704 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1705 { UninstExpr }, UninstExpr->getType());
1706 if (ErrorResult.isUsable())
1707 PVD->setDefaultArg(ErrorResult.get());
1708 }
1709 }
1710
1711 return Result;
1712 }
1713
1714 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1715 // Currently, we instantiate the body when instantiating the lambda
1716 // expression. However, `EvaluateConstraints` is disabled during the
1717 // instantiation of the lambda expression, causing the instantiation
1718 // failure of the return type requirement in the body. If p0588r1 is fully
1719 // implemented, the body will be lazily instantiated, and this problem
1720 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1721 // `true` to temporarily fix this issue.
1722 // FIXME: This temporary fix can be removed after fully implementing
1723 // p0588r1.
1724 bool Prev = EvaluateConstraints;
1725 EvaluateConstraints = true;
1726 StmtResult Stmt = inherited::TransformLambdaBody(E, Body);
1727 EvaluateConstraints = Prev;
1728 return Stmt;
1729 }
1730
1731 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1732 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1733 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1734 if (TransReq.isInvalid())
1735 return TransReq;
1736 assert(TransReq.get() != E &&
1737 "Do not change value of isSatisfied for the existing expression. "
1738 "Create a new expression instead.");
1739 if (E->getBody()->isDependentContext()) {
1740 Sema::SFINAETrap Trap(SemaRef);
1741 // We recreate the RequiresExpr body, but not by instantiating it.
1742 // Produce pending diagnostics for dependent access check.
1743 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1744 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1745 if (Trap.hasErrorOccurred())
1746 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1747 }
1748 return TransReq;
1749 }
1750
1751 bool TransformRequiresExprRequirements(
1754 bool SatisfactionDetermined = false;
1755 for (concepts::Requirement *Req : Reqs) {
1756 concepts::Requirement *TransReq = nullptr;
1757 if (!SatisfactionDetermined) {
1758 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1759 TransReq = TransformTypeRequirement(TypeReq);
1760 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1761 TransReq = TransformExprRequirement(ExprReq);
1762 else
1763 TransReq = TransformNestedRequirement(
1764 cast<concepts::NestedRequirement>(Req));
1765 if (!TransReq)
1766 return true;
1767 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1768 // [expr.prim.req]p6
1769 // [...] The substitution and semantic constraint checking
1770 // proceeds in lexical order and stops when a condition that
1771 // determines the result of the requires-expression is
1772 // encountered. [..]
1773 SatisfactionDetermined = true;
1774 } else
1775 TransReq = Req;
1776 Transformed.push_back(TransReq);
1777 }
1778 return false;
1779 }
1780
1781 TemplateParameterList *TransformTemplateParameterList(
1782 TemplateParameterList *OrigTPL) {
1783 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1784
1785 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1786 TemplateDeclInstantiator DeclInstantiator(getSema(),
1787 /* DeclContext *Owner */ Owner, TemplateArgs);
1788 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1789 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1790 }
1791
1793 TransformTypeRequirement(concepts::TypeRequirement *Req);
1795 TransformExprRequirement(concepts::ExprRequirement *Req);
1797 TransformNestedRequirement(concepts::NestedRequirement *Req);
1798 ExprResult TransformRequiresTypeParams(
1799 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1802 SmallVectorImpl<ParmVarDecl *> &TransParams,
1804
1805 private:
1807 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1808 const NonTypeTemplateParmDecl *parm,
1810 std::optional<unsigned> PackIndex);
1811 };
1812}
1813
1814bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1815 if (T.isNull())
1816 return true;
1817
1819 return false;
1820
1821 getSema().MarkDeclarationsReferencedInType(Loc, T);
1822 return true;
1823}
1824
1825static TemplateArgument
1827 assert(S.ArgumentPackSubstitutionIndex >= 0);
1828 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1830 if (Arg.isPackExpansion())
1831 Arg = Arg.getPackExpansionPattern();
1832 return Arg;
1833}
1834
1835Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1836 if (!D)
1837 return nullptr;
1838
1839 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1840 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1841 // If the corresponding template argument is NULL or non-existent, it's
1842 // because we are performing instantiation from explicitly-specified
1843 // template arguments in a function template, but there were some
1844 // arguments left unspecified.
1845 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1846 TTP->getPosition()))
1847 return D;
1848
1849 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1850
1851 if (TTP->isParameterPack()) {
1852 assert(Arg.getKind() == TemplateArgument::Pack &&
1853 "Missing argument pack");
1854 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1855 }
1856
1858 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1859 "Wrong kind of template template argument");
1860 return Template.getAsTemplateDecl();
1861 }
1862
1863 // Fall through to find the instantiated declaration for this template
1864 // template parameter.
1865 }
1866
1867 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1868}
1869
1870Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1871 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1872 if (!Inst)
1873 return nullptr;
1874
1875 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1876 return Inst;
1877}
1878
1879bool TemplateInstantiator::TransformExceptionSpec(
1881 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1882 if (ESI.Type == EST_Uninstantiated) {
1883 ESI.instantiate();
1884 Changed = true;
1885 }
1886 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1887}
1888
1889NamedDecl *
1890TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1891 SourceLocation Loc) {
1892 // If the first part of the nested-name-specifier was a template type
1893 // parameter, instantiate that type parameter down to a tag type.
1894 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1895 const TemplateTypeParmType *TTP
1896 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1897
1898 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1899 // FIXME: This needs testing w/ member access expressions.
1900 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1901
1902 if (TTP->isParameterPack()) {
1903 assert(Arg.getKind() == TemplateArgument::Pack &&
1904 "Missing argument pack");
1905
1906 if (getSema().ArgumentPackSubstitutionIndex == -1)
1907 return nullptr;
1908
1909 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1910 }
1911
1912 QualType T = Arg.getAsType();
1913 if (T.isNull())
1914 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1915
1916 if (const TagType *Tag = T->getAs<TagType>())
1917 return Tag->getDecl();
1918
1919 // The resulting type is not a tag; complain.
1920 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1921 return nullptr;
1922 }
1923 }
1924
1925 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1926}
1927
1928VarDecl *
1929TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1931 SourceLocation StartLoc,
1932 SourceLocation NameLoc,
1933 IdentifierInfo *Name) {
1934 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1935 StartLoc, NameLoc, Name);
1936 if (Var)
1937 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1938 return Var;
1939}
1940
1941VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1942 TypeSourceInfo *TSInfo,
1943 QualType T) {
1944 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1945 if (Var)
1946 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1947 return Var;
1948}
1949
1951TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1952 ElaboratedTypeKeyword Keyword,
1953 NestedNameSpecifierLoc QualifierLoc,
1954 QualType T) {
1955 if (const TagType *TT = T->getAs<TagType>()) {
1956 TagDecl* TD = TT->getDecl();
1957
1958 SourceLocation TagLocation = KeywordLoc;
1959
1961
1962 // TODO: should we even warn on struct/class mismatches for this? Seems
1963 // like it's likely to produce a lot of spurious errors.
1964 if (Id && Keyword != ElaboratedTypeKeyword::None &&
1967 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1968 TagLocation, Id)) {
1969 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1970 << Id
1972 TD->getKindName());
1973 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1974 }
1975 }
1976 }
1977
1978 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1979}
1980
1981TemplateName TemplateInstantiator::TransformTemplateName(
1982 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1983 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1984 bool AllowInjectedClassName) {
1986 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1987 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1988 // If the corresponding template argument is NULL or non-existent, it's
1989 // because we are performing instantiation from explicitly-specified
1990 // template arguments in a function template, but there were some
1991 // arguments left unspecified.
1992 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1993 TTP->getPosition()))
1994 return Name;
1995
1996 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1997
1998 if (TemplateArgs.isRewrite()) {
1999 // We're rewriting the template parameter as a reference to another
2000 // template parameter.
2001 if (Arg.getKind() == TemplateArgument::Pack) {
2002 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2003 "unexpected pack arguments in template rewrite");
2004 Arg = Arg.pack_begin()->getPackExpansionPattern();
2005 }
2006 assert(Arg.getKind() == TemplateArgument::Template &&
2007 "unexpected nontype template argument kind in template rewrite");
2008 return Arg.getAsTemplate();
2009 }
2010
2011 auto [AssociatedDecl, Final] =
2012 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2013 std::optional<unsigned> PackIndex;
2014 if (TTP->isParameterPack()) {
2015 assert(Arg.getKind() == TemplateArgument::Pack &&
2016 "Missing argument pack");
2017
2018 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2019 // We have the template argument pack to substitute, but we're not
2020 // actually expanding the enclosing pack expansion yet. So, just
2021 // keep the entire argument pack.
2022 return getSema().Context.getSubstTemplateTemplateParmPack(
2023 Arg, AssociatedDecl, TTP->getIndex(), Final);
2024 }
2025
2026 PackIndex = getPackIndex(Arg);
2027 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2028 }
2029
2031 assert(!Template.isNull() && "Null template template argument");
2032 assert(!Template.getAsQualifiedTemplateName() &&
2033 "template decl to substitute is qualified?");
2034
2035 if (Final)
2036 return Template;
2037 return getSema().Context.getSubstTemplateTemplateParm(
2038 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2039 }
2040 }
2041
2043 = Name.getAsSubstTemplateTemplateParmPack()) {
2044 if (getSema().ArgumentPackSubstitutionIndex == -1)
2045 return Name;
2046
2047 TemplateArgument Pack = SubstPack->getArgumentPack();
2048 TemplateName Template =
2050 if (SubstPack->getFinal())
2051 return Template;
2052 return getSema().Context.getSubstTemplateTemplateParm(
2053 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
2054 SubstPack->getIndex(), getPackIndex(Pack));
2055 }
2056
2057 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2058 FirstQualifierInScope,
2059 AllowInjectedClassName);
2060}
2061
2063TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2064 if (!E->isTypeDependent())
2065 return E;
2066
2067 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2068}
2069
2071TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2073 // If the corresponding template argument is NULL or non-existent, it's
2074 // because we are performing instantiation from explicitly-specified
2075 // template arguments in a function template, but there were some
2076 // arguments left unspecified.
2077 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2078 NTTP->getPosition()))
2079 return E;
2080
2081 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2082
2083 if (TemplateArgs.isRewrite()) {
2084 // We're rewriting the template parameter as a reference to another
2085 // template parameter.
2086 if (Arg.getKind() == TemplateArgument::Pack) {
2087 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2088 "unexpected pack arguments in template rewrite");
2089 Arg = Arg.pack_begin()->getPackExpansionPattern();
2090 }
2091 assert(Arg.getKind() == TemplateArgument::Expression &&
2092 "unexpected nontype template argument kind in template rewrite");
2093 // FIXME: This can lead to the same subexpression appearing multiple times
2094 // in a complete expression.
2095 return Arg.getAsExpr();
2096 }
2097
2098 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2099 std::optional<unsigned> PackIndex;
2100 if (NTTP->isParameterPack()) {
2101 assert(Arg.getKind() == TemplateArgument::Pack &&
2102 "Missing argument pack");
2103
2104 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2105 // We have an argument pack, but we can't select a particular argument
2106 // out of it yet. Therefore, we'll build an expression to hold on to that
2107 // argument pack.
2108 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2109 E->getLocation(),
2110 NTTP->getDeclName());
2111 if (TargetType.isNull())
2112 return ExprError();
2113
2114 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2115 if (TargetType->isRecordType())
2116 ExprType.addConst();
2117 // FIXME: Pass in Final.
2119 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2120 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2121 }
2122 PackIndex = getPackIndex(Arg);
2123 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2124 }
2125 // FIXME: Don't put subst node on Final replacement.
2126 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2127 Arg, PackIndex);
2128}
2129
2130const CXXAssumeAttr *
2131TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2132 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2133 if (!Res.isUsable())
2134 return AA;
2135
2136 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2137 AA->getRange());
2138 if (!Res.isUsable())
2139 return AA;
2140
2141 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2142 AA->getRange());
2143}
2144
2145const LoopHintAttr *
2146TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2147 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2148
2149 if (TransformedExpr == LH->getValue())
2150 return LH;
2151
2152 // Generate error if there is a problem with the value.
2153 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2154 LH->getOption() == LoopHintAttr::UnrollCount))
2155 return LH;
2156
2157 // Create new LoopHintValueAttr with integral expression in place of the
2158 // non-type template parameter.
2159 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
2160 LH->getState(), TransformedExpr, *LH);
2161}
2162const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2163 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2164 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2165 return nullptr;
2166
2167 return A;
2168}
2169const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2170 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2171 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2172 return nullptr;
2173
2174 return A;
2175}
2176
2177const CodeAlignAttr *
2178TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2179 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2180 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2181}
2182
2183ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2184 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2186 std::optional<unsigned> PackIndex) {
2187 ExprResult result;
2188
2189 // Determine the substituted parameter type. We can usually infer this from
2190 // the template argument, but not always.
2191 auto SubstParamType = [&] {
2192 QualType T;
2193 if (parm->isExpandedParameterPack())
2195 else
2196 T = parm->getType();
2197 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2198 T = cast<PackExpansionType>(T)->getPattern();
2199 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2200 };
2201
2202 bool refParam = false;
2203
2204 // The template argument itself might be an expression, in which case we just
2205 // return that expression. This happens when substituting into an alias
2206 // template.
2207 if (arg.getKind() == TemplateArgument::Expression) {
2208 Expr *argExpr = arg.getAsExpr();
2209 result = argExpr;
2210 if (argExpr->isLValue()) {
2211 if (argExpr->getType()->isRecordType()) {
2212 // Check whether the parameter was actually a reference.
2213 QualType paramType = SubstParamType();
2214 if (paramType.isNull())
2215 return ExprError();
2216 refParam = paramType->isReferenceType();
2217 } else {
2218 refParam = true;
2219 }
2220 }
2221 } else if (arg.getKind() == TemplateArgument::Declaration ||
2222 arg.getKind() == TemplateArgument::NullPtr) {
2223 if (arg.getKind() == TemplateArgument::Declaration) {
2224 ValueDecl *VD = arg.getAsDecl();
2225
2226 // Find the instantiation of the template argument. This is
2227 // required for nested templates.
2228 VD = cast_or_null<ValueDecl>(
2229 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2230 if (!VD)
2231 return ExprError();
2232 }
2233
2234 QualType paramType = arg.getNonTypeTemplateArgumentType();
2235 assert(!paramType.isNull() && "type substitution failed for param type");
2236 assert(!paramType->isDependentType() && "param type still dependent");
2237 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2238 refParam = paramType->isReferenceType();
2239 } else {
2240 QualType paramType = arg.getNonTypeTemplateArgumentType();
2242 refParam = paramType->isReferenceType();
2243 assert(result.isInvalid() ||
2245 paramType.getNonReferenceType()));
2246 }
2247
2248 if (result.isInvalid())
2249 return ExprError();
2250
2251 Expr *resultExpr = result.get();
2252 // FIXME: Don't put subst node on final replacement.
2254 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2255 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2256}
2257
2259TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2261 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2262 // We aren't expanding the parameter pack, so just return ourselves.
2263 return E;
2264 }
2265
2268 // FIXME: Don't put subst node on final replacement.
2269 return transformNonTypeTemplateParmRef(
2271 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2272}
2273
2275TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2277 ExprResult SubstReplacement = E->getReplacement();
2278 if (!isa<ConstantExpr>(SubstReplacement.get()))
2279 SubstReplacement = TransformExpr(E->getReplacement());
2280 if (SubstReplacement.isInvalid())
2281 return true;
2282 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2283 if (SubstType.isNull())
2284 return true;
2285 // The type may have been previously dependent and not now, which means we
2286 // might have to implicit cast the argument to the new type, for example:
2287 // template<auto T, decltype(T) U>
2288 // concept C = sizeof(U) == 4;
2289 // void foo() requires C<2, 'a'> { }
2290 // When normalizing foo(), we first form the normalized constraints of C:
2291 // AtomicExpr(sizeof(U) == 4,
2292 // U=SubstNonTypeTemplateParmExpr(Param=U,
2293 // Expr=DeclRef(U),
2294 // Type=decltype(T)))
2295 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2296 // produce:
2297 // AtomicExpr(sizeof(U) == 4,
2298 // U=SubstNonTypeTemplateParmExpr(Param=U,
2299 // Expr=ImpCast(
2300 // decltype(2),
2301 // SubstNTTPE(Param=U, Expr='a',
2302 // Type=char)),
2303 // Type=decltype(2)))
2304 // The call to CheckTemplateArgument here produces the ImpCast.
2305 TemplateArgument SugaredConverted, CanonicalConverted;
2306 if (SemaRef
2308 SubstReplacement.get(), SugaredConverted,
2309 CanonicalConverted, Sema::CTAK_Specified)
2310 .isInvalid())
2311 return true;
2312 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2313 E->getParameter(), E->getExprLoc(),
2314 SugaredConverted, E->getPackIndex());
2315}
2316
2317ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2318 SourceLocation Loc) {
2319 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2320 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2321}
2322
2324TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2325 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2326 // We can expand this parameter pack now.
2328 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2329 if (!VD)
2330 return ExprError();
2331 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2332 }
2333
2334 QualType T = TransformType(E->getType());
2335 if (T.isNull())
2336 return ExprError();
2337
2338 // Transform each of the parameter expansions into the corresponding
2339 // parameters in the instantiation of the function decl.
2341 Vars.reserve(E->getNumExpansions());
2342 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2343 I != End; ++I) {
2344 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2345 if (!D)
2346 return ExprError();
2347 Vars.push_back(D);
2348 }
2349
2350 auto *PackExpr =
2352 E->getParameterPackLocation(), Vars);
2353 getSema().MarkFunctionParmPackReferenced(PackExpr);
2354 return PackExpr;
2355}
2356
2358TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2359 VarDecl *PD) {
2360 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2361 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2362 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2363 assert(Found && "no instantiation for parameter pack");
2364
2365 Decl *TransformedDecl;
2366 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2367 // If this is a reference to a function parameter pack which we can
2368 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2369 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2370 QualType T = TransformType(E->getType());
2371 if (T.isNull())
2372 return ExprError();
2373 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2374 E->getExprLoc(), *Pack);
2375 getSema().MarkFunctionParmPackReferenced(PackExpr);
2376 return PackExpr;
2377 }
2378
2379 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2380 } else {
2381 TransformedDecl = Found->get<Decl*>();
2382 }
2383
2384 // We have either an unexpanded pack or a specific expansion.
2385 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2386}
2387
2389TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2390 NamedDecl *D = E->getDecl();
2391
2392 // Handle references to non-type template parameters and non-type template
2393 // parameter packs.
2394 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2395 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2396 return TransformTemplateParmRefExpr(E, NTTP);
2397
2398 // We have a non-type template parameter that isn't fully substituted;
2399 // FindInstantiatedDecl will find it in the local instantiation scope.
2400 }
2401
2402 // Handle references to function parameter packs.
2403 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2404 if (PD->isParameterPack())
2405 return TransformFunctionParmPackRefExpr(E, PD);
2406
2407 return inherited::TransformDeclRefExpr(E);
2408}
2409
2410ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2411 CXXDefaultArgExpr *E) {
2412 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2413 getDescribedFunctionTemplate() &&
2414 "Default arg expressions are never formed in dependent cases.");
2416 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2417 E->getParam());
2418}
2419
2420template<typename Fn>
2421QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2423 CXXRecordDecl *ThisContext,
2424 Qualifiers ThisTypeQuals,
2425 Fn TransformExceptionSpec) {
2426 // We need a local instantiation scope for this function prototype.
2427 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2428 return inherited::TransformFunctionProtoType(
2429 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2430}
2431
2432ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2433 ParmVarDecl *OldParm, int indexAdjustment,
2434 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2435 auto NewParm = SemaRef.SubstParmVarDecl(
2436 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2437 ExpectParameterPack, EvaluateConstraints);
2438 if (NewParm && SemaRef.getLangOpts().OpenCL)
2440 return NewParm;
2441}
2442
2443QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2444 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2445 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2446 TemplateArgument Arg, SourceLocation NameLoc) {
2447 QualType Replacement = Arg.getAsType();
2448
2449 // If the template parameter had ObjC lifetime qualifiers,
2450 // then any such qualifiers on the replacement type are ignored.
2451 if (SuppressObjCLifetime) {
2452 Qualifiers RQs;
2453 RQs = Replacement.getQualifiers();
2454 RQs.removeObjCLifetime();
2455 Replacement =
2456 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2457 }
2458
2459 if (Final) {
2460 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2461 return Replacement;
2462 }
2463 // TODO: only do this uniquing once, at the start of instantiation.
2464 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2465 Replacement, AssociatedDecl, Index, PackIndex);
2468 NewTL.setNameLoc(NameLoc);
2469 return Result;
2470}
2471
2473TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2475 bool SuppressObjCLifetime) {
2476 const TemplateTypeParmType *T = TL.getTypePtr();
2477 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2478 // Replace the template type parameter with its corresponding
2479 // template argument.
2480
2481 // If the corresponding template argument is NULL or doesn't exist, it's
2482 // because we are performing instantiation from explicitly-specified
2483 // template arguments in a function template class, but there were some
2484 // arguments left unspecified.
2485 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2488 NewTL.setNameLoc(TL.getNameLoc());
2489 return TL.getType();
2490 }
2491
2492 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2493
2494 if (TemplateArgs.isRewrite()) {
2495 // We're rewriting the template parameter as a reference to another
2496 // template parameter.
2497 if (Arg.getKind() == TemplateArgument::Pack) {
2498 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2499 "unexpected pack arguments in template rewrite");
2500 Arg = Arg.pack_begin()->getPackExpansionPattern();
2501 }
2502 assert(Arg.getKind() == TemplateArgument::Type &&
2503 "unexpected nontype template argument kind in template rewrite");
2504 QualType NewT = Arg.getAsType();
2505 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2506 return NewT;
2507 }
2508
2509 auto [AssociatedDecl, Final] =
2510 TemplateArgs.getAssociatedDecl(T->getDepth());
2511 std::optional<unsigned> PackIndex;
2512 if (T->isParameterPack()) {
2513 assert(Arg.getKind() == TemplateArgument::Pack &&
2514 "Missing argument pack");
2515
2516 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2517 // We have the template argument pack, but we're not expanding the
2518 // enclosing pack expansion yet. Just save the template argument
2519 // pack for later substitution.
2520 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2521 AssociatedDecl, T->getIndex(), Final, Arg);
2524 NewTL.setNameLoc(TL.getNameLoc());
2525 return Result;
2526 }
2527
2528 // PackIndex starts from last element.
2529 PackIndex = getPackIndex(Arg);
2530 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2531 }
2532
2533 assert(Arg.getKind() == TemplateArgument::Type &&
2534 "Template argument kind mismatch");
2535
2536 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2537 AssociatedDecl, T->getIndex(),
2538 PackIndex, Arg, TL.getNameLoc());
2539 }
2540
2541 // The template type parameter comes from an inner template (e.g.,
2542 // the template parameter list of a member template inside the
2543 // template we are instantiating). Create a new template type
2544 // parameter with the template "level" reduced by one.
2545 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2546 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2547 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2548 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2549 QualType Result = getSema().Context.getTemplateTypeParmType(
2550 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2551 T->isParameterPack(), NewTTPDecl);
2553 NewTL.setNameLoc(TL.getNameLoc());
2554 return Result;
2555}
2556
2557QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2559 bool SuppressObjCLifetime) {
2561
2562 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2563
2564 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2565 // We aren't expanding the parameter pack, so just return ourselves.
2566 QualType Result = TL.getType();
2567 if (NewReplaced != T->getAssociatedDecl())
2568 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2569 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2572 NewTL.setNameLoc(TL.getNameLoc());
2573 return Result;
2574 }
2575
2576 TemplateArgument Pack = T->getArgumentPack();
2578 return BuildSubstTemplateTypeParmType(
2579 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2580 getPackIndex(Pack), Arg, TL.getNameLoc());
2581}
2582
2585 concepts::EntityPrinter Printer) {
2586 SmallString<128> Message;
2587 SourceLocation ErrorLoc;
2588 if (Info.hasSFINAEDiagnostic()) {
2591 Info.takeSFINAEDiagnostic(PDA);
2592 PDA.second.EmitToString(S.getDiagnostics(), Message);
2593 ErrorLoc = PDA.first;
2594 } else {
2595 ErrorLoc = Info.getLocation();
2596 }
2597 char *MessageBuf = new (S.Context) char[Message.size()];
2598 std::copy(Message.begin(), Message.end(), MessageBuf);
2599 SmallString<128> Entity;
2600 llvm::raw_svector_ostream OS(Entity);
2601 Printer(OS);
2602 char *EntityBuf = new (S.Context) char[Entity.size()];
2603 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2605 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2606 StringRef(MessageBuf, Message.size())};
2607}
2608
2611 EntityPrinter Printer) {
2612 SmallString<128> Entity;
2613 llvm::raw_svector_ostream OS(Entity);
2614 Printer(OS);
2615 char *EntityBuf = new (S.Context) char[Entity.size()];
2616 llvm::copy(Entity, EntityBuf);
2618 /*SubstitutedEntity=*/StringRef(EntityBuf, Entity.size()),
2619 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2620}
2621
2622ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2623 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2626 SmallVectorImpl<ParmVarDecl *> &TransParams,
2628
2629 TemplateDeductionInfo Info(KWLoc);
2630 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2631 RE, Info,
2632 SourceRange{KWLoc, RBraceLoc});
2634
2635 unsigned ErrorIdx;
2636 if (getDerived().TransformFunctionTypeParams(
2637 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2638 &TransParams, PInfos, &ErrorIdx) ||
2639 Trap.hasErrorOccurred()) {
2641 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2642 // Add a 'failed' Requirement to contain the error that caused the failure
2643 // here.
2644 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2645 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2646 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2647 TransParams, RE->getRParenLoc(),
2648 TransReqs, RBraceLoc);
2649 }
2650
2651 return ExprResult{};
2652}
2653
2655TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2656 if (!Req->isDependent() && !AlwaysRebuild())
2657 return Req;
2658 if (Req->isSubstitutionFailure()) {
2659 if (AlwaysRebuild())
2660 return RebuildTypeRequirement(
2662 return Req;
2663 }
2664
2668 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2669 Req->getType()->getTypeLoc().getSourceRange());
2670 if (TypeInst.isInvalid())
2671 return nullptr;
2672 TypeSourceInfo *TransType = TransformType(Req->getType());
2673 if (!TransType || Trap.hasErrorOccurred())
2674 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2675 [&] (llvm::raw_ostream& OS) {
2676 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2677 }));
2678 return RebuildTypeRequirement(TransType);
2679}
2680
2682TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2683 if (!Req->isDependent() && !AlwaysRebuild())
2684 return Req;
2685
2687
2688 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2689 TransExpr;
2690 if (Req->isExprSubstitutionFailure())
2691 TransExpr = Req->getExprSubstitutionDiagnostic();
2692 else {
2693 Expr *E = Req->getExpr();
2695 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2696 E->getSourceRange());
2697 if (ExprInst.isInvalid())
2698 return nullptr;
2699 ExprResult TransExprRes = TransformExpr(E);
2700 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2701 TransExprRes.get()->hasPlaceholderType())
2702 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2703 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2704 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2705 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2706 });
2707 else
2708 TransExpr = TransExprRes.get();
2709 }
2710
2711 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2712 const auto &RetReq = Req->getReturnTypeRequirement();
2713 if (RetReq.isEmpty())
2714 TransRetReq.emplace();
2715 else if (RetReq.isSubstitutionFailure())
2716 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2717 else if (RetReq.isTypeConstraint()) {
2718 TemplateParameterList *OrigTPL =
2719 RetReq.getTypeConstraintTemplateParameterList();
2720 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2722 Req, Info, OrigTPL->getSourceRange());
2723 if (TPLInst.isInvalid())
2724 return nullptr;
2725 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2726 if (!TPL)
2727 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2728 [&] (llvm::raw_ostream& OS) {
2729 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2730 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2731 }));
2732 else {
2733 TPLInst.Clear();
2734 TransRetReq.emplace(TPL);
2735 }
2736 }
2737 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2738 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2739 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2740 std::move(*TransRetReq));
2741 return RebuildExprRequirement(
2743 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2744}
2745
2747TemplateInstantiator::TransformNestedRequirement(
2749 if (!Req->isDependent() && !AlwaysRebuild())
2750 return Req;
2751 if (Req->hasInvalidConstraint()) {
2752 if (AlwaysRebuild())
2753 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2755 return Req;
2756 }
2758 Req->getConstraintExpr()->getBeginLoc(), Req,
2761 if (!getEvaluateConstraints()) {
2762 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2763 if (TransConstraint.isInvalid() || !TransConstraint.get())
2764 return nullptr;
2765 if (TransConstraint.get()->isInstantiationDependent())
2766 return new (SemaRef.Context)
2767 concepts::NestedRequirement(TransConstraint.get());
2768 ConstraintSatisfaction Satisfaction;
2770 SemaRef.Context, TransConstraint.get(), Satisfaction);
2771 }
2772
2773 ExprResult TransConstraint;
2774 ConstraintSatisfaction Satisfaction;
2776 {
2781 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2783 if (ConstrInst.isInvalid())
2784 return nullptr;
2787 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2788 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2789 !Result.empty())
2790 TransConstraint = Result[0];
2791 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2792 "by CheckConstraintSatisfaction.");
2793 }
2794 if (TransConstraint.isUsable() &&
2795 TransConstraint.get()->isInstantiationDependent())
2796 return new (SemaRef.Context)
2797 concepts::NestedRequirement(TransConstraint.get());
2798 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2799 Satisfaction.HasSubstitutionFailure()) {
2800 SmallString<128> Entity;
2801 llvm::raw_svector_ostream OS(Entity);
2802 Req->getConstraintExpr()->printPretty(OS, nullptr,
2804 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2805 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2807 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2808 }
2810 SemaRef.Context, TransConstraint.get(), Satisfaction);
2811}
2812
2813
2814/// Perform substitution on the type T with a given set of template
2815/// arguments.
2816///
2817/// This routine substitutes the given template arguments into the
2818/// type T and produces the instantiated type.
2819///
2820/// \param T the type into which the template arguments will be
2821/// substituted. If this type is not dependent, it will be returned
2822/// immediately.
2823///
2824/// \param Args the template arguments that will be
2825/// substituted for the top-level template parameters within T.
2826///
2827/// \param Loc the location in the source code where this substitution
2828/// is being performed. It will typically be the location of the
2829/// declarator (if we're instantiating the type of some declaration)
2830/// or the location of the type in the source code (if, e.g., we're
2831/// instantiating the type of a cast expression).
2832///
2833/// \param Entity the name of the entity associated with a declaration
2834/// being instantiated (if any). May be empty to indicate that there
2835/// is no such entity (if, e.g., this is a type that occurs as part of
2836/// a cast expression) or that the entity has no name (e.g., an
2837/// unnamed function parameter).
2838///
2839/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2840/// acceptable as the top level type of the result.
2841///
2842/// \returns If the instantiation succeeds, the instantiated
2843/// type. Otherwise, produces diagnostics and returns a NULL type.
2846 SourceLocation Loc,
2847 DeclarationName Entity,
2848 bool AllowDeducedTST) {
2849 assert(!CodeSynthesisContexts.empty() &&
2850 "Cannot perform an instantiation without some context on the "
2851 "instantiation stack");
2852
2853 if (!T->getType()->isInstantiationDependentType() &&
2854 !T->getType()->isVariablyModifiedType())
2855 return T;
2856
2857 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2858 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2859 : Instantiator.TransformType(T);
2860}
2861
2864 SourceLocation Loc,
2865 DeclarationName Entity) {
2866 assert(!CodeSynthesisContexts.empty() &&
2867 "Cannot perform an instantiation without some context on the "
2868 "instantiation stack");
2869
2870 if (TL.getType().isNull())
2871 return nullptr;
2872
2875 // FIXME: Make a copy of the TypeLoc data here, so that we can
2876 // return a new TypeSourceInfo. Inefficient!
2877 TypeLocBuilder TLB;
2878 TLB.pushFullCopy(TL);
2879 return TLB.getTypeSourceInfo(Context, TL.getType());
2880 }
2881
2882 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2883 TypeLocBuilder TLB;
2884 TLB.reserve(TL.getFullDataSize());
2885 QualType Result = Instantiator.TransformType(TLB, TL);
2886 if (Result.isNull())
2887 return nullptr;
2888
2889 return TLB.getTypeSourceInfo(Context, Result);
2890}
2891
2892/// Deprecated form of the above.
2894 const MultiLevelTemplateArgumentList &TemplateArgs,
2895 SourceLocation Loc, DeclarationName Entity) {
2896 assert(!CodeSynthesisContexts.empty() &&
2897 "Cannot perform an instantiation without some context on the "
2898 "instantiation stack");
2899
2900 // If T is not a dependent type or a variably-modified type, there
2901 // is nothing to do.
2903 return T;
2904
2905 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2906 return Instantiator.TransformType(T);
2907}
2908
2910 if (T->getType()->isInstantiationDependentType() ||
2911 T->getType()->isVariablyModifiedType())
2912 return true;
2913
2914 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2915 if (!TL.getAs<FunctionProtoTypeLoc>())
2916 return false;
2917
2919 for (ParmVarDecl *P : FP.getParams()) {
2920 // This must be synthesized from a typedef.
2921 if (!P) continue;
2922
2923 // If there are any parameters, a new TypeSourceInfo that refers to the
2924 // instantiated parameters must be built.
2925 return true;
2926 }
2927
2928 return false;
2929}
2930
2931/// A form of SubstType intended specifically for instantiating the
2932/// type of a FunctionDecl. Its purpose is solely to force the
2933/// instantiation of default-argument expressions and to avoid
2934/// instantiating an exception-specification.
2937 SourceLocation Loc,
2938 DeclarationName Entity,
2939 CXXRecordDecl *ThisContext,
2940 Qualifiers ThisTypeQuals,
2941 bool EvaluateConstraints) {
2942 assert(!CodeSynthesisContexts.empty() &&
2943 "Cannot perform an instantiation without some context on the "
2944 "instantiation stack");
2945
2947 return T;
2948
2949 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2950 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2951
2952 TypeLocBuilder TLB;
2953
2954 TypeLoc TL = T->getTypeLoc();
2955 TLB.reserve(TL.getFullDataSize());
2956
2958
2959 if (FunctionProtoTypeLoc Proto =
2961 // Instantiate the type, other than its exception specification. The
2962 // exception specification is instantiated in InitFunctionInstantiation
2963 // once we've built the FunctionDecl.
2964 // FIXME: Set the exception specification to EST_Uninstantiated here,
2965 // instead of rebuilding the function type again later.
2966 Result = Instantiator.TransformFunctionProtoType(
2967 TLB, Proto, ThisContext, ThisTypeQuals,
2969 bool &Changed) { return false; });
2970 } else {
2971 Result = Instantiator.TransformType(TLB, TL);
2972 }
2973 // When there are errors resolving types, clang may use IntTy as a fallback,
2974 // breaking our assumption that function declarations have function types.
2975 if (Result.isNull() || !Result->isFunctionType())
2976 return nullptr;
2977
2978 return TLB.getTypeSourceInfo(Context, Result);
2979}
2980
2983 SmallVectorImpl<QualType> &ExceptionStorage,
2984 const MultiLevelTemplateArgumentList &Args) {
2985 bool Changed = false;
2986 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2987 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2988 Changed);
2989}
2990
2992 const MultiLevelTemplateArgumentList &Args) {
2995
2996 SmallVector<QualType, 4> ExceptionStorage;
2998 ESI, ExceptionStorage, Args))
2999 // On error, recover by dropping the exception specification.
3000 ESI.Type = EST_None;
3001
3002 UpdateExceptionSpec(New, ESI);
3003}
3004
3005namespace {
3006
3007 struct GetContainedInventedTypeParmVisitor :
3008 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3009 TemplateTypeParmDecl *> {
3010 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3011 TemplateTypeParmDecl *>::Visit;
3012
3014 if (T.isNull())
3015 return nullptr;
3016 return Visit(T.getTypePtr());
3017 }
3018 // The deduced type itself.
3019 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3020 const TemplateTypeParmType *T) {
3021 if (!T->getDecl() || !T->getDecl()->isImplicit())
3022 return nullptr;
3023 return T->getDecl();
3024 }
3025
3026 // Only these types can contain 'auto' types, and subsequently be replaced
3027 // by references to invented parameters.
3028
3029 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3030 return Visit(T->getNamedType());
3031 }
3032
3033 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3034 return Visit(T->getPointeeType());
3035 }
3036
3037 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3038 return Visit(T->getPointeeType());
3039 }
3040
3041 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3042 return Visit(T->getPointeeTypeAsWritten());
3043 }
3044
3045 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3046 return Visit(T->getPointeeType());
3047 }
3048
3049 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3050 return Visit(T->getElementType());
3051 }
3052
3053 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3055 return Visit(T->getElementType());
3056 }
3057
3058 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3059 return Visit(T->getElementType());
3060 }
3061
3062 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3063 return VisitFunctionType(T);
3064 }
3065
3066 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3067 return Visit(T->getReturnType());
3068 }
3069
3070 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3071 return Visit(T->getInnerType());
3072 }
3073
3074 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3075 return Visit(T->getModifiedType());
3076 }
3077
3078 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3079 return Visit(T->getUnderlyingType());
3080 }
3081
3082 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3083 return Visit(T->getOriginalType());
3084 }
3085
3086 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3087 return Visit(T->getPattern());
3088 }
3089 };
3090
3091} // namespace
3092
3094 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3095 const MultiLevelTemplateArgumentList &TemplateArgs,
3096 bool EvaluateConstraints) {
3097 const ASTTemplateArgumentListInfo *TemplArgInfo =
3099
3100 if (!EvaluateConstraints) {
3103 return false;
3104 }
3105
3106 TemplateArgumentListInfo InstArgs;
3107
3108 if (TemplArgInfo) {
3109 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3110 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3111 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3112 InstArgs))
3113 return true;
3114 }
3115 return AttachTypeConstraint(
3117 TC->getNamedConcept(),
3118 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3119 Inst->isParameterPack()
3120 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3121 ->getEllipsisLoc()
3122 : SourceLocation());
3123}
3124
3126 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3127 int indexAdjustment, std::optional<unsigned> NumExpansions,
3128 bool ExpectParameterPack, bool EvaluateConstraint) {
3129 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3130 TypeSourceInfo *NewDI = nullptr;
3131
3132 TypeLoc OldTL = OldDI->getTypeLoc();
3133 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3134
3135 // We have a function parameter pack. Substitute into the pattern of the
3136 // expansion.
3137 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3138 OldParm->getLocation(), OldParm->getDeclName());
3139 if (!NewDI)
3140 return nullptr;
3141
3142 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3143 // We still have unexpanded parameter packs, which means that
3144 // our function parameter is still a function parameter pack.
3145 // Therefore, make its type a pack expansion type.
3146 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3147 NumExpansions);
3148 } else if (ExpectParameterPack) {
3149 // We expected to get a parameter pack but didn't (because the type
3150 // itself is not a pack expansion type), so complain. This can occur when
3151 // the substitution goes through an alias template that "loses" the
3152 // pack expansion.
3153 Diag(OldParm->getLocation(),
3154 diag::err_function_parameter_pack_without_parameter_packs)
3155 << NewDI->getType();
3156 return nullptr;
3157 }
3158 } else {
3159 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3160 OldParm->getDeclName());
3161 }
3162
3163 if (!NewDI)
3164 return nullptr;
3165
3166 if (NewDI->getType()->isVoidType()) {
3167 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3168 return nullptr;
3169 }
3170
3171 // In abbreviated templates, TemplateTypeParmDecls with possible
3172 // TypeConstraints are created when the parameter list is originally parsed.
3173 // The TypeConstraints can therefore reference other functions parameters in
3174 // the abbreviated function template, which is why we must instantiate them
3175 // here, when the instantiated versions of those referenced parameters are in
3176 // scope.
3177 if (TemplateTypeParmDecl *TTP =
3178 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3179 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3180 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3181 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3182 // We will first get here when instantiating the abbreviated function
3183 // template's described function, but we might also get here later.
3184 // Make sure we do not instantiate the TypeConstraint more than once.
3185 if (Inst && !Inst->getTypeConstraint()) {
3186 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3187 return nullptr;
3188 }
3189 }
3190 }
3191
3193 OldParm->getInnerLocStart(),
3194 OldParm->getLocation(),
3195 OldParm->getIdentifier(),
3196 NewDI->getType(), NewDI,
3197 OldParm->getStorageClass());
3198 if (!NewParm)
3199 return nullptr;
3200
3201 // Mark the (new) default argument as uninstantiated (if any).
3202 if (OldParm->hasUninstantiatedDefaultArg()) {
3203 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3204 NewParm->setUninstantiatedDefaultArg(Arg);
3205 } else if (OldParm->hasUnparsedDefaultArg()) {
3206 NewParm->setUnparsedDefaultArg();
3207 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3208 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3209 // Default arguments cannot be substituted until the declaration context
3210 // for the associated function or lambda capture class is available.
3211 // This is necessary for cases like the following where construction of
3212 // the lambda capture class for the outer lambda is dependent on the
3213 // parameter types but where the default argument is dependent on the
3214 // outer lambda's declaration context.
3215 // template <typename T>
3216 // auto f() {
3217 // return [](T = []{ return T{}; }()) { return 0; };
3218 // }
3219 NewParm->setUninstantiatedDefaultArg(Arg);
3220 }
3221
3225
3226 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3227 // Add the new parameter to the instantiated parameter pack.
3229 } else {
3230 // Introduce an Old -> New mapping
3232 }
3233
3234 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3235 // can be anything, is this right ?
3236 NewParm->setDeclContext(CurContext);
3237
3238 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3239 OldParm->getFunctionScopeIndex() + indexAdjustment);
3240
3241 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3242
3243 return NewParm;
3244}
3245
3246/// Substitute the given template arguments into the given set of
3247/// parameters, producing the set of parameter types that would be generated
3248/// from such a substitution.
3251 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3252 const MultiLevelTemplateArgumentList &TemplateArgs,
3253 SmallVectorImpl<QualType> &ParamTypes,
3255 ExtParameterInfoBuilder &ParamInfos) {
3256 assert(!CodeSynthesisContexts.empty() &&
3257 "Cannot perform an instantiation without some context on the "
3258 "instantiation stack");
3259
3260 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3261 DeclarationName());
3262 return Instantiator.TransformFunctionTypeParams(
3263 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3264}
3265
3266/// Substitute the given template arguments into the default argument.
3268 SourceLocation Loc,
3269 ParmVarDecl *Param,
3270 const MultiLevelTemplateArgumentList &TemplateArgs,
3271 bool ForCallExpr) {
3272 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3273 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3274
3277
3278 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3279 if (Inst.isInvalid())
3280 return true;
3281 if (Inst.isAlreadyInstantiating()) {
3282 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3283 Param->setInvalidDecl();
3284 return true;
3285 }
3286
3288 {
3289 // C++ [dcl.fct.default]p5:
3290 // The names in the [default argument] expression are bound, and
3291 // the semantic constraints are checked, at the point where the
3292 // default argument expression appears.
3293 ContextRAII SavedContext(*this, FD);
3294 std::unique_ptr<LocalInstantiationScope> LIS;
3295 MultiLevelTemplateArgumentList NewTemplateArgs = TemplateArgs;
3296
3297 if (ForCallExpr) {
3298 // When instantiating a default argument due to use in a call expression,
3299 // an instantiation scope that includes the parameters of the callee is
3300 // required to satisfy references from the default argument. For example:
3301 // template<typename T> void f(T a, int = decltype(a)());
3302 // void g() { f(0); }
3303 LIS = std::make_unique<LocalInstantiationScope>(*this);
3305 /*ForDefinition*/ false);
3306 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3307 return true;
3308 const FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate();
3309 if (PrimaryTemplate && PrimaryTemplate->isOutOfLine()) {
3310 TemplateArgumentList *CurrentTemplateArgumentList =
3312 TemplateArgs.getInnermost());
3313 NewTemplateArgs = getTemplateInstantiationArgs(
3314 FD, FD->getDeclContext(), /*Final=*/false,
3315 CurrentTemplateArgumentList->asArray(), /*RelativeToPrimary=*/true);
3316 }
3317 }
3318
3320 Result = SubstInitializer(PatternExpr, NewTemplateArgs,
3321 /*DirectInit*/ false);
3322 });
3323 }
3324 if (Result.isInvalid())
3325 return true;
3326
3327 if (ForCallExpr) {
3328 // Check the expression as an initializer for the parameter.
3329 InitializedEntity Entity
3332 Param->getLocation(),
3333 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3334 Expr *ResultE = Result.getAs<Expr>();
3335
3336 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3337 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3338 if (Result.isInvalid())
3339 return true;
3340
3341 Result =
3343 /*DiscardedValue*/ false);
3344 } else {
3345 // FIXME: Obtain the source location for the '=' token.
3346 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3347 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3348 }
3349 if (Result.isInvalid())
3350 return true;
3351
3352 // Remember the instantiated default argument.
3353 Param->setDefaultArg(Result.getAs<Expr>());
3354
3355 return false;
3356}
3357
3358/// Perform substitution on the base class specifiers of the
3359/// given class template specialization.
3360///
3361/// Produces a diagnostic and returns true on error, returns false and
3362/// attaches the instantiated base classes to the class template
3363/// specialization if successful.
3364bool
3366 CXXRecordDecl *Pattern,
3367 const MultiLevelTemplateArgumentList &TemplateArgs) {
3368 bool Invalid = false;
3369 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3370 for (const auto &Base : Pattern->bases()) {
3371 if (!Base.getType()->isDependentType()) {
3372 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3373 if (RD->isInvalidDecl())
3374 Instantiation->setInvalidDecl();
3375 }
3376 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3377 continue;
3378 }
3379
3380 SourceLocation EllipsisLoc;
3381 TypeSourceInfo *BaseTypeLoc;
3382 if (Base.isPackExpansion()) {
3383 // This is a pack expansion. See whether we should expand it now, or
3384 // wait until later.
3386 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3387 Unexpanded);
3388 bool ShouldExpand = false;
3389 bool RetainExpansion = false;
3390 std::optional<unsigned> NumExpansions;
3391 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3392 Base.getSourceRange(),
3393 Unexpanded,
3394 TemplateArgs, ShouldExpand,
3395 RetainExpansion,
3396 NumExpansions)) {
3397 Invalid = true;
3398 continue;
3399 }
3400
3401 // If we should expand this pack expansion now, do so.
3402 if (ShouldExpand) {
3403 for (unsigned I = 0; I != *NumExpansions; ++I) {
3404 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3405
3406 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3407 TemplateArgs,
3408 Base.getSourceRange().getBegin(),
3409 DeclarationName());
3410 if (!BaseTypeLoc) {
3411 Invalid = true;
3412 continue;
3413 }
3414
3415 if (CXXBaseSpecifier *InstantiatedBase
3416 = CheckBaseSpecifier(Instantiation,
3417 Base.getSourceRange(),
3418 Base.isVirtual(),
3419 Base.getAccessSpecifierAsWritten(),
3420 BaseTypeLoc,
3421 SourceLocation()))
3422 InstantiatedBases.push_back(InstantiatedBase);
3423 else
3424 Invalid = true;
3425 }
3426
3427 continue;
3428 }
3429
3430 // The resulting base specifier will (still) be a pack expansion.
3431 EllipsisLoc = Base.getEllipsisLoc();
3432 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3433 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3434 TemplateArgs,
3435 Base.getSourceRange().getBegin(),
3436 DeclarationName());
3437 } else {
3438 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3439 TemplateArgs,
3440 Base.getSourceRange().getBegin(),
3441 DeclarationName());
3442 }
3443
3444 if (!BaseTypeLoc) {
3445 Invalid = true;
3446 continue;
3447 }
3448
3449 if (CXXBaseSpecifier *InstantiatedBase
3450 = CheckBaseSpecifier(Instantiation,
3451 Base.getSourceRange(),
3452 Base.isVirtual(),
3453 Base.getAccessSpecifierAsWritten(),
3454 BaseTypeLoc,
3455 EllipsisLoc))
3456 InstantiatedBases.push_back(InstantiatedBase);
3457 else
3458 Invalid = true;
3459 }
3460
3461 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3462 Invalid = true;
3463
3464 return Invalid;
3465}
3466
3467// Defined via #include from SemaTemplateInstantiateDecl.cpp
3468namespace clang {
3469 namespace sema {
3471 const MultiLevelTemplateArgumentList &TemplateArgs);
3473 const Attr *At, ASTContext &C, Sema &S,
3474 const MultiLevelTemplateArgumentList &TemplateArgs);
3475 }
3476}
3477
3478/// Instantiate the definition of a class from a given pattern.
3479///
3480/// \param PointOfInstantiation The point of instantiation within the
3481/// source code.
3482///
3483/// \param Instantiation is the declaration whose definition is being
3484/// instantiated. This will be either a class template specialization
3485/// or a member class of a class template specialization.
3486///
3487/// \param Pattern is the pattern from which the instantiation
3488/// occurs. This will be either the declaration of a class template or
3489/// the declaration of a member class of a class template.
3490///
3491/// \param TemplateArgs The template arguments to be substituted into
3492/// the pattern.
3493///
3494/// \param TSK the kind of implicit or explicit instantiation to perform.
3495///
3496/// \param Complain whether to complain if the class cannot be instantiated due
3497/// to the lack of a definition.
3498///
3499/// \returns true if an error occurred, false otherwise.
3500bool
3502 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3503 const MultiLevelTemplateArgumentList &TemplateArgs,
3505 bool Complain) {
3506 CXXRecordDecl *PatternDef
3507 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3508 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3509 Instantiation->getInstantiatedFromMemberClass(),
3510 Pattern, PatternDef, TSK, Complain))
3511 return true;
3512
3513 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3514 std::string Name;
3515 llvm::raw_string_ostream OS(Name);
3516 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3517 /*Qualified=*/true);
3518 return Name;
3519 });
3520
3521 Pattern = PatternDef;
3522
3523 // Record the point of instantiation.
3524 if (MemberSpecializationInfo *MSInfo
3525 = Instantiation->getMemberSpecializationInfo()) {
3526 MSInfo->setTemplateSpecializationKind(TSK);
3527 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3528 } else if (ClassTemplateSpecializationDecl *Spec
3529 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3530 Spec->setTemplateSpecializationKind(TSK);
3531 Spec->setPointOfInstantiation(PointOfInstantiation);
3532 }
3533
3534 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3535 if (Inst.isInvalid())
3536 return true;
3537 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3538 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3539 "instantiating class definition");
3540
3541 // Enter the scope of this instantiation. We don't use
3542 // PushDeclContext because we don't have a scope.
3543 ContextRAII SavedContext(*this, Instantiation);
3546
3547 // If this is an instantiation of a local class, merge this local
3548 // instantiation scope with the enclosing scope. Otherwise, every
3549 // instantiation of a class has its own local instantiation scope.
3550 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3551 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3552
3553 // Some class state isn't processed immediately but delayed till class
3554 // instantiation completes. We may not be ready to handle any delayed state
3555 // already on the stack as it might correspond to a different class, so save
3556 // it now and put it back later.
3557 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3558
3559 // Pull attributes from the pattern onto the instantiation.
3560 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3561
3562 // Start the definition of this instantiation.
3563 Instantiation->startDefinition();
3564
3565 // The instantiation is visible here, even if it was first declared in an
3566 // unimported module.
3567 Instantiation->setVisibleDespiteOwningModule();
3568
3569 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3570 Instantiation->setTagKind(Pattern->getTagKind());
3571
3572 // Do substitution on the base class specifiers.
3573 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3574 Instantiation->setInvalidDecl();
3575
3576 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3577 Instantiator.setEvaluateConstraints(false);
3578 SmallVector<Decl*, 4> Fields;
3579 // Delay instantiation of late parsed attributes.
3580 LateInstantiatedAttrVec LateAttrs;
3581 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3582
3583 bool MightHaveConstexprVirtualFunctions = false;
3584 for (auto *Member : Pattern->decls()) {
3585 // Don't instantiate members not belonging in this semantic context.
3586 // e.g. for:
3587 // @code
3588 // template <int i> class A {
3589 // class B *g;
3590 // };
3591 // @endcode
3592 // 'class B' has the template as lexical context but semantically it is
3593 // introduced in namespace scope.
3594 if (Member->getDeclContext() != Pattern)
3595 continue;
3596
3597 // BlockDecls can appear in a default-member-initializer. They must be the
3598 // child of a BlockExpr, so we only know how to instantiate them from there.
3599 // Similarly, lambda closure types are recreated when instantiating the
3600 // corresponding LambdaExpr.
3601 if (isa<BlockDecl>(Member) ||
3602 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3603 continue;
3604
3605 if (Member->isInvalidDecl()) {
3606 Instantiation->setInvalidDecl();
3607 continue;
3608 }
3609
3610 Decl *NewMember = Instantiator.Visit(Member);
3611 if (NewMember) {
3612 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3613 Fields.push_back(Field);
3614 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3615 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3616 // specialization causes the implicit instantiation of the definitions
3617 // of unscoped member enumerations.
3618 // Record a point of instantiation for this implicit instantiation.
3619 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3620 Enum->isCompleteDefinition()) {
3621 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3622 assert(MSInfo && "no spec info for member enum specialization");
3624 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3625 }
3626 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3627 if (SA->isFailed()) {
3628 // A static_assert failed. Bail out; instantiating this
3629 // class is probably not meaningful.
3630 Instantiation->setInvalidDecl();
3631 break;
3632 }
3633 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3634 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3635 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3636 MightHaveConstexprVirtualFunctions = true;
3637 }
3638
3639 if (NewMember->isInvalidDecl())
3640 Instantiation->setInvalidDecl();
3641 } else {
3642 // FIXME: Eventually, a NULL return will mean that one of the
3643 // instantiations was a semantic disaster, and we'll want to mark the
3644 // declaration invalid.
3645 // For now, we expect to skip some members that we can't yet handle.
3646 }
3647 }
3648
3649 // Finish checking fields.
3650 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3652 CheckCompletedCXXClass(nullptr, Instantiation);
3653
3654 // Default arguments are parsed, if not instantiated. We can go instantiate
3655 // default arg exprs for default constructors if necessary now. Unless we're
3656 // parsing a class, in which case wait until that's finished.
3657 if (ParsingClassDepth == 0)
3659
3660 // Instantiate late parsed attributes, and attach them to their decls.
3661 // See Sema::InstantiateAttrs
3662 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3663 E = LateAttrs.end(); I != E; ++I) {
3664 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3665 CurrentInstantiationScope = I->Scope;
3666
3667 // Allow 'this' within late-parsed attributes.
3668 auto *ND = cast<NamedDecl>(I->NewDecl);
3669 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3670 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3671 ND->isCXXInstanceMember());
3672
3673 Attr *NewAttr =
3674 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3675 if (NewAttr)
3676 I->NewDecl->addAttr(NewAttr);
3678 Instantiator.getStartingScope());
3679 }
3680 Instantiator.disableLateAttributeInstantiation();
3681 LateAttrs.clear();
3682
3684
3685 // FIXME: We should do something similar for explicit instantiations so they
3686 // end up in the right module.
3687 if (TSK == TSK_ImplicitInstantiation) {
3688 Instantiation->setLocation(Pattern->getLocation());
3689 Instantiation->setLocStart(Pattern->getInnerLocStart());
3690 Instantiation->setBraceRange(Pattern->getBraceRange());
3691 }
3692
3693 if (!Instantiation->isInvalidDecl()) {
3694 // Perform any dependent diagnostics from the pattern.
3695 if (Pattern->isDependentContext())
3696 PerformDependentDiagnostics(Pattern, TemplateArgs);
3697
3698 // Instantiate any out-of-line class template partial
3699 // specializations now.
3701 P = Instantiator.delayed_partial_spec_begin(),
3702 PEnd = Instantiator.delayed_partial_spec_end();
3703 P != PEnd; ++P) {
3705 P->first, P->second)) {
3706 Instantiation->setInvalidDecl();
3707 break;
3708 }
3709 }
3710
3711 // Instantiate any out-of-line variable template partial
3712 // specializations now.
3714 P = Instantiator.delayed_var_partial_spec_begin(),
3715 PEnd = Instantiator.delayed_var_partial_spec_end();
3716 P != PEnd; ++P) {
3718 P->first, P->second)) {
3719 Instantiation->setInvalidDecl();
3720 break;
3721 }
3722 }
3723 }
3724
3725 // Exit the scope of this instantiation.
3726 SavedContext.pop();
3727
3728 if (!Instantiation->isInvalidDecl()) {
3729 // Always emit the vtable for an explicit instantiation definition
3730 // of a polymorphic class template specialization. Otherwise, eagerly
3731 // instantiate only constexpr virtual functions in preparation for their use
3732 // in constant evaluation.
3734 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3735 else if (MightHaveConstexprVirtualFunctions)
3736 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3737 /*ConstexprOnly*/ true);
3738 }
3739
3740 Consumer.HandleTagDeclDefinition(Instantiation);
3741
3742 return Instantiation->isInvalidDecl();
3743}
3744
3745/// Instantiate the definition of an enum from a given pattern.
3746///
3747/// \param PointOfInstantiation The point of instantiation within the
3748/// source code.
3749/// \param Instantiation is the declaration whose definition is being
3750/// instantiated. This will be a member enumeration of a class
3751/// temploid specialization, or a local enumeration within a
3752/// function temploid specialization.
3753/// \param Pattern The templated declaration from which the instantiation
3754/// occurs.
3755/// \param TemplateArgs The template arguments to be substituted into
3756/// the pattern.
3757/// \param TSK The kind of implicit or explicit instantiation to perform.
3758///
3759/// \return \c true if an error occurred, \c false otherwise.
3760bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3761 EnumDecl *Instantiation, EnumDecl *Pattern,
3762 const MultiLevelTemplateArgumentList &TemplateArgs,
3764 EnumDecl *PatternDef = Pattern->getDefinition();
3765 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3766 Instantiation->getInstantiatedFromMemberEnum(),
3767 Pattern, PatternDef, TSK,/*Complain*/true))
3768 return true;
3769 Pattern = PatternDef;
3770
3771 // Record the point of instantiation.
3772 if (MemberSpecializationInfo *MSInfo
3773 = Instantiation->getMemberSpecializationInfo()) {
3774 MSInfo->setTemplateSpecializationKind(TSK);
3775 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3776 }
3777
3778 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3779 if (Inst.isInvalid())
3780 return true;
3781 if (Inst.isAlreadyInstantiating())
3782 return false;
3783 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3784 "instantiating enum definition");
3785
3786 // The instantiation is visible here, even if it was first declared in an
3787 // unimported module.
3788 Instantiation->setVisibleDespiteOwningModule();
3789
3790 // Enter the scope of this instantiation. We don't use
3791 // PushDeclContext because we don't have a scope.
3792 ContextRAII SavedContext(*this, Instantiation);
3795
3796 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3797
3798 // Pull attributes from the pattern onto the instantiation.
3799 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3800
3801 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3802 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3803
3804 // Exit the scope of this instantiation.
3805 SavedContext.pop();
3806
3807 return Instantiation->isInvalidDecl();
3808}
3809
3810
3811/// Instantiate the definition of a field from the given pattern.
3812///
3813/// \param PointOfInstantiation The point of instantiation within the
3814/// source code.
3815/// \param Instantiation is the declaration whose definition is being
3816/// instantiated. This will be a class of a class temploid
3817/// specialization, or a local enumeration within a function temploid
3818/// specialization.
3819/// \param Pattern The templated declaration from which the instantiation
3820/// occurs.
3821/// \param TemplateArgs The template arguments to be substituted into
3822/// the pattern.
3823///
3824/// \return \c true if an error occurred, \c false otherwise.
3826 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3827 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3828 // If there is no initializer, we don't need to do anything.
3829 if (!Pattern->hasInClassInitializer())
3830 return false;
3831
3832 assert(Instantiation->getInClassInitStyle() ==
3833 Pattern->getInClassInitStyle() &&
3834 "pattern and instantiation disagree about init style");
3835
3836 // Error out if we haven't parsed the initializer of the pattern yet because
3837 // we are waiting for the closing brace of the outer class.
3838 Expr *OldInit = Pattern->getInClassInitializer();
3839 if (!OldInit) {
3840 RecordDecl *PatternRD = Pattern->getParent();
3841 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3842 Diag(PointOfInstantiation,
3843 diag::err_default_member_initializer_not_yet_parsed)
3844 << OutermostClass << Pattern;
3845 Diag(Pattern->getEndLoc(),
3846 diag::note_default_member_initializer_not_yet_parsed);
3847 Instantiation->setInvalidDecl();
3848 return true;
3849 }
3850
3851 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3852 if (Inst.isInvalid())
3853 return true;
3854 if (Inst.isAlreadyInstantiating()) {
3855 // Error out if we hit an instantiation cycle for this initializer.
3856 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3857 << Instantiation;
3858 return true;
3859 }
3860 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3861 "instantiating default member init");
3862
3863 // Enter the scope of this instantiation. We don't use PushDeclContext because
3864 // we don't have a scope.
3865 ContextRAII SavedContext(*this, Instantiation->getParent());
3868 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3869 PointOfInstantiation, Instantiation, CurContext};
3870
3871 LocalInstantiationScope Scope(*this, true);
3872
3873 // Instantiate the initializer.
3875 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3876
3877 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3878 /*CXXDirectInit=*/false);
3879 Expr *Init = NewInit.get();
3880 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3882 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3883
3884 if (auto *L = getASTMutationListener())
3885 L->DefaultMemberInitializerInstantiated(Instantiation);
3886
3887 // Return true if the in-class initializer is still missing.
3888 return !Instantiation->getInClassInitializer();
3889}
3890
3891namespace {
3892 /// A partial specialization whose template arguments have matched
3893 /// a given template-id.
3894 struct PartialSpecMatchResult {
3897 };
3898}
3899
3901 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3902 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3904 return true;
3905
3907 ClassTemplateSpec->getSpecializedTemplate()
3908 ->getPartialSpecializations(PartialSpecs);
3909 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3910 TemplateDeductionInfo Info(Loc);
3911 if (DeduceTemplateArguments(PartialSpecs[I],
3912 ClassTemplateSpec->getTemplateArgs().asArray(),
3914 return true;
3915 }
3916
3917 return false;
3918}
3919
3920/// Get the instantiation pattern to use to instantiate the definition of a
3921/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3922/// template or of a partial specialization).
3925 Sema &S, SourceLocation PointOfInstantiation,
3926 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3928 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3929 if (Inst.isInvalid())
3930 return {/*Invalid=*/true};
3931 if (Inst.isAlreadyInstantiating())
3932 return {/*Invalid=*/false};
3933
3934 llvm::PointerUnion<ClassTemplateDecl *,
3936 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3937 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3938 // Find best matching specialization.
3939 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3940
3941 // C++ [temp.class.spec.match]p1:
3942 // When a class template is used in a context that requires an
3943 // instantiation of the class, it is necessary to determine
3944 // whether the instantiation is to be generated using the primary
3945 // template or one of the partial specializations. This is done by
3946 // matching the template arguments of the class template
3947 // specialization with the template argument lists of the partial
3948 // specializations.
3949 typedef PartialSpecMatchResult MatchResult;
3952 Template->getPartialSpecializations(PartialSpecs);
3953 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3954 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3955 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3956 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3958 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3960 // Store the failed-deduction information for use in diagnostics, later.
3961 // TODO: Actually use the failed-deduction info?
3962 FailedCandidates.addCandidate().set(
3963 DeclAccessPair::make(Template, AS_public), Partial,
3965 (void)Result;
3966 } else {
3967 Matched.push_back(PartialSpecMatchResult());
3968 Matched.back().Partial = Partial;
3969 Matched.back().Args = Info.takeCanonical();
3970 }
3971 }
3972
3973 // If we're dealing with a member template where the template parameters
3974 // have been instantiated, this provides the original template parameters
3975 // from which the member template's parameters were instantiated.
3976
3977 if (Matched.size() >= 1) {
3978 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3979 if (Matched.size() == 1) {
3980 // -- If exactly one matching specialization is found, the
3981 // instantiation is generated from that specialization.
3982 // We don't need to do anything for this.
3983 } else {
3984 // -- If more than one matching specialization is found, the
3985 // partial order rules (14.5.4.2) are used to determine
3986 // whether one of the specializations is more specialized
3987 // than the others. If none of the specializations is more
3988 // specialized than all of the other matching
3989 // specializations, then the use of the class template is
3990 // ambiguous and the program is ill-formed.
3992 PEnd = Matched.end();
3993 P != PEnd; ++P) {
3995 P->Partial, Best->Partial, PointOfInstantiation) ==
3996 P->Partial)
3997 Best = P;
3998 }
3999
4000 // Determine if the best partial specialization is more specialized than
4001 // the others.
4002 bool Ambiguous = false;
4003 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4004 PEnd = Matched.end();
4005 P != PEnd; ++P) {
4007 P->Partial, Best->Partial,
4008 PointOfInstantiation) != Best->Partial) {
4009 Ambiguous = true;
4010 break;
4011 }
4012 }
4013
4014 if (Ambiguous) {
4015 // Partial ordering did not produce a clear winner. Complain.
4016 Inst.Clear();
4017 ClassTemplateSpec->setInvalidDecl();
4018 S.Diag(PointOfInstantiation,
4019 diag::err_partial_spec_ordering_ambiguous)
4020 << ClassTemplateSpec;
4021
4022 // Print the matching partial specializations.
4023 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4024 PEnd = Matched.end();
4025 P != PEnd; ++P)
4026 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4028 P->Partial->getTemplateParameters(), *P->Args);
4029
4030 return {/*Invalid=*/true};
4031 }
4032 }
4033
4034 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4035 } else {
4036 // -- If no matches are found, the instantiation is generated
4037 // from the primary template.
4038 }
4039 }
4040
4041 CXXRecordDecl *Pattern = nullptr;
4042 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4043 if (auto *PartialSpec =
4044 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4045 // Instantiate using the best class template partial specialization.
4046 while (PartialSpec->getInstantiatedFromMember()) {
4047 // If we've found an explicit specialization of this class template,
4048 // stop here and use that as the pattern.
4049 if (PartialSpec->isMemberSpecialization())
4050 break;
4051
4052 PartialSpec = PartialSpec->getInstantiatedFromMember();
4053 }
4054 Pattern = PartialSpec;
4055 } else {
4056 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4057 while (Template->getInstantiatedFromMemberTemplate()) {
4058 // If we've found an explicit specialization of this class template,
4059 // stop here and use that as the pattern.
4060 if (Template->isMemberSpecialization())
4061 break;
4062
4063 Template = Template->getInstantiatedFromMemberTemplate();
4064 }
4065 Pattern = Template->getTemplatedDecl();
4066 }
4067
4068 return Pattern;
4069}
4070
4072 SourceLocation PointOfInstantiation,
4073 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4074 TemplateSpecializationKind TSK, bool Complain) {
4075 // Perform the actual instantiation on the canonical declaration.
4076 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4077 ClassTemplateSpec->getCanonicalDecl());
4078 if (ClassTemplateSpec->isInvalidDecl())
4079 return true;
4080
4082 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4083 ClassTemplateSpec, TSK);
4084 if (!Pattern.isUsable())
4085 return Pattern.isInvalid();
4086
4087 return InstantiateClass(
4088 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4089 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4090}
4091
4092/// Instantiates the definitions of all of the member
4093/// of the given class, which is an instantiation of a class template
4094/// or a member class of a template.
4095void
4097 CXXRecordDecl *Instantiation,
4098 const MultiLevelTemplateArgumentList &TemplateArgs,
4100 // FIXME: We need to notify the ASTMutationListener that we did all of these
4101 // things, in case we have an explicit instantiation definition in a PCM, a
4102 // module, or preamble, and the declaration is in an imported AST.
4103 assert(
4106 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4107 "Unexpected template specialization kind!");
4108 for (auto *D : Instantiation->decls()) {
4109 bool SuppressNew = false;
4110 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4111 if (FunctionDecl *Pattern =
4112 Function->getInstantiatedFromMemberFunction()) {
4113
4114 if (Function->isIneligibleOrNotSelected())
4115 continue;
4116
4117 if (Function->getTrailingRequiresClause()) {
4118 ConstraintSatisfaction Satisfaction;
4119 if (CheckFunctionConstraints(Function, Satisfaction) ||
4120 !Satisfaction.IsSatisfied) {
4121 continue;
4122 }
4123 }
4124
4125 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4126 continue;
4127
4128 MemberSpecializationInfo *MSInfo =
4129 Function->getMemberSpecializationInfo();
4130 assert(MSInfo && "No member specialization information?");
4131 if (MSInfo->getTemplateSpecializationKind()
4133 continue;
4134
4135 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4136 Function,
4138 MSInfo->getPointOfInstantiation(),
4139 SuppressNew) ||
4140 SuppressNew)
4141 continue;
4142
4143 // C++11 [temp.explicit]p8:
4144 // An explicit instantiation definition that names a class template
4145 // specialization explicitly instantiates the class template
4146 // specialization and is only an explicit instantiation definition
4147 // of members whose definition is visible at the point of
4148 // instantiation.
4149 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4150 continue;
4151
4152 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4153
4154 if (Function->isDefined()) {
4155 // Let the ASTConsumer know that this function has been explicitly
4156 // instantiated now, and its linkage might have changed.
4158 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4159 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4160 } else if (TSK == TSK_ImplicitInstantiation) {
4162 std::make_pair(Function, PointOfInstantiation));
4163 }
4164 }
4165 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4166 if (isa<VarTemplateSpecializationDecl>(Var))
4167 continue;
4168
4169 if (Var->isStaticDataMember()) {
4170 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4171 continue;
4172
4174 assert(MSInfo && "No member specialization information?");
4175 if (MSInfo->getTemplateSpecializationKind()
4177 continue;
4178
4179 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4180 Var,
4182 MSInfo->getPointOfInstantiation(),
4183 SuppressNew) ||
4184 SuppressNew)
4185 continue;
4186
4188 // C++0x [temp.explicit]p8:
4189 // An explicit instantiation definition that names a class template
4190 // specialization explicitly instantiates the class template
4191 // specialization and is only an explicit instantiation definition
4192 // of members whose definition is visible at the point of
4193 // instantiation.
4195 continue;
4196
4197 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4198 InstantiateVariableDefinition(PointOfInstantiation, Var);
4199 } else {
4200 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4201 }
4202 }
4203 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4204 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4205 continue;
4206
4207 // Always skip the injected-class-name, along with any
4208 // redeclarations of nested classes, since both would cause us
4209 // to try to instantiate the members of a class twice.
4210 // Skip closure types; they'll get instantiated when we instantiate
4211 // the corresponding lambda-expression.
4212 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4213 Record->isLambda())
4214 continue;
4215
4216 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4217 assert(MSInfo && "No member specialization information?");
4218
4219 if (MSInfo->getTemplateSpecializationKind()
4221 continue;
4222
4223 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4225 // On Windows, explicit instantiation decl of the outer class doesn't
4226 // affect the inner class. Typically extern template declarations are
4227 // used in combination with dll import/export annotations, but those
4228 // are not propagated from the outer class templates to inner classes.
4229 // Therefore, do not instantiate inner classes on this platform, so
4230 // that users don't end up with undefined symbols during linking.
4231 continue;
4232 }
4233
4234 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4235 Record,
4237 MSInfo->getPointOfInstantiation(),
4238 SuppressNew) ||
4239 SuppressNew)
4240 continue;
4241
4243 assert(Pattern && "Missing instantiated-from-template information");
4244
4245 if (!Record->getDefinition()) {
4246 if (!Pattern->getDefinition()) {
4247 // C++0x [temp.explicit]p8:
4248 // An explicit instantiation definition that names a class template
4249 // specialization explicitly instantiates the class template
4250 // specialization and is only an explicit instantiation definition
4251 // of members whose definition is visible at the point of
4252 // instantiation.
4254 MSInfo->setTemplateSpecializationKind(TSK);
4255 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4256 }
4257
4258 continue;
4259 }
4260
4261 InstantiateClass(PointOfInstantiation, Record, Pattern,
4262 TemplateArgs,
4263 TSK);
4264 } else {
4266 Record->getTemplateSpecializationKind() ==
4268 Record->setTemplateSpecializationKind(TSK);
4269 MarkVTableUsed(PointOfInstantiation, Record, true);
4270 }
4271 }
4272
4273 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4274 if (Pattern)
4275 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4276 TSK);
4277 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4278 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4279 assert(MSInfo && "No member specialization information?");
4280
4281 if (MSInfo->getTemplateSpecializationKind()
4283 continue;
4284
4286 PointOfInstantiation, TSK, Enum,
4288 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4289 SuppressNew)
4290 continue;
4291
4292 if (Enum->getDefinition())
4293 continue;
4294
4295 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4296 assert(Pattern && "Missing instantiated-from-template information");
4297
4299 if (!Pattern->getDefinition())
4300 continue;
4301
4302 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4303 } else {
4304 MSInfo->setTemplateSpecializationKind(TSK);
4305 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4306 }
4307 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4308 // No need to instantiate in-class initializers during explicit
4309 // instantiation.
4310 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4311 CXXRecordDecl *ClassPattern =
4312 Instantiation->getTemplateInstantiationPattern();
4314 ClassPattern->lookup(Field->getDeclName());
4315 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4316 assert(Pattern);
4317 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4318 TemplateArgs);
4319 }
4320 }
4321 }
4322}
4323
4324/// Instantiate the definitions of all of the members of the
4325/// given class template specialization, which was named as part of an
4326/// explicit instantiation.
4327void
4329 SourceLocation PointOfInstantiation,
4330 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4332 // C++0x [temp.explicit]p7:
4333 // An explicit instantiation that names a class template
4334 // specialization is an explicit instantion of the same kind
4335 // (declaration or definition) of each of its members (not
4336 // including members inherited from base classes) that has not
4337 // been previously explicitly specialized in the translation unit
4338 // containing the explicit instantiation, except as described
4339 // below.
4340 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4341 getTemplateInstantiationArgs(ClassTemplateSpec),
4342 TSK);
4343}
4344
4347 if (!S)
4348 return S;
4349
4350 TemplateInstantiator Instantiator(*this, TemplateArgs,
4352 DeclarationName());
4353 return Instantiator.TransformStmt(S);
4354}
4355
4357 const TemplateArgumentLoc &Input,
4358 const MultiLevelTemplateArgumentList &TemplateArgs,
4359 TemplateArgumentLoc &Output) {
4360 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4361 DeclarationName());
4362 return Instantiator.TransformTemplateArgument(Input, Output);
4363}
4364
4367 const MultiLevelTemplateArgumentList &TemplateArgs,
4369 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4370 DeclarationName());
4371 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4372}
4373
4376 if (!E)
4377 return E;
4378
4379 TemplateInstantiator Instantiator(*this, TemplateArgs,
4381 DeclarationName());
4382 return Instantiator.TransformExpr(E);
4383}
4384
4387 const MultiLevelTemplateArgumentList &TemplateArgs) {
4388 // FIXME: should call SubstExpr directly if this function is equivalent or
4389 // should it be different?
4390 return SubstExpr(E, TemplateArgs);
4391}
4392
4394 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4395 if (!E)
4396 return E;
4397
4398 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4399 DeclarationName());
4400 Instantiator.setEvaluateConstraints(false);
4401 return Instantiator.TransformExpr(E);
4402}
4403
4405 const MultiLevelTemplateArgumentList &TemplateArgs,
4406 bool CXXDirectInit) {
4407 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4408 DeclarationName());
4409 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4410}
4411
4412bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4413 const MultiLevelTemplateArgumentList &TemplateArgs,
4414 SmallVectorImpl<Expr *> &Outputs) {
4415 if (Exprs.empty())
4416 return false;
4417
4418 TemplateInstantiator Instantiator(*this, TemplateArgs,
4420 DeclarationName());
4421 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4422 IsCall, Outputs);
4423}
4424
4427 const MultiLevelTemplateArgumentList &TemplateArgs) {
4428 if (!NNS)
4429 return NestedNameSpecifierLoc();
4430
4431 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4432 DeclarationName());
4433 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4434}
4435
4436/// Do template substitution on declaration name info.
4439 const MultiLevelTemplateArgumentList &TemplateArgs) {
4440 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4441 NameInfo.getName());
4442 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4443}
4444
4447 TemplateName Name, SourceLocation Loc,
4448 const MultiLevelTemplateArgumentList &TemplateArgs) {
4449 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4450 DeclarationName());
4451 CXXScopeSpec SS;
4452 SS.Adopt(QualifierLoc);
4453 return Instantiator.TransformTemplateName(SS, Name, Loc);
4454}
4455
4456static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4457 // When storing ParmVarDecls in the local instantiation scope, we always
4458 // want to use the ParmVarDecl from the canonical function declaration,
4459 // since the map is then valid for any redeclaration or definition of that
4460 // function.
4461 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4462 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4463 unsigned i = PV->getFunctionScopeIndex();
4464 // This parameter might be from a freestanding function type within the
4465 // function and isn't necessarily referring to one of FD's parameters.
4466 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4467 return FD->getCanonicalDecl()->getParamDecl(i);
4468 }
4469 }
4470 return D;
4471}
4472
4473
4474llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4477 for (LocalInstantiationScope *Current = this; Current;
4478 Current = Current->Outer) {
4479
4480 // Check if we found something within this scope.
4481 const Decl *CheckD = D;
4482 do {
4483 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4484 if (Found != Current->LocalDecls.end())
4485 return &Found->second;
4486
4487 // If this is a tag declaration, it's possible that we need to look for
4488 // a previous declaration.
4489 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4490 CheckD = Tag->getPreviousDecl();
4491 else
4492 CheckD = nullptr;
4493 } while (CheckD);
4494
4495 // If we aren't combined with our outer scope, we're done.
4496 if (!Current->CombineWithOuterScope)
4497 break;
4498 }
4499
4500 // If we're performing a partial substitution during template argument
4501 // deduction, we may not have values for template parameters yet.
4502 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4503 isa<TemplateTemplateParmDecl>(D))
4504 return nullptr;
4505
4506 // Local types referenced prior to definition may require instantiation.
4507 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4508 if (RD->isLocalClass())
4509 return nullptr;
4510
4511 // Enumeration types referenced prior to definition may appear as a result of
4512 // error recovery.
4513 if (isa<EnumDecl>(D))
4514 return nullptr;
4515
4516 // Materialized typedefs/type alias for implicit deduction guides may require
4517 // instantiation.
4518 if (isa<TypedefNameDecl>(D) &&
4519 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4520 return nullptr;
4521
4522 // If we didn't find the decl, then we either have a sema bug, or we have a
4523 // forward reference to a label declaration. Return null to indicate that
4524 // we have an uninstantiated label.
4525 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4526 return nullptr;
4527}
4528
4531 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4532 if (Stored.isNull()) {
4533#ifndef NDEBUG
4534 // It should not be present in any surrounding scope either.
4535 LocalInstantiationScope *Current = this;
4536 while (Current->CombineWithOuterScope && Current->Outer) {
4537 Current = Current->Outer;
4538 assert(!Current->LocalDecls.contains(D) &&
4539 "Instantiated local in inner and outer scopes");
4540 }
4541#endif
4542 Stored = Inst;
4543 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4544 Pack->push_back(cast<VarDecl>(Inst));
4545 } else {
4546 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4547 }
4548}
4549
4551 VarDecl *Inst) {
4553 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4554 Pack->push_back(Inst);
4555}
4556
4558#ifndef NDEBUG
4559 // This should be the first time we've been told about this decl.
4560 for (LocalInstantiationScope *Current = this;
4561 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4562 assert(!Current->LocalDecls.contains(D) &&
4563 "Creating local pack after instantiation of local");
4564#endif
4565
4567 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4569 Stored = Pack;
4570 ArgumentPacks.push_back(Pack);
4571}
4572
4574 for (DeclArgumentPack *Pack : ArgumentPacks)
4575 if (llvm::is_contained(*Pack, D))
4576 return true;
4577 return false;
4578}
4579
4581 const TemplateArgument *ExplicitArgs,
4582 unsigned NumExplicitArgs) {
4583 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4584 "Already have a partially-substituted pack");
4585 assert((!PartiallySubstitutedPack
4586 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4587 "Wrong number of arguments in partially-substituted pack");
4588 PartiallySubstitutedPack = Pack;
4589 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4590 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4591}
4592
4594 const TemplateArgument **ExplicitArgs,
4595 unsigned *NumExplicitArgs) const {
4596 if (ExplicitArgs)
4597 *ExplicitArgs = nullptr;
4598 if (NumExplicitArgs)
4599 *NumExplicitArgs = 0;
4600
4601 for (const LocalInstantiationScope *Current = this; Current;
4602 Current = Current->Outer) {
4603 if (Current->PartiallySubstitutedPack) {
4604 if (ExplicitArgs)
4605 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4606 if (NumExplicitArgs)
4607 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4608
4609 return Current->PartiallySubstitutedPack;
4610 }
4611
4612 if (!Current->CombineWithOuterScope)
4613 break;
4614 }
4615
4616 return nullptr;
4617}
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
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:2590
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:1590
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2156
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:3294
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3514
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:5600
Pointer to a block type.
Definition: Type.h:3345
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:73
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:132
Declaration of a class template.
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
Represents a class template specialization, which refers to a class template with a given set of temp...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
ClassTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
bool isClassScopeExplicitSpecialization() const
Is this an explicit specialization at class scope (within the class that owns the primary template)?...
llvm::PointerUnion< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the class template or class template partial specialization which was specialized by this.
const TemplateArgumentList & getTemplateArgs() const
Retrieve the template arguments of the class template specialization.
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate members of the class templa...
void setInstantiationOf(ClassTemplatePartialSpecializationDecl *PartialSpec, const TemplateArgumentList *TemplateArgs)
Note that this class template specialization is actually an instantiation of the given class template...
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:1264
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1784
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:1946
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:1003
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:1147
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:1898
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3895
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:6367
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3868
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4127
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:4914
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4940
EnumDecl * getDefinition() const
Definition: Decl.h:3971
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
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:3058
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4572
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3219
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3213
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
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:2684
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:2433
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2314
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4606
VarDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition: ExprCXX.h:4633
iterator end() const
Definition: ExprCXX.h:4642
VarDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition: ExprCXX.h:4648
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4640
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition: ExprCXX.h:4645
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition: ExprCXX.h:4636
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:4641
Represents a prototype with parameter type info, e.g.
Definition: Type.h:4652
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4896
Declaration of a template function.
Definition: DeclTemplate.h:958
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:4278
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4252
QualType getReturnType() const
Definition: Type.h:4569
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:6217
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1948
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:5238
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3456
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:616
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:647
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:638
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:656
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:661
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:6565
Sugar for parentheses used when specifying types.
Definition: Type.h:3109
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:3135
[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:3454
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:7556
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:4169
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5545
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:861
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3376
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:10305
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:6552
A RAII object to temporarily push a declaration context.
Definition: Sema.h:2544
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:4681
DefaultedComparisonKind asComparison() const
Definition: Sema.h:4713
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:4710
A helper class for building up ExtParameterInfos.
Definition: Sema.h:9758
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9508
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:457
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:10255
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:10239
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9787
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:10242
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:7025
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:9176
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:858
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:10266
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:524
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:527
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:775
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:17127
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:520
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:11246
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:10291
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:3886
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
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:9799
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:10299
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:996
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:10530
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15364
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:21227
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:10275
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:5714
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:859
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:10283
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:19320
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:6438
DiagnosticsEngine & Diags
Definition: Sema.h:860
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:10250
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:21454
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)
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:512
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:6733
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:4442
std::optional< unsigned > getPackIndex() const
Definition: ExprCXX.h:4490
Decl * getAssociatedDecl() const
A template-like entity which owns the whole pattern being substituted.
Definition: ExprCXX.h:4484
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:4527
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:4567
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:4557
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:5885
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
void setTagKind(TagKind TK)
Definition: Decl.h:3784
SourceRange getBraceRange() const
Definition: Decl.h:3664
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3669
StringRef getKindName() const
Definition: Decl.h:3776
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4739
TagKind getTagKind() const
Definition: Decl.h:3780
void setBraceRange(SourceRange R)
Definition: Decl.h:3665
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1236
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:6085
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:5776
unsigned getIndex() const
Definition: Type.h:5775
unsigned getDepth() const
Definition: Type.h:5774
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:3419
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:7326
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:7337
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:3156
The base class of the type hierarchy.
Definition: Type.h:1813
bool isVoidType() const
Definition: Type.h:7901
bool isReferenceType() const
Definition: Type.h:7620
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:694
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2657
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2649
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:2667
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8119
bool isRecordType() const
Definition: Type.h:7702
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:3965
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:6295
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:373
@ 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:6270
@ 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:5394
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
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:4703
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:4705
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:4738
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:9804
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:9965
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:9918
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:9934
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:9960
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:9929
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:9921
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:9806
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:9898
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:9816
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:9825
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:9844
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:9895
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:9852
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:9859
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:9902
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:9870
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:9908
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:9835
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:9914
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:9911
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:9832
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:9840
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:9848
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:9809
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:9862
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:9866
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:9821
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:9892
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:9855
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:9924
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:9989
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:10143
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:10147
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)