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