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