clang 20.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
21#include "clang/AST/Expr.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/STLForwardCompat.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/SaveAndRestore.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
108 }
109 return LambdaCallOperator;
110}
111
112struct EnclosingTypeAliasTemplateDetails {
113 TypeAliasTemplateDecl *Template = nullptr;
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
116
117 explicit operator bool() noexcept { return Template; }
118};
119
120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121// well as its primary template and instantiating template arguments.
122EnclosingTypeAliasTemplateDetails
123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
135 };
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
139 }
140 return Result;
141 }
142 return {};
143}
144
145// Check if we are currently inside of a lambda expression that is
146// surrounded by a using alias declaration. e.g.
147// template <class> using type = decltype([](auto) { ^ }());
148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149// a DeclContext, nor does it have an associated specialization Decl from which
150// we could collect these template arguments.
151bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
160 CallOperator;
161 }
162 const FunctionDecl *CallOperator;
163 };
164
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
167
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(Underlying);
170}
171
172// Add template arguments from a variable template instantiation.
173Response
174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
181
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
184 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
185 return Response::Done();
186
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
193 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
208 }
209 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
210}
211
212// If we have a template template parameter with translation unit context,
213// then we're performing substitution into a default template argument of
214// this template template parameter before we've constructed the template
215// that will own this template template parameter. In this case, we
216// use empty template parameter lists for all of the outer templates
217// to avoid performing any substitutions.
218Response
219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
224}
225
226Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
232}
233
234// Add template arguments from a class template instantiation.
235Response
236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
242 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
243 return Response::Done();
244
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
250
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
256
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
264 return Response::ChangeDecl(
265 InstFromPartialTempl->getLexicalDeclContext());
266 }
267 return Response::UseNextDecl(ClassTemplSpec);
268}
269
270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
279 return Response::Done();
280
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
291 TemplateArgs->asArray(),
292 /*Final=*/false);
293
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(Function);
300
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
307
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
311 return Response::Done();
312
313 } else if (Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
317 }
318 // If this is a friend or local declaration and it declares an entity at
319 // namespace scope, take arguments from its lexical parent
320 // instead of its semantic parent, unless of course the pattern we're
321 // instantiating actually comes from the file's context!
322 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
323 Function->getNonTransparentDeclContext()->isFileContext() &&
324 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
325 return Response::ChangeDecl(Function->getLexicalDeclContext());
326 }
327
328 if (ForConstraintInstantiation && Function->getFriendObjectKind())
329 return Response::ChangeDecl(Function->getLexicalDeclContext());
330 return Response::UseNextDecl(Function);
331}
332
333Response HandleFunctionTemplateDecl(Sema &SemaRef,
334 const FunctionTemplateDecl *FTD,
336 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
337 Result.addOuterTemplateArguments(
338 const_cast<FunctionTemplateDecl *>(FTD),
339 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
340 SemaRef.Context),
341 /*Final=*/false);
342
344
345 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
346 if (NNS->isInstantiationDependent()) {
347 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
348 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
349 // Prefer template arguments from the injected-class-type if possible.
350 // For example,
351 // ```cpp
352 // template <class... Pack> struct S {
353 // template <class T> void foo();
354 // };
355 // template <class... Pack> template <class T>
356 // ^^^^^^^^^^^^^ InjectedTemplateArgs
357 // They're of kind TemplateArgument::Pack, not of
358 // TemplateArgument::Type.
359 // void S<Pack...>::foo() {}
360 // ^^^^^^^
361 // TSTy->template_arguments() (which are of PackExpansionType)
362 // ```
363 // This meets the contract in
364 // TreeTransform::TryExpandParameterPacks that the template arguments
365 // for unexpanded parameters should be of a Pack kind.
366 if (TSTy->isCurrentInstantiation()) {
367 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
368 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
369 Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);
370 else if (auto *Specialization =
371 dyn_cast<ClassTemplateSpecializationDecl>(RD))
372 Arguments =
373 Specialization->getTemplateInstantiationArgs().asArray();
374 }
375 Result.addOuterTemplateArguments(
376 TSTy->getTemplateName().getAsTemplateDecl(), Arguments,
377 /*Final=*/false);
378 }
379 }
380
381 NNS = NNS->getPrefix();
382 }
383 }
384
385 return Response::ChangeDecl(FTD->getLexicalDeclContext());
386}
387
388Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
390 ASTContext &Context,
391 bool ForConstraintInstantiation) {
392 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
393 assert(
394 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
395 "Outer template not instantiated?");
396 if (ClassTemplate->isMemberSpecialization())
397 return Response::Done();
398 if (ForConstraintInstantiation)
399 Result.addOuterTemplateArguments(
400 const_cast<CXXRecordDecl *>(Rec),
401 ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),
402 /*Final=*/false);
403 }
404
405 if (const MemberSpecializationInfo *MSInfo =
407 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
408 return Response::Done();
409
410 bool IsFriend = Rec->getFriendObjectKind() ||
413 if (ForConstraintInstantiation && IsFriend &&
415 return Response::ChangeDecl(Rec->getLexicalDeclContext());
416 }
417
418 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
419 // TypeAliasTemplateDecl that this lambda is defined inside of.
420 if (Rec->isLambda()) {
421 if (const Decl *LCD = Rec->getLambdaContextDecl())
422 return Response::ChangeDecl(LCD);
423 // Retrieve the template arguments for a using alias declaration.
424 // This is necessary for constraint checking, since we always keep
425 // constraints relative to the primary template.
426 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
427 ForConstraintInstantiation && TypeAlias) {
428 if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
429 TypeAlias.PrimaryTypeAliasDecl)) {
430 Result.addOuterTemplateArguments(TypeAlias.Template,
431 TypeAlias.AssociatedTemplateArguments,
432 /*Final=*/false);
433 // Visit the parent of the current type alias declaration rather than
434 // the lambda thereof.
435 // E.g., in the following example:
436 // struct S {
437 // template <class> using T = decltype([]<Concept> {} ());
438 // };
439 // void foo() {
440 // S::T var;
441 // }
442 // The instantiated lambda expression (which we're visiting at 'var')
443 // has a function DeclContext 'foo' rather than the Record DeclContext
444 // S. This seems to be an oversight to me that we may want to set a
445 // Sema Context from the CXXScopeSpec before substituting into T.
446 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
447 }
448 }
449 }
450
451 return Response::UseNextDecl(Rec);
452}
453
454Response HandleImplicitConceptSpecializationDecl(
457 Result.addOuterTemplateArguments(
458 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
460 /*Final=*/false);
461 return Response::UseNextDecl(CSD);
462}
463
464Response HandleGenericDeclContext(const Decl *CurDecl) {
465 return Response::UseNextDecl(CurDecl);
466}
467} // namespace TemplateInstArgsHelpers
468} // namespace
469
471 const NamedDecl *ND, const DeclContext *DC, bool Final,
472 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
473 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
474 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
475 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
476 // Accumulate the set of template argument lists in this structure.
479 Result, ND, DC, Final, Innermost, RelativeToPrimary, Pattern,
480 ForConstraintInstantiation, SkipForSpecialization,
481 ForDefaultArgumentSubstitution);
482 return Result;
483}
484
487 const DeclContext *DC, bool Final,
488 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
489 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
490 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
491 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
492 // Accumulate the set of template argument lists in this structure.
493
494 using namespace TemplateInstArgsHelpers;
495 const Decl *CurDecl = ND;
496
497 if (!CurDecl)
498 CurDecl = Decl::castFromDeclContext(DC);
499
500 if (Innermost) {
501 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
502 Final);
503 // Populate placeholder template arguments for TemplateTemplateParmDecls.
504 // This is essential for the case e.g.
505 //
506 // template <class> concept Concept = false;
507 // template <template <Concept C> class T> void foo(T<int>)
508 //
509 // where parameter C has a depth of 1 but the substituting argument `int`
510 // has a depth of 0.
511 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
512 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
513 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
514 }
515
516 while (!CurDecl->isFileContextDecl()) {
517 Response R;
518 if (const auto *VarTemplSpec =
519 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
520 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
521 } else if (const auto *PartialClassTemplSpec =
522 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
523 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
524 SkipForSpecialization);
525 } else if (const auto *ClassTemplSpec =
526 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
527 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
528 SkipForSpecialization);
529 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
530 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
531 ForConstraintInstantiation,
532 ForDefaultArgumentSubstitution);
533 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
534 R = HandleRecordDecl(*this, Rec, Result, Context,
535 ForConstraintInstantiation);
536 } else if (const auto *CSD =
537 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
538 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
539 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
540 R = HandleFunctionTemplateDecl(*this, FTD, Result);
541 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
542 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
543 } else if (!isa<DeclContext>(CurDecl)) {
544 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
545 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
546 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
547 }
548 } else {
549 R = HandleGenericDeclContext(CurDecl);
550 }
551
552 if (R.IsDone)
553 return;
554 if (R.ClearRelativeToPrimary)
555 RelativeToPrimary = false;
556 assert(R.NextDecl);
557 CurDecl = R.NextDecl;
558 }
559}
560
562 switch (Kind) {
570 case ConstraintsCheck:
572 return true;
573
591 return false;
592
593 // This function should never be called when Kind's value is Memoization.
594 case Memoization:
595 break;
596 }
597
598 llvm_unreachable("Invalid SynthesisKind!");
599}
600
603 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
604 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
605 sema::TemplateDeductionInfo *DeductionInfo)
606 : SemaRef(SemaRef) {
607 // Don't allow further instantiation if a fatal error and an uncompilable
608 // error have occurred. Any diagnostics we might have raised will not be
609 // visible, and we do not need to construct a correct AST.
612 Invalid = true;
613 return;
614 }
615 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
616 if (!Invalid) {
618 Inst.Kind = Kind;
619 Inst.PointOfInstantiation = PointOfInstantiation;
620 Inst.Entity = Entity;
621 Inst.Template = Template;
622 Inst.TemplateArgs = TemplateArgs.data();
623 Inst.NumTemplateArgs = TemplateArgs.size();
624 Inst.DeductionInfo = DeductionInfo;
625 Inst.InstantiationRange = InstantiationRange;
627
628 AlreadyInstantiating = !Inst.Entity ? false :
630 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
631 .second;
633 }
634}
635
637 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
638 SourceRange InstantiationRange)
640 CodeSynthesisContext::TemplateInstantiation,
641 PointOfInstantiation, InstantiationRange, Entity) {}
642
644 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
645 ExceptionSpecification, SourceRange InstantiationRange)
647 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
648 PointOfInstantiation, InstantiationRange, Entity) {}
649
651 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
652 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
653 SourceRange InstantiationRange)
655 SemaRef,
656 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
657 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
658 Template, TemplateArgs) {}
659
661 Sema &SemaRef, SourceLocation PointOfInstantiation,
663 ArrayRef<TemplateArgument> TemplateArgs,
665 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
666 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
667 InstantiationRange, FunctionTemplate, nullptr,
668 TemplateArgs, &DeductionInfo) {
672}
673
675 Sema &SemaRef, SourceLocation PointOfInstantiation,
676 TemplateDecl *Template,
677 ArrayRef<TemplateArgument> TemplateArgs,
678 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
680 SemaRef,
681 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
682 PointOfInstantiation, InstantiationRange, Template, nullptr,
683 TemplateArgs, &DeductionInfo) {}
684
686 Sema &SemaRef, SourceLocation PointOfInstantiation,
688 ArrayRef<TemplateArgument> TemplateArgs,
689 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
691 SemaRef,
692 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
693 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
694 TemplateArgs, &DeductionInfo) {}
695
697 Sema &SemaRef, SourceLocation PointOfInstantiation,
699 ArrayRef<TemplateArgument> TemplateArgs,
700 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
702 SemaRef,
703 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
704 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
705 TemplateArgs, &DeductionInfo) {}
706
708 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
709 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
711 SemaRef,
712 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
713 PointOfInstantiation, InstantiationRange, Param, nullptr,
714 TemplateArgs) {}
715
717 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
719 SourceRange InstantiationRange)
721 SemaRef,
722 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
723 PointOfInstantiation, InstantiationRange, Param, Template,
724 TemplateArgs) {}
725
727 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
729 SourceRange InstantiationRange)
731 SemaRef,
732 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
733 PointOfInstantiation, InstantiationRange, Param, Template,
734 TemplateArgs) {}
735
737 Sema &SemaRef, SourceLocation PointOfInstantiation,
739 SourceRange InstantiationRange)
741 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
742 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
743 /*Template=*/nullptr, TemplateArgs) {}
744
746 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
747 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
748 SourceRange InstantiationRange)
750 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
751 PointOfInstantiation, InstantiationRange, Param, Template,
752 TemplateArgs) {}
753
755 Sema &SemaRef, SourceLocation PointOfInstantiation,
757 SourceRange InstantiationRange)
759 SemaRef, CodeSynthesisContext::RequirementInstantiation,
760 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
761 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
762
764 Sema &SemaRef, SourceLocation PointOfInstantiation,
766 SourceRange InstantiationRange)
768 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
769 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
770 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
771
773 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
774 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
776 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
777 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
778 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
779
781 Sema &SemaRef, SourceLocation PointOfInstantiation,
782 ConstraintsCheck, NamedDecl *Template,
783 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
786 PointOfInstantiation, InstantiationRange, Template, nullptr,
787 TemplateArgs) {}
788
790 Sema &SemaRef, SourceLocation PointOfInstantiation,
792 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
795 PointOfInstantiation, InstantiationRange, Template, nullptr,
796 {}, &DeductionInfo) {}
797
799 Sema &SemaRef, SourceLocation PointOfInstantiation,
801 SourceRange InstantiationRange)
804 PointOfInstantiation, InstantiationRange, Template) {}
805
807 Sema &SemaRef, SourceLocation PointOfInstantiation,
809 SourceRange InstantiationRange)
812 PointOfInstantiation, InstantiationRange, Template) {}
813
815 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
816 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
818 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
819 PointOfInstantiation, InstantiationRange, Entity) {}
820
821
825
826 CodeSynthesisContexts.push_back(Ctx);
827
828 if (!Ctx.isInstantiationRecord())
830
831 // Check to see if we're low on stack space. We can't do anything about this
832 // from here, but we can at least warn the user.
834}
835
837 auto &Active = CodeSynthesisContexts.back();
838 if (!Active.isInstantiationRecord()) {
839 assert(NonInstantiationEntries > 0);
841 }
842
843 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
844
845 // Name lookup no longer looks in this template's defining module.
846 assert(CodeSynthesisContexts.size() >=
848 "forgot to remove a lookup module for a template instantiation");
849 if (CodeSynthesisContexts.size() ==
852 LookupModulesCache.erase(M);
854 }
855
856 // If we've left the code synthesis context for the current context stack,
857 // stop remembering that we've emitted that stack.
858 if (CodeSynthesisContexts.size() ==
861
862 CodeSynthesisContexts.pop_back();
863}
864
866 if (!Invalid) {
867 if (!AlreadyInstantiating) {
868 auto &Active = SemaRef.CodeSynthesisContexts.back();
869 if (Active.Entity)
871 {Active.Entity->getCanonicalDecl(), Active.Kind});
872 }
873
876
878 Invalid = true;
879 }
880}
881
882static std::string convertCallArgsToString(Sema &S,
884 std::string Result;
885 llvm::raw_string_ostream OS(Result);
886 llvm::ListSeparator Comma;
887 for (const Expr *Arg : Args) {
888 OS << Comma;
889 Arg->IgnoreParens()->printPretty(OS, nullptr,
891 }
892 return Result;
893}
894
895bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
896 SourceLocation PointOfInstantiation,
897 SourceRange InstantiationRange) {
900 if ((SemaRef.CodeSynthesisContexts.size() -
902 <= SemaRef.getLangOpts().InstantiationDepth)
903 return false;
904
905 SemaRef.Diag(PointOfInstantiation,
906 diag::err_template_recursion_depth_exceeded)
907 << SemaRef.getLangOpts().InstantiationDepth
908 << InstantiationRange;
909 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
910 << SemaRef.getLangOpts().InstantiationDepth;
911 return true;
912}
913
915 // Determine which template instantiations to skip, if any.
916 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
917 unsigned Limit = Diags.getTemplateBacktraceLimit();
918 if (Limit && Limit < CodeSynthesisContexts.size()) {
919 SkipStart = Limit / 2 + Limit % 2;
920 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
921 }
922
923 // FIXME: In all of these cases, we need to show the template arguments
924 unsigned InstantiationIdx = 0;
926 Active = CodeSynthesisContexts.rbegin(),
927 ActiveEnd = CodeSynthesisContexts.rend();
928 Active != ActiveEnd;
929 ++Active, ++InstantiationIdx) {
930 // Skip this instantiation?
931 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
932 if (InstantiationIdx == SkipStart) {
933 // Note that we're skipping instantiations.
934 Diags.Report(Active->PointOfInstantiation,
935 diag::note_instantiation_contexts_suppressed)
936 << unsigned(CodeSynthesisContexts.size() - Limit);
937 }
938 continue;
939 }
940
941 switch (Active->Kind) {
943 Decl *D = Active->Entity;
944 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
945 unsigned DiagID = diag::note_template_member_class_here;
946 if (isa<ClassTemplateSpecializationDecl>(Record))
947 DiagID = diag::note_template_class_instantiation_here;
948 Diags.Report(Active->PointOfInstantiation, DiagID)
949 << Record << Active->InstantiationRange;
950 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
951 unsigned DiagID;
952 if (Function->getPrimaryTemplate())
953 DiagID = diag::note_function_template_spec_here;
954 else
955 DiagID = diag::note_template_member_function_here;
956 Diags.Report(Active->PointOfInstantiation, DiagID)
957 << Function
958 << Active->InstantiationRange;
959 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
960 Diags.Report(Active->PointOfInstantiation,
961 VD->isStaticDataMember()?
962 diag::note_template_static_data_member_def_here
963 : diag::note_template_variable_def_here)
964 << VD
965 << Active->InstantiationRange;
966 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
967 Diags.Report(Active->PointOfInstantiation,
968 diag::note_template_enum_def_here)
969 << ED
970 << Active->InstantiationRange;
971 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
972 Diags.Report(Active->PointOfInstantiation,
973 diag::note_template_nsdmi_here)
974 << FD << Active->InstantiationRange;
975 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
976 Diags.Report(Active->PointOfInstantiation,
977 diag::note_template_class_instantiation_here)
978 << CTD << Active->InstantiationRange;
979 }
980 break;
981 }
982
984 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
985 SmallString<128> TemplateArgsStr;
986 llvm::raw_svector_ostream OS(TemplateArgsStr);
987 Template->printName(OS, getPrintingPolicy());
988 printTemplateArgumentList(OS, Active->template_arguments(),
990 Diags.Report(Active->PointOfInstantiation,
991 diag::note_default_arg_instantiation_here)
992 << OS.str()
993 << Active->InstantiationRange;
994 break;
995 }
996
998 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
999 Diags.Report(Active->PointOfInstantiation,
1000 diag::note_explicit_template_arg_substitution_here)
1001 << FnTmpl
1003 Active->TemplateArgs,
1004 Active->NumTemplateArgs)
1005 << Active->InstantiationRange;
1006 break;
1007 }
1008
1010 if (FunctionTemplateDecl *FnTmpl =
1011 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1012 Diags.Report(Active->PointOfInstantiation,
1013 diag::note_function_template_deduction_instantiation_here)
1014 << FnTmpl
1015 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1016 Active->TemplateArgs,
1017 Active->NumTemplateArgs)
1018 << Active->InstantiationRange;
1019 } else {
1020 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1021 isa<VarTemplateSpecializationDecl>(Active->Entity);
1022 bool IsTemplate = false;
1023 TemplateParameterList *Params;
1024 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1025 IsTemplate = true;
1026 Params = D->getTemplateParameters();
1027 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1028 Active->Entity)) {
1029 Params = D->getTemplateParameters();
1030 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1031 Active->Entity)) {
1032 Params = D->getTemplateParameters();
1033 } else {
1034 llvm_unreachable("unexpected template kind");
1035 }
1036
1037 Diags.Report(Active->PointOfInstantiation,
1038 diag::note_deduced_template_arg_substitution_here)
1039 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1040 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1041 Active->NumTemplateArgs)
1042 << Active->InstantiationRange;
1043 }
1044 break;
1045 }
1046
1048 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1049 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1050
1051 SmallString<128> TemplateArgsStr;
1052 llvm::raw_svector_ostream OS(TemplateArgsStr);
1054 printTemplateArgumentList(OS, Active->template_arguments(),
1056 Diags.Report(Active->PointOfInstantiation,
1057 diag::note_default_function_arg_instantiation_here)
1058 << OS.str()
1059 << Active->InstantiationRange;
1060 break;
1061 }
1062
1064 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1065 std::string Name;
1066 if (!Parm->getName().empty())
1067 Name = std::string(" '") + Parm->getName().str() + "'";
1068
1069 TemplateParameterList *TemplateParams = nullptr;
1070 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1071 TemplateParams = Template->getTemplateParameters();
1072 else
1073 TemplateParams =
1074 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1075 ->getTemplateParameters();
1076 Diags.Report(Active->PointOfInstantiation,
1077 diag::note_prior_template_arg_substitution)
1078 << isa<TemplateTemplateParmDecl>(Parm)
1079 << Name
1080 << getTemplateArgumentBindingsText(TemplateParams,
1081 Active->TemplateArgs,
1082 Active->NumTemplateArgs)
1083 << Active->InstantiationRange;
1084 break;
1085 }
1086
1088 TemplateParameterList *TemplateParams = nullptr;
1089 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1090 TemplateParams = Template->getTemplateParameters();
1091 else
1092 TemplateParams =
1093 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1094 ->getTemplateParameters();
1095
1096 Diags.Report(Active->PointOfInstantiation,
1097 diag::note_template_default_arg_checking)
1098 << getTemplateArgumentBindingsText(TemplateParams,
1099 Active->TemplateArgs,
1100 Active->NumTemplateArgs)
1101 << Active->InstantiationRange;
1102 break;
1103 }
1104
1106 Diags.Report(Active->PointOfInstantiation,
1107 diag::note_evaluating_exception_spec_here)
1108 << cast<FunctionDecl>(Active->Entity);
1109 break;
1110
1112 Diags.Report(Active->PointOfInstantiation,
1113 diag::note_template_exception_spec_instantiation_here)
1114 << cast<FunctionDecl>(Active->Entity)
1115 << Active->InstantiationRange;
1116 break;
1117
1119 Diags.Report(Active->PointOfInstantiation,
1120 diag::note_template_requirement_instantiation_here)
1121 << Active->InstantiationRange;
1122 break;
1124 Diags.Report(Active->PointOfInstantiation,
1125 diag::note_template_requirement_params_instantiation_here)
1126 << Active->InstantiationRange;
1127 break;
1128
1130 Diags.Report(Active->PointOfInstantiation,
1131 diag::note_nested_requirement_here)
1132 << Active->InstantiationRange;
1133 break;
1134
1136 Diags.Report(Active->PointOfInstantiation,
1137 diag::note_in_declaration_of_implicit_special_member)
1138 << cast<CXXRecordDecl>(Active->Entity)
1139 << llvm::to_underlying(Active->SpecialMember);
1140 break;
1141
1143 Diags.Report(Active->Entity->getLocation(),
1144 diag::note_in_declaration_of_implicit_equality_comparison);
1145 break;
1146
1148 // FIXME: For synthesized functions that are not defaulted,
1149 // produce a note.
1150 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1153 if (DFK.isSpecialMember()) {
1154 auto *MD = cast<CXXMethodDecl>(FD);
1155 Diags.Report(Active->PointOfInstantiation,
1156 diag::note_member_synthesized_at)
1157 << MD->isExplicitlyDefaulted()
1158 << llvm::to_underlying(DFK.asSpecialMember())
1159 << Context.getTagDeclType(MD->getParent());
1160 } else if (DFK.isComparison()) {
1161 QualType RecordType = FD->getParamDecl(0)
1162 ->getType()
1163 .getNonReferenceType()
1164 .getUnqualifiedType();
1165 Diags.Report(Active->PointOfInstantiation,
1166 diag::note_comparison_synthesized_at)
1167 << (int)DFK.asComparison() << RecordType;
1168 }
1169 break;
1170 }
1171
1173 Diags.Report(Active->Entity->getLocation(),
1174 diag::note_rewriting_operator_as_spaceship);
1175 break;
1176
1178 Diags.Report(Active->PointOfInstantiation,
1179 diag::note_in_binding_decl_init)
1180 << cast<BindingDecl>(Active->Entity);
1181 break;
1182
1184 Diags.Report(Active->PointOfInstantiation,
1185 diag::note_due_to_dllexported_class)
1186 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1187 break;
1188
1190 Diags.Report(Active->PointOfInstantiation,
1191 diag::note_building_builtin_dump_struct_call)
1193 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1194 break;
1195
1197 break;
1198
1200 Diags.Report(Active->PointOfInstantiation,
1201 diag::note_lambda_substitution_here);
1202 break;
1204 unsigned DiagID = 0;
1205 if (!Active->Entity) {
1206 Diags.Report(Active->PointOfInstantiation,
1207 diag::note_nested_requirement_here)
1208 << Active->InstantiationRange;
1209 break;
1210 }
1211 if (isa<ConceptDecl>(Active->Entity))
1212 DiagID = diag::note_concept_specialization_here;
1213 else if (isa<TemplateDecl>(Active->Entity))
1214 DiagID = diag::note_checking_constraints_for_template_id_here;
1215 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1216 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1217 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1218 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1219 else {
1220 assert(isa<FunctionDecl>(Active->Entity));
1221 DiagID = diag::note_checking_constraints_for_function_here;
1222 }
1223 SmallString<128> TemplateArgsStr;
1224 llvm::raw_svector_ostream OS(TemplateArgsStr);
1225 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1226 if (!isa<FunctionDecl>(Active->Entity)) {
1227 printTemplateArgumentList(OS, Active->template_arguments(),
1229 }
1230 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1231 << Active->InstantiationRange;
1232 break;
1233 }
1235 Diags.Report(Active->PointOfInstantiation,
1236 diag::note_constraint_substitution_here)
1237 << Active->InstantiationRange;
1238 break;
1240 Diags.Report(Active->PointOfInstantiation,
1241 diag::note_constraint_normalization_here)
1242 << cast<NamedDecl>(Active->Entity) << Active->InstantiationRange;
1243 break;
1245 Diags.Report(Active->PointOfInstantiation,
1246 diag::note_parameter_mapping_substitution_here)
1247 << Active->InstantiationRange;
1248 break;
1250 Diags.Report(Active->PointOfInstantiation,
1251 diag::note_building_deduction_guide_here);
1252 break;
1254 Diags.Report(Active->PointOfInstantiation,
1255 diag::note_template_type_alias_instantiation_here)
1256 << cast<TypeAliasTemplateDecl>(Active->Entity)
1257 << Active->InstantiationRange;
1258 break;
1259 }
1260 }
1261}
1262
1263std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1265 return std::optional<TemplateDeductionInfo *>(nullptr);
1266
1268 Active = CodeSynthesisContexts.rbegin(),
1269 ActiveEnd = CodeSynthesisContexts.rend();
1270 Active != ActiveEnd;
1271 ++Active)
1272 {
1273 switch (Active->Kind) {
1275 // An instantiation of an alias template may or may not be a SFINAE
1276 // context, depending on what else is on the stack.
1277 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1278 break;
1279 [[fallthrough]];
1287 // This is a template instantiation, so there is no SFINAE.
1288 return std::nullopt;
1290 // [temp.deduct]p9
1291 // A lambda-expression appearing in a function type or a template
1292 // parameter is not considered part of the immediate context for the
1293 // purposes of template argument deduction.
1294 // CWG2672: A lambda-expression body is never in the immediate context.
1295 return std::nullopt;
1296
1301 // A default template argument instantiation and substitution into
1302 // template parameters with arguments for prior parameters may or may
1303 // not be a SFINAE context; look further up the stack.
1304 break;
1305
1308 // We're either substituting explicitly-specified template arguments,
1309 // deduced template arguments. SFINAE applies unless we are in a lambda
1310 // body, see [temp.deduct]p9.
1314 // SFINAE always applies in a constraint expression or a requirement
1315 // in a requires expression.
1316 assert(Active->DeductionInfo && "Missing deduction info pointer");
1317 return Active->DeductionInfo;
1318
1326 // This happens in a context unrelated to template instantiation, so
1327 // there is no SFINAE.
1328 return std::nullopt;
1329
1331 // FIXME: This should not be treated as a SFINAE context, because
1332 // we will cache an incorrect exception specification. However, clang
1333 // bootstrap relies this! See PR31692.
1334 break;
1335
1337 break;
1338 }
1339
1340 // The inner context was transparent for SFINAE. If it occurred within a
1341 // non-instantiation SFINAE context, then SFINAE applies.
1342 if (Active->SavedInNonInstantiationSFINAEContext)
1343 return std::optional<TemplateDeductionInfo *>(nullptr);
1344 }
1345
1346 return std::nullopt;
1347}
1348
1349//===----------------------------------------------------------------------===/
1350// Template Instantiation for Types
1351//===----------------------------------------------------------------------===/
1352namespace {
1353 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1354 const MultiLevelTemplateArgumentList &TemplateArgs;
1356 DeclarationName Entity;
1357 // Whether to evaluate the C++20 constraints or simply substitute into them.
1358 bool EvaluateConstraints = true;
1359 // Whether Substitution was Incomplete, that is, we tried to substitute in
1360 // any user provided template arguments which were null.
1361 bool IsIncomplete = false;
1362 // Whether an incomplete substituion should be treated as an error.
1363 bool BailOutOnIncomplete;
1364
1365 private:
1366 bool isSubstitutingConstraints() const {
1367 return llvm::any_of(SemaRef.CodeSynthesisContexts, [](auto &Context) {
1368 return Context.Kind ==
1369 Sema::CodeSynthesisContext::ConstraintSubstitution;
1370 });
1371 }
1372
1373 // CWG2770: Function parameters should be instantiated when they are
1374 // needed by a satisfaction check of an atomic constraint or
1375 // (recursively) by another function parameter.
1376 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1377
1378 public:
1379 typedef TreeTransform<TemplateInstantiator> inherited;
1380
1381 TemplateInstantiator(Sema &SemaRef,
1382 const MultiLevelTemplateArgumentList &TemplateArgs,
1384 bool BailOutOnIncomplete = false)
1385 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1386 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1387
1388 void setEvaluateConstraints(bool B) {
1389 EvaluateConstraints = B;
1390 }
1391 bool getEvaluateConstraints() {
1392 return EvaluateConstraints;
1393 }
1394
1395 /// Determine whether the given type \p T has already been
1396 /// transformed.
1397 ///
1398 /// For the purposes of template instantiation, a type has already been
1399 /// transformed if it is NULL or if it is not dependent.
1400 bool AlreadyTransformed(QualType T);
1401
1402 /// Returns the location of the entity being instantiated, if known.
1403 SourceLocation getBaseLocation() { return Loc; }
1404
1405 /// Returns the name of the entity being instantiated, if any.
1406 DeclarationName getBaseEntity() { return Entity; }
1407
1408 /// Returns whether any substitution so far was incomplete.
1409 bool getIsIncomplete() const { return IsIncomplete; }
1410
1411 /// Sets the "base" location and entity when that
1412 /// information is known based on another transformation.
1413 void setBase(SourceLocation Loc, DeclarationName Entity) {
1414 this->Loc = Loc;
1415 this->Entity = Entity;
1416 }
1417
1418 unsigned TransformTemplateDepth(unsigned Depth) {
1419 return TemplateArgs.getNewDepth(Depth);
1420 }
1421
1422 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1423 int Index = getSema().ArgumentPackSubstitutionIndex;
1424 if (Index == -1)
1425 return std::nullopt;
1426 return Pack.pack_size() - 1 - Index;
1427 }
1428
1429 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1430 SourceRange PatternRange,
1432 bool &ShouldExpand, bool &RetainExpansion,
1433 std::optional<unsigned> &NumExpansions) {
1434 if (SemaRef.CurrentInstantiationScope && isSubstitutingConstraints()) {
1435 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1436 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1437 if (!isa_and_present<ParmVarDecl>(VD))
1438 continue;
1439 if (maybeInstantiateFunctionParameterToScope(cast<ParmVarDecl>(VD)))
1440 return true;
1441 }
1442 }
1443
1444 return getSema().CheckParameterPacksForExpansion(
1445 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs, ShouldExpand,
1446 RetainExpansion, NumExpansions);
1447 }
1448
1449 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1451 }
1452
1453 TemplateArgument ForgetPartiallySubstitutedPack() {
1454 TemplateArgument Result;
1455 if (NamedDecl *PartialPack
1457 MultiLevelTemplateArgumentList &TemplateArgs
1458 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1459 unsigned Depth, Index;
1460 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1461 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1462 Result = TemplateArgs(Depth, Index);
1463 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1464 } else {
1465 IsIncomplete = true;
1466 if (BailOutOnIncomplete)
1467 return TemplateArgument();
1468 }
1469 }
1470
1471 return Result;
1472 }
1473
1474 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1475 if (Arg.isNull())
1476 return;
1477
1478 if (NamedDecl *PartialPack
1480 MultiLevelTemplateArgumentList &TemplateArgs
1481 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1482 unsigned Depth, Index;
1483 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1484 TemplateArgs.setArgument(Depth, Index, Arg);
1485 }
1486 }
1487
1488 /// Transform the given declaration by instantiating a reference to
1489 /// this declaration.
1490 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1491
1492 void transformAttrs(Decl *Old, Decl *New) {
1493 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1494 }
1495
1496 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1497 if (Old->isParameterPack() &&
1498 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1500 for (auto *New : NewDecls)
1502 Old, cast<VarDecl>(New));
1503 return;
1504 }
1505
1506 assert(NewDecls.size() == 1 &&
1507 "should only have multiple expansions for a pack");
1508 Decl *New = NewDecls.front();
1509
1510 // If we've instantiated the call operator of a lambda or the call
1511 // operator template of a generic lambda, update the "instantiation of"
1512 // information.
1513 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1514 if (NewMD && isLambdaCallOperator(NewMD)) {
1515 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1516 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1517 NewTD->setInstantiatedFromMemberTemplate(
1518 OldMD->getDescribedFunctionTemplate());
1519 else
1520 NewMD->setInstantiationOfMemberFunction(OldMD,
1522 }
1523
1525
1526 // We recreated a local declaration, but not by instantiating it. There
1527 // may be pending dependent diagnostics to produce.
1528 if (auto *DC = dyn_cast<DeclContext>(Old);
1529 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1530 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1531 }
1532
1533 /// Transform the definition of the given declaration by
1534 /// instantiating it.
1535 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1536
1537 /// Transform the first qualifier within a scope by instantiating the
1538 /// declaration.
1539 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1540
1541 bool TransformExceptionSpec(SourceLocation Loc,
1543 SmallVectorImpl<QualType> &Exceptions,
1544 bool &Changed);
1545
1546 /// Rebuild the exception declaration and register the declaration
1547 /// as an instantiated local.
1548 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1550 SourceLocation StartLoc,
1551 SourceLocation NameLoc,
1552 IdentifierInfo *Name);
1553
1554 /// Rebuild the Objective-C exception declaration and register the
1555 /// declaration as an instantiated local.
1556 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1557 TypeSourceInfo *TSInfo, QualType T);
1558
1559 /// Check for tag mismatches when instantiating an
1560 /// elaborated type.
1561 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1562 ElaboratedTypeKeyword Keyword,
1563 NestedNameSpecifierLoc QualifierLoc,
1564 QualType T);
1565
1567 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1568 SourceLocation NameLoc,
1569 QualType ObjectType = QualType(),
1570 NamedDecl *FirstQualifierInScope = nullptr,
1571 bool AllowInjectedClassName = false);
1572
1573 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1574 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1575 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1576 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1577 const Stmt *InstS,
1578 const NoInlineAttr *A);
1579 const AlwaysInlineAttr *
1580 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1581 const AlwaysInlineAttr *A);
1582 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1583 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1584 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1585 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1586
1587 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1589 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1591 ExprResult TransformSubstNonTypeTemplateParmExpr(
1593
1594 /// Rebuild a DeclRefExpr for a VarDecl reference.
1595 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1596
1597 /// Transform a reference to a function or init-capture parameter pack.
1598 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1599
1600 /// Transform a FunctionParmPackExpr which was built when we couldn't
1601 /// expand a function parameter pack reference which refers to an expanded
1602 /// pack.
1603 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1604
1605 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1607 // Call the base version; it will forward to our overridden version below.
1608 return inherited::TransformFunctionProtoType(TLB, TL);
1609 }
1610
1611 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1613 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1614 // Special case for transforming a deduction guide, we return a
1615 // transformed TemplateSpecializationType.
1616 if (Type.isNull() &&
1617 SemaRef.CodeSynthesisContexts.back().Kind ==
1619 // Return a TemplateSpecializationType for transforming a deduction
1620 // guide.
1621 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1622 auto Type =
1623 inherited::TransformType(ICT->getInjectedSpecializationType());
1624 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1625 return Type;
1626 }
1627 }
1628 return Type;
1629 }
1630 // Override the default version to handle a rewrite-template-arg-pack case
1631 // for building a deduction guide.
1632 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1633 TemplateArgumentLoc &Output,
1634 bool Uneval = false) {
1635 const TemplateArgument &Arg = Input.getArgument();
1636 std::vector<TemplateArgument> TArgs;
1637 switch (Arg.getKind()) {
1639 // Literally rewrite the template argument pack, instead of unpacking
1640 // it.
1641 for (auto &pack : Arg.getPackAsArray()) {
1643 pack, QualType(), SourceLocation{});
1644 TemplateArgumentLoc Output;
1645 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1646 return true; // fails
1647 TArgs.push_back(Output.getArgument());
1648 }
1649 Output = SemaRef.getTrivialTemplateArgumentLoc(
1650 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1652 return false;
1653 default:
1654 break;
1655 }
1656 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1657 }
1658
1659 template<typename Fn>
1660 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1662 CXXRecordDecl *ThisContext,
1663 Qualifiers ThisTypeQuals,
1664 Fn TransformExceptionSpec);
1665
1666 ParmVarDecl *
1667 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1668 std::optional<unsigned> NumExpansions,
1669 bool ExpectParameterPack);
1670
1671 using inherited::TransformTemplateTypeParmType;
1672 /// Transforms a template type parameter type by performing
1673 /// substitution of the corresponding template type argument.
1674 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1676 bool SuppressObjCLifetime);
1677
1678 QualType BuildSubstTemplateTypeParmType(
1679 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1680 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1681 TemplateArgument Arg, SourceLocation NameLoc);
1682
1683 /// Transforms an already-substituted template type parameter pack
1684 /// into either itself (if we aren't substituting into its pack expansion)
1685 /// or the appropriate substituted argument.
1686 using inherited::TransformSubstTemplateTypeParmPackType;
1687 QualType
1688 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1690 bool SuppressObjCLifetime);
1691
1692 QualType
1693 TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
1696 if (Type->getSubstitutionFlag() !=
1697 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace)
1698 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1699
1700 assert(Type->getPackIndex());
1701 TemplateArgument TA = TemplateArgs(
1702 Type->getReplacedParameter()->getDepth(), Type->getIndex());
1703 assert(*Type->getPackIndex() + 1 <= TA.pack_size());
1705 SemaRef, TA.pack_size() - 1 - *Type->getPackIndex());
1706
1707 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1708 }
1709
1711 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1712 if (auto TypeAlias =
1713 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1714 getSema());
1715 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1716 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1717 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1718 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1719 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1720 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1721 if (TA.isDependent())
1722 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1723 }
1724 return inherited::ComputeLambdaDependency(LSI);
1725 }
1726
1727 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1728 // Do not rebuild lambdas to avoid creating a new type.
1729 // Lambdas have already been processed inside their eval contexts.
1731 return E;
1732 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1733 /*InstantiatingLambdaOrBlock=*/true);
1735
1736 return inherited::TransformLambdaExpr(E);
1737 }
1738
1739 ExprResult TransformBlockExpr(BlockExpr *E) {
1740 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1741 /*InstantiatingLambdaOrBlock=*/true);
1742 return inherited::TransformBlockExpr(E);
1743 }
1744
1745 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1746 LambdaScopeInfo *LSI) {
1747 CXXMethodDecl *MD = LSI->CallOperator;
1748 for (ParmVarDecl *PVD : MD->parameters()) {
1749 assert(PVD && "null in a parameter list");
1750 if (!PVD->hasDefaultArg())
1751 continue;
1752 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1753 // FIXME: Obtain the source location for the '=' token.
1754 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1755 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1756 // If substitution fails, the default argument is set to a
1757 // RecoveryExpr that wraps the uninstantiated default argument so
1758 // that downstream diagnostics are omitted.
1759 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1760 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1761 UninstExpr->getType());
1762 if (ErrorResult.isUsable())
1763 PVD->setDefaultArg(ErrorResult.get());
1764 }
1765 }
1766 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1767 }
1768
1769 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1770 // Currently, we instantiate the body when instantiating the lambda
1771 // expression. However, `EvaluateConstraints` is disabled during the
1772 // instantiation of the lambda expression, causing the instantiation
1773 // failure of the return type requirement in the body. If p0588r1 is fully
1774 // implemented, the body will be lazily instantiated, and this problem
1775 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1776 // `true` to temporarily fix this issue.
1777 // FIXME: This temporary fix can be removed after fully implementing
1778 // p0588r1.
1779 llvm::SaveAndRestore _(EvaluateConstraints, true);
1780 return inherited::TransformLambdaBody(E, Body);
1781 }
1782
1783 ExprResult TransformSizeOfPackExpr(SizeOfPackExpr *E) {
1784 ExprResult Transformed = inherited::TransformSizeOfPackExpr(E);
1785 if (!Transformed.isUsable())
1786 return Transformed;
1787 auto *TransformedExpr = cast<SizeOfPackExpr>(Transformed.get());
1788 if (SemaRef.CodeSynthesisContexts.back().Kind ==
1790 TransformedExpr->getPack() == E->getPack()) {
1791 Decl *NewPack =
1792 TransformDecl(E->getPackLoc(), TransformedExpr->getPack());
1793 if (!NewPack)
1794 return ExprError();
1795 TransformedExpr->setPack(cast<NamedDecl>(NewPack));
1796 }
1797 return TransformedExpr;
1798 }
1799
1800 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1801 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1802 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1803 if (TransReq.isInvalid())
1804 return TransReq;
1805 assert(TransReq.get() != E &&
1806 "Do not change value of isSatisfied for the existing expression. "
1807 "Create a new expression instead.");
1808 if (E->getBody()->isDependentContext()) {
1809 Sema::SFINAETrap Trap(SemaRef);
1810 // We recreate the RequiresExpr body, but not by instantiating it.
1811 // Produce pending diagnostics for dependent access check.
1812 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1813 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1814 if (Trap.hasErrorOccurred())
1815 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1816 }
1817 return TransReq;
1818 }
1819
1820 bool TransformRequiresExprRequirements(
1823 bool SatisfactionDetermined = false;
1824 for (concepts::Requirement *Req : Reqs) {
1825 concepts::Requirement *TransReq = nullptr;
1826 if (!SatisfactionDetermined) {
1827 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1828 TransReq = TransformTypeRequirement(TypeReq);
1829 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1830 TransReq = TransformExprRequirement(ExprReq);
1831 else
1832 TransReq = TransformNestedRequirement(
1833 cast<concepts::NestedRequirement>(Req));
1834 if (!TransReq)
1835 return true;
1836 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1837 // [expr.prim.req]p6
1838 // [...] The substitution and semantic constraint checking
1839 // proceeds in lexical order and stops when a condition that
1840 // determines the result of the requires-expression is
1841 // encountered. [..]
1842 SatisfactionDetermined = true;
1843 } else
1844 TransReq = Req;
1845 Transformed.push_back(TransReq);
1846 }
1847 return false;
1848 }
1849
1850 TemplateParameterList *TransformTemplateParameterList(
1851 TemplateParameterList *OrigTPL) {
1852 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1853
1854 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1855 TemplateDeclInstantiator DeclInstantiator(getSema(),
1856 /* DeclContext *Owner */ Owner, TemplateArgs);
1857 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1858 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1859 }
1860
1862 TransformTypeRequirement(concepts::TypeRequirement *Req);
1864 TransformExprRequirement(concepts::ExprRequirement *Req);
1866 TransformNestedRequirement(concepts::NestedRequirement *Req);
1867 ExprResult TransformRequiresTypeParams(
1868 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1871 SmallVectorImpl<ParmVarDecl *> &TransParams,
1873
1874 private:
1876 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1877 const NonTypeTemplateParmDecl *parm,
1879 std::optional<unsigned> PackIndex);
1880 };
1881}
1882
1883bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1884 if (T.isNull())
1885 return true;
1886
1888 return false;
1889
1890 getSema().MarkDeclarationsReferencedInType(Loc, T);
1891 return true;
1892}
1893
1894static TemplateArgument
1896 assert(S.ArgumentPackSubstitutionIndex >= 0);
1897 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1899 if (Arg.isPackExpansion())
1900 Arg = Arg.getPackExpansionPattern();
1901 return Arg;
1902}
1903
1904Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1905 if (!D)
1906 return nullptr;
1907
1908 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1909 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1910 // If the corresponding template argument is NULL or non-existent, it's
1911 // because we are performing instantiation from explicitly-specified
1912 // template arguments in a function template, but there were some
1913 // arguments left unspecified.
1914 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1915 TTP->getPosition())) {
1916 IsIncomplete = true;
1917 return BailOutOnIncomplete ? nullptr : D;
1918 }
1919
1920 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1921
1922 if (TTP->isParameterPack()) {
1923 // We might not have an index for pack expansion when normalizing
1924 // constraint expressions. In that case, resort to instantiation scopes
1925 // for the transformed declarations.
1927 SemaRef.CodeSynthesisContexts.back().Kind ==
1929 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D),
1930 TemplateArgs);
1931 }
1932 assert(Arg.getKind() == TemplateArgument::Pack &&
1933 "Missing argument pack");
1934 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1935 }
1936
1937 TemplateName Template = Arg.getAsTemplate();
1938 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1939 "Wrong kind of template template argument");
1940 return Template.getAsTemplateDecl();
1941 }
1942
1943 // Fall through to find the instantiated declaration for this template
1944 // template parameter.
1945 }
1946
1948 if (isSubstitutingConstraints() && isa<ParmVarDecl>(D) &&
1949 maybeInstantiateFunctionParameterToScope(cast<ParmVarDecl>(D)))
1950 return nullptr;
1951 }
1952
1953 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1954}
1955
1956bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
1957 ParmVarDecl *OldParm) {
1959 return false;
1960 // We're instantiating a function parameter whose associated function template
1961 // has not been instantiated at this point for constraint evaluation, so make
1962 // sure the instantiated parameters are owned by a function declaration such
1963 // that they can be correctly 'captured' in tryCaptureVariable().
1965
1966 if (!OldParm->isParameterPack())
1967 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1968 /*NumExpansions=*/std::nullopt,
1969 /*ExpectParameterPack=*/false);
1970
1972
1973 // Find the parameter packs that could be expanded.
1974 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
1976 TypeLoc Pattern = ExpansionTL.getPatternLoc();
1977 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1978 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1979
1980 bool ShouldExpand = false;
1981 bool RetainExpansion = false;
1982 std::optional<unsigned> OrigNumExpansions =
1983 ExpansionTL.getTypePtr()->getNumExpansions();
1984 std::optional<unsigned> NumExpansions = OrigNumExpansions;
1985 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
1986 Pattern.getSourceRange(), Unexpanded,
1987 ShouldExpand, RetainExpansion, NumExpansions))
1988 return true;
1989
1990 assert(ShouldExpand && !RetainExpansion &&
1991 "Shouldn't preserve pack expansion when evaluating constraints");
1992 ExpandingFunctionParameterPack(OldParm);
1993 for (unsigned I = 0; I != *NumExpansions; ++I) {
1994 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
1995 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1996 /*NumExpansions=*/OrigNumExpansions,
1997 /*ExpectParameterPack=*/false))
1998 return true;
1999 }
2000 return false;
2001}
2002
2003Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2004 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
2005 if (!Inst)
2006 return nullptr;
2007
2008 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2009 return Inst;
2010}
2011
2012bool TemplateInstantiator::TransformExceptionSpec(
2014 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2015 if (ESI.Type == EST_Uninstantiated) {
2016 ESI.instantiate();
2017 Changed = true;
2018 }
2019 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2020}
2021
2022NamedDecl *
2023TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2025 // If the first part of the nested-name-specifier was a template type
2026 // parameter, instantiate that type parameter down to a tag type.
2027 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
2028 const TemplateTypeParmType *TTP
2029 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
2030
2031 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2032 // FIXME: This needs testing w/ member access expressions.
2033 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2034
2035 if (TTP->isParameterPack()) {
2036 assert(Arg.getKind() == TemplateArgument::Pack &&
2037 "Missing argument pack");
2038
2039 if (getSema().ArgumentPackSubstitutionIndex == -1)
2040 return nullptr;
2041
2042 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2043 }
2044
2045 QualType T = Arg.getAsType();
2046 if (T.isNull())
2047 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2048
2049 if (const TagType *Tag = T->getAs<TagType>())
2050 return Tag->getDecl();
2051
2052 // The resulting type is not a tag; complain.
2053 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2054 return nullptr;
2055 }
2056 }
2057
2058 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2059}
2060
2061VarDecl *
2062TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2064 SourceLocation StartLoc,
2065 SourceLocation NameLoc,
2066 IdentifierInfo *Name) {
2067 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2068 StartLoc, NameLoc, Name);
2069 if (Var)
2070 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2071 return Var;
2072}
2073
2074VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2075 TypeSourceInfo *TSInfo,
2076 QualType T) {
2077 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2078 if (Var)
2079 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2080 return Var;
2081}
2082
2084TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
2085 ElaboratedTypeKeyword Keyword,
2086 NestedNameSpecifierLoc QualifierLoc,
2087 QualType T) {
2088 if (const TagType *TT = T->getAs<TagType>()) {
2089 TagDecl* TD = TT->getDecl();
2090
2091 SourceLocation TagLocation = KeywordLoc;
2092
2094
2095 // TODO: should we even warn on struct/class mismatches for this? Seems
2096 // like it's likely to produce a lot of spurious errors.
2097 if (Id && Keyword != ElaboratedTypeKeyword::None &&
2100 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
2101 TagLocation, Id)) {
2102 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
2103 << Id
2105 TD->getKindName());
2106 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
2107 }
2108 }
2109 }
2110
2111 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
2112}
2113
2114TemplateName TemplateInstantiator::TransformTemplateName(
2115 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
2116 QualType ObjectType, NamedDecl *FirstQualifierInScope,
2117 bool AllowInjectedClassName) {
2119 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
2120 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2121 // If the corresponding template argument is NULL or non-existent, it's
2122 // because we are performing instantiation from explicitly-specified
2123 // template arguments in a function template, but there were some
2124 // arguments left unspecified.
2125 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2126 TTP->getPosition())) {
2127 IsIncomplete = true;
2128 return BailOutOnIncomplete ? TemplateName() : Name;
2129 }
2130
2131 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2132
2133 if (TemplateArgs.isRewrite()) {
2134 // We're rewriting the template parameter as a reference to another
2135 // template parameter.
2136 if (Arg.getKind() == TemplateArgument::Pack) {
2137 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2138 "unexpected pack arguments in template rewrite");
2139 Arg = Arg.pack_begin()->getPackExpansionPattern();
2140 }
2141 assert(Arg.getKind() == TemplateArgument::Template &&
2142 "unexpected nontype template argument kind in template rewrite");
2143 return Arg.getAsTemplate();
2144 }
2145
2146 auto [AssociatedDecl, Final] =
2147 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2148 std::optional<unsigned> PackIndex;
2149 if (TTP->isParameterPack()) {
2150 assert(Arg.getKind() == TemplateArgument::Pack &&
2151 "Missing argument pack");
2152
2153 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2154 // We have the template argument pack to substitute, but we're not
2155 // actually expanding the enclosing pack expansion yet. So, just
2156 // keep the entire argument pack.
2157 return getSema().Context.getSubstTemplateTemplateParmPack(
2158 Arg, AssociatedDecl, TTP->getIndex(), Final);
2159 }
2160
2161 PackIndex = getPackIndex(Arg);
2162 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2163 }
2164
2165 TemplateName Template = Arg.getAsTemplate();
2166 assert(!Template.isNull() && "Null template template argument");
2167
2168 if (Final)
2169 return Template;
2170 return getSema().Context.getSubstTemplateTemplateParm(
2171 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2172 }
2173 }
2174
2176 = Name.getAsSubstTemplateTemplateParmPack()) {
2177 if (getSema().ArgumentPackSubstitutionIndex == -1)
2178 return Name;
2179
2180 TemplateArgument Pack = SubstPack->getArgumentPack();
2181 TemplateName Template =
2183 if (SubstPack->getFinal())
2184 return Template;
2185 return getSema().Context.getSubstTemplateTemplateParm(
2186 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2187 getPackIndex(Pack));
2188 }
2189
2190 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2191 FirstQualifierInScope,
2192 AllowInjectedClassName);
2193}
2194
2196TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2197 if (!E->isTypeDependent())
2198 return E;
2199
2200 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2201}
2202
2204TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2206 // If the corresponding template argument is NULL or non-existent, it's
2207 // because we are performing instantiation from explicitly-specified
2208 // template arguments in a function template, but there were some
2209 // arguments left unspecified.
2210 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2211 NTTP->getPosition())) {
2212 IsIncomplete = true;
2213 return BailOutOnIncomplete ? ExprError() : E;
2214 }
2215
2216 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2217
2218 if (TemplateArgs.isRewrite()) {
2219 // We're rewriting the template parameter as a reference to another
2220 // template parameter.
2221 if (Arg.getKind() == TemplateArgument::Pack) {
2222 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2223 "unexpected pack arguments in template rewrite");
2224 Arg = Arg.pack_begin()->getPackExpansionPattern();
2225 }
2226 assert(Arg.getKind() == TemplateArgument::Expression &&
2227 "unexpected nontype template argument kind in template rewrite");
2228 // FIXME: This can lead to the same subexpression appearing multiple times
2229 // in a complete expression.
2230 return Arg.getAsExpr();
2231 }
2232
2233 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2234 std::optional<unsigned> PackIndex;
2235 if (NTTP->isParameterPack()) {
2236 assert(Arg.getKind() == TemplateArgument::Pack &&
2237 "Missing argument pack");
2238
2239 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2240 // We have an argument pack, but we can't select a particular argument
2241 // out of it yet. Therefore, we'll build an expression to hold on to that
2242 // argument pack.
2243 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2244 E->getLocation(),
2245 NTTP->getDeclName());
2246 if (TargetType.isNull())
2247 return ExprError();
2248
2249 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2250 if (TargetType->isRecordType())
2251 ExprType.addConst();
2252 // FIXME: Pass in Final.
2254 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2255 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2256 }
2257 PackIndex = getPackIndex(Arg);
2258 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2259 }
2260 // FIXME: Don't put subst node on Final replacement.
2261 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2262 Arg, PackIndex);
2263}
2264
2265const AnnotateAttr *
2266TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2268 for (Expr *Arg : AA->args()) {
2269 ExprResult Res = getDerived().TransformExpr(Arg);
2270 if (Res.isUsable())
2271 Args.push_back(Res.get());
2272 }
2273 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2274 Args.data(), Args.size(), AA->getRange());
2275}
2276
2277const CXXAssumeAttr *
2278TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2279 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2280 if (!Res.isUsable())
2281 return AA;
2282
2283 Res = getSema().ActOnFinishFullExpr(Res.get(),
2284 /*DiscardedValue=*/false);
2285 if (!Res.isUsable())
2286 return AA;
2287
2288 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2289 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2290 AA->getRange());
2291 if (!Res.isUsable())
2292 return AA;
2293 }
2294
2295 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2296 AA->getRange());
2297}
2298
2299const LoopHintAttr *
2300TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2301 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2302
2303 if (TransformedExpr == LH->getValue())
2304 return LH;
2305
2306 // Generate error if there is a problem with the value.
2307 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2308 LH->getSemanticSpelling() ==
2309 LoopHintAttr::Pragma_unroll))
2310 return LH;
2311
2312 LoopHintAttr::OptionType Option = LH->getOption();
2313 LoopHintAttr::LoopHintState State = LH->getState();
2314
2315 llvm::APSInt ValueAPS =
2316 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2317 // The values of 0 and 1 block any unrolling of the loop.
2318 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2319 Option = LoopHintAttr::Unroll;
2320 State = LoopHintAttr::Disable;
2321 }
2322
2323 // Create new LoopHintValueAttr with integral expression in place of the
2324 // non-type template parameter.
2325 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2326 TransformedExpr, *LH);
2327}
2328const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2329 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2330 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2331 return nullptr;
2332
2333 return A;
2334}
2335const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2336 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2337 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2338 return nullptr;
2339
2340 return A;
2341}
2342
2343const CodeAlignAttr *
2344TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2345 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2346 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2347}
2348
2349ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2350 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2352 std::optional<unsigned> PackIndex) {
2353 ExprResult result;
2354
2355 // Determine the substituted parameter type. We can usually infer this from
2356 // the template argument, but not always.
2357 auto SubstParamType = [&] {
2358 QualType T;
2359 if (parm->isExpandedParameterPack())
2361 else
2362 T = parm->getType();
2363 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2364 T = cast<PackExpansionType>(T)->getPattern();
2365 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2366 };
2367
2368 bool refParam = false;
2369
2370 // The template argument itself might be an expression, in which case we just
2371 // return that expression. This happens when substituting into an alias
2372 // template.
2373 if (arg.getKind() == TemplateArgument::Expression) {
2374 Expr *argExpr = arg.getAsExpr();
2375 result = argExpr;
2376 if (argExpr->isLValue()) {
2377 if (argExpr->getType()->isRecordType()) {
2378 // Check whether the parameter was actually a reference.
2379 QualType paramType = SubstParamType();
2380 if (paramType.isNull())
2381 return ExprError();
2382 refParam = paramType->isReferenceType();
2383 } else {
2384 refParam = true;
2385 }
2386 }
2387 } else if (arg.getKind() == TemplateArgument::Declaration ||
2388 arg.getKind() == TemplateArgument::NullPtr) {
2389 if (arg.getKind() == TemplateArgument::Declaration) {
2390 ValueDecl *VD = arg.getAsDecl();
2391
2392 // Find the instantiation of the template argument. This is
2393 // required for nested templates.
2394 VD = cast_or_null<ValueDecl>(
2395 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2396 if (!VD)
2397 return ExprError();
2398 }
2399
2400 QualType paramType = arg.getNonTypeTemplateArgumentType();
2401 assert(!paramType.isNull() && "type substitution failed for param type");
2402 assert(!paramType->isDependentType() && "param type still dependent");
2403 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2404 refParam = paramType->isReferenceType();
2405 } else {
2406 QualType paramType = arg.getNonTypeTemplateArgumentType();
2408 refParam = paramType->isReferenceType();
2409 assert(result.isInvalid() ||
2411 paramType.getNonReferenceType()));
2412 }
2413
2414 if (result.isInvalid())
2415 return ExprError();
2416
2417 Expr *resultExpr = result.get();
2418 // FIXME: Don't put subst node on final replacement.
2420 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2421 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2422}
2423
2425TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2427 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2428 // We aren't expanding the parameter pack, so just return ourselves.
2429 return E;
2430 }
2431
2432 TemplateArgument Pack = E->getArgumentPack();
2434 // FIXME: Don't put subst node on final replacement.
2435 return transformNonTypeTemplateParmRef(
2436 E->getAssociatedDecl(), E->getParameterPack(),
2437 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2438}
2439
2441TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2443 ExprResult SubstReplacement = E->getReplacement();
2444 if (!isa<ConstantExpr>(SubstReplacement.get()))
2445 SubstReplacement = TransformExpr(E->getReplacement());
2446 if (SubstReplacement.isInvalid())
2447 return true;
2448 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2449 if (SubstType.isNull())
2450 return true;
2451 // The type may have been previously dependent and not now, which means we
2452 // might have to implicit cast the argument to the new type, for example:
2453 // template<auto T, decltype(T) U>
2454 // concept C = sizeof(U) == 4;
2455 // void foo() requires C<2, 'a'> { }
2456 // When normalizing foo(), we first form the normalized constraints of C:
2457 // AtomicExpr(sizeof(U) == 4,
2458 // U=SubstNonTypeTemplateParmExpr(Param=U,
2459 // Expr=DeclRef(U),
2460 // Type=decltype(T)))
2461 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2462 // produce:
2463 // AtomicExpr(sizeof(U) == 4,
2464 // U=SubstNonTypeTemplateParmExpr(Param=U,
2465 // Expr=ImpCast(
2466 // decltype(2),
2467 // SubstNTTPE(Param=U, Expr='a',
2468 // Type=char)),
2469 // Type=decltype(2)))
2470 // The call to CheckTemplateArgument here produces the ImpCast.
2471 TemplateArgument SugaredConverted, CanonicalConverted;
2472 if (SemaRef
2473 .CheckTemplateArgument(E->getParameter(), SubstType,
2474 SubstReplacement.get(), SugaredConverted,
2475 CanonicalConverted, Sema::CTAK_Specified)
2476 .isInvalid())
2477 return true;
2478 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2479 E->getParameter(), E->getExprLoc(),
2480 SugaredConverted, E->getPackIndex());
2481}
2482
2483ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2485 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2486 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2487}
2488
2490TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2491 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2492 // We can expand this parameter pack now.
2493 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2494 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2495 if (!VD)
2496 return ExprError();
2497 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2498 }
2499
2500 QualType T = TransformType(E->getType());
2501 if (T.isNull())
2502 return ExprError();
2503
2504 // Transform each of the parameter expansions into the corresponding
2505 // parameters in the instantiation of the function decl.
2507 Vars.reserve(E->getNumExpansions());
2508 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2509 I != End; ++I) {
2510 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2511 if (!D)
2512 return ExprError();
2513 Vars.push_back(D);
2514 }
2515
2516 auto *PackExpr =
2517 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2518 E->getParameterPackLocation(), Vars);
2519 getSema().MarkFunctionParmPackReferenced(PackExpr);
2520 return PackExpr;
2521}
2522
2524TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2525 VarDecl *PD) {
2526 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2527 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2528 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2529 assert(Found && "no instantiation for parameter pack");
2530
2531 Decl *TransformedDecl;
2532 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2533 // If this is a reference to a function parameter pack which we can
2534 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2535 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2536 QualType T = TransformType(E->getType());
2537 if (T.isNull())
2538 return ExprError();
2539 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2540 E->getExprLoc(), *Pack);
2541 getSema().MarkFunctionParmPackReferenced(PackExpr);
2542 return PackExpr;
2543 }
2544
2545 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2546 } else {
2547 TransformedDecl = cast<Decl *>(*Found);
2548 }
2549
2550 // We have either an unexpanded pack or a specific expansion.
2551 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2552}
2553
2555TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2556 NamedDecl *D = E->getDecl();
2557
2558 // Handle references to non-type template parameters and non-type template
2559 // parameter packs.
2560 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2561 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2562 return TransformTemplateParmRefExpr(E, NTTP);
2563
2564 // We have a non-type template parameter that isn't fully substituted;
2565 // FindInstantiatedDecl will find it in the local instantiation scope.
2566 }
2567
2568 // Handle references to function parameter packs.
2569 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2570 if (PD->isParameterPack())
2571 return TransformFunctionParmPackRefExpr(E, PD);
2572
2573 return inherited::TransformDeclRefExpr(E);
2574}
2575
2576ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2578 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2579 getDescribedFunctionTemplate() &&
2580 "Default arg expressions are never formed in dependent cases.");
2582 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2583 E->getParam());
2584}
2585
2586template<typename Fn>
2587QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2589 CXXRecordDecl *ThisContext,
2590 Qualifiers ThisTypeQuals,
2591 Fn TransformExceptionSpec) {
2592 // If this is a lambda or block, the transformation MUST be done in the
2593 // CurrentInstantiationScope since it introduces a mapping of
2594 // the original to the newly created transformed parameters.
2595 //
2596 // In that case, TemplateInstantiator::TransformLambdaExpr will
2597 // have already pushed a scope for this prototype, so don't create
2598 // a second one.
2599 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2600 std::optional<LocalInstantiationScope> Scope;
2601 if (!Current || !Current->isLambdaOrBlock())
2602 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2603
2604 return inherited::TransformFunctionProtoType(
2605 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2606}
2607
2608ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2609 ParmVarDecl *OldParm, int indexAdjustment,
2610 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2611 auto NewParm = SemaRef.SubstParmVarDecl(
2612 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2613 ExpectParameterPack, EvaluateConstraints);
2614 if (NewParm && SemaRef.getLangOpts().OpenCL)
2616 return NewParm;
2617}
2618
2619QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2620 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2621 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2622 TemplateArgument Arg, SourceLocation NameLoc) {
2623 QualType Replacement = Arg.getAsType();
2624
2625 // If the template parameter had ObjC lifetime qualifiers,
2626 // then any such qualifiers on the replacement type are ignored.
2627 if (SuppressObjCLifetime) {
2628 Qualifiers RQs;
2629 RQs = Replacement.getQualifiers();
2630 RQs.removeObjCLifetime();
2631 Replacement =
2632 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2633 }
2634
2635 if (Final) {
2636 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2637 return Replacement;
2638 }
2639 // TODO: only do this uniquing once, at the start of instantiation.
2640 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2641 Replacement, AssociatedDecl, Index, PackIndex);
2644 NewTL.setNameLoc(NameLoc);
2645 return Result;
2646}
2647
2649TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2651 bool SuppressObjCLifetime) {
2652 const TemplateTypeParmType *T = TL.getTypePtr();
2653 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2654 // Replace the template type parameter with its corresponding
2655 // template argument.
2656
2657 // If the corresponding template argument is NULL or doesn't exist, it's
2658 // because we are performing instantiation from explicitly-specified
2659 // template arguments in a function template class, but there were some
2660 // arguments left unspecified.
2661 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2662 IsIncomplete = true;
2663 if (BailOutOnIncomplete)
2664 return QualType();
2665
2668 NewTL.setNameLoc(TL.getNameLoc());
2669 return TL.getType();
2670 }
2671
2672 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2673
2674 if (TemplateArgs.isRewrite()) {
2675 // We're rewriting the template parameter as a reference to another
2676 // template parameter.
2677 if (Arg.getKind() == TemplateArgument::Pack) {
2678 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2679 "unexpected pack arguments in template rewrite");
2680 Arg = Arg.pack_begin()->getPackExpansionPattern();
2681 }
2682 assert(Arg.getKind() == TemplateArgument::Type &&
2683 "unexpected nontype template argument kind in template rewrite");
2684 QualType NewT = Arg.getAsType();
2685 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2686 return NewT;
2687 }
2688
2689 auto [AssociatedDecl, Final] =
2690 TemplateArgs.getAssociatedDecl(T->getDepth());
2691 std::optional<unsigned> PackIndex;
2692 if (T->isParameterPack()) {
2693 assert(Arg.getKind() == TemplateArgument::Pack &&
2694 "Missing argument pack");
2695
2696 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2697 // We have the template argument pack, but we're not expanding the
2698 // enclosing pack expansion yet. Just save the template argument
2699 // pack for later substitution.
2700 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2701 AssociatedDecl, T->getIndex(), Final, Arg);
2704 NewTL.setNameLoc(TL.getNameLoc());
2705 return Result;
2706 }
2707
2708 // PackIndex starts from last element.
2709 PackIndex = getPackIndex(Arg);
2710 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2711 }
2712
2713 assert(Arg.getKind() == TemplateArgument::Type &&
2714 "Template argument kind mismatch");
2715
2716 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2717 AssociatedDecl, T->getIndex(),
2718 PackIndex, Arg, TL.getNameLoc());
2719 }
2720
2721 // The template type parameter comes from an inner template (e.g.,
2722 // the template parameter list of a member template inside the
2723 // template we are instantiating). Create a new template type
2724 // parameter with the template "level" reduced by one.
2725 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2726 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2727 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2728 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2729 QualType Result = getSema().Context.getTemplateTypeParmType(
2730 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2731 T->isParameterPack(), NewTTPDecl);
2733 NewTL.setNameLoc(TL.getNameLoc());
2734 return Result;
2735}
2736
2737QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2739 bool SuppressObjCLifetime) {
2741
2742 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2743
2744 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2745 // We aren't expanding the parameter pack, so just return ourselves.
2746 QualType Result = TL.getType();
2747 if (NewReplaced != T->getAssociatedDecl())
2748 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2749 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2752 NewTL.setNameLoc(TL.getNameLoc());
2753 return Result;
2754 }
2755
2756 TemplateArgument Pack = T->getArgumentPack();
2758 return BuildSubstTemplateTypeParmType(
2759 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2760 getPackIndex(Pack), Arg, TL.getNameLoc());
2761}
2762
2765 Sema::EntityPrinter Printer) {
2766 SmallString<128> Message;
2767 SourceLocation ErrorLoc;
2768 if (Info.hasSFINAEDiagnostic()) {
2771 Info.takeSFINAEDiagnostic(PDA);
2772 PDA.second.EmitToString(S.getDiagnostics(), Message);
2773 ErrorLoc = PDA.first;
2774 } else {
2775 ErrorLoc = Info.getLocation();
2776 }
2777 SmallString<128> Entity;
2778 llvm::raw_svector_ostream OS(Entity);
2779 Printer(OS);
2780 const ASTContext &C = S.Context;
2782 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2783}
2784
2787 SmallString<128> Entity;
2788 llvm::raw_svector_ostream OS(Entity);
2789 Printer(OS);
2790 const ASTContext &C = Context;
2792 /*SubstitutedEntity=*/C.backupStr(Entity),
2793 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2794}
2795
2796ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2797 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2800 SmallVectorImpl<ParmVarDecl *> &TransParams,
2802
2803 TemplateDeductionInfo Info(KWLoc);
2804 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2805 RE, Info,
2806 SourceRange{KWLoc, RBraceLoc});
2808
2809 unsigned ErrorIdx;
2810 if (getDerived().TransformFunctionTypeParams(
2811 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2812 &TransParams, PInfos, &ErrorIdx) ||
2813 Trap.hasErrorOccurred()) {
2815 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2816 // Add a 'failed' Requirement to contain the error that caused the failure
2817 // here.
2818 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2819 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2820 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2821 TransParams, RE->getRParenLoc(),
2822 TransReqs, RBraceLoc);
2823 }
2824
2825 return ExprResult{};
2826}
2827
2829TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2830 if (!Req->isDependent() && !AlwaysRebuild())
2831 return Req;
2832 if (Req->isSubstitutionFailure()) {
2833 if (AlwaysRebuild())
2834 return RebuildTypeRequirement(
2836 return Req;
2837 }
2838
2842 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2843 Req->getType()->getTypeLoc().getSourceRange());
2844 if (TypeInst.isInvalid())
2845 return nullptr;
2846 TypeSourceInfo *TransType = TransformType(Req->getType());
2847 if (!TransType || Trap.hasErrorOccurred())
2848 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2849 [&] (llvm::raw_ostream& OS) {
2850 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2851 }));
2852 return RebuildTypeRequirement(TransType);
2853}
2854
2856TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2857 if (!Req->isDependent() && !AlwaysRebuild())
2858 return Req;
2859
2861
2862 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2863 TransExpr;
2864 if (Req->isExprSubstitutionFailure())
2865 TransExpr = Req->getExprSubstitutionDiagnostic();
2866 else {
2867 Expr *E = Req->getExpr();
2869 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2870 E->getSourceRange());
2871 if (ExprInst.isInvalid())
2872 return nullptr;
2873 ExprResult TransExprRes = TransformExpr(E);
2874 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2875 TransExprRes.get()->hasPlaceholderType())
2876 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2877 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2878 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2880 });
2881 else
2882 TransExpr = TransExprRes.get();
2883 }
2884
2885 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2886 const auto &RetReq = Req->getReturnTypeRequirement();
2887 if (RetReq.isEmpty())
2888 TransRetReq.emplace();
2889 else if (RetReq.isSubstitutionFailure())
2890 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2891 else if (RetReq.isTypeConstraint()) {
2892 TemplateParameterList *OrigTPL =
2893 RetReq.getTypeConstraintTemplateParameterList();
2894 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2896 Req, Info, OrigTPL->getSourceRange());
2897 if (TPLInst.isInvalid())
2898 return nullptr;
2899 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2900 if (!TPL || Trap.hasErrorOccurred())
2901 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2902 [&] (llvm::raw_ostream& OS) {
2903 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2904 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2905 }));
2906 else {
2907 TPLInst.Clear();
2908 TransRetReq.emplace(TPL);
2909 }
2910 }
2911 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2912 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2913 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2914 std::move(*TransRetReq));
2915 return RebuildExprRequirement(
2916 cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),
2917 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2918}
2919
2921TemplateInstantiator::TransformNestedRequirement(
2923 if (!Req->isDependent() && !AlwaysRebuild())
2924 return Req;
2925 if (Req->hasInvalidConstraint()) {
2926 if (AlwaysRebuild())
2927 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2929 return Req;
2930 }
2932 Req->getConstraintExpr()->getBeginLoc(), Req,
2935 if (!getEvaluateConstraints()) {
2936 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2937 if (TransConstraint.isInvalid() || !TransConstraint.get())
2938 return nullptr;
2939 if (TransConstraint.get()->isInstantiationDependent())
2940 return new (SemaRef.Context)
2941 concepts::NestedRequirement(TransConstraint.get());
2942 ConstraintSatisfaction Satisfaction;
2944 SemaRef.Context, TransConstraint.get(), Satisfaction);
2945 }
2946
2947 ExprResult TransConstraint;
2948 ConstraintSatisfaction Satisfaction;
2950 {
2955 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2957 if (ConstrInst.isInvalid())
2958 return nullptr;
2961 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2962 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2963 !Result.empty())
2964 TransConstraint = Result[0];
2965 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2966 "by CheckConstraintSatisfaction.");
2967 }
2969 if (TransConstraint.isUsable() &&
2970 TransConstraint.get()->isInstantiationDependent())
2971 return new (C) concepts::NestedRequirement(TransConstraint.get());
2972 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2973 Satisfaction.HasSubstitutionFailure()) {
2974 SmallString<128> Entity;
2975 llvm::raw_svector_ostream OS(Entity);
2976 Req->getConstraintExpr()->printPretty(OS, nullptr,
2978 return new (C) concepts::NestedRequirement(
2979 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2980 }
2981 return new (C)
2982 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2983}
2984
2988 DeclarationName Entity,
2989 bool AllowDeducedTST) {
2990 assert(!CodeSynthesisContexts.empty() &&
2991 "Cannot perform an instantiation without some context on the "
2992 "instantiation stack");
2993
2994 if (!T->getType()->isInstantiationDependentType() &&
2995 !T->getType()->isVariablyModifiedType())
2996 return T;
2997
2998 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2999 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
3000 : Instantiator.TransformType(T);
3001}
3002
3006 DeclarationName Entity) {
3007 assert(!CodeSynthesisContexts.empty() &&
3008 "Cannot perform an instantiation without some context on the "
3009 "instantiation stack");
3010
3011 if (TL.getType().isNull())
3012 return nullptr;
3013
3016 // FIXME: Make a copy of the TypeLoc data here, so that we can
3017 // return a new TypeSourceInfo. Inefficient!
3018 TypeLocBuilder TLB;
3019 TLB.pushFullCopy(TL);
3020 return TLB.getTypeSourceInfo(Context, TL.getType());
3021 }
3022
3023 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3024 TypeLocBuilder TLB;
3025 TLB.reserve(TL.getFullDataSize());
3026 QualType Result = Instantiator.TransformType(TLB, TL);
3027 if (Result.isNull())
3028 return nullptr;
3029
3030 return TLB.getTypeSourceInfo(Context, Result);
3031}
3032
3033/// Deprecated form of the above.
3035 const MultiLevelTemplateArgumentList &TemplateArgs,
3037 bool *IsIncompleteSubstitution) {
3038 assert(!CodeSynthesisContexts.empty() &&
3039 "Cannot perform an instantiation without some context on the "
3040 "instantiation stack");
3041
3042 // If T is not a dependent type or a variably-modified type, there
3043 // is nothing to do.
3045 return T;
3046
3047 TemplateInstantiator Instantiator(
3048 *this, TemplateArgs, Loc, Entity,
3049 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
3050 QualType QT = Instantiator.TransformType(T);
3051 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
3052 *IsIncompleteSubstitution = true;
3053 return QT;
3054}
3055
3057 if (T->getType()->isInstantiationDependentType() ||
3058 T->getType()->isVariablyModifiedType())
3059 return true;
3060
3061 TypeLoc TL = T->getTypeLoc().IgnoreParens();
3062 if (!TL.getAs<FunctionProtoTypeLoc>())
3063 return false;
3064
3066 for (ParmVarDecl *P : FP.getParams()) {
3067 // This must be synthesized from a typedef.
3068 if (!P) continue;
3069
3070 // If there are any parameters, a new TypeSourceInfo that refers to the
3071 // instantiated parameters must be built.
3072 return true;
3073 }
3074
3075 return false;
3076}
3077
3081 DeclarationName Entity,
3082 CXXRecordDecl *ThisContext,
3083 Qualifiers ThisTypeQuals,
3084 bool EvaluateConstraints) {
3085 assert(!CodeSynthesisContexts.empty() &&
3086 "Cannot perform an instantiation without some context on the "
3087 "instantiation stack");
3088
3090 return T;
3091
3092 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3093 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3094
3095 TypeLocBuilder TLB;
3096
3097 TypeLoc TL = T->getTypeLoc();
3098 TLB.reserve(TL.getFullDataSize());
3099
3101
3102 if (FunctionProtoTypeLoc Proto =
3104 // Instantiate the type, other than its exception specification. The
3105 // exception specification is instantiated in InitFunctionInstantiation
3106 // once we've built the FunctionDecl.
3107 // FIXME: Set the exception specification to EST_Uninstantiated here,
3108 // instead of rebuilding the function type again later.
3109 Result = Instantiator.TransformFunctionProtoType(
3110 TLB, Proto, ThisContext, ThisTypeQuals,
3112 bool &Changed) { return false; });
3113 } else {
3114 Result = Instantiator.TransformType(TLB, TL);
3115 }
3116 // When there are errors resolving types, clang may use IntTy as a fallback,
3117 // breaking our assumption that function declarations have function types.
3118 if (Result.isNull() || !Result->isFunctionType())
3119 return nullptr;
3120
3121 return TLB.getTypeSourceInfo(Context, Result);
3122}
3123
3126 SmallVectorImpl<QualType> &ExceptionStorage,
3127 const MultiLevelTemplateArgumentList &Args) {
3128 bool Changed = false;
3129 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3130 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3131 Changed);
3132}
3133
3135 const MultiLevelTemplateArgumentList &Args) {
3138
3139 SmallVector<QualType, 4> ExceptionStorage;
3141 ESI, ExceptionStorage, Args))
3142 // On error, recover by dropping the exception specification.
3143 ESI.Type = EST_None;
3144
3145 UpdateExceptionSpec(New, ESI);
3146}
3147
3148namespace {
3149
3150 struct GetContainedInventedTypeParmVisitor :
3151 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3152 TemplateTypeParmDecl *> {
3153 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3154 TemplateTypeParmDecl *>::Visit;
3155
3157 if (T.isNull())
3158 return nullptr;
3159 return Visit(T.getTypePtr());
3160 }
3161 // The deduced type itself.
3162 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3163 const TemplateTypeParmType *T) {
3164 if (!T->getDecl() || !T->getDecl()->isImplicit())
3165 return nullptr;
3166 return T->getDecl();
3167 }
3168
3169 // Only these types can contain 'auto' types, and subsequently be replaced
3170 // by references to invented parameters.
3171
3172 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3173 return Visit(T->getNamedType());
3174 }
3175
3176 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3177 return Visit(T->getPointeeType());
3178 }
3179
3180 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3181 return Visit(T->getPointeeType());
3182 }
3183
3184 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3185 return Visit(T->getPointeeTypeAsWritten());
3186 }
3187
3188 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3189 return Visit(T->getPointeeType());
3190 }
3191
3192 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3193 return Visit(T->getElementType());
3194 }
3195
3196 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3198 return Visit(T->getElementType());
3199 }
3200
3201 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3202 return Visit(T->getElementType());
3203 }
3204
3205 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3206 return VisitFunctionType(T);
3207 }
3208
3209 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3210 return Visit(T->getReturnType());
3211 }
3212
3213 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3214 return Visit(T->getInnerType());
3215 }
3216
3217 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3218 return Visit(T->getModifiedType());
3219 }
3220
3221 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3222 return Visit(T->getUnderlyingType());
3223 }
3224
3225 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3226 return Visit(T->getOriginalType());
3227 }
3228
3229 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3230 return Visit(T->getPattern());
3231 }
3232 };
3233
3234} // namespace
3235
3236namespace {
3237
3238struct ExpandPackedTypeConstraints
3239 : TreeTransform<ExpandPackedTypeConstraints> {
3240
3242
3243 const MultiLevelTemplateArgumentList &TemplateArgs;
3244
3245 ExpandPackedTypeConstraints(
3246 Sema &SemaRef, const MultiLevelTemplateArgumentList &TemplateArgs)
3247 : inherited(SemaRef), TemplateArgs(TemplateArgs) {}
3248
3249 using inherited::TransformTemplateTypeParmType;
3250
3251 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
3252 TemplateTypeParmTypeLoc TL, bool) {
3253 const TemplateTypeParmType *T = TL.getTypePtr();
3254 if (!T->isParameterPack()) {
3257 NewTL.setNameLoc(TL.getNameLoc());
3258 return TL.getType();
3259 }
3260
3261 assert(SemaRef.ArgumentPackSubstitutionIndex != -1);
3262
3263 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
3264
3265 std::optional<unsigned> PackIndex;
3266 if (Arg.getKind() == TemplateArgument::Pack)
3267 PackIndex = Arg.pack_size() - 1 - SemaRef.ArgumentPackSubstitutionIndex;
3268
3270 TL.getType(), T->getDecl(), T->getIndex(), PackIndex,
3271 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace);
3274 NewTL.setNameLoc(TL.getNameLoc());
3275 return Result;
3276 }
3277
3278 QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
3281 if (T->getPackIndex()) {
3284 TypeLoc.setNameLoc(TL.getNameLoc());
3285 return TypeLoc.getType();
3286 }
3287 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
3288 }
3289
3290 bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3292 return inherited::TransformTemplateArguments(Args.begin(), Args.end(), Out);
3293 }
3294};
3295
3296} // namespace
3297
3299 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3300 const MultiLevelTemplateArgumentList &TemplateArgs,
3301 bool EvaluateConstraints) {
3302 const ASTTemplateArgumentListInfo *TemplArgInfo =
3304
3305 if (!EvaluateConstraints) {
3306 bool ShouldExpandExplicitTemplateArgs =
3307 TemplArgInfo && ArgumentPackSubstitutionIndex != -1 &&
3308 llvm::any_of(TemplArgInfo->arguments(), [](auto &Arg) {
3309 return Arg.getArgument().containsUnexpandedParameterPack();
3310 });
3311
3312 // We want to transform the packs into Subst* nodes for type constraints
3313 // inside a pack expansion. For example,
3314 //
3315 // template <class... Ts> void foo() {
3316 // bar([](C<Ts> auto value) {}...);
3317 // }
3318 //
3319 // As we expand Ts in the process of instantiating foo(), and retain
3320 // the original template depths of Ts until the constraint evaluation, we
3321 // would otherwise have no chance to expand Ts by the time of evaluating
3322 // C<auto, Ts>.
3323 //
3324 // So we form a Subst* node for Ts along with a proper substitution index
3325 // here, and substitute the node with a complete MLTAL later in evaluation.
3326 if (ShouldExpandExplicitTemplateArgs) {
3327 TemplateArgumentListInfo InstArgs;
3328 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3329 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3330 if (ExpandPackedTypeConstraints(*this, TemplateArgs)
3331 .SubstTemplateArguments(TemplArgInfo->arguments(), InstArgs))
3332 return true;
3333
3334 // The type of the original parameter.
3335 auto *ConstraintExpr = TC->getImmediatelyDeclaredConstraint();
3336 QualType ConstrainedType;
3337
3338 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr)) {
3339 assert(FE->getLHS());
3340 ConstraintExpr = FE->getLHS();
3341 }
3342 auto *CSE = cast<ConceptSpecializationExpr>(ConstraintExpr);
3343 assert(!CSE->getTemplateArguments().empty() &&
3344 "Empty template arguments?");
3345 ConstrainedType = CSE->getTemplateArguments()[0].getAsType();
3346 assert(!ConstrainedType.isNull() &&
3347 "Failed to extract the original ConstrainedType?");
3348
3349 return AttachTypeConstraint(
3351 TC->getNamedConcept(),
3352 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs,
3353 Inst, ConstrainedType,
3354 Inst->isParameterPack()
3355 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3356 ->getEllipsisLoc()
3357 : SourceLocation());
3358 }
3361 return false;
3362 }
3363
3364 TemplateArgumentListInfo InstArgs;
3365
3366 if (TemplArgInfo) {
3367 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3368 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3369 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3370 InstArgs))
3371 return true;
3372 }
3373 return AttachTypeConstraint(
3375 TC->getNamedConcept(),
3376 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3378 Inst->isParameterPack()
3379 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3380 ->getEllipsisLoc()
3381 : SourceLocation());
3382}
3383
3385 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3386 int indexAdjustment, std::optional<unsigned> NumExpansions,
3387 bool ExpectParameterPack, bool EvaluateConstraint) {
3388 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3389 TypeSourceInfo *NewDI = nullptr;
3390
3391 TypeLoc OldTL = OldDI->getTypeLoc();
3392 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3393
3394 // We have a function parameter pack. Substitute into the pattern of the
3395 // expansion.
3396 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3397 OldParm->getLocation(), OldParm->getDeclName());
3398 if (!NewDI)
3399 return nullptr;
3400
3401 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3402 // We still have unexpanded parameter packs, which means that
3403 // our function parameter is still a function parameter pack.
3404 // Therefore, make its type a pack expansion type.
3405 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3406 NumExpansions);
3407 } else if (ExpectParameterPack) {
3408 // We expected to get a parameter pack but didn't (because the type
3409 // itself is not a pack expansion type), so complain. This can occur when
3410 // the substitution goes through an alias template that "loses" the
3411 // pack expansion.
3412 Diag(OldParm->getLocation(),
3413 diag::err_function_parameter_pack_without_parameter_packs)
3414 << NewDI->getType();
3415 return nullptr;
3416 }
3417 } else {
3418 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3419 OldParm->getDeclName());
3420 }
3421
3422 if (!NewDI)
3423 return nullptr;
3424
3425 if (NewDI->getType()->isVoidType()) {
3426 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3427 return nullptr;
3428 }
3429
3430 // In abbreviated templates, TemplateTypeParmDecls with possible
3431 // TypeConstraints are created when the parameter list is originally parsed.
3432 // The TypeConstraints can therefore reference other functions parameters in
3433 // the abbreviated function template, which is why we must instantiate them
3434 // here, when the instantiated versions of those referenced parameters are in
3435 // scope.
3436 if (TemplateTypeParmDecl *TTP =
3437 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3438 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3439 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3440 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3441 // We will first get here when instantiating the abbreviated function
3442 // template's described function, but we might also get here later.
3443 // Make sure we do not instantiate the TypeConstraint more than once.
3444 if (Inst && !Inst->getTypeConstraint()) {
3445 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3446 return nullptr;
3447 }
3448 }
3449 }
3450
3452 OldParm->getInnerLocStart(),
3453 OldParm->getLocation(),
3454 OldParm->getIdentifier(),
3455 NewDI->getType(), NewDI,
3456 OldParm->getStorageClass());
3457 if (!NewParm)
3458 return nullptr;
3459
3460 // Mark the (new) default argument as uninstantiated (if any).
3461 if (OldParm->hasUninstantiatedDefaultArg()) {
3462 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3463 NewParm->setUninstantiatedDefaultArg(Arg);
3464 } else if (OldParm->hasUnparsedDefaultArg()) {
3465 NewParm->setUnparsedDefaultArg();
3466 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3467 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3468 // Default arguments cannot be substituted until the declaration context
3469 // for the associated function or lambda capture class is available.
3470 // This is necessary for cases like the following where construction of
3471 // the lambda capture class for the outer lambda is dependent on the
3472 // parameter types but where the default argument is dependent on the
3473 // outer lambda's declaration context.
3474 // template <typename T>
3475 // auto f() {
3476 // return [](T = []{ return T{}; }()) { return 0; };
3477 // }
3478 NewParm->setUninstantiatedDefaultArg(Arg);
3479 }
3480
3484
3485 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3486 // Add the new parameter to the instantiated parameter pack.
3488 } else {
3489 // Introduce an Old -> New mapping
3491 }
3492
3493 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3494 // can be anything, is this right ?
3495 NewParm->setDeclContext(CurContext);
3496
3497 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3498 OldParm->getFunctionScopeIndex() + indexAdjustment);
3499
3500 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3501
3502 return NewParm;
3503}
3504
3507 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3508 const MultiLevelTemplateArgumentList &TemplateArgs,
3509 SmallVectorImpl<QualType> &ParamTypes,
3511 ExtParameterInfoBuilder &ParamInfos) {
3512 assert(!CodeSynthesisContexts.empty() &&
3513 "Cannot perform an instantiation without some context on the "
3514 "instantiation stack");
3515
3516 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3517 DeclarationName());
3518 return Instantiator.TransformFunctionTypeParams(
3519 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3520}
3521
3524 ParmVarDecl *Param,
3525 const MultiLevelTemplateArgumentList &TemplateArgs,
3526 bool ForCallExpr) {
3527 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3528 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3529
3532
3533 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3534 if (Inst.isInvalid())
3535 return true;
3536 if (Inst.isAlreadyInstantiating()) {
3537 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3538 Param->setInvalidDecl();
3539 return true;
3540 }
3541
3543 {
3544 // C++ [dcl.fct.default]p5:
3545 // The names in the [default argument] expression are bound, and
3546 // the semantic constraints are checked, at the point where the
3547 // default argument expression appears.
3548 ContextRAII SavedContext(*this, FD);
3549 std::unique_ptr<LocalInstantiationScope> LIS;
3550
3551 if (ForCallExpr) {
3552 // When instantiating a default argument due to use in a call expression,
3553 // an instantiation scope that includes the parameters of the callee is
3554 // required to satisfy references from the default argument. For example:
3555 // template<typename T> void f(T a, int = decltype(a)());
3556 // void g() { f(0); }
3557 LIS = std::make_unique<LocalInstantiationScope>(*this);
3559 /*ForDefinition*/ false);
3560 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3561 return true;
3562 }
3563
3565 Result = SubstInitializer(PatternExpr, TemplateArgs,
3566 /*DirectInit*/ false);
3567 });
3568 }
3569 if (Result.isInvalid())
3570 return true;
3571
3572 if (ForCallExpr) {
3573 // Check the expression as an initializer for the parameter.
3574 InitializedEntity Entity
3577 Param->getLocation(),
3578 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3579 Expr *ResultE = Result.getAs<Expr>();
3580
3581 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3582 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3583 if (Result.isInvalid())
3584 return true;
3585
3586 Result =
3588 /*DiscardedValue*/ false);
3589 } else {
3590 // FIXME: Obtain the source location for the '=' token.
3591 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3592 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3593 }
3594 if (Result.isInvalid())
3595 return true;
3596
3597 // Remember the instantiated default argument.
3598 Param->setDefaultArg(Result.getAs<Expr>());
3599
3600 return false;
3601}
3602
3603bool
3605 CXXRecordDecl *Pattern,
3606 const MultiLevelTemplateArgumentList &TemplateArgs) {
3607 bool Invalid = false;
3608 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3609 for (const auto &Base : Pattern->bases()) {
3610 if (!Base.getType()->isDependentType()) {
3611 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3612 if (RD->isInvalidDecl())
3613 Instantiation->setInvalidDecl();
3614 }
3615 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3616 continue;
3617 }
3618
3619 SourceLocation EllipsisLoc;
3620 TypeSourceInfo *BaseTypeLoc;
3621 if (Base.isPackExpansion()) {
3622 // This is a pack expansion. See whether we should expand it now, or
3623 // wait until later.
3625 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3626 Unexpanded);
3627 bool ShouldExpand = false;
3628 bool RetainExpansion = false;
3629 std::optional<unsigned> NumExpansions;
3630 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3631 Base.getSourceRange(),
3632 Unexpanded,
3633 TemplateArgs, ShouldExpand,
3634 RetainExpansion,
3635 NumExpansions)) {
3636 Invalid = true;
3637 continue;
3638 }
3639
3640 // If we should expand this pack expansion now, do so.
3641 if (ShouldExpand) {
3642 for (unsigned I = 0; I != *NumExpansions; ++I) {
3643 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3644
3645 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3646 TemplateArgs,
3647 Base.getSourceRange().getBegin(),
3648 DeclarationName());
3649 if (!BaseTypeLoc) {
3650 Invalid = true;
3651 continue;
3652 }
3653
3654 if (CXXBaseSpecifier *InstantiatedBase
3655 = CheckBaseSpecifier(Instantiation,
3656 Base.getSourceRange(),
3657 Base.isVirtual(),
3658 Base.getAccessSpecifierAsWritten(),
3659 BaseTypeLoc,
3660 SourceLocation()))
3661 InstantiatedBases.push_back(InstantiatedBase);
3662 else
3663 Invalid = true;
3664 }
3665
3666 continue;
3667 }
3668
3669 // The resulting base specifier will (still) be a pack expansion.
3670 EllipsisLoc = Base.getEllipsisLoc();
3671 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3672 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3673 TemplateArgs,
3674 Base.getSourceRange().getBegin(),
3675 DeclarationName());
3676 } else {
3677 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3678 TemplateArgs,
3679 Base.getSourceRange().getBegin(),
3680 DeclarationName());
3681 }
3682
3683 if (!BaseTypeLoc) {
3684 Invalid = true;
3685 continue;
3686 }
3687
3688 if (CXXBaseSpecifier *InstantiatedBase
3689 = CheckBaseSpecifier(Instantiation,
3690 Base.getSourceRange(),
3691 Base.isVirtual(),
3692 Base.getAccessSpecifierAsWritten(),
3693 BaseTypeLoc,
3694 EllipsisLoc))
3695 InstantiatedBases.push_back(InstantiatedBase);
3696 else
3697 Invalid = true;
3698 }
3699
3700 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3701 Invalid = true;
3702
3703 return Invalid;
3704}
3705
3706// Defined via #include from SemaTemplateInstantiateDecl.cpp
3707namespace clang {
3708 namespace sema {
3710 const MultiLevelTemplateArgumentList &TemplateArgs);
3712 const Attr *At, ASTContext &C, Sema &S,
3713 const MultiLevelTemplateArgumentList &TemplateArgs);
3714 }
3715}
3716
3717bool
3719 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3720 const MultiLevelTemplateArgumentList &TemplateArgs,
3722 bool Complain) {
3723 CXXRecordDecl *PatternDef
3724 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3725 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3726 Instantiation->getInstantiatedFromMemberClass(),
3727 Pattern, PatternDef, TSK, Complain))
3728 return true;
3729
3730 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3731 llvm::TimeTraceMetadata M;
3732 llvm::raw_string_ostream OS(M.Detail);
3733 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3734 /*Qualified=*/true);
3735 if (llvm::isTimeTraceVerbose()) {
3736 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3737 M.File = SourceMgr.getFilename(Loc);
3739 }
3740 return M;
3741 });
3742
3743 Pattern = PatternDef;
3744
3745 // Record the point of instantiation.
3746 if (MemberSpecializationInfo *MSInfo
3747 = Instantiation->getMemberSpecializationInfo()) {
3748 MSInfo->setTemplateSpecializationKind(TSK);
3749 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3750 } else if (ClassTemplateSpecializationDecl *Spec
3751 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3752 Spec->setTemplateSpecializationKind(TSK);
3753 Spec->setPointOfInstantiation(PointOfInstantiation);
3754 }
3755
3756 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3757 if (Inst.isInvalid())
3758 return true;
3759 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3760 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3761 "instantiating class definition");
3762
3763 // Enter the scope of this instantiation. We don't use
3764 // PushDeclContext because we don't have a scope.
3765 ContextRAII SavedContext(*this, Instantiation);
3768
3769 // If this is an instantiation of a local class, merge this local
3770 // instantiation scope with the enclosing scope. Otherwise, every
3771 // instantiation of a class has its own local instantiation scope.
3772 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3773 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3774
3775 // Some class state isn't processed immediately but delayed till class
3776 // instantiation completes. We may not be ready to handle any delayed state
3777 // already on the stack as it might correspond to a different class, so save
3778 // it now and put it back later.
3779 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3780
3781 // Pull attributes from the pattern onto the instantiation.
3782 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3783
3784 // Start the definition of this instantiation.
3785 Instantiation->startDefinition();
3786
3787 // The instantiation is visible here, even if it was first declared in an
3788 // unimported module.
3789 Instantiation->setVisibleDespiteOwningModule();
3790
3791 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3792 Instantiation->setTagKind(Pattern->getTagKind());
3793
3794 // Do substitution on the base class specifiers.
3795 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3796 Instantiation->setInvalidDecl();
3797
3798 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3799 Instantiator.setEvaluateConstraints(false);
3800 SmallVector<Decl*, 4> Fields;
3801 // Delay instantiation of late parsed attributes.
3802 LateInstantiatedAttrVec LateAttrs;
3803 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3804
3805 bool MightHaveConstexprVirtualFunctions = false;
3806 for (auto *Member : Pattern->decls()) {
3807 // Don't instantiate members not belonging in this semantic context.
3808 // e.g. for:
3809 // @code
3810 // template <int i> class A {
3811 // class B *g;
3812 // };
3813 // @endcode
3814 // 'class B' has the template as lexical context but semantically it is
3815 // introduced in namespace scope.
3816 if (Member->getDeclContext() != Pattern)
3817 continue;
3818
3819 // BlockDecls can appear in a default-member-initializer. They must be the
3820 // child of a BlockExpr, so we only know how to instantiate them from there.
3821 // Similarly, lambda closure types are recreated when instantiating the
3822 // corresponding LambdaExpr.
3823 if (isa<BlockDecl>(Member) ||
3824 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3825 continue;
3826
3827 if (Member->isInvalidDecl()) {
3828 Instantiation->setInvalidDecl();
3829 continue;
3830 }
3831
3832 Decl *NewMember = Instantiator.Visit(Member);
3833 if (NewMember) {
3834 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3835 Fields.push_back(Field);
3836 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3837 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3838 // specialization causes the implicit instantiation of the definitions
3839 // of unscoped member enumerations.
3840 // Record a point of instantiation for this implicit instantiation.
3841 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3842 Enum->isCompleteDefinition()) {
3843 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3844 assert(MSInfo && "no spec info for member enum specialization");
3846 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3847 }
3848 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3849 if (SA->isFailed()) {
3850 // A static_assert failed. Bail out; instantiating this
3851 // class is probably not meaningful.
3852 Instantiation->setInvalidDecl();
3853 break;
3854 }
3855 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3856 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3857 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3858 MightHaveConstexprVirtualFunctions = true;
3859 }
3860
3861 if (NewMember->isInvalidDecl())
3862 Instantiation->setInvalidDecl();
3863 } else {
3864 // FIXME: Eventually, a NULL return will mean that one of the
3865 // instantiations was a semantic disaster, and we'll want to mark the
3866 // declaration invalid.
3867 // For now, we expect to skip some members that we can't yet handle.
3868 }
3869 }
3870
3871 // Finish checking fields.
3872 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3874 CheckCompletedCXXClass(nullptr, Instantiation);
3875
3876 // Default arguments are parsed, if not instantiated. We can go instantiate
3877 // default arg exprs for default constructors if necessary now. Unless we're
3878 // parsing a class, in which case wait until that's finished.
3879 if (ParsingClassDepth == 0)
3881
3882 // Instantiate late parsed attributes, and attach them to their decls.
3883 // See Sema::InstantiateAttrs
3884 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3885 E = LateAttrs.end(); I != E; ++I) {
3886 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3887 CurrentInstantiationScope = I->Scope;
3888
3889 // Allow 'this' within late-parsed attributes.
3890 auto *ND = cast<NamedDecl>(I->NewDecl);
3891 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3892 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3893 ND->isCXXInstanceMember());
3894
3895 Attr *NewAttr =
3896 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3897 if (NewAttr)
3898 I->NewDecl->addAttr(NewAttr);
3900 Instantiator.getStartingScope());
3901 }
3902 Instantiator.disableLateAttributeInstantiation();
3903 LateAttrs.clear();
3904
3906
3907 // FIXME: We should do something similar for explicit instantiations so they
3908 // end up in the right module.
3909 if (TSK == TSK_ImplicitInstantiation) {
3910 Instantiation->setLocation(Pattern->getLocation());
3911 Instantiation->setLocStart(Pattern->getInnerLocStart());
3912 Instantiation->setBraceRange(Pattern->getBraceRange());
3913 }
3914
3915 if (!Instantiation->isInvalidDecl()) {
3916 // Perform any dependent diagnostics from the pattern.
3917 if (Pattern->isDependentContext())
3918 PerformDependentDiagnostics(Pattern, TemplateArgs);
3919
3920 // Instantiate any out-of-line class template partial
3921 // specializations now.
3923 P = Instantiator.delayed_partial_spec_begin(),
3924 PEnd = Instantiator.delayed_partial_spec_end();
3925 P != PEnd; ++P) {
3927 P->first, P->second)) {
3928 Instantiation->setInvalidDecl();
3929 break;
3930 }
3931 }
3932
3933 // Instantiate any out-of-line variable template partial
3934 // specializations now.
3936 P = Instantiator.delayed_var_partial_spec_begin(),
3937 PEnd = Instantiator.delayed_var_partial_spec_end();
3938 P != PEnd; ++P) {
3940 P->first, P->second)) {
3941 Instantiation->setInvalidDecl();
3942 break;
3943 }
3944 }
3945 }
3946
3947 // Exit the scope of this instantiation.
3948 SavedContext.pop();
3949
3950 if (!Instantiation->isInvalidDecl()) {
3951 // Always emit the vtable for an explicit instantiation definition
3952 // of a polymorphic class template specialization. Otherwise, eagerly
3953 // instantiate only constexpr virtual functions in preparation for their use
3954 // in constant evaluation.
3956 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3957 else if (MightHaveConstexprVirtualFunctions)
3958 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3959 /*ConstexprOnly*/ true);
3960 }
3961
3962 Consumer.HandleTagDeclDefinition(Instantiation);
3963
3964 return Instantiation->isInvalidDecl();
3965}
3966
3967bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3968 EnumDecl *Instantiation, EnumDecl *Pattern,
3969 const MultiLevelTemplateArgumentList &TemplateArgs,
3971 EnumDecl *PatternDef = Pattern->getDefinition();
3972 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3973 Instantiation->getInstantiatedFromMemberEnum(),
3974 Pattern, PatternDef, TSK,/*Complain*/true))
3975 return true;
3976 Pattern = PatternDef;
3977
3978 // Record the point of instantiation.
3979 if (MemberSpecializationInfo *MSInfo
3980 = Instantiation->getMemberSpecializationInfo()) {
3981 MSInfo->setTemplateSpecializationKind(TSK);
3982 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3983 }
3984
3985 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3986 if (Inst.isInvalid())
3987 return true;
3988 if (Inst.isAlreadyInstantiating())
3989 return false;
3990 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3991 "instantiating enum definition");
3992
3993 // The instantiation is visible here, even if it was first declared in an
3994 // unimported module.
3995 Instantiation->setVisibleDespiteOwningModule();
3996
3997 // Enter the scope of this instantiation. We don't use
3998 // PushDeclContext because we don't have a scope.
3999 ContextRAII SavedContext(*this, Instantiation);
4002
4003 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
4004
4005 // Pull attributes from the pattern onto the instantiation.
4006 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
4007
4008 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
4009 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
4010
4011 // Exit the scope of this instantiation.
4012 SavedContext.pop();
4013
4014 return Instantiation->isInvalidDecl();
4015}
4016
4018 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
4019 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
4020 // If there is no initializer, we don't need to do anything.
4021 if (!Pattern->hasInClassInitializer())
4022 return false;
4023
4024 assert(Instantiation->getInClassInitStyle() ==
4025 Pattern->getInClassInitStyle() &&
4026 "pattern and instantiation disagree about init style");
4027
4028 // Error out if we haven't parsed the initializer of the pattern yet because
4029 // we are waiting for the closing brace of the outer class.
4030 Expr *OldInit = Pattern->getInClassInitializer();
4031 if (!OldInit) {
4032 RecordDecl *PatternRD = Pattern->getParent();
4033 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
4034 Diag(PointOfInstantiation,
4035 diag::err_default_member_initializer_not_yet_parsed)
4036 << OutermostClass << Pattern;
4037 Diag(Pattern->getEndLoc(),
4038 diag::note_default_member_initializer_not_yet_parsed);
4039 Instantiation->setInvalidDecl();
4040 return true;
4041 }
4042
4043 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
4044 if (Inst.isInvalid())
4045 return true;
4046 if (Inst.isAlreadyInstantiating()) {
4047 // Error out if we hit an instantiation cycle for this initializer.
4048 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
4049 << Instantiation;
4050 return true;
4051 }
4052 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
4053 "instantiating default member init");
4054
4055 // Enter the scope of this instantiation. We don't use PushDeclContext because
4056 // we don't have a scope.
4057 ContextRAII SavedContext(*this, Instantiation->getParent());
4060 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
4061 PointOfInstantiation, Instantiation, CurContext};
4062
4063 LocalInstantiationScope Scope(*this, true);
4064
4065 // Instantiate the initializer.
4067 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
4068
4069 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
4070 /*CXXDirectInit=*/false);
4071 Expr *Init = NewInit.get();
4072 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
4074 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
4075
4076 if (auto *L = getASTMutationListener())
4077 L->DefaultMemberInitializerInstantiated(Instantiation);
4078
4079 // Return true if the in-class initializer is still missing.
4080 return !Instantiation->getInClassInitializer();
4081}
4082
4083namespace {
4084 /// A partial specialization whose template arguments have matched
4085 /// a given template-id.
4086 struct PartialSpecMatchResult {
4089 };
4090}
4091
4094 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4096 return true;
4097
4099 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4100 CTD->getPartialSpecializations(PartialSpecs);
4101 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4102 // C++ [temp.spec.partial.member]p2:
4103 // If the primary member template is explicitly specialized for a given
4104 // (implicit) specialization of the enclosing class template, the partial
4105 // specializations of the member template are ignored for this
4106 // specialization of the enclosing class template. If a partial
4107 // specialization of the member template is explicitly specialized for a
4108 // given (implicit) specialization of the enclosing class template, the
4109 // primary member template and its other partial specializations are still
4110 // considered for this specialization of the enclosing class template.
4112 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
4113 continue;
4114
4116 if (DeduceTemplateArguments(CTPSD,
4117 ClassTemplateSpec->getTemplateArgs().asArray(),
4119 return true;
4120 }
4121
4122 return false;
4123}
4124
4125/// Get the instantiation pattern to use to instantiate the definition of a
4126/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4127/// template or of a partial specialization).
4130 Sema &S, SourceLocation PointOfInstantiation,
4131 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4133 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4134 if (Inst.isInvalid())
4135 return {/*Invalid=*/true};
4136 if (Inst.isAlreadyInstantiating())
4137 return {/*Invalid=*/false};
4138
4139 llvm::PointerUnion<ClassTemplateDecl *,
4141 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4142 if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4143 // Find best matching specialization.
4144 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4145
4146 // C++ [temp.class.spec.match]p1:
4147 // When a class template is used in a context that requires an
4148 // instantiation of the class, it is necessary to determine
4149 // whether the instantiation is to be generated using the primary
4150 // template or one of the partial specializations. This is done by
4151 // matching the template arguments of the class template
4152 // specialization with the template argument lists of the partial
4153 // specializations.
4154 typedef PartialSpecMatchResult MatchResult;
4157 Template->getPartialSpecializations(PartialSpecs);
4158 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4159 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4160 // C++ [temp.spec.partial.member]p2:
4161 // If the primary member template is explicitly specialized for a given
4162 // (implicit) specialization of the enclosing class template, the
4163 // partial specializations of the member template are ignored for this
4164 // specialization of the enclosing class template. If a partial
4165 // specialization of the member template is explicitly specialized for a
4166 // given (implicit) specialization of the enclosing class template, the
4167 // primary member template and its other partial specializations are
4168 // still considered for this specialization of the enclosing class
4169 // template.
4170 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4171 !Partial->getMostRecentDecl()->isMemberSpecialization())
4172 continue;
4173
4174 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4176 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4178 // Store the failed-deduction information for use in diagnostics, later.
4179 // TODO: Actually use the failed-deduction info?
4180 FailedCandidates.addCandidate().set(
4181 DeclAccessPair::make(Template, AS_public), Partial,
4183 (void)Result;
4184 } else {
4185 Matched.push_back(PartialSpecMatchResult());
4186 Matched.back().Partial = Partial;
4187 Matched.back().Args = Info.takeCanonical();
4188 }
4189 }
4190
4191 // If we're dealing with a member template where the template parameters
4192 // have been instantiated, this provides the original template parameters
4193 // from which the member template's parameters were instantiated.
4194
4195 if (Matched.size() >= 1) {
4196 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4197 if (Matched.size() == 1) {
4198 // -- If exactly one matching specialization is found, the
4199 // instantiation is generated from that specialization.
4200 // We don't need to do anything for this.
4201 } else {
4202 // -- If more than one matching specialization is found, the
4203 // partial order rules (14.5.4.2) are used to determine
4204 // whether one of the specializations is more specialized
4205 // than the others. If none of the specializations is more
4206 // specialized than all of the other matching
4207 // specializations, then the use of the class template is
4208 // ambiguous and the program is ill-formed.
4210 PEnd = Matched.end();
4211 P != PEnd; ++P) {
4213 P->Partial, Best->Partial, PointOfInstantiation) ==
4214 P->Partial)
4215 Best = P;
4216 }
4217
4218 // Determine if the best partial specialization is more specialized than
4219 // the others.
4220 bool Ambiguous = false;
4221 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4222 PEnd = Matched.end();
4223 P != PEnd; ++P) {
4225 P->Partial, Best->Partial,
4226 PointOfInstantiation) != Best->Partial) {
4227 Ambiguous = true;
4228 break;
4229 }
4230 }
4231
4232 if (Ambiguous) {
4233 // Partial ordering did not produce a clear winner. Complain.
4234 Inst.Clear();
4235 ClassTemplateSpec->setInvalidDecl();
4236 S.Diag(PointOfInstantiation,
4237 diag::err_partial_spec_ordering_ambiguous)
4238 << ClassTemplateSpec;
4239
4240 // Print the matching partial specializations.
4241 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4242 PEnd = Matched.end();
4243 P != PEnd; ++P)
4244 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4246 P->Partial->getTemplateParameters(), *P->Args);
4247
4248 return {/*Invalid=*/true};
4249 }
4250 }
4251
4252 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4253 } else {
4254 // -- If no matches are found, the instantiation is generated
4255 // from the primary template.
4256 }
4257 }
4258
4259 CXXRecordDecl *Pattern = nullptr;
4260 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4261 if (auto *PartialSpec =
4262 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4263 // Instantiate using the best class template partial specialization.
4264 while (PartialSpec->getInstantiatedFromMember()) {
4265 // If we've found an explicit specialization of this class template,
4266 // stop here and use that as the pattern.
4267 if (PartialSpec->isMemberSpecialization())
4268 break;
4269
4270 PartialSpec = PartialSpec->getInstantiatedFromMember();
4271 }
4272 Pattern = PartialSpec;
4273 } else {
4274 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4275 while (Template->getInstantiatedFromMemberTemplate()) {
4276 // If we've found an explicit specialization of this class template,
4277 // stop here and use that as the pattern.
4278 if (Template->isMemberSpecialization())
4279 break;
4280
4281 Template = Template->getInstantiatedFromMemberTemplate();
4282 }
4283 Pattern = Template->getTemplatedDecl();
4284 }
4285
4286 return Pattern;
4287}
4288
4290 SourceLocation PointOfInstantiation,
4291 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4292 TemplateSpecializationKind TSK, bool Complain) {
4293 // Perform the actual instantiation on the canonical declaration.
4294 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4295 ClassTemplateSpec->getCanonicalDecl());
4296 if (ClassTemplateSpec->isInvalidDecl())
4297 return true;
4298
4300 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4301 ClassTemplateSpec, TSK);
4302 if (!Pattern.isUsable())
4303 return Pattern.isInvalid();
4304
4305 return InstantiateClass(
4306 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4307 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4308}
4309
4310void
4312 CXXRecordDecl *Instantiation,
4313 const MultiLevelTemplateArgumentList &TemplateArgs,
4315 // FIXME: We need to notify the ASTMutationListener that we did all of these
4316 // things, in case we have an explicit instantiation definition in a PCM, a
4317 // module, or preamble, and the declaration is in an imported AST.
4318 assert(
4321 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4322 "Unexpected template specialization kind!");
4323 for (auto *D : Instantiation->decls()) {
4324 bool SuppressNew = false;
4325 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4326 if (FunctionDecl *Pattern =
4327 Function->getInstantiatedFromMemberFunction()) {
4328
4329 if (Function->isIneligibleOrNotSelected())
4330 continue;
4331
4332 if (Function->getTrailingRequiresClause()) {
4333 ConstraintSatisfaction Satisfaction;
4334 if (CheckFunctionConstraints(Function, Satisfaction) ||
4335 !Satisfaction.IsSatisfied) {
4336 continue;
4337 }
4338 }
4339
4340 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4341 continue;
4342
4344 Function->getTemplateSpecializationKind();
4345 if (PrevTSK == TSK_ExplicitSpecialization)
4346 continue;
4347
4349 PointOfInstantiation, TSK, Function, PrevTSK,
4350 Function->getPointOfInstantiation(), SuppressNew) ||
4351 SuppressNew)
4352 continue;
4353
4354 // C++11 [temp.explicit]p8:
4355 // An explicit instantiation definition that names a class template
4356 // specialization explicitly instantiates the class template
4357 // specialization and is only an explicit instantiation definition
4358 // of members whose definition is visible at the point of
4359 // instantiation.
4360 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4361 continue;
4362
4363 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4364
4365 if (Function->isDefined()) {
4366 // Let the ASTConsumer know that this function has been explicitly
4367 // instantiated now, and its linkage might have changed.
4369 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4370 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4371 } else if (TSK == TSK_ImplicitInstantiation) {
4373 std::make_pair(Function, PointOfInstantiation));
4374 }
4375 }
4376 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4377 if (isa<VarTemplateSpecializationDecl>(Var))
4378 continue;
4379
4380 if (Var->isStaticDataMember()) {
4381 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4382 continue;
4383
4385 assert(MSInfo && "No member specialization information?");
4386 if (MSInfo->getTemplateSpecializationKind()
4388 continue;
4389
4390 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4391 Var,
4393 MSInfo->getPointOfInstantiation(),
4394 SuppressNew) ||
4395 SuppressNew)
4396 continue;
4397
4399 // C++0x [temp.explicit]p8:
4400 // An explicit instantiation definition that names a class template
4401 // specialization explicitly instantiates the class template
4402 // specialization and is only an explicit instantiation definition
4403 // of members whose definition is visible at the point of
4404 // instantiation.
4406 continue;
4407
4408 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4409 InstantiateVariableDefinition(PointOfInstantiation, Var);
4410 } else {
4411 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4412 }
4413 }
4414 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4415 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4416 continue;
4417
4418 // Always skip the injected-class-name, along with any
4419 // redeclarations of nested classes, since both would cause us
4420 // to try to instantiate the members of a class twice.
4421 // Skip closure types; they'll get instantiated when we instantiate
4422 // the corresponding lambda-expression.
4423 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4424 Record->isLambda())
4425 continue;
4426
4427 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4428 assert(MSInfo && "No member specialization information?");
4429
4430 if (MSInfo->getTemplateSpecializationKind()
4432 continue;
4433
4434 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4436 // On Windows, explicit instantiation decl of the outer class doesn't
4437 // affect the inner class. Typically extern template declarations are
4438 // used in combination with dll import/export annotations, but those
4439 // are not propagated from the outer class templates to inner classes.
4440 // Therefore, do not instantiate inner classes on this platform, so
4441 // that users don't end up with undefined symbols during linking.
4442 continue;
4443 }
4444
4445 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4446 Record,
4448 MSInfo->getPointOfInstantiation(),
4449 SuppressNew) ||
4450 SuppressNew)
4451 continue;
4452
4454 assert(Pattern && "Missing instantiated-from-template information");
4455
4456 if (!Record->getDefinition()) {
4457 if (!Pattern->getDefinition()) {
4458 // C++0x [temp.explicit]p8:
4459 // An explicit instantiation definition that names a class template
4460 // specialization explicitly instantiates the class template
4461 // specialization and is only an explicit instantiation definition
4462 // of members whose definition is visible at the point of
4463 // instantiation.
4465 MSInfo->setTemplateSpecializationKind(TSK);
4466 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4467 }
4468
4469 continue;
4470 }
4471
4472 InstantiateClass(PointOfInstantiation, Record, Pattern,
4473 TemplateArgs,
4474 TSK);
4475 } else {
4477 Record->getTemplateSpecializationKind() ==
4479 Record->setTemplateSpecializationKind(TSK);
4480 MarkVTableUsed(PointOfInstantiation, Record, true);
4481 }
4482 }
4483
4484 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4485 if (Pattern)
4486 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4487 TSK);
4488 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4489 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4490 assert(MSInfo && "No member specialization information?");
4491
4492 if (MSInfo->getTemplateSpecializationKind()
4494 continue;
4495
4497 PointOfInstantiation, TSK, Enum,
4499 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4500 SuppressNew)
4501 continue;
4502
4503 if (Enum->getDefinition())
4504 continue;
4505
4506 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4507 assert(Pattern && "Missing instantiated-from-template information");
4508
4510 if (!Pattern->getDefinition())
4511 continue;
4512
4513 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4514 } else {
4515 MSInfo->setTemplateSpecializationKind(TSK);
4516 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4517 }
4518 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4519 // No need to instantiate in-class initializers during explicit
4520 // instantiation.
4521 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4522 CXXRecordDecl *ClassPattern =
4523 Instantiation->getTemplateInstantiationPattern();
4525 ClassPattern->lookup(Field->getDeclName());
4526 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4527 assert(Pattern);
4528 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4529 TemplateArgs);
4530 }
4531 }
4532 }
4533}
4534
4535void
4537 SourceLocation PointOfInstantiation,
4538 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4540 // C++0x [temp.explicit]p7:
4541 // An explicit instantiation that names a class template
4542 // specialization is an explicit instantion of the same kind
4543 // (declaration or definition) of each of its members (not
4544 // including members inherited from base classes) that has not
4545 // been previously explicitly specialized in the translation unit
4546 // containing the explicit instantiation, except as described
4547 // below.
4548 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4549 getTemplateInstantiationArgs(ClassTemplateSpec),
4550 TSK);
4551}
4552
4555 if (!S)
4556 return S;
4557
4558 TemplateInstantiator Instantiator(*this, TemplateArgs,
4560 DeclarationName());
4561 return Instantiator.TransformStmt(S);
4562}
4563
4565 const TemplateArgumentLoc &Input,
4566 const MultiLevelTemplateArgumentList &TemplateArgs,
4568 const DeclarationName &Entity) {
4569 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4570 return Instantiator.TransformTemplateArgument(Input, Output);
4571}
4572
4575 const MultiLevelTemplateArgumentList &TemplateArgs,
4577 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4578 DeclarationName());
4579 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4580}
4581
4584 if (!E)
4585 return E;
4586
4587 TemplateInstantiator Instantiator(*this, TemplateArgs,
4589 DeclarationName());
4590 return Instantiator.TransformExpr(E);
4591}
4592
4595 const MultiLevelTemplateArgumentList &TemplateArgs) {
4596 // FIXME: should call SubstExpr directly if this function is equivalent or
4597 // should it be different?
4598 return SubstExpr(E, TemplateArgs);
4599}
4600
4602 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4603 if (!E)
4604 return E;
4605
4606 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4607 DeclarationName());
4608 Instantiator.setEvaluateConstraints(false);
4609 return Instantiator.TransformExpr(E);
4610}
4611
4613 const MultiLevelTemplateArgumentList &TemplateArgs,
4614 bool CXXDirectInit) {
4615 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4616 DeclarationName());
4617 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4618}
4619
4620bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4621 const MultiLevelTemplateArgumentList &TemplateArgs,
4622 SmallVectorImpl<Expr *> &Outputs) {
4623 if (Exprs.empty())
4624 return false;
4625
4626 TemplateInstantiator Instantiator(*this, TemplateArgs,
4628 DeclarationName());
4629 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4630 IsCall, Outputs);
4631}
4632
4635 const MultiLevelTemplateArgumentList &TemplateArgs) {
4636 if (!NNS)
4637 return NestedNameSpecifierLoc();
4638
4639 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4640 DeclarationName());
4641 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4642}
4643
4646 const MultiLevelTemplateArgumentList &TemplateArgs) {
4647 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4648 NameInfo.getName());
4649 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4650}
4651
4655 const MultiLevelTemplateArgumentList &TemplateArgs) {
4656 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4657 DeclarationName());
4658 CXXScopeSpec SS;
4659 SS.Adopt(QualifierLoc);
4660 return Instantiator.TransformTemplateName(SS, Name, Loc);
4661}
4662
4663static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4664 // When storing ParmVarDecls in the local instantiation scope, we always
4665 // want to use the ParmVarDecl from the canonical function declaration,
4666 // since the map is then valid for any redeclaration or definition of that
4667 // function.
4668 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4669 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4670 unsigned i = PV->getFunctionScopeIndex();
4671 // This parameter might be from a freestanding function type within the
4672 // function and isn't necessarily referring to one of FD's parameters.
4673 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4674 return FD->getCanonicalDecl()->getParamDecl(i);
4675 }
4676 }
4677 return D;
4678}
4679
4680llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4683 for (LocalInstantiationScope *Current = this; Current;
4684 Current = Current->Outer) {
4685
4686 // Check if we found something within this scope.
4687 const Decl *CheckD = D;
4688 do {
4689 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4690 if (Found != Current->LocalDecls.end())
4691 return &Found->second;
4692
4693 // If this is a tag declaration, it's possible that we need to look for
4694 // a previous declaration.
4695 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4696 CheckD = Tag->getPreviousDecl();
4697 else
4698 CheckD = nullptr;
4699 } while (CheckD);
4700
4701 // If we aren't combined with our outer scope, we're done.
4702 if (!Current->CombineWithOuterScope)
4703 break;
4704 }
4705
4706 return nullptr;
4707}
4708
4709llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4711 auto *Result = findInstantiationUnsafe(D);
4712 if (Result)
4713 return Result;
4714 // If we're performing a partial substitution during template argument
4715 // deduction, we may not have values for template parameters yet.
4716 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4717 isa<TemplateTemplateParmDecl>(D))
4718 return nullptr;
4719
4720 // Local types referenced prior to definition may require instantiation.
4721 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4722 if (RD->isLocalClass())
4723 return nullptr;
4724
4725 // Enumeration types referenced prior to definition may appear as a result of
4726 // error recovery.
4727 if (isa<EnumDecl>(D))
4728 return nullptr;
4729
4730 // Materialized typedefs/type alias for implicit deduction guides may require
4731 // instantiation.
4732 if (isa<TypedefNameDecl>(D) &&
4733 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4734 return nullptr;
4735
4736 // If we didn't find the decl, then we either have a sema bug, or we have a
4737 // forward reference to a label declaration. Return null to indicate that
4738 // we have an uninstantiated label.
4739 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4740 return nullptr;
4741}
4742
4745 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4746 if (Stored.isNull()) {
4747#ifndef NDEBUG
4748 // It should not be present in any surrounding scope either.
4749 LocalInstantiationScope *Current = this;
4750 while (Current->CombineWithOuterScope && Current->Outer) {
4751 Current = Current->Outer;
4752 assert(!Current->LocalDecls.contains(D) &&
4753 "Instantiated local in inner and outer scopes");
4754 }
4755#endif
4756 Stored = Inst;
4757 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4758 Pack->push_back(cast<VarDecl>(Inst));
4759 } else {
4760 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4761 }
4762}
4763
4765 VarDecl *Inst) {
4767 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4768 Pack->push_back(Inst);
4769}
4770
4772#ifndef NDEBUG
4773 // This should be the first time we've been told about this decl.
4774 for (LocalInstantiationScope *Current = this;
4775 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4776 assert(!Current->LocalDecls.contains(D) &&
4777 "Creating local pack after instantiation of local");
4778#endif
4779
4781 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4783 Stored = Pack;
4784 ArgumentPacks.push_back(Pack);
4785}
4786
4788 for (DeclArgumentPack *Pack : ArgumentPacks)
4789 if (llvm::is_contained(*Pack, D))
4790 return true;
4791 return false;
4792}
4793
4795 const TemplateArgument *ExplicitArgs,
4796 unsigned NumExplicitArgs) {
4797 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4798 "Already have a partially-substituted pack");
4799 assert((!PartiallySubstitutedPack
4800 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4801 "Wrong number of arguments in partially-substituted pack");
4802 PartiallySubstitutedPack = Pack;
4803 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4804 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4805}
4806
4808 const TemplateArgument **ExplicitArgs,
4809 unsigned *NumExplicitArgs) const {
4810 if (ExplicitArgs)
4811 *ExplicitArgs = nullptr;
4812 if (NumExplicitArgs)
4813 *NumExplicitArgs = 0;
4814
4815 for (const LocalInstantiationScope *Current = this; Current;
4816 Current = Current->Outer) {
4817 if (Current->PartiallySubstitutedPack) {
4818 if (ExplicitArgs)
4819 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4820 if (NumExplicitArgs)
4821 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4822
4823 return Current->PartiallySubstitutedPack;
4824 }
4825
4826 if (!Current->CombineWithOuterScope)
4827 break;
4828 }
4829
4830 return nullptr;
4831}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
const Decl * D
Expr * E
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
MatchFinder::MatchResult MatchResult
uint32_t Id
Definition: SemaARM.cpp:1134
SourceLocation Loc
Definition: SemaObjC.cpp:759
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, Sema::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 the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
#define bool
Definition: amdgpuintrin.h:20
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
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:2732
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex, SubstTemplateTypeParmTypeFlag Flag=SubstTemplateTypeParmTypeFlag::None) const
Retrieve a substitution-result type.
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:1703
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2289
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
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:3357
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
Attr - This represents one attribute.
Definition: Attr.h:43
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6127
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:1779
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1563
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:1970
base_class_range bases()
Definition: DeclCXX.h:620
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2024
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1999
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1991
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1977
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1688
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:2010
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Declaration of a class template.
ClassTemplateDecl * getMostRecentDecl()
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:195
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:421
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:1368
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1435
bool isFileContext() const
Definition: DeclBase.h:2160
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1334
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1854
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2016
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2349
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:258
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1215
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:239
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:151
bool isFileContextDecl() const
Definition: DeclBase.cpp:427
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1038
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:293
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1217
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setLocation(SourceLocation L)
Definition: DeclBase.h:443
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:938
DeclContext * getDeclContext()
Definition: DeclBase.h:451
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:355
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:907
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:967
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:859
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:792
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2039
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:873
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:654
Recursive AST visitor that supports extension via dynamic dispatch.
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6943
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3847
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4106
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:4935
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4961
EnumDecl * getDefinition() const
Definition: Decl.h:3950
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:277
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
ExprDependence getDependence() const
Definition: Expr.h:162
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4580
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3194
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3188
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3250
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:138
Represents a function declaration or definition.
Definition: Decl.h:1935
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
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:4123
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4172
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4654
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4688
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1796
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5102
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5366
Declaration of a template function.
Definition: DeclTemplate.h:959
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1522
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4347
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
QualType getReturnType() const
Definition: Type.h:4643
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:6793
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
void SetPartiallySubstitutedPack(NamedDecl *Pack, const TemplateArgument *ExplicitArgs, unsigned NumExplicitArgs)
Note that the given parameter pack has been partially substituted via explicit specification of templ...
NamedDecl * getPartiallySubstitutedPack(const TemplateArgument **ExplicitArgs=nullptr, unsigned *NumExplicitArgs=nullptr) const
Retrieve the partially-substitued template parameter pack.
bool isLocalPackExpansion(const Decl *D)
Determine whether D is a pack expansion created in this scope.
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationUnsafe(const Decl *D)
Similar to findInstantiationOf(), but it wouldn't assert if the instantiation was not found within th...
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:505
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:5765
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:620
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:651
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:642
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:660
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:665
Describes a module or submodule.
Definition: Module.h:115
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:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:1818
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1660
A C++ nested-name-specifier augmented with source location information.
SourceLocation getBeginLoc() const
Retrieve the location of the beginning of this nested-name-specifier.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
SourceLocation getEllipsisLoc() const
Definition: TypeLoc.h:2609
TypeLoc getPatternLoc() const
Definition: TypeLoc.h:2625
Represents a pack expansion of types.
Definition: Type.h:7141
std::optional< unsigned > getNumExpansions() const
Retrieve the number of expansions that this pack expansion will generate, if known.
Definition: Type.h:7166
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2987
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1821
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1866
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3012
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
bool hasInheritedDefaultArg() const
Definition: Decl.h:1870
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1817
Expr * getDefaultArg()
Definition: Decl.cpp:2975
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3017
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1775
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1874
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:929
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
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:996
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:8134
The collection of all-type qualifiers we support.
Definition: Type.h:324
void removeObjCLifetime()
Definition: Type.h:544
Represents a struct/union/class.
Definition: Decl.h:4148
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6072
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:859
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
Represents the body of a requires-expression.
Definition: DeclCXX.h:2047
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:502
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:570
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:571
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
Sema & SemaRef
Definition: SemaBase.h:40
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13212
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5891
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5923
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12614
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12086
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13162
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:13146
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12643
TemplateArgumentLoc getTrivialTemplateArgumentLoc(const TemplateArgument &Arg, QualType NTTPType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Allocate a TemplateArgumentLoc where all locations have been initialized to the given location.
DefaultedFunctionKind getDefaultedFunctionKind(const FunctionDecl *FD)
Determine the kind of defaulting that would be done for a given function.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
void ActOnFinishCXXNonNestedClass()
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
void InstantiateClassTemplateSpecializationMembers(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Instantiate the definitions of all of the members of the given class template specialization,...
ClassTemplatePartialSpecializationDecl * getMoreSpecializedPartialSpecialization(ClassTemplatePartialSpecializationDecl *PS1, ClassTemplatePartialSpecializationDecl *PS2, SourceLocation Loc)
Returns the more specialized class template partial specialization according to the rules of partial ...
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13149
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6828
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition: Sema.h:13506
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
concepts::Requirement::SubstitutionDiagnostic * createSubstDiagAt(SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using ASTConte...
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11638
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:909
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:13173
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
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:532
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:817
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:16951
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:525
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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:14387
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:13198
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:3638
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition: Sema.h:12655
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:13206
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
MultiLevelTemplateArgumentList getTemplateInstantiationArgs(const NamedDecl *D, const DeclContext *DC=nullptr, bool Final=false, std::optional< ArrayRef< TemplateArgument > > Innermost=std::nullopt, bool RelativeToPrimary=false, const FunctionDecl *Pattern=nullptr, bool ForConstraintInstantiation=false, bool SkipForSpecialization=false, bool ForDefaultArgumentSubstitution=false)
Retrieve the template argument list(s) that should be used to instantiate the definition of the given...
std::deque< PendingImplicitInstantiation > PendingLocalImplicitInstantiations
The queue of implicit template instantiations that are required and must be performed within the curr...
Definition: Sema.h:13555
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15219
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:20964
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:13182
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, ExprResult Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5487
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 SubstTemplateArgument(const TemplateArgumentLoc &Input, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentLoc &Output, SourceLocation Loc={}, const DeclarationName &Entity={})
void InstantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given function from its template.
bool SubstDefaultArgument(SourceLocation Loc, ParmVarDecl *Param, const MultiLevelTemplateArgumentList &TemplateArgs, bool ForCallExpr=false)
Substitute the given template arguments into the default argument.
ExprResult SubstConstraintExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTConsumer & Consumer
Definition: Sema.h:910
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
@ 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:13190
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:18992
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7767
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:7917
SourceManager & SourceMgr
Definition: Sema.h:912
DiagnosticsEngine & Diags
Definition: Sema.h:911
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:13157
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:564
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:21161
bool InstantiateEnum(SourceLocation PointOfInstantiation, EnumDecl *Instantiation, EnumDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiate the definition of an enum from a given pattern.
void UpdateExceptionSpec(FunctionDecl *FD, const FunctionProtoType::ExceptionSpecInfo &ESI)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
bool SubstBaseSpecifiers(CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Perform substitution on the base class specifiers of the given class template specialization.
void PerformDependentDiagnostics(const DeclContext *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
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.
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4258
Encodes a location in the source.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void warnOnStackNearlyExhausted(SourceLocation Loc)
Check to see if we're low on stack space and produce a warning if we're low on stack space (Currently...
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4076
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:357
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:333
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:345
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4575
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:149
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:6464
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6383
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3564
void setTagKind(TagKind TK)
Definition: Decl.h:3763
SourceRange getBraceRange() const
Definition: Decl.h:3643
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3648
StringRef getKindName() const
Definition: Decl.h:3755
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4760
TagKind getTagKind() const
Definition: Decl.h:3759
void setBraceRange(SourceRange R)
Definition: Decl.h:3644
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
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:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
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
bool isDependent() const
Whether this template argument is dependent on a template parameter such that its result can change f...
pack_iterator pack_begin() const
Iterator referencing the first argument of a template argument pack.
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:664
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:703
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition: Template.h:687
void setEvaluateConstraints(bool B)
Definition: Template.h:608
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:681
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:675
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:678
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:699
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:691
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:399
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:418
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isNull() const
Determine whether this template name is NULL.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
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:6661
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:6344
unsigned getIndex() const
Definition: Type.h:6343
unsigned getDepth() const
Definition: Type.h:6342
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Declaration of an alias template.
TypeAliasDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Models the abbreviated syntax to constrain a template type parameter: template <convertible_to<string...
Definition: ASTConcept.h:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition: ASTConcept.h:260
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:270
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:274
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
void setLocStart(SourceLocation L)
Definition: Decl.h:3399
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:1256
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:7902
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:7913
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:3213
The base class of the type hierarchy.
Definition: Type.h:1828
bool isVoidType() const
Definition: Type.h:8510
bool isReferenceType() const
Definition: Type.h:8204
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8731
bool isRecordType() const
Definition: Type.h:8286
QualType getUnderlyingType() const
Definition: Decl.h:3468
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
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:2883
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
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:4034
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
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
Defines the clang::TargetInfo interface.
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...
NamedDecl * getAsNamedDecl(TemplateParameter P)
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.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
TagTypeKind
The kind of a tag type.
Definition: Type.h:6871
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
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition: Specifiers.h:139
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< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl * >, SourceLocation > UnexpandedParameterPack
Definition: Sema.h:236
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:365
@ Success
Template argument deduction was successful.
TemplateSpecializationKind
Describes the kind of template specialization that a particular template specialization declaration r...
Definition: Specifiers.h:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition: Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition: Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:194
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6846
@ 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:124
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define false
Definition: stdbool.h:26
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:5159
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5161
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5194
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12660
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:12821
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:12774
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:12790
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:12816
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:12785
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12777
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12662
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12754
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:12672
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12681
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:12700
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12751
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:12708
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:12715
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12758
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:12726
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12764
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:12691
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:12770
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12767
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12688
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:12696
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12704
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:12665
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12718
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12722
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12677
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12748
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:12711
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12780
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:12845
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:12999
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:13003
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)