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