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 // CWG2770: Function parameters should be instantiated when they are
1333 // needed by a satisfaction check of an atomic constraint or
1334 // (recursively) by another function parameter.
1335 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1336
1337 public:
1338 typedef TreeTransform<TemplateInstantiator> inherited;
1339
1340 TemplateInstantiator(Sema &SemaRef,
1341 const MultiLevelTemplateArgumentList &TemplateArgs,
1342 SourceLocation Loc, DeclarationName Entity,
1343 bool BailOutOnIncomplete = false)
1344 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1345 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1346
1347 void setEvaluateConstraints(bool B) {
1348 EvaluateConstraints = B;
1349 }
1350 bool getEvaluateConstraints() {
1351 return EvaluateConstraints;
1352 }
1353
1354 inline static struct ForParameterMappingSubstitution_t {
1355 } ForParameterMappingSubstitution;
1356
1357 TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,
1358 SourceLocation Loc,
1359 const MultiLevelTemplateArgumentList &TemplateArgs)
1360 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1361 BailOutOnIncomplete(false) {}
1362
1363 /// Determine whether the given type \p T has already been
1364 /// transformed.
1365 ///
1366 /// For the purposes of template instantiation, a type has already been
1367 /// transformed if it is NULL or if it is not dependent.
1368 bool AlreadyTransformed(QualType T);
1369
1370 /// Returns the location of the entity being instantiated, if known.
1371 SourceLocation getBaseLocation() { return Loc; }
1372
1373 /// Returns the name of the entity being instantiated, if any.
1374 DeclarationName getBaseEntity() { return Entity; }
1375
1376 /// Returns whether any substitution so far was incomplete.
1377 bool getIsIncomplete() const { return IsIncomplete; }
1378
1379 /// Sets the "base" location and entity when that
1380 /// information is known based on another transformation.
1381 void setBase(SourceLocation Loc, DeclarationName Entity) {
1382 this->Loc = Loc;
1383 this->Entity = Entity;
1384 }
1385
1386 unsigned TransformTemplateDepth(unsigned Depth) {
1387 return TemplateArgs.getNewDepth(Depth);
1388 }
1389
1390 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1391 SourceRange PatternRange,
1392 ArrayRef<UnexpandedParameterPack> Unexpanded,
1393 bool FailOnPackProducingTemplates,
1394 bool &ShouldExpand, bool &RetainExpansion,
1395 UnsignedOrNone &NumExpansions) {
1396 if (SemaRef.CurrentInstantiationScope &&
1397 (SemaRef.inConstraintSubstitution() ||
1398 SemaRef.inParameterMappingSubstitution())) {
1399 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1400 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1401 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);
1402 PVD && maybeInstantiateFunctionParameterToScope(PVD))
1403 return true;
1404 }
1405 }
1406
1407 return getSema().CheckParameterPacksForExpansion(
1408 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1409 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1410 NumExpansions);
1411 }
1412
1413 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1415 }
1416
1417 TemplateArgument ForgetPartiallySubstitutedPack() {
1418 TemplateArgument Result;
1419 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1421 MultiLevelTemplateArgumentList &TemplateArgs =
1422 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1423 unsigned Depth, Index;
1424 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1425 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1426 Result = TemplateArgs(Depth, Index);
1427 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1428 } else {
1429 IsIncomplete = true;
1430 if (BailOutOnIncomplete)
1431 return TemplateArgument();
1432 }
1433 }
1434
1435 return Result;
1436 }
1437
1438 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1439 if (Arg.isNull())
1440 return;
1441
1442 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1444 MultiLevelTemplateArgumentList &TemplateArgs =
1445 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1446 unsigned Depth, Index;
1447 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1448 TemplateArgs.setArgument(Depth, Index, Arg);
1449 }
1450 }
1451
1452 MultiLevelTemplateArgumentList ForgetSubstitution() {
1453 MultiLevelTemplateArgumentList New;
1454 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1455
1456 MultiLevelTemplateArgumentList Old =
1457 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1458 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1459 std::move(New);
1460 return Old;
1461 }
1462
1463 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1464 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1465 std::move(Old);
1466 }
1467
1468 TemplateArgument
1469 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1470 if (TA.getKind() != TemplateArgument::Pack)
1471 return TA;
1472 if (SemaRef.ArgPackSubstIndex)
1473 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1474 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1475 "unexpected pack arguments in template rewrite");
1476 TemplateArgument Arg = *TA.pack_begin();
1477 if (Arg.isPackExpansion())
1478 Arg = Arg.getPackExpansionPattern();
1479 return Arg;
1480 }
1481
1482 /// Transform the given declaration by instantiating a reference to
1483 /// this declaration.
1484 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1485
1486 void transformAttrs(Decl *Old, Decl *New) {
1487 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1488 }
1489
1490 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1491 if (Old->isParameterPack() &&
1492 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1494 for (auto *New : NewDecls)
1496 Old, cast<VarDecl>(New));
1497 return;
1498 }
1499
1500 assert(NewDecls.size() == 1 &&
1501 "should only have multiple expansions for a pack");
1502 Decl *New = NewDecls.front();
1503
1504 // If we've instantiated the call operator of a lambda or the call
1505 // operator template of a generic lambda, update the "instantiation of"
1506 // information.
1507 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1508 if (NewMD && isLambdaCallOperator(NewMD)) {
1509 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1510 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1511 NewTD->setInstantiatedFromMemberTemplate(
1512 OldMD->getDescribedFunctionTemplate());
1513 else
1514 NewMD->setInstantiationOfMemberFunction(OldMD,
1516 }
1517
1519
1520 // We recreated a local declaration, but not by instantiating it. There
1521 // may be pending dependent diagnostics to produce.
1522 if (auto *DC = dyn_cast<DeclContext>(Old);
1523 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1524 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1525 }
1526
1527 /// Transform the definition of the given declaration by
1528 /// instantiating it.
1529 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1530
1531 /// Transform the first qualifier within a scope by instantiating the
1532 /// declaration.
1533 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1534
1535 bool TransformExceptionSpec(SourceLocation Loc,
1536 FunctionProtoType::ExceptionSpecInfo &ESI,
1537 SmallVectorImpl<QualType> &Exceptions,
1538 bool &Changed);
1539
1540 /// Rebuild the exception declaration and register the declaration
1541 /// as an instantiated local.
1542 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1543 TypeSourceInfo *Declarator,
1544 SourceLocation StartLoc,
1545 SourceLocation NameLoc,
1546 IdentifierInfo *Name);
1547
1548 /// Rebuild the Objective-C exception declaration and register the
1549 /// declaration as an instantiated local.
1550 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1551 TypeSourceInfo *TSInfo, QualType T);
1552
1554 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1555 SourceLocation TemplateKWLoc, TemplateName Name,
1556 SourceLocation NameLoc,
1557 QualType ObjectType = QualType(),
1558 NamedDecl *FirstQualifierInScope = nullptr,
1559 bool AllowInjectedClassName = false);
1560
1561 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1562 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1563 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1564 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1565 const Stmt *InstS,
1566 const NoInlineAttr *A);
1567 const AlwaysInlineAttr *
1568 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1569 const AlwaysInlineAttr *A);
1570 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1571 const OpenACCRoutineDeclAttr *
1572 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1573 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1574 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1575 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1576
1577 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1578 NonTypeTemplateParmDecl *D);
1579
1580 /// Rebuild a DeclRefExpr for a VarDecl reference.
1581 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1582
1583 /// Transform a reference to a function or init-capture parameter pack.
1584 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1585
1586 /// Transform a FunctionParmPackExpr which was built when we couldn't
1587 /// expand a function parameter pack reference which refers to an expanded
1588 /// pack.
1589 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1590
1591 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1592 FunctionProtoTypeLoc TL) {
1593 // Call the base version; it will forward to our overridden version below.
1594 return inherited::TransformFunctionProtoType(TLB, TL);
1595 }
1596
1597 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1598 auto Type = inherited::TransformTagType(TLB, TL);
1599 if (!Type.isNull())
1600 return Type;
1601 // Special case for transforming a deduction guide, we return a
1602 // transformed TemplateSpecializationType.
1603 // FIXME: Why is this hack necessary?
1604 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1605 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1607 Type = inherited::TransformType(
1608 ICNT->getDecl()->getCanonicalTemplateSpecializationType(
1609 SemaRef.Context));
1610 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1611 }
1612 return Type;
1613 }
1614 // Override the default version to handle a rewrite-template-arg-pack case
1615 // for building a deduction guide.
1616 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1617 TemplateArgumentLoc &Output,
1618 bool Uneval = false) {
1619 const TemplateArgument &Arg = Input.getArgument();
1620 std::vector<TemplateArgument> TArgs;
1621 switch (Arg.getKind()) {
1623 assert(SemaRef.CodeSynthesisContexts.empty() ||
1624 SemaRef.CodeSynthesisContexts.back().Kind ==
1626 // Literally rewrite the template argument pack, instead of unpacking
1627 // it.
1628 for (auto &pack : Arg.getPackAsArray()) {
1629 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1630 pack, QualType(), SourceLocation{});
1631 TemplateArgumentLoc Output;
1632 if (TransformTemplateArgument(Input, Output, Uneval))
1633 return true; // fails
1634 TArgs.push_back(Output.getArgument());
1635 }
1636 Output = SemaRef.getTrivialTemplateArgumentLoc(
1637 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1638 QualType(), SourceLocation{});
1639 return false;
1640 default:
1641 break;
1642 }
1643 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1644 }
1645
1647 QualType
1648 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1649 TemplateSpecializationTypeLoc TL) {
1650 auto *T = TL.getTypePtr();
1651 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1652 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1654 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1655 // need to substitute into.
1656
1657 // `TransformType` code below will handle picking the element from a pack
1658 // with the index `ArgPackSubstIndex`.
1659 // FIXME: add ability to represent sugarred type for N-th element of a
1660 // builtin pack and produce the sugar here.
1661 QualType R = TransformType(T->desugar());
1662 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1663 return R;
1664 }
1665
1666 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1667 ArrayRef<TemplateArgument> PackArgs) {
1668 // Don't do this when rewriting template parameters for CTAD:
1669 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1670 // expanded size, but this never applies since Subst* nodes are not
1671 // created in rewrite scenarios.
1672 //
1673 // 2) The heuristic substitutes into the pattern with pack expansion
1674 // suppressed, which does not meet the requirements for argument
1675 // rewriting when template arguments include a non-pack matching against
1676 // a pack, particularly when rewriting an alias CTAD.
1677 if (TemplateArgs.isRewrite())
1678 return std::nullopt;
1679
1680 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1681 }
1682
1683 template<typename Fn>
1684 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1685 FunctionProtoTypeLoc TL,
1686 CXXRecordDecl *ThisContext,
1687 Qualifiers ThisTypeQuals,
1688 Fn TransformExceptionSpec);
1689
1690 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1691 int indexAdjustment,
1692 UnsignedOrNone NumExpansions,
1693 bool ExpectParameterPack);
1694
1695 using inherited::TransformTemplateTypeParmType;
1696 /// Transforms a template type parameter type by performing
1697 /// substitution of the corresponding template type argument.
1698 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1699 TemplateTypeParmTypeLoc TL,
1700 bool SuppressObjCLifetime);
1701
1702 QualType BuildSubstTemplateTypeParmType(
1703 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1704 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1705 TemplateArgument Arg, SourceLocation NameLoc);
1706
1707 /// Transforms an already-substituted template type parameter pack
1708 /// into either itself (if we aren't substituting into its pack expansion)
1709 /// or the appropriate substituted argument.
1710 using inherited::TransformSubstTemplateTypeParmPackType;
1711 QualType
1712 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1713 SubstTemplateTypeParmPackTypeLoc TL,
1714 bool SuppressObjCLifetime);
1715 QualType
1716 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1717 SubstBuiltinTemplatePackTypeLoc TL);
1718
1720 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1721 if (auto TypeAlias =
1722 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1723 getSema());
1724 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1725 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1726 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1727 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1728 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1729 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1730 if (TA.isDependent())
1731 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1732 }
1733 return inherited::ComputeLambdaDependency(LSI);
1734 }
1735
1736 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1737 // Do not rebuild lambdas to avoid creating a new type.
1738 // Lambdas have already been processed inside their eval contexts.
1740 return E;
1741 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1742 /*InstantiatingLambdaOrBlock=*/true);
1743 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1744
1745 return inherited::TransformLambdaExpr(E);
1746 }
1747
1748 ExprResult TransformBlockExpr(BlockExpr *E) {
1749 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1750 /*InstantiatingLambdaOrBlock=*/true);
1751 return inherited::TransformBlockExpr(E);
1752 }
1753
1754 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1755 LambdaScopeInfo *LSI) {
1756 CXXMethodDecl *MD = LSI->CallOperator;
1757 for (ParmVarDecl *PVD : MD->parameters()) {
1758 assert(PVD && "null in a parameter list");
1759 if (!PVD->hasDefaultArg())
1760 continue;
1761 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1762 // FIXME: Obtain the source location for the '=' token.
1763 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1764 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1765 // If substitution fails, the default argument is set to a
1766 // RecoveryExpr that wraps the uninstantiated default argument so
1767 // that downstream diagnostics are omitted.
1768 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1769 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1770 UninstExpr->getType());
1771 if (ErrorResult.isUsable())
1772 PVD->setDefaultArg(ErrorResult.get());
1773 }
1774 }
1775 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1776 }
1777
1778 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1779 // Currently, we instantiate the body when instantiating the lambda
1780 // expression. However, `EvaluateConstraints` is disabled during the
1781 // instantiation of the lambda expression, causing the instantiation
1782 // failure of the return type requirement in the body. If p0588r1 is fully
1783 // implemented, the body will be lazily instantiated, and this problem
1784 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1785 // `true` to temporarily fix this issue.
1786 // FIXME: This temporary fix can be removed after fully implementing
1787 // p0588r1.
1788 llvm::SaveAndRestore _(EvaluateConstraints, true);
1789 return inherited::TransformLambdaBody(E, Body);
1790 }
1791
1792 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1793 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1794 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1795 if (TransReq.isInvalid())
1796 return TransReq;
1797 assert(TransReq.get() != E &&
1798 "Do not change value of isSatisfied for the existing expression. "
1799 "Create a new expression instead.");
1800 if (E->getBody()->isDependentContext()) {
1801 Sema::SFINAETrap Trap(SemaRef);
1802 // We recreate the RequiresExpr body, but not by instantiating it.
1803 // Produce pending diagnostics for dependent access check.
1804 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1805 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1806 if (Trap.hasErrorOccurred())
1807 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1808 }
1809 return TransReq;
1810 }
1811
1812 bool TransformRequiresExprRequirements(
1813 ArrayRef<concepts::Requirement *> Reqs,
1814 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1815 bool SatisfactionDetermined = false;
1816 for (concepts::Requirement *Req : Reqs) {
1817 concepts::Requirement *TransReq = nullptr;
1818 if (!SatisfactionDetermined) {
1819 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1820 TransReq = TransformTypeRequirement(TypeReq);
1821 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1822 TransReq = TransformExprRequirement(ExprReq);
1823 else
1824 TransReq = TransformNestedRequirement(
1826 if (!TransReq)
1827 return true;
1828 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1829 // [expr.prim.req]p6
1830 // [...] The substitution and semantic constraint checking
1831 // proceeds in lexical order and stops when a condition that
1832 // determines the result of the requires-expression is
1833 // encountered. [..]
1834 SatisfactionDetermined = true;
1835 } else
1836 TransReq = Req;
1837 Transformed.push_back(TransReq);
1838 }
1839 return false;
1840 }
1841
1842 TemplateParameterList *TransformTemplateParameterList(
1843 TemplateParameterList *OrigTPL) {
1844 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1845
1846 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1847 TemplateDeclInstantiator DeclInstantiator(getSema(),
1848 /* DeclContext *Owner */ Owner, TemplateArgs);
1849 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1850 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1851 }
1852
1853 concepts::TypeRequirement *
1854 TransformTypeRequirement(concepts::TypeRequirement *Req);
1855 concepts::ExprRequirement *
1856 TransformExprRequirement(concepts::ExprRequirement *Req);
1857 concepts::NestedRequirement *
1858 TransformNestedRequirement(concepts::NestedRequirement *Req);
1859 ExprResult TransformRequiresTypeParams(
1860 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1861 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1862 SmallVectorImpl<QualType> &PTypes,
1863 SmallVectorImpl<ParmVarDecl *> &TransParams,
1864 Sema::ExtParameterInfoBuilder &PInfos);
1865 };
1866}
1867
1868bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1869 if (T.isNull())
1870 return true;
1871
1874 return false;
1875
1876 getSema().MarkDeclarationsReferencedInType(Loc, T);
1877 return true;
1878}
1879
1880Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1881 if (!D)
1882 return nullptr;
1883
1884 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1885 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1886 // If the corresponding template argument is NULL or non-existent, it's
1887 // because we are performing instantiation from explicitly-specified
1888 // template arguments in a function template, but there were some
1889 // arguments left unspecified.
1890 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1891 TTP->getPosition())) {
1892 IsIncomplete = true;
1893 return BailOutOnIncomplete ? nullptr : D;
1894 }
1895
1896 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1897
1898 if (TTP->isParameterPack()) {
1899 assert(Arg.getKind() == TemplateArgument::Pack &&
1900 "Missing argument pack");
1901 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1902 }
1903
1905 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1906 "Wrong kind of template template argument");
1907 return Template.getAsTemplateDecl();
1908 }
1909
1910 // Fall through to find the instantiated declaration for this template
1911 // template parameter.
1912 }
1913
1914 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);
1915 PVD && SemaRef.CurrentInstantiationScope &&
1916 (SemaRef.inConstraintSubstitution() ||
1917 SemaRef.inParameterMappingSubstitution()) &&
1918 maybeInstantiateFunctionParameterToScope(PVD))
1919 return nullptr;
1920
1921 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1922}
1923
1924bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
1925 ParmVarDecl *OldParm) {
1926 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))
1927 return false;
1928
1929 if (!OldParm->isParameterPack())
1930 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1931 /*NumExpansions=*/std::nullopt,
1932 /*ExpectParameterPack=*/false);
1933
1934 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1935
1936 // Find the parameter packs that could be expanded.
1937 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
1938 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
1939 TypeLoc Pattern = ExpansionTL.getPatternLoc();
1940 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1941 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1942
1943 bool ShouldExpand = false;
1944 bool RetainExpansion = false;
1945 UnsignedOrNone OrigNumExpansions =
1946 ExpansionTL.getTypePtr()->getNumExpansions();
1947 UnsignedOrNone NumExpansions = OrigNumExpansions;
1948 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
1949 Pattern.getSourceRange(), Unexpanded,
1950 /*FailOnPackProducingTemplates=*/true,
1951 ShouldExpand, RetainExpansion, NumExpansions))
1952 return true;
1953
1954 assert(ShouldExpand && !RetainExpansion &&
1955 "Shouldn't preserve pack expansion when evaluating constraints");
1956 ExpandingFunctionParameterPack(OldParm);
1957 for (unsigned I = 0; I != *NumExpansions; ++I) {
1958 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
1959 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1960 /*NumExpansions=*/OrigNumExpansions,
1961 /*ExpectParameterPack=*/false))
1962 return true;
1963 }
1964 return false;
1965}
1966
1967Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1968 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1969 if (!Inst)
1970 return nullptr;
1971
1972 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1973 return Inst;
1974}
1975
1976bool TemplateInstantiator::TransformExceptionSpec(
1977 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
1978 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1979 if (ESI.Type == EST_Uninstantiated) {
1980 ESI.instantiate();
1981 Changed = true;
1982 }
1983 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1984}
1985
1986NamedDecl *
1987TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1988 SourceLocation Loc) {
1989 // If the first part of the nested-name-specifier was a template type
1990 // parameter, instantiate that type parameter down to a tag type.
1991 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1992 const TemplateTypeParmType *TTP
1993 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1994
1995 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1996 // FIXME: This needs testing w/ member access expressions.
1997 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1998
1999 if (TTP->isParameterPack()) {
2000 assert(Arg.getKind() == TemplateArgument::Pack &&
2001 "Missing argument pack");
2002
2003 if (!getSema().ArgPackSubstIndex)
2004 return nullptr;
2005
2006 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2007 }
2008
2009 QualType T = Arg.getAsType();
2010 if (T.isNull())
2011 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2012
2013 if (const TagType *Tag = T->getAs<TagType>())
2014 return Tag->getDecl();
2015
2016 // The resulting type is not a tag; complain.
2017 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2018 return nullptr;
2019 }
2020 }
2021
2022 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2023}
2024
2025VarDecl *
2026TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2027 TypeSourceInfo *Declarator,
2028 SourceLocation StartLoc,
2029 SourceLocation NameLoc,
2030 IdentifierInfo *Name) {
2031 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2032 StartLoc, NameLoc, Name);
2033 if (Var)
2034 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2035 return Var;
2036}
2037
2038VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2039 TypeSourceInfo *TSInfo,
2040 QualType T) {
2041 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2042 if (Var)
2043 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2044 return Var;
2045}
2046
2047TemplateName TemplateInstantiator::TransformTemplateName(
2048 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2049 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2050 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2051 if (Name.getKind() == TemplateName::Template) {
2052 assert(!QualifierLoc && "Unexpected qualifier");
2053 if (auto *TTP =
2054 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2055 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2056 // If the corresponding template argument is NULL or non-existent, it's
2057 // because we are performing instantiation from explicitly-specified
2058 // template arguments in a function template, but there were some
2059 // arguments left unspecified.
2060 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2061 TTP->getPosition())) {
2062 IsIncomplete = true;
2063 return BailOutOnIncomplete ? TemplateName() : Name;
2064 }
2065
2066 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2067
2068 if (TemplateArgs.isRewrite()) {
2069 // We're rewriting the template parameter as a reference to another
2070 // template parameter.
2071 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2072 assert(Arg.getKind() == TemplateArgument::Template &&
2073 "unexpected nontype template argument kind in template rewrite");
2074 return Arg.getAsTemplate();
2075 }
2076
2077 auto [AssociatedDecl, Final] =
2078 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2079 UnsignedOrNone PackIndex = std::nullopt;
2080 if (TTP->isParameterPack()) {
2081 assert(Arg.getKind() == TemplateArgument::Pack &&
2082 "Missing argument pack");
2083
2084 if (!getSema().ArgPackSubstIndex) {
2085 // We have the template argument pack to substitute, but we're not
2086 // actually expanding the enclosing pack expansion yet. So, just
2087 // keep the entire argument pack.
2088 return getSema().Context.getSubstTemplateTemplateParmPack(
2089 Arg, AssociatedDecl, TTP->getIndex(), Final);
2090 }
2091
2092 PackIndex = SemaRef.getPackIndex(Arg);
2093 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2094 }
2095
2097 assert(!Template.isNull() && "Null template template argument");
2098 return getSema().Context.getSubstTemplateTemplateParm(
2099 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2100 }
2101 }
2102
2103 if (SubstTemplateTemplateParmPackStorage *SubstPack
2105 if (!getSema().ArgPackSubstIndex)
2106 return Name;
2107
2108 TemplateArgument Pack = SubstPack->getArgumentPack();
2110 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2111 return getSema().Context.getSubstTemplateTemplateParm(
2112 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2113 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2114 }
2115
2116 return inherited::TransformTemplateName(
2117 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2118 FirstQualifierInScope, AllowInjectedClassName);
2119}
2120
2122TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2123 if (!E->isTypeDependent())
2124 return E;
2125
2126 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2127}
2128
2130TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2131 NonTypeTemplateParmDecl *NTTP) {
2132 // If the corresponding template argument is NULL or non-existent, it's
2133 // because we are performing instantiation from explicitly-specified
2134 // template arguments in a function template, but there were some
2135 // arguments left unspecified.
2136 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2137 NTTP->getPosition())) {
2138 IsIncomplete = true;
2139 return BailOutOnIncomplete ? ExprError() : E;
2140 }
2141
2142 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2143
2144 if (TemplateArgs.isRewrite()) {
2145 // We're rewriting the template parameter as a reference to another
2146 // template parameter.
2147 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2148 assert(Arg.getKind() == TemplateArgument::Expression &&
2149 "unexpected nontype template argument kind in template rewrite");
2150 // FIXME: This can lead to the same subexpression appearing multiple times
2151 // in a complete expression.
2152 return Arg.getAsExpr();
2153 }
2154
2155 auto [AssociatedDecl, Final] =
2156 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2157 UnsignedOrNone PackIndex = std::nullopt;
2158 if (NTTP->isParameterPack()) {
2159 assert(Arg.getKind() == TemplateArgument::Pack &&
2160 "Missing argument pack");
2161
2162 if (!getSema().ArgPackSubstIndex) {
2163 // We have an argument pack, but we can't select a particular argument
2164 // out of it yet. Therefore, we'll build an expression to hold on to that
2165 // argument pack.
2166 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2167 E->getLocation(),
2168 NTTP->getDeclName());
2169 if (TargetType.isNull())
2170 return ExprError();
2171
2172 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2173 if (TargetType->isRecordType())
2174 ExprType.addConst();
2175 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2176 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2177 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2178 }
2179 PackIndex = SemaRef.getPackIndex(Arg);
2180 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2181 }
2182 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2183 AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);
2184}
2185
2186const AnnotateAttr *
2187TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2188 SmallVector<Expr *> Args;
2189 for (Expr *Arg : AA->args()) {
2190 ExprResult Res = getDerived().TransformExpr(Arg);
2191 if (Res.isUsable())
2192 Args.push_back(Res.get());
2193 }
2194 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2195 Args.data(), Args.size(), AA->getRange());
2196}
2197
2198const CXXAssumeAttr *
2199TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2200 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2201 if (!Res.isUsable())
2202 return AA;
2203
2204 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2205 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2206 AA->getRange());
2207 if (!Res.isUsable())
2208 return AA;
2209 }
2210
2211 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2212 AA->getRange());
2213}
2214
2215const LoopHintAttr *
2216TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2217 ExprResult TransformedExprResult = getDerived().TransformExpr(LH->getValue());
2218 if (!TransformedExprResult.isUsable() ||
2219 TransformedExprResult.get() == LH->getValue())
2220 return LH;
2221 Expr *TransformedExpr = TransformedExprResult.get();
2222
2223 // Generate error if there is a problem with the value.
2224 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2225 /*AllowZero=*/LH->getSemanticSpelling() ==
2226 LoopHintAttr::Pragma_unroll))
2227 return LH;
2228
2229 LoopHintAttr::OptionType Option = LH->getOption();
2230 LoopHintAttr::LoopHintState State = LH->getState();
2231
2232 // Since C++ does not have partial instantiation, we would expect a
2233 // transformed loop hint expression to not be value dependent. However, at
2234 // the time of writing, the use of a generic lambda inside a template
2235 // triggers a double instantiation, so we must protect against this event.
2236 // This provision may become unneeded in the future.
2237 if (Option == LoopHintAttr::UnrollCount &&
2238 !TransformedExpr->isValueDependent()) {
2239 llvm::APSInt ValueAPS =
2240 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2241 // The values of 0 and 1 block any unrolling of the loop (also see
2242 // handleLoopHintAttr in SemaStmtAttr).
2243 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2244 Option = LoopHintAttr::Unroll;
2245 State = LoopHintAttr::Disable;
2246 }
2247 }
2248
2249 // Create new LoopHintValueAttr with integral expression in place of the
2250 // non-type template parameter.
2251 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2252 TransformedExpr, *LH);
2253}
2254const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2255 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2256 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2257 return nullptr;
2258
2259 return A;
2260}
2261const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2262 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2263 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2264 return nullptr;
2265
2266 return A;
2267}
2268
2269const CodeAlignAttr *
2270TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2271 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2272 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2273}
2274const OpenACCRoutineDeclAttr *
2275TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2276 const OpenACCRoutineDeclAttr *A) {
2277 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2278 "applies to a Function Decl (and a few places for VarDecl)");
2279}
2280
2281ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2282 SourceLocation Loc) {
2283 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2284 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2285}
2286
2288TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2289 if (getSema().ArgPackSubstIndex) {
2290 // We can expand this parameter pack now.
2291 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2292 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2293 if (!VD)
2294 return ExprError();
2295 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2296 }
2297
2298 QualType T = TransformType(E->getType());
2299 if (T.isNull())
2300 return ExprError();
2301
2302 // Transform each of the parameter expansions into the corresponding
2303 // parameters in the instantiation of the function decl.
2304 SmallVector<ValueDecl *, 8> Vars;
2305 Vars.reserve(E->getNumExpansions());
2306 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2307 I != End; ++I) {
2308 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2309 if (!D)
2310 return ExprError();
2311 Vars.push_back(D);
2312 }
2313
2314 auto *PackExpr =
2316 E->getParameterPackLocation(), Vars);
2317 getSema().MarkFunctionParmPackReferenced(PackExpr);
2318 return PackExpr;
2319}
2320
2322TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2323 ValueDecl *PD) {
2324 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2325 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2326 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2327 assert(Found && "no instantiation for parameter pack");
2328
2329 Decl *TransformedDecl;
2330 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2331 // If this is a reference to a function parameter pack which we can
2332 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2333 if (!getSema().ArgPackSubstIndex) {
2334 QualType T = TransformType(E->getType());
2335 if (T.isNull())
2336 return ExprError();
2337 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2338 E->getExprLoc(), *Pack);
2339 getSema().MarkFunctionParmPackReferenced(PackExpr);
2340 return PackExpr;
2341 }
2342
2343 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2344 } else {
2345 TransformedDecl = cast<Decl *>(*Found);
2346 }
2347
2348 // We have either an unexpanded pack or a specific expansion.
2349 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2350 E->getExprLoc());
2351}
2352
2354TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2355 NamedDecl *D = E->getDecl();
2356
2357 // Handle references to non-type template parameters and non-type template
2358 // parameter packs.
2359 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2360 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2361 return TransformTemplateParmRefExpr(E, NTTP);
2362
2363 // We have a non-type template parameter that isn't fully substituted;
2364 // FindInstantiatedDecl will find it in the local instantiation scope.
2365 }
2366
2367 // Handle references to function parameter packs.
2368 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2369 if (PD->isParameterPack())
2370 return TransformFunctionParmPackRefExpr(E, PD);
2371
2372 return inherited::TransformDeclRefExpr(E);
2373}
2374
2375ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2376 CXXDefaultArgExpr *E) {
2377 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2378 getDescribedFunctionTemplate() &&
2379 "Default arg expressions are never formed in dependent cases.");
2380 return SemaRef.BuildCXXDefaultArgExpr(
2382 E->getParam());
2383}
2384
2385template<typename Fn>
2386QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2387 FunctionProtoTypeLoc TL,
2388 CXXRecordDecl *ThisContext,
2389 Qualifiers ThisTypeQuals,
2390 Fn TransformExceptionSpec) {
2391 // If this is a lambda or block, the transformation MUST be done in the
2392 // CurrentInstantiationScope since it introduces a mapping of
2393 // the original to the newly created transformed parameters.
2394 //
2395 // In that case, TemplateInstantiator::TransformLambdaExpr will
2396 // have already pushed a scope for this prototype, so don't create
2397 // a second one.
2398 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2399 std::optional<LocalInstantiationScope> Scope;
2400 if (!Current || !Current->isLambdaOrBlock())
2401 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2402
2403 return inherited::TransformFunctionProtoType(
2404 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2405}
2406
2407ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2408 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2409 bool ExpectParameterPack) {
2410 auto NewParm = SemaRef.SubstParmVarDecl(
2411 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2412 ExpectParameterPack, EvaluateConstraints);
2413 if (NewParm && SemaRef.getLangOpts().OpenCL)
2414 SemaRef.deduceOpenCLAddressSpace(NewParm);
2415 return NewParm;
2416}
2417
2418QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2419 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2420 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2421 TemplateArgument Arg, SourceLocation NameLoc) {
2422 QualType Replacement = Arg.getAsType();
2423
2424 // If the template parameter had ObjC lifetime qualifiers,
2425 // then any such qualifiers on the replacement type are ignored.
2426 if (SuppressObjCLifetime) {
2427 Qualifiers RQs;
2428 RQs = Replacement.getQualifiers();
2429 RQs.removeObjCLifetime();
2430 Replacement =
2431 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2432 }
2433
2434 // TODO: only do this uniquing once, at the start of instantiation.
2435 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2436 Replacement, AssociatedDecl, Index, PackIndex, Final);
2437 SubstTemplateTypeParmTypeLoc NewTL =
2438 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2439 NewTL.setNameLoc(NameLoc);
2440 return Result;
2441}
2442
2443QualType
2444TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2445 TemplateTypeParmTypeLoc TL,
2446 bool SuppressObjCLifetime) {
2447 const TemplateTypeParmType *T = TL.getTypePtr();
2448 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2449 // Replace the template type parameter with its corresponding
2450 // template argument.
2451
2452 // If the corresponding template argument is NULL or doesn't exist, it's
2453 // because we are performing instantiation from explicitly-specified
2454 // template arguments in a function template class, but there were some
2455 // arguments left unspecified.
2456 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2457 IsIncomplete = true;
2458 if (BailOutOnIncomplete)
2459 return QualType();
2460
2461 TemplateTypeParmTypeLoc NewTL
2462 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2463 NewTL.setNameLoc(TL.getNameLoc());
2464 return TL.getType();
2465 }
2466
2467 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2468
2469 if (TemplateArgs.isRewrite()) {
2470 // We're rewriting the template parameter as a reference to another
2471 // template parameter.
2472 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2473 assert(Arg.getKind() == TemplateArgument::Type &&
2474 "unexpected nontype template argument kind in template rewrite");
2475 QualType NewT = Arg.getAsType();
2476 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2477 return NewT;
2478 }
2479
2480 auto [AssociatedDecl, Final] =
2481 TemplateArgs.getAssociatedDecl(T->getDepth());
2482 UnsignedOrNone PackIndex = std::nullopt;
2483 if (T->isParameterPack() ||
2484 // In concept parameter mapping for fold expressions, packs that aren't
2485 // expanded in place are treated as having non-pack dependency, so that
2486 // a PackExpansionType won't prevent expanding the packs outside the
2487 // TreeTransform. However, we still need to unpack the arguments during
2488 // any template argument substitution, so we check the associated
2489 // declaration instead.
2490 (T->getDecl() && T->getDecl()->isTemplateParameterPack())) {
2491 assert(Arg.getKind() == TemplateArgument::Pack &&
2492 "Missing argument pack");
2493
2494 if (!getSema().ArgPackSubstIndex) {
2495 // We have the template argument pack, but we're not expanding the
2496 // enclosing pack expansion yet. Just save the template argument
2497 // pack for later substitution.
2498 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2499 AssociatedDecl, T->getIndex(), Final, Arg);
2500 SubstTemplateTypeParmPackTypeLoc NewTL
2501 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2502 NewTL.setNameLoc(TL.getNameLoc());
2503 return Result;
2504 }
2505
2506 // PackIndex starts from last element.
2507 PackIndex = SemaRef.getPackIndex(Arg);
2508 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2509 }
2510
2511 assert(Arg.getKind() == TemplateArgument::Type &&
2512 "Template argument kind mismatch");
2513
2514 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2515 AssociatedDecl, T->getIndex(),
2516 PackIndex, Arg, TL.getNameLoc());
2517 }
2518
2519 // The template type parameter comes from an inner template (e.g.,
2520 // the template parameter list of a member template inside the
2521 // template we are instantiating). Create a new template type
2522 // parameter with the template "level" reduced by one.
2523 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2524 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2525 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2526 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2527 QualType Result = getSema().Context.getTemplateTypeParmType(
2528 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2529 T->isParameterPack(), NewTTPDecl);
2530 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2531 NewTL.setNameLoc(TL.getNameLoc());
2532 return Result;
2533}
2534
2535QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2536 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2537 bool SuppressObjCLifetime) {
2538 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2539
2540 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2541
2542 if (!getSema().ArgPackSubstIndex) {
2543 // We aren't expanding the parameter pack, so just return ourselves.
2544 QualType Result = TL.getType();
2545 if (NewReplaced != T->getAssociatedDecl())
2546 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2547 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2548 SubstTemplateTypeParmPackTypeLoc NewTL =
2549 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2550 NewTL.setNameLoc(TL.getNameLoc());
2551 return Result;
2552 }
2553
2554 TemplateArgument Pack = T->getArgumentPack();
2555 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2556 return BuildSubstTemplateTypeParmType(
2557 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2558 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2559}
2560
2561QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2562 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2563 if (!getSema().ArgPackSubstIndex)
2564 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2565 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2566 TL.getTypePtr()->getArgumentPack());
2567 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2568 TL.getBeginLoc());
2569 return Result.getAsType();
2570}
2571
2572static concepts::Requirement::SubstitutionDiagnostic *
2574 Sema::EntityPrinter Printer) {
2575 SmallString<128> Message;
2576 SourceLocation ErrorLoc;
2577 if (Info.hasSFINAEDiagnostic()) {
2580 Info.takeSFINAEDiagnostic(PDA);
2581 PDA.second.EmitToString(S.getDiagnostics(), Message);
2582 ErrorLoc = PDA.first;
2583 } else {
2584 ErrorLoc = Info.getLocation();
2585 }
2586 SmallString<128> Entity;
2587 llvm::raw_svector_ostream OS(Entity);
2588 Printer(OS);
2589 const ASTContext &C = S.Context;
2591 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2592}
2593
2594concepts::Requirement::SubstitutionDiagnostic *
2596 SmallString<128> Entity;
2597 llvm::raw_svector_ostream OS(Entity);
2598 Printer(OS);
2599 const ASTContext &C = Context;
2601 /*SubstitutedEntity=*/C.backupStr(Entity),
2602 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2603}
2604
2605ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2606 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2609 SmallVectorImpl<ParmVarDecl *> &TransParams,
2611
2612 TemplateDeductionInfo Info(KWLoc);
2613 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc, RE,
2614 SourceRange{KWLoc, RBraceLoc});
2615 Sema::SFINAETrap Trap(SemaRef, Info);
2616
2617 unsigned ErrorIdx;
2618 if (getDerived().TransformFunctionTypeParams(
2619 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2620 &TransParams, PInfos, &ErrorIdx) ||
2621 Trap.hasErrorOccurred()) {
2623 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2624 // Add a 'failed' Requirement to contain the error that caused the failure
2625 // here.
2626 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2627 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2628 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2629 TransParams, RE->getRParenLoc(),
2630 TransReqs, RBraceLoc);
2631 }
2632
2633 return ExprResult{};
2634}
2635
2636concepts::TypeRequirement *
2637TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2638 if (!Req->isDependent() && !AlwaysRebuild())
2639 return Req;
2640 if (Req->isSubstitutionFailure()) {
2641 if (AlwaysRebuild())
2642 return RebuildTypeRequirement(
2644 return Req;
2645 }
2646
2647 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2648 Sema::SFINAETrap Trap(SemaRef, Info);
2649 Sema::InstantiatingTemplate TypeInst(
2650 SemaRef, Req->getType()->getTypeLoc().getBeginLoc(), Req,
2651 Req->getType()->getTypeLoc().getSourceRange());
2652 if (TypeInst.isInvalid())
2653 return nullptr;
2654 TypeSourceInfo *TransType = TransformType(Req->getType());
2655 if (!TransType || Trap.hasErrorOccurred())
2656 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2657 [&] (llvm::raw_ostream& OS) {
2658 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2659 }));
2660 return RebuildTypeRequirement(TransType);
2661}
2662
2663concepts::ExprRequirement *
2664TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2665 if (!Req->isDependent() && !AlwaysRebuild())
2666 return Req;
2667
2668 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2669 TransExpr;
2670 if (Req->isExprSubstitutionFailure())
2671 TransExpr = Req->getExprSubstitutionDiagnostic();
2672 else {
2673 Expr *E = Req->getExpr();
2674 TemplateDeductionInfo Info(E->getBeginLoc());
2675 Sema::SFINAETrap Trap(SemaRef, Info);
2676 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req,
2677 E->getSourceRange());
2678 if (ExprInst.isInvalid())
2679 return nullptr;
2680 ExprResult TransExprRes = TransformExpr(E);
2681 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2682 TransExprRes.get()->hasPlaceholderType())
2683 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2684 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2685 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2686 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2687 });
2688 else
2689 TransExpr = TransExprRes.get();
2690 }
2691
2692 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2693 const auto &RetReq = Req->getReturnTypeRequirement();
2694 if (RetReq.isEmpty())
2695 TransRetReq.emplace();
2696 else if (RetReq.isSubstitutionFailure())
2697 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2698 else if (RetReq.isTypeConstraint()) {
2699 TemplateParameterList *OrigTPL =
2700 RetReq.getTypeConstraintTemplateParameterList();
2701 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2702 Sema::SFINAETrap Trap(SemaRef, Info);
2703 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(), Req,
2704 OrigTPL->getSourceRange());
2705 if (TPLInst.isInvalid())
2706 return nullptr;
2707 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2708 if (!TPL || Trap.hasErrorOccurred())
2709 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2710 [&] (llvm::raw_ostream& OS) {
2711 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2712 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2713 }));
2714 else {
2715 TPLInst.Clear();
2716 TransRetReq.emplace(TPL);
2717 }
2718 }
2719 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2720 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2721 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2722 std::move(*TransRetReq));
2723 return RebuildExprRequirement(
2725 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2726}
2727
2728concepts::NestedRequirement *
2729TemplateInstantiator::TransformNestedRequirement(
2730 concepts::NestedRequirement *Req) {
2731
2732 ASTContext &C = SemaRef.Context;
2733
2734 Expr *Constraint = Req->getConstraintExpr();
2735 ConstraintSatisfaction Satisfaction;
2736
2737 auto NestedReqWithDiag = [&C, this](Expr *E,
2738 ConstraintSatisfaction Satisfaction) {
2739 Satisfaction.IsSatisfied = false;
2740 SmallString<128> Entity;
2741 llvm::raw_svector_ostream OS(Entity);
2742 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2743 return new (C) concepts::NestedRequirement(
2744 SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));
2745 };
2746
2747 if (Req->hasInvalidConstraint()) {
2748 if (AlwaysRebuild())
2749 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2751 return Req;
2752 }
2753
2754 if (!getEvaluateConstraints()) {
2755 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2756 if (TransConstraint.isInvalid() || !TransConstraint.get())
2757 return nullptr;
2758 if (TransConstraint.get()->isInstantiationDependent())
2759 return new (SemaRef.Context)
2760 concepts::NestedRequirement(TransConstraint.get());
2761 ConstraintSatisfaction Satisfaction;
2762 return new (SemaRef.Context) concepts::NestedRequirement(
2763 SemaRef.Context, TransConstraint.get(), Satisfaction);
2764 }
2765
2766 bool Success;
2767 Expr *NewConstraint;
2768 {
2769 EnterExpressionEvaluationContext ContextRAII(
2771 Sema::InstantiatingTemplate ConstrInst(
2772 SemaRef, Constraint->getBeginLoc(), Req,
2773 Sema::InstantiatingTemplate::ConstraintsCheck(),
2774 Constraint->getSourceRange());
2775
2776 if (ConstrInst.isInvalid())
2777 return nullptr;
2778
2779 Success = !SemaRef.CheckConstraintSatisfaction(
2780 Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),
2781 TemplateArgs, Constraint->getSourceRange(), Satisfaction,
2782 /*TopLevelConceptId=*/nullptr, &NewConstraint);
2783 }
2784
2785 if (!Success || Satisfaction.HasSubstitutionFailure())
2786 return NestedReqWithDiag(Constraint, Satisfaction);
2787
2788 // FIXME: const correctness
2789 // MLTAL might be dependent.
2790 if (!NewConstraint) {
2791 if (!Satisfaction.IsSatisfied)
2792 return NestedReqWithDiag(Constraint, Satisfaction);
2793
2794 NewConstraint = Constraint;
2795 }
2796 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2797}
2798
2801 SourceLocation Loc,
2802 DeclarationName Entity,
2803 bool AllowDeducedTST) {
2804 assert(!CodeSynthesisContexts.empty() &&
2805 "Cannot perform an instantiation without some context on the "
2806 "instantiation stack");
2807
2808 if (!T->getType()->isInstantiationDependentType() &&
2809 !T->getType()->isVariablyModifiedType())
2810 return T;
2811
2812 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2813 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2814 : Instantiator.TransformType(T);
2815}
2816
2819 SourceLocation Loc,
2820 DeclarationName Entity) {
2821 assert(!CodeSynthesisContexts.empty() &&
2822 "Cannot perform an instantiation without some context on the "
2823 "instantiation stack");
2824
2825 if (TL.getType().isNull())
2826 return nullptr;
2827
2830 // FIXME: Make a copy of the TypeLoc data here, so that we can
2831 // return a new TypeSourceInfo. Inefficient!
2832 TypeLocBuilder TLB;
2833 TLB.pushFullCopy(TL);
2834 return TLB.getTypeSourceInfo(Context, TL.getType());
2835 }
2836
2837 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2838 TypeLocBuilder TLB;
2839 TLB.reserve(TL.getFullDataSize());
2840 QualType Result = Instantiator.TransformType(TLB, TL);
2841 if (Result.isNull())
2842 return nullptr;
2843
2844 return TLB.getTypeSourceInfo(Context, Result);
2845}
2846
2847/// Deprecated form of the above.
2849 const MultiLevelTemplateArgumentList &TemplateArgs,
2850 SourceLocation Loc, DeclarationName Entity,
2851 bool *IsIncompleteSubstitution) {
2852 assert(!CodeSynthesisContexts.empty() &&
2853 "Cannot perform an instantiation without some context on the "
2854 "instantiation stack");
2855
2856 // If T is not a dependent type or a variably-modified type, there
2857 // is nothing to do.
2858 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2859 return T;
2860
2861 TemplateInstantiator Instantiator(
2862 *this, TemplateArgs, Loc, Entity,
2863 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2864 QualType QT = Instantiator.TransformType(T);
2865 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2866 *IsIncompleteSubstitution = true;
2867 return QT;
2868}
2869
2871 if (T->getType()->isInstantiationDependentType() ||
2872 T->getType()->isVariablyModifiedType())
2873 return true;
2874
2875 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2876 if (!TL.getAs<FunctionProtoTypeLoc>())
2877 return false;
2878
2880 for (ParmVarDecl *P : FP.getParams()) {
2881 // This must be synthesized from a typedef.
2882 if (!P) continue;
2883
2884 // If there are any parameters, a new TypeSourceInfo that refers to the
2885 // instantiated parameters must be built.
2886 return true;
2887 }
2888
2889 return false;
2890}
2891
2894 SourceLocation Loc,
2895 DeclarationName Entity,
2896 CXXRecordDecl *ThisContext,
2897 Qualifiers ThisTypeQuals,
2898 bool EvaluateConstraints) {
2899 assert(!CodeSynthesisContexts.empty() &&
2900 "Cannot perform an instantiation without some context on the "
2901 "instantiation stack");
2902
2904 return T;
2905
2906 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2907 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2908
2909 TypeLocBuilder TLB;
2910
2911 TypeLoc TL = T->getTypeLoc();
2912 TLB.reserve(TL.getFullDataSize());
2913
2915
2916 if (FunctionProtoTypeLoc Proto =
2918 // Instantiate the type, other than its exception specification. The
2919 // exception specification is instantiated in InitFunctionInstantiation
2920 // once we've built the FunctionDecl.
2921 // FIXME: Set the exception specification to EST_Uninstantiated here,
2922 // instead of rebuilding the function type again later.
2923 Result = Instantiator.TransformFunctionProtoType(
2924 TLB, Proto, ThisContext, ThisTypeQuals,
2926 bool &Changed) { return false; });
2927 } else {
2928 Result = Instantiator.TransformType(TLB, TL);
2929 }
2930 // When there are errors resolving types, clang may use IntTy as a fallback,
2931 // breaking our assumption that function declarations have function types.
2932 if (Result.isNull() || !Result->isFunctionType())
2933 return nullptr;
2934
2935 return TLB.getTypeSourceInfo(Context, Result);
2936}
2937
2940 SmallVectorImpl<QualType> &ExceptionStorage,
2941 const MultiLevelTemplateArgumentList &Args) {
2942 bool Changed = false;
2943 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2944 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2945 Changed);
2946}
2947
2949 const MultiLevelTemplateArgumentList &Args) {
2952
2953 SmallVector<QualType, 4> ExceptionStorage;
2954 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2955 ESI, ExceptionStorage, Args))
2956 // On error, recover by dropping the exception specification.
2957 ESI.Type = EST_None;
2958
2960}
2961
2962namespace {
2963
2964 struct GetContainedInventedTypeParmVisitor :
2965 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2966 TemplateTypeParmDecl *> {
2967 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2968 TemplateTypeParmDecl *>::Visit;
2969
2970 TemplateTypeParmDecl *Visit(QualType T) {
2971 if (T.isNull())
2972 return nullptr;
2973 return Visit(T.getTypePtr());
2974 }
2975 // The deduced type itself.
2976 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2977 const TemplateTypeParmType *T) {
2978 if (!T->getDecl() || !T->getDecl()->isImplicit())
2979 return nullptr;
2980 return T->getDecl();
2981 }
2982
2983 // Only these types can contain 'auto' types, and subsequently be replaced
2984 // by references to invented parameters.
2985
2986 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2987 return Visit(T->getPointeeType());
2988 }
2989
2990 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2991 return Visit(T->getPointeeType());
2992 }
2993
2994 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2995 return Visit(T->getPointeeTypeAsWritten());
2996 }
2997
2998 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2999 return Visit(T->getPointeeType());
3000 }
3001
3002 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3003 return Visit(T->getElementType());
3004 }
3005
3006 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3007 const DependentSizedExtVectorType *T) {
3008 return Visit(T->getElementType());
3009 }
3010
3011 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3012 return Visit(T->getElementType());
3013 }
3014
3015 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3016 return VisitFunctionType(T);
3017 }
3018
3019 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3020 return Visit(T->getReturnType());
3021 }
3022
3023 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3024 return Visit(T->getInnerType());
3025 }
3026
3027 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3028 return Visit(T->getModifiedType());
3029 }
3030
3031 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3032 return Visit(T->getUnderlyingType());
3033 }
3034
3035 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3036 return Visit(T->getOriginalType());
3037 }
3038
3039 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3040 return Visit(T->getPattern());
3041 }
3042 };
3043
3044} // namespace
3045
3047 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3048 const MultiLevelTemplateArgumentList &TemplateArgs,
3049 bool EvaluateConstraints) {
3050 const ASTTemplateArgumentListInfo *TemplArgInfo =
3052
3053 if (!EvaluateConstraints && !inParameterMappingSubstitution()) {
3055 if (!Index)
3056 Index = SemaRef.ArgPackSubstIndex;
3059 return false;
3060 }
3061
3062 TemplateArgumentListInfo InstArgs;
3063
3064 if (TemplArgInfo) {
3065 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3066 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3067 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3068 InstArgs))
3069 return true;
3070 }
3071 return AttachTypeConstraint(
3073 TC->getNamedConcept(),
3074 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3075 Inst->isParameterPack()
3077 ->getEllipsisLoc()
3078 : SourceLocation());
3079}
3080
3083 const MultiLevelTemplateArgumentList &TemplateArgs,
3084 int indexAdjustment, UnsignedOrNone NumExpansions,
3085 bool ExpectParameterPack, bool EvaluateConstraint) {
3086 TypeSourceInfo *OldTSI = OldParm->getTypeSourceInfo();
3087 TypeSourceInfo *NewTSI = nullptr;
3088
3089 TypeLoc OldTL = OldTSI->getTypeLoc();
3090 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3091
3092 // We have a function parameter pack. Substitute into the pattern of the
3093 // expansion.
3094 NewTSI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3095 OldParm->getLocation(), OldParm->getDeclName());
3096 if (!NewTSI)
3097 return nullptr;
3098
3099 if (NewTSI->getType()->containsUnexpandedParameterPack()) {
3100 // We still have unexpanded parameter packs, which means that
3101 // our function parameter is still a function parameter pack.
3102 // Therefore, make its type a pack expansion type.
3103 NewTSI = CheckPackExpansion(NewTSI, ExpansionTL.getEllipsisLoc(),
3104 NumExpansions);
3105 } else if (ExpectParameterPack) {
3106 // We expected to get a parameter pack but didn't (because the type
3107 // itself is not a pack expansion type), so complain. This can occur when
3108 // the substitution goes through an alias template that "loses" the
3109 // pack expansion.
3110 Diag(OldParm->getLocation(),
3111 diag::err_function_parameter_pack_without_parameter_packs)
3112 << NewTSI->getType();
3113 return nullptr;
3114 }
3115 } else {
3116 NewTSI = SubstType(OldTSI, TemplateArgs, OldParm->getLocation(),
3117 OldParm->getDeclName());
3118 }
3119
3120 if (!NewTSI)
3121 return nullptr;
3122
3123 if (NewTSI->getType()->isVoidType()) {
3124 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3125 return nullptr;
3126 }
3127
3128 // In abbreviated templates, TemplateTypeParmDecls with possible
3129 // TypeConstraints are created when the parameter list is originally parsed.
3130 // The TypeConstraints can therefore reference other functions parameters in
3131 // the abbreviated function template, which is why we must instantiate them
3132 // here, when the instantiated versions of those referenced parameters are in
3133 // scope.
3134 if (TemplateTypeParmDecl *TTP =
3135 GetContainedInventedTypeParmVisitor().Visit(OldTSI->getType())) {
3136 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3137 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3138 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3139 // We will first get here when instantiating the abbreviated function
3140 // template's described function, but we might also get here later.
3141 // Make sure we do not instantiate the TypeConstraint more than once.
3142 if (Inst && !Inst->getTypeConstraint()) {
3143 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3144 return nullptr;
3145 }
3146 }
3147 }
3148
3149 ParmVarDecl *NewParm = CheckParameter(
3150 Context.getTranslationUnitDecl(), OldParm->getInnerLocStart(),
3151 OldParm->getLocation(), OldParm->getIdentifier(), NewTSI->getType(),
3152 NewTSI, OldParm->getStorageClass());
3153 if (!NewParm)
3154 return nullptr;
3155
3156 // Mark the (new) default argument as uninstantiated (if any).
3157 if (OldParm->hasUninstantiatedDefaultArg()) {
3158 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3159 NewParm->setUninstantiatedDefaultArg(Arg);
3160 } else if (OldParm->hasUnparsedDefaultArg()) {
3161 NewParm->setUnparsedDefaultArg();
3162 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3163 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3164 // Default arguments cannot be substituted until the declaration context
3165 // for the associated function or lambda capture class is available.
3166 // This is necessary for cases like the following where construction of
3167 // the lambda capture class for the outer lambda is dependent on the
3168 // parameter types but where the default argument is dependent on the
3169 // outer lambda's declaration context.
3170 // template <typename T>
3171 // auto f() {
3172 // return [](T = []{ return T{}; }()) { return 0; };
3173 // }
3174 NewParm->setUninstantiatedDefaultArg(Arg);
3175 }
3176
3180
3181 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3182 // Add the new parameter to the instantiated parameter pack.
3183 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3184 } else {
3185 // Introduce an Old -> New mapping
3186 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3187 }
3188
3189 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3190 // can be anything, is this right ?
3191 NewParm->setDeclContext(CurContext);
3192
3193 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3194 OldParm->getFunctionScopeIndex() + indexAdjustment);
3195
3196 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3197
3198 return NewParm;
3199}
3200
3203 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3204 const MultiLevelTemplateArgumentList &TemplateArgs,
3205 SmallVectorImpl<QualType> &ParamTypes,
3207 ExtParameterInfoBuilder &ParamInfos) {
3208 assert(!CodeSynthesisContexts.empty() &&
3209 "Cannot perform an instantiation without some context on the "
3210 "instantiation stack");
3211
3212 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3213 DeclarationName());
3214 return Instantiator.TransformFunctionTypeParams(
3215 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3216}
3217
3219 SourceLocation Loc,
3220 ParmVarDecl *Param,
3221 const MultiLevelTemplateArgumentList &TemplateArgs,
3222 bool ForCallExpr) {
3223 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3224 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3225
3226 RecursiveInstGuard AlreadyInstantiating(
3228 if (AlreadyInstantiating) {
3229 Param->setInvalidDecl();
3230 return Diag(Param->getBeginLoc(), diag::err_recursive_default_argument)
3231 << FD << PatternExpr->getSourceRange();
3232 }
3233
3236 NonSFINAEContext _(*this);
3237 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3238 if (Inst.isInvalid())
3239 return true;
3240
3242 // C++ [dcl.fct.default]p5:
3243 // The names in the [default argument] expression are bound, and
3244 // the semantic constraints are checked, at the point where the
3245 // default argument expression appears.
3246 ContextRAII SavedContext(*this, FD);
3247 {
3248 std::optional<LocalInstantiationScope> LIS;
3249
3250 if (ForCallExpr) {
3251 // When instantiating a default argument due to use in a call expression,
3252 // an instantiation scope that includes the parameters of the callee is
3253 // required to satisfy references from the default argument. For example:
3254 // template<typename T> void f(T a, int = decltype(a)());
3255 // void g() { f(0); }
3256 LIS.emplace(*this);
3258 /*ForDefinition*/ false);
3259 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3260 return true;
3261 }
3262
3264 Result = SubstInitializer(PatternExpr, TemplateArgs,
3265 /*DirectInit*/ false);
3266 });
3267 }
3268 if (Result.isInvalid())
3269 return true;
3270
3271 if (ForCallExpr) {
3272 // Check the expression as an initializer for the parameter.
3273 InitializedEntity Entity
3276 Param->getLocation(),
3277 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3278 Expr *ResultE = Result.getAs<Expr>();
3279
3280 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3281 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3282 if (Result.isInvalid())
3283 return true;
3284
3285 Result =
3286 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3287 /*DiscardedValue*/ false);
3288 } else {
3289 // FIXME: Obtain the source location for the '=' token.
3290 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3291 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3292 }
3293 if (Result.isInvalid())
3294 return true;
3295
3296 // Remember the instantiated default argument.
3297 Param->setDefaultArg(Result.getAs<Expr>());
3298
3299 return false;
3300}
3301
3302// See TreeTransform::PreparePackForExpansion for the relevant comment.
3303// This function implements the same concept for base specifiers.
3304static bool
3306 const MultiLevelTemplateArgumentList &TemplateArgs,
3307 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3308 SourceRange BaseSourceRange = Base.getSourceRange();
3309 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3310 Info.Ellipsis = Base.getEllipsisLoc();
3311 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3312 TypeSourceInfo *BaseTypeInfo,
3313 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3314 // This is a pack expansion. See whether we should expand it now, or
3315 // wait until later.
3317 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3318 if (IsLateExpansionAttempt) {
3319 // Request expansion only when there is an opportunity to expand a pack
3320 // that required a substituion first.
3321 bool SawPackTypes =
3322 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3323 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3324 });
3325 if (!SawPackTypes) {
3326 Info.Expand = false;
3327 return false;
3328 }
3329 }
3330
3331 // Determine whether the set of unexpanded parameter packs can and should be
3332 // expanded.
3333 Info.Expand = false;
3334 Info.RetainExpansion = false;
3335 Info.NumExpansions = std::nullopt;
3337 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3338 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3339 Info.RetainExpansion, Info.NumExpansions);
3340 };
3341
3342 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3343 return true;
3344
3345 if (Info.Expand) {
3346 Out = Base.getTypeSourceInfo();
3347 return false;
3348 }
3349
3350 // The resulting base specifier will (still) be a pack expansion.
3351 {
3352 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3353 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3354 BaseSourceRange.getBegin(), DeclarationName());
3355 }
3356 if (!Out->getType()->containsUnexpandedParameterPack())
3357 return false;
3358
3359 // Some packs will learn their length after substitution.
3360 // We may need to request their expansion.
3361 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3362 return true;
3363 if (Info.Expand)
3364 Info.ExpandUnderForgetSubstitions = true;
3365 return false;
3366}
3367
3368bool
3370 CXXRecordDecl *Pattern,
3371 const MultiLevelTemplateArgumentList &TemplateArgs) {
3372 bool Invalid = false;
3373 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3374 for (const auto &Base : Pattern->bases()) {
3375 if (!Base.getType()->isDependentType()) {
3376 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3377 if (RD->isInvalidDecl())
3378 Instantiation->setInvalidDecl();
3379 }
3380 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3381 continue;
3382 }
3383
3384 SourceLocation EllipsisLoc;
3385 TypeSourceInfo *BaseTypeLoc = nullptr;
3386 if (Base.isPackExpansion()) {
3387 UnexpandedInfo Info;
3388 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3389 Info)) {
3390 Invalid = true;
3391 continue;
3392 }
3393
3394 // If we should expand this pack expansion now, do so.
3396 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3398 ArgsForSubst = &EmptyList;
3399
3400 if (Info.Expand) {
3401 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3402 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3403
3404 TypeSourceInfo *Expanded =
3405 SubstType(BaseTypeLoc, *ArgsForSubst,
3406 Base.getSourceRange().getBegin(), DeclarationName());
3407 if (!Expanded) {
3408 Invalid = true;
3409 continue;
3410 }
3411
3412 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3413 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3414 Base.getAccessSpecifierAsWritten(), Expanded,
3415 SourceLocation()))
3416 InstantiatedBases.push_back(InstantiatedBase);
3417 else
3418 Invalid = true;
3419 }
3420
3421 continue;
3422 }
3423
3424 // The resulting base specifier will (still) be a pack expansion.
3425 EllipsisLoc = Base.getEllipsisLoc();
3426 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3427 BaseTypeLoc =
3428 SubstType(BaseTypeLoc, *ArgsForSubst,
3429 Base.getSourceRange().getBegin(), DeclarationName());
3430 } else {
3431 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3432 TemplateArgs,
3433 Base.getSourceRange().getBegin(),
3434 DeclarationName());
3435 }
3436
3437 if (!BaseTypeLoc) {
3438 Invalid = true;
3439 continue;
3440 }
3441
3442 if (CXXBaseSpecifier *InstantiatedBase
3443 = CheckBaseSpecifier(Instantiation,
3444 Base.getSourceRange(),
3445 Base.isVirtual(),
3446 Base.getAccessSpecifierAsWritten(),
3447 BaseTypeLoc,
3448 EllipsisLoc))
3449 InstantiatedBases.push_back(InstantiatedBase);
3450 else
3451 Invalid = true;
3452 }
3453
3454 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3455 Invalid = true;
3456
3457 return Invalid;
3458}
3459
3460// Defined via #include from SemaTemplateInstantiateDecl.cpp
3461namespace clang {
3462 namespace sema {
3464 const MultiLevelTemplateArgumentList &TemplateArgs);
3466 const Attr *At, ASTContext &C, Sema &S,
3467 const MultiLevelTemplateArgumentList &TemplateArgs);
3468 }
3469}
3470
3471bool Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3472 CXXRecordDecl *Instantiation,
3473 CXXRecordDecl *Pattern,
3474 const MultiLevelTemplateArgumentList &TemplateArgs,
3475 TemplateSpecializationKind TSK, bool Complain) {
3476#ifndef NDEBUG
3477 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3479 assert(!AlreadyInstantiating && "should have been caught by caller");
3480#endif
3481
3482 return InstantiateClassImpl(PointOfInstantiation, Instantiation, Pattern,
3483 TemplateArgs, TSK, Complain);
3484}
3485
3486bool Sema::InstantiateClassImpl(
3487 SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation,
3488 CXXRecordDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs,
3489 TemplateSpecializationKind TSK, bool Complain) {
3490
3491 CXXRecordDecl *PatternDef
3492 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3493 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3494 Instantiation->getInstantiatedFromMemberClass(),
3495 Pattern, PatternDef, TSK, Complain))
3496 return true;
3497
3498 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3499 llvm::TimeTraceMetadata M;
3500 llvm::raw_string_ostream OS(M.Detail);
3501 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3502 /*Qualified=*/true);
3503 if (llvm::isTimeTraceVerbose()) {
3504 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3505 M.File = SourceMgr.getFilename(Loc);
3506 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3507 }
3508 return M;
3509 });
3510
3511 Pattern = PatternDef;
3512
3513 // Record the point of instantiation.
3514 if (MemberSpecializationInfo *MSInfo
3515 = Instantiation->getMemberSpecializationInfo()) {
3516 MSInfo->setTemplateSpecializationKind(TSK);
3517 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3518 } else if (ClassTemplateSpecializationDecl *Spec
3519 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3520 Spec->setTemplateSpecializationKind(TSK);
3521 Spec->setPointOfInstantiation(PointOfInstantiation);
3522 }
3523
3524 NonSFINAEContext _(*this);
3525 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3526 if (Inst.isInvalid())
3527 return true;
3528 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3529 "instantiating class definition");
3530
3531 // Enter the scope of this instantiation. We don't use
3532 // PushDeclContext because we don't have a scope.
3533 ContextRAII SavedContext(*this, Instantiation);
3534 EnterExpressionEvaluationContext EvalContext(
3535 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3536
3537 // If this is an instantiation of a local class, merge this local
3538 // instantiation scope with the enclosing scope. Otherwise, every
3539 // instantiation of a class has its own local instantiation scope.
3540 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3541 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3542
3543 // Some class state isn't processed immediately but delayed till class
3544 // instantiation completes. We may not be ready to handle any delayed state
3545 // already on the stack as it might correspond to a different class, so save
3546 // it now and put it back later.
3547 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3548
3549 // Pull attributes from the pattern onto the instantiation.
3550 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3551
3552 // Start the definition of this instantiation.
3553 Instantiation->startDefinition();
3554
3555 // The instantiation is visible here, even if it was first declared in an
3556 // unimported module.
3557 Instantiation->setVisibleDespiteOwningModule();
3558
3559 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3560 Instantiation->setTagKind(Pattern->getTagKind());
3561
3562 // Do substitution on the base class specifiers.
3563 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3564 Instantiation->setInvalidDecl();
3565
3566 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3567 Instantiator.setEvaluateConstraints(false);
3568 SmallVector<Decl*, 4> Fields;
3569 // Delay instantiation of late parsed attributes.
3570 LateInstantiatedAttrVec LateAttrs;
3571 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3572
3573 bool MightHaveConstexprVirtualFunctions = false;
3574 for (auto *Member : Pattern->decls()) {
3575 // Don't instantiate members not belonging in this semantic context.
3576 // e.g. for:
3577 // @code
3578 // template <int i> class A {
3579 // class B *g;
3580 // };
3581 // @endcode
3582 // 'class B' has the template as lexical context but semantically it is
3583 // introduced in namespace scope.
3584 if (Member->getDeclContext() != Pattern)
3585 continue;
3586
3587 // BlockDecls can appear in a default-member-initializer. They must be the
3588 // child of a BlockExpr, so we only know how to instantiate them from there.
3589 // Similarly, lambda closure types are recreated when instantiating the
3590 // corresponding LambdaExpr.
3591 if (isa<BlockDecl>(Member) ||
3593 continue;
3594
3595 if (Member->isInvalidDecl()) {
3596 Instantiation->setInvalidDecl();
3597 continue;
3598 }
3599
3600 Decl *NewMember = Instantiator.Visit(Member);
3601 if (NewMember) {
3602 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3603 Fields.push_back(Field);
3604 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3605 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3606 // specialization causes the implicit instantiation of the definitions
3607 // of unscoped member enumerations.
3608 // Record a point of instantiation for this implicit instantiation.
3609 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3610 Enum->isCompleteDefinition()) {
3611 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3612 assert(MSInfo && "no spec info for member enum specialization");
3614 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3615 }
3616 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3617 if (SA->isFailed()) {
3618 // A static_assert failed. Bail out; instantiating this
3619 // class is probably not meaningful.
3620 Instantiation->setInvalidDecl();
3621 break;
3622 }
3623 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3624 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3625 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3626 MightHaveConstexprVirtualFunctions = true;
3627 }
3628
3629 if (NewMember->isInvalidDecl())
3630 Instantiation->setInvalidDecl();
3631 } else {
3632 // FIXME: Eventually, a NULL return will mean that one of the
3633 // instantiations was a semantic disaster, and we'll want to mark the
3634 // declaration invalid.
3635 // For now, we expect to skip some members that we can't yet handle.
3636 }
3637 }
3638
3639 // Finish checking fields.
3640 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3641 SourceLocation(), SourceLocation(), ParsedAttributesView());
3642 CheckCompletedCXXClass(nullptr, Instantiation);
3643
3644 // Default arguments are parsed, if not instantiated. We can go instantiate
3645 // default arg exprs for default constructors if necessary now. Unless we're
3646 // parsing a class, in which case wait until that's finished.
3647 if (ParsingClassDepth == 0)
3648 ActOnFinishCXXNonNestedClass();
3649
3650 // Instantiate late parsed attributes, and attach them to their decls.
3651 // See Sema::InstantiateAttrs
3652 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3653 E = LateAttrs.end(); I != E; ++I) {
3654 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3655 CurrentInstantiationScope = I->Scope;
3656
3657 // Allow 'this' within late-parsed attributes.
3658 auto *ND = cast<NamedDecl>(I->NewDecl);
3659 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3660 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3661 ND->isCXXInstanceMember());
3662
3663 Attr *NewAttr =
3664 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3665 if (NewAttr)
3666 I->NewDecl->addAttr(NewAttr);
3668 Instantiator.getStartingScope());
3669 }
3670 Instantiator.disableLateAttributeInstantiation();
3671 LateAttrs.clear();
3672
3673 ActOnFinishDelayedMemberInitializers(Instantiation);
3674
3675 // FIXME: We should do something similar for explicit instantiations so they
3676 // end up in the right module.
3677 if (TSK == TSK_ImplicitInstantiation) {
3678 Instantiation->setLocation(Pattern->getLocation());
3679 Instantiation->setLocStart(Pattern->getInnerLocStart());
3680 Instantiation->setBraceRange(Pattern->getBraceRange());
3681 }
3682
3683 if (!Instantiation->isInvalidDecl()) {
3684 // Perform any dependent diagnostics from the pattern.
3685 if (Pattern->isDependentContext())
3686 PerformDependentDiagnostics(Pattern, TemplateArgs);
3687
3688 // Instantiate any out-of-line class template partial
3689 // specializations now.
3691 P = Instantiator.delayed_partial_spec_begin(),
3692 PEnd = Instantiator.delayed_partial_spec_end();
3693 P != PEnd; ++P) {
3694 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3695 P->first, P->second)) {
3696 Instantiation->setInvalidDecl();
3697 break;
3698 }
3699 }
3700
3701 // Instantiate any out-of-line variable template partial
3702 // specializations now.
3704 P = Instantiator.delayed_var_partial_spec_begin(),
3705 PEnd = Instantiator.delayed_var_partial_spec_end();
3706 P != PEnd; ++P) {
3707 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3708 P->first, P->second)) {
3709 Instantiation->setInvalidDecl();
3710 break;
3711 }
3712 }
3713 }
3714
3715 // Exit the scope of this instantiation.
3716 SavedContext.pop();
3717
3718 if (!Instantiation->isInvalidDecl()) {
3719 // Always emit the vtable for an explicit instantiation definition
3720 // of a polymorphic class template specialization. Otherwise, eagerly
3721 // instantiate only constexpr virtual functions in preparation for their use
3722 // in constant evaluation.
3724 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3725 else if (MightHaveConstexprVirtualFunctions)
3726 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3727 /*ConstexprOnly*/ true);
3728 }
3729
3730 Consumer.HandleTagDeclDefinition(Instantiation);
3731
3732 return Instantiation->isInvalidDecl();
3733}
3734
3735bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3736 EnumDecl *Instantiation, EnumDecl *Pattern,
3737 const MultiLevelTemplateArgumentList &TemplateArgs,
3739#ifndef NDEBUG
3740 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3742 assert(!AlreadyInstantiating && "should have been caught by caller");
3743#endif
3744
3745 EnumDecl *PatternDef = Pattern->getDefinition();
3746 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3747 Instantiation->getInstantiatedFromMemberEnum(),
3748 Pattern, PatternDef, TSK,/*Complain*/true))
3749 return true;
3750 Pattern = PatternDef;
3751
3752 // Record the point of instantiation.
3753 if (MemberSpecializationInfo *MSInfo
3754 = Instantiation->getMemberSpecializationInfo()) {
3755 MSInfo->setTemplateSpecializationKind(TSK);
3756 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3757 }
3758
3759 NonSFINAEContext _(*this);
3760 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3761 if (Inst.isInvalid())
3762 return true;
3763 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3764 "instantiating enum definition");
3765
3766 // The instantiation is visible here, even if it was first declared in an
3767 // unimported module.
3768 Instantiation->setVisibleDespiteOwningModule();
3769
3770 // Enter the scope of this instantiation. We don't use
3771 // PushDeclContext because we don't have a scope.
3772 ContextRAII SavedContext(*this, Instantiation);
3775
3776 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3777
3778 // Pull attributes from the pattern onto the instantiation.
3779 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3780
3781 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3782 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3783
3784 // Exit the scope of this instantiation.
3785 SavedContext.pop();
3786
3787 return Instantiation->isInvalidDecl();
3788}
3789
3791 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3792 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3793 // If there is no initializer, we don't need to do anything.
3794 if (!Pattern->hasInClassInitializer())
3795 return false;
3796
3797 assert(Instantiation->getInClassInitStyle() ==
3798 Pattern->getInClassInitStyle() &&
3799 "pattern and instantiation disagree about init style");
3800
3801 RecursiveInstGuard AlreadyInstantiating(*this, Instantiation,
3803 if (AlreadyInstantiating)
3804 // Error out if we hit an instantiation cycle for this initializer.
3805 return Diag(PointOfInstantiation,
3806 diag::err_default_member_initializer_cycle)
3807 << Instantiation;
3808
3809 // Error out if we haven't parsed the initializer of the pattern yet because
3810 // we are waiting for the closing brace of the outer class.
3811 Expr *OldInit = Pattern->getInClassInitializer();
3812 if (!OldInit) {
3813 RecordDecl *PatternRD = Pattern->getParent();
3814 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3815 Diag(PointOfInstantiation,
3816 diag::err_default_member_initializer_not_yet_parsed)
3817 << OutermostClass << Pattern;
3818 Diag(Pattern->getEndLoc(),
3819 diag::note_default_member_initializer_not_yet_parsed);
3820 Instantiation->setInvalidDecl();
3821 return true;
3822 }
3823
3824 NonSFINAEContext _(*this);
3825 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3826 if (Inst.isInvalid())
3827 return true;
3828 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3829 "instantiating default member init");
3830
3831 // Enter the scope of this instantiation. We don't use PushDeclContext because
3832 // we don't have a scope.
3833 ContextRAII SavedContext(*this, Instantiation->getParent());
3836 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3837 PointOfInstantiation, Instantiation, CurContext};
3838
3839 LocalInstantiationScope Scope(*this, true);
3840
3841 // Instantiate the initializer.
3843 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3844
3845 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3846 /*CXXDirectInit=*/false);
3847 Expr *Init = NewInit.get();
3848 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3850 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3851
3852 if (auto *L = getASTMutationListener())
3853 L->DefaultMemberInitializerInstantiated(Instantiation);
3854
3855 // Return true if the in-class initializer is still missing.
3856 return !Instantiation->getInClassInitializer();
3857}
3858
3859namespace {
3860 /// A partial specialization whose template arguments have matched
3861 /// a given template-id.
3862 struct PartialSpecMatchResult {
3865 };
3866}
3867
3869 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3870 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3872 return true;
3873
3875 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3876 CTD->getPartialSpecializations(PartialSpecs);
3877 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3878 // C++ [temp.spec.partial.member]p2:
3879 // If the primary member template is explicitly specialized for a given
3880 // (implicit) specialization of the enclosing class template, the partial
3881 // specializations of the member template are ignored for this
3882 // specialization of the enclosing class template. If a partial
3883 // specialization of the member template is explicitly specialized for a
3884 // given (implicit) specialization of the enclosing class template, the
3885 // primary member template and its other partial specializations are still
3886 // considered for this specialization of the enclosing class template.
3888 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3889 continue;
3890
3891 TemplateDeductionInfo Info(Loc);
3892 if (DeduceTemplateArguments(CTPSD,
3893 ClassTemplateSpec->getTemplateArgs().asArray(),
3895 return true;
3896 }
3897
3898 return false;
3899}
3900
3901/// Get the instantiation pattern to use to instantiate the definition of a
3902/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3903/// template or of a partial specialization).
3905 Sema &S, SourceLocation PointOfInstantiation,
3906 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3907 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3908 std::optional<Sema::NonSFINAEContext> NSC(S);
3909 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3910 if (Inst.isInvalid())
3911 return {/*Invalid=*/true};
3912
3913 llvm::PointerUnion<ClassTemplateDecl *,
3915 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3917 // Find best matching specialization.
3918 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3919
3920 // C++ [temp.class.spec.match]p1:
3921 // When a class template is used in a context that requires an
3922 // instantiation of the class, it is necessary to determine
3923 // whether the instantiation is to be generated using the primary
3924 // template or one of the partial specializations. This is done by
3925 // matching the template arguments of the class template
3926 // specialization with the template argument lists of the partial
3927 // specializations.
3928 typedef PartialSpecMatchResult MatchResult;
3929 SmallVector<MatchResult, 4> Matched, ExtraMatched;
3931 Template->getPartialSpecializations(PartialSpecs);
3932 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3933 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
3934 // C++ [temp.spec.partial.member]p2:
3935 // If the primary member template is explicitly specialized for a given
3936 // (implicit) specialization of the enclosing class template, the
3937 // partial specializations of the member template are ignored for this
3938 // specialization of the enclosing class template. If a partial
3939 // specialization of the member template is explicitly specialized for a
3940 // given (implicit) specialization of the enclosing class template, the
3941 // primary member template and its other partial specializations are
3942 // still considered for this specialization of the enclosing class
3943 // template.
3944 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
3945 !Partial->getMostRecentDecl()->isMemberSpecialization())
3946 continue;
3947
3948 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3950 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3952 // Store the failed-deduction information for use in diagnostics, later.
3953 // TODO: Actually use the failed-deduction info?
3954 FailedCandidates.addCandidate().set(
3956 MakeDeductionFailureInfo(S.Context, Result, Info));
3957 (void)Result;
3958 } else {
3959 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
3960 List.push_back(MatchResult{Partial, Info.takeCanonical()});
3961 }
3962 }
3963 if (Matched.empty() && PrimaryStrictPackMatch)
3964 Matched = std::move(ExtraMatched);
3965
3966 // If we're dealing with a member template where the template parameters
3967 // have been instantiated, this provides the original template parameters
3968 // from which the member template's parameters were instantiated.
3969
3970 if (Matched.size() >= 1) {
3971 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3972 if (Matched.size() == 1) {
3973 // -- If exactly one matching specialization is found, the
3974 // instantiation is generated from that specialization.
3975 // We don't need to do anything for this.
3976 } else {
3977 // -- If more than one matching specialization is found, the
3978 // partial order rules (14.5.4.2) are used to determine
3979 // whether one of the specializations is more specialized
3980 // than the others. If none of the specializations is more
3981 // specialized than all of the other matching
3982 // specializations, then the use of the class template is
3983 // ambiguous and the program is ill-formed.
3985 PEnd = Matched.end();
3986 P != PEnd; ++P) {
3988 P->Partial, Best->Partial, PointOfInstantiation) ==
3989 P->Partial)
3990 Best = P;
3991 }
3992
3993 // Determine if the best partial specialization is more specialized than
3994 // the others.
3995 bool Ambiguous = false;
3996 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3997 PEnd = Matched.end();
3998 P != PEnd; ++P) {
3999 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4000 P->Partial, Best->Partial,
4001 PointOfInstantiation) != Best->Partial) {
4002 Ambiguous = true;
4003 break;
4004 }
4005 }
4006
4007 if (Ambiguous) {
4008 // Partial ordering did not produce a clear winner. Complain.
4009 Inst.Clear();
4010 NSC.reset();
4011 S.Diag(PointOfInstantiation,
4012 diag::err_partial_spec_ordering_ambiguous)
4013 << ClassTemplateSpec;
4014
4015 // Print the matching partial specializations.
4016 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4017 PEnd = Matched.end();
4018 P != PEnd; ++P)
4019 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4021 P->Partial->getTemplateParameters(), *P->Args);
4022
4023 return {/*Invalid=*/true};
4024 }
4025 }
4026
4027 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4028 } else {
4029 // -- If no matches are found, the instantiation is generated
4030 // from the primary template.
4031 }
4032 }
4033
4034 CXXRecordDecl *Pattern = nullptr;
4035 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4036 if (auto *PartialSpec =
4037 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4038 // Instantiate using the best class template partial specialization.
4039 while (PartialSpec->getInstantiatedFromMember()) {
4040 // If we've found an explicit specialization of this class template,
4041 // stop here and use that as the pattern.
4042 if (PartialSpec->isMemberSpecialization())
4043 break;
4044
4045 PartialSpec = PartialSpec->getInstantiatedFromMember();
4046 }
4047 Pattern = PartialSpec;
4048 } else {
4049 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4050 while (Template->getInstantiatedFromMemberTemplate()) {
4051 // If we've found an explicit specialization of this class template,
4052 // stop here and use that as the pattern.
4053 if (Template->isMemberSpecialization())
4054 break;
4055
4056 Template = Template->getInstantiatedFromMemberTemplate();
4057 }
4058 Pattern = Template->getTemplatedDecl();
4059 }
4060
4061 return Pattern;
4062}
4063
4065 SourceLocation PointOfInstantiation,
4066 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4067 TemplateSpecializationKind TSK, bool Complain,
4068 bool PrimaryStrictPackMatch) {
4069 // Perform the actual instantiation on the canonical declaration.
4070 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4071 ClassTemplateSpec->getCanonicalDecl());
4072 if (ClassTemplateSpec->isInvalidDecl())
4073 return true;
4074
4075 Sema::RecursiveInstGuard AlreadyInstantiating(
4076 *this, ClassTemplateSpec, Sema::RecursiveInstGuard::Kind::Template);
4077 if (AlreadyInstantiating)
4078 return false;
4079
4080 bool HadAvaibilityWarning =
4081 ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
4082 .first != AR_Available;
4083
4085 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4086 ClassTemplateSpec, TSK,
4087 PrimaryStrictPackMatch);
4088
4089 if (!Pattern.isUsable())
4090 return Pattern.isInvalid();
4091
4092 bool Err = InstantiateClassImpl(
4093 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4094 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4095
4096 // If we haven't already warn on avaibility, consider the avaibility
4097 // attributes of the partial specialization.
4098 // Note that - because we need to have deduced the partial specialization -
4099 // We can only emit these warnings when the specialization is instantiated.
4100 if (!Err && !HadAvaibilityWarning) {
4101 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4103 DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);
4104 }
4105 return Err;
4106}
4107
4108void
4110 CXXRecordDecl *Instantiation,
4111 const MultiLevelTemplateArgumentList &TemplateArgs,
4113 // FIXME: We need to notify the ASTMutationListener that we did all of these
4114 // things, in case we have an explicit instantiation definition in a PCM, a
4115 // module, or preamble, and the declaration is in an imported AST.
4116 assert(
4119 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4120 "Unexpected template specialization kind!");
4121 for (auto *D : Instantiation->decls()) {
4122 bool SuppressNew = false;
4123 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4124 if (FunctionDecl *Pattern =
4125 Function->getInstantiatedFromMemberFunction()) {
4126
4127 if (Function->getTrailingRequiresClause()) {
4128 ConstraintSatisfaction Satisfaction;
4129 if (CheckFunctionConstraints(Function, Satisfaction) ||
4130 !Satisfaction.IsSatisfied) {
4131 continue;
4132 }
4133 }
4134
4135 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4136 continue;
4137
4139 Function->getTemplateSpecializationKind();
4140 if (PrevTSK == TSK_ExplicitSpecialization)
4141 continue;
4142
4144 PointOfInstantiation, TSK, Function, PrevTSK,
4145 Function->getPointOfInstantiation(), SuppressNew) ||
4146 SuppressNew)
4147 continue;
4148
4149 // C++11 [temp.explicit]p8:
4150 // An explicit instantiation definition that names a class template
4151 // specialization explicitly instantiates the class template
4152 // specialization and is only an explicit instantiation definition
4153 // of members whose definition is visible at the point of
4154 // instantiation.
4155 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4156 continue;
4157
4158 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4159
4160 if (Function->isDefined()) {
4161 // Let the ASTConsumer know that this function has been explicitly
4162 // instantiated now, and its linkage might have changed.
4163 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4164 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4165 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4166 } else if (TSK == TSK_ImplicitInstantiation) {
4168 std::make_pair(Function, PointOfInstantiation));
4169 }
4170 }
4171 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4173 continue;
4174
4175 if (Var->isStaticDataMember()) {
4176 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4177 continue;
4178
4180 assert(MSInfo && "No member specialization information?");
4181 if (MSInfo->getTemplateSpecializationKind()
4183 continue;
4184
4185 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4186 Var,
4188 MSInfo->getPointOfInstantiation(),
4189 SuppressNew) ||
4190 SuppressNew)
4191 continue;
4192
4194 // C++0x [temp.explicit]p8:
4195 // An explicit instantiation definition that names a class template
4196 // specialization explicitly instantiates the class template
4197 // specialization and is only an explicit instantiation definition
4198 // of members whose definition is visible at the point of
4199 // instantiation.
4201 continue;
4202
4203 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4204 InstantiateVariableDefinition(PointOfInstantiation, Var);
4205 } else {
4206 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4207 }
4208 }
4209 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4210 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4211 continue;
4212
4213 // Always skip the injected-class-name, along with any
4214 // redeclarations of nested classes, since both would cause us
4215 // to try to instantiate the members of a class twice.
4216 // Skip closure types; they'll get instantiated when we instantiate
4217 // the corresponding lambda-expression.
4218 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4219 Record->isLambda())
4220 continue;
4221
4222 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4223 assert(MSInfo && "No member specialization information?");
4224
4225 if (MSInfo->getTemplateSpecializationKind()
4227 continue;
4228
4229 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4231 // On Windows, explicit instantiation decl of the outer class doesn't
4232 // affect the inner class. Typically extern template declarations are
4233 // used in combination with dll import/export annotations, but those
4234 // are not propagated from the outer class templates to inner classes.
4235 // Therefore, do not instantiate inner classes on this platform, so
4236 // that users don't end up with undefined symbols during linking.
4237 continue;
4238 }
4239
4240 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4241 Record,
4243 MSInfo->getPointOfInstantiation(),
4244 SuppressNew) ||
4245 SuppressNew)
4246 continue;
4247
4248 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4249 assert(Pattern && "Missing instantiated-from-template information");
4250
4251 if (!Record->getDefinition()) {
4252 if (!Pattern->getDefinition()) {
4253 // C++0x [temp.explicit]p8:
4254 // An explicit instantiation definition that names a class template
4255 // specialization explicitly instantiates the class template
4256 // specialization and is only an explicit instantiation definition
4257 // of members whose definition is visible at the point of
4258 // instantiation.
4260 MSInfo->setTemplateSpecializationKind(TSK);
4261 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4262 }
4263
4264 continue;
4265 }
4266
4267 InstantiateClass(PointOfInstantiation, Record, Pattern,
4268 TemplateArgs,
4269 TSK);
4270 } else {
4272 Record->getTemplateSpecializationKind() ==
4274 Record->setTemplateSpecializationKind(TSK);
4275 MarkVTableUsed(PointOfInstantiation, Record, true);
4276 }
4277 }
4278
4279 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4280 if (Pattern)
4281 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4282 TSK);
4283 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4284 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4285 assert(MSInfo && "No member specialization information?");
4286
4287 if (MSInfo->getTemplateSpecializationKind()
4289 continue;
4290
4292 PointOfInstantiation, TSK, Enum,
4294 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4295 SuppressNew)
4296 continue;
4297
4298 if (Enum->getDefinition())
4299 continue;
4300
4301 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4302 assert(Pattern && "Missing instantiated-from-template information");
4303
4305 if (!Pattern->getDefinition())
4306 continue;
4307
4308 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4309 } else {
4310 MSInfo->setTemplateSpecializationKind(TSK);
4311 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4312 }
4313 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4314 // No need to instantiate in-class initializers during explicit
4315 // instantiation.
4316 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4317 // Handle local classes which could have substituted template params.
4318 CXXRecordDecl *ClassPattern =
4319 Instantiation->isLocalClass()
4320 ? Instantiation->getInstantiatedFromMemberClass()
4321 : Instantiation->getTemplateInstantiationPattern();
4322
4324 ClassPattern->lookup(Field->getDeclName());
4325 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4326 assert(Pattern);
4327 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4328 TemplateArgs);
4329 }
4330 }
4331 }
4332}
4333
4334void
4336 SourceLocation PointOfInstantiation,
4337 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4339 // C++0x [temp.explicit]p7:
4340 // An explicit instantiation that names a class template
4341 // specialization is an explicit instantion of the same kind
4342 // (declaration or definition) of each of its members (not
4343 // including members inherited from base classes) that has not
4344 // been previously explicitly specialized in the translation unit
4345 // containing the explicit instantiation, except as described
4346 // below.
4347 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4348 getTemplateInstantiationArgs(ClassTemplateSpec),
4349 TSK);
4350}
4351
4354 if (!S)
4355 return S;
4356
4357 TemplateInstantiator Instantiator(*this, TemplateArgs,
4359 DeclarationName());
4360 return Instantiator.TransformStmt(S);
4361}
4362
4364 const TemplateArgumentLoc &Input,
4365 const MultiLevelTemplateArgumentList &TemplateArgs,
4367 const DeclarationName &Entity) {
4368 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4369 return Instantiator.TransformTemplateArgument(Input, Output);
4370}
4371
4374 const MultiLevelTemplateArgumentList &TemplateArgs,
4376 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4377 DeclarationName());
4378 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4379}
4380
4383 const MultiLevelTemplateArgumentList &TemplateArgs,
4385 TemplateInstantiator Instantiator(
4386 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4387 TemplateArgs);
4388 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4389}
4390
4393 if (!E)
4394 return E;
4395
4396 TemplateInstantiator Instantiator(*this, TemplateArgs,
4398 DeclarationName());
4399 return Instantiator.TransformExpr(E);
4400}
4401
4404 const MultiLevelTemplateArgumentList &TemplateArgs) {
4405 if (!E)
4406 return E;
4407
4408 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4409 DeclarationName());
4410 return Instantiator.TransformAddressOfOperand(E);
4411}
4412
4415 const MultiLevelTemplateArgumentList &TemplateArgs) {
4416 // FIXME: should call SubstExpr directly if this function is equivalent or
4417 // should it be different?
4418 return SubstExpr(E, TemplateArgs);
4419}
4420
4422 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4423 if (!E)
4424 return E;
4425
4426 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4427 DeclarationName());
4428 Instantiator.setEvaluateConstraints(false);
4429 return Instantiator.TransformExpr(E);
4430}
4431
4433 const ConceptSpecializationExpr *CSE, const Expr *ConstraintExpr,
4434 const MultiLevelTemplateArgumentList &MLTAL) {
4435 TemplateInstantiator Instantiator(*this, MLTAL, SourceLocation(),
4436 DeclarationName());
4437 const ASTTemplateArgumentListInfo *ArgsAsWritten =
4439 TemplateArgumentListInfo SubstArgs(ArgsAsWritten->getLAngleLoc(),
4440 ArgsAsWritten->getRAngleLoc());
4441
4442 NonSFINAEContext _(*this);
4444 *this, ArgsAsWritten->arguments().front().getSourceRange().getBegin(),
4446 CSE->getNamedConcept(),
4447 ArgsAsWritten->arguments().front().getSourceRange());
4448
4449 if (Inst.isInvalid())
4450 return ExprError();
4451
4452 if (Instantiator.TransformConceptTemplateArguments(
4453 ArgsAsWritten->getTemplateArgs(),
4454 ArgsAsWritten->getTemplateArgs() +
4455 ArgsAsWritten->getNumTemplateArgs(),
4456 SubstArgs))
4457 return true;
4458
4459 llvm::SmallVector<TemplateArgument, 4> NewArgList = llvm::map_to_vector(
4460 SubstArgs.arguments(),
4461 [](const TemplateArgumentLoc &Loc) { return Loc.getArgument(); });
4462
4463 MultiLevelTemplateArgumentList MLTALForConstraint =
4465 CSE->getNamedConcept(),
4467 /*Final=*/false,
4468 /*Innermost=*/NewArgList,
4469 /*RelativeToPrimary=*/true,
4470 /*Pattern=*/nullptr,
4471 /*ForConstraintInstantiation=*/true);
4472
4473 // Rebuild a constraint, only substituting non-dependent concept names
4474 // and nothing else.
4475 // Given C<SomeType, SomeValue, SomeConceptName, SomeDependentConceptName>.
4476 // only SomeConceptName is substituted, in the constraint expression of C.
4477 struct ConstraintExprTransformer : TreeTransform<ConstraintExprTransformer> {
4480
4481 ConstraintExprTransformer(Sema &SemaRef,
4483 : TreeTransform(SemaRef), MLTAL(MLTAL) {}
4484
4485 ExprResult TransformExpr(Expr *E) {
4486 if (!E)
4487 return E;
4488 switch (E->getStmtClass()) {
4489 case Stmt::BinaryOperatorClass:
4490 case Stmt::ConceptSpecializationExprClass:
4491 case Stmt::ParenExprClass:
4492 case Stmt::UnresolvedLookupExprClass:
4493 return Base::TransformExpr(E);
4494 default:
4495 break;
4496 }
4497 return E;
4498 }
4499
4500 // Rebuild both branches of a conjunction / disjunction
4501 // even if there is a substitution failure in one of
4502 // the branch.
4503 ExprResult TransformBinaryOperator(BinaryOperator *E) {
4504 if (!(E->getOpcode() == BinaryOperatorKind::BO_LAnd ||
4505 E->getOpcode() == BinaryOperatorKind::BO_LOr))
4506 return E;
4507
4508 ExprResult LHS = TransformExpr(E->getLHS());
4509 ExprResult RHS = TransformExpr(E->getRHS());
4510
4511 if (LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
4512 return E;
4513
4514 return BinaryOperator::Create(SemaRef.Context, LHS.get(), RHS.get(),
4515 E->getOpcode(), SemaRef.Context.BoolTy,
4518 }
4519
4520 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
4521 TemplateArgumentLoc &Output,
4522 bool Uneval = false) {
4524 return Base::TransformTemplateArgument(Input, Output, Uneval);
4525
4526 Output = Input;
4527 return false;
4528 }
4529
4530 ExprResult TransformUnresolvedLookupExpr(UnresolvedLookupExpr *E,
4531 bool IsAddressOfOperand = false) {
4532 if (E->isConceptReference()) {
4533 ExprResult Res = SemaRef.SubstExpr(E, MLTAL);
4534 return Res;
4535 }
4536 return E;
4537 }
4538 };
4539
4540 ConstraintExprTransformer Transformer(*this, MLTALForConstraint);
4541 ExprResult Res =
4542 Transformer.TransformExpr(const_cast<Expr *>(ConstraintExpr));
4543 return Res;
4544}
4545
4547 const MultiLevelTemplateArgumentList &TemplateArgs,
4548 bool CXXDirectInit) {
4549 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4550 DeclarationName());
4551 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4552}
4553
4554bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4555 const MultiLevelTemplateArgumentList &TemplateArgs,
4556 SmallVectorImpl<Expr *> &Outputs) {
4557 if (Exprs.empty())
4558 return false;
4559
4560 TemplateInstantiator Instantiator(*this, TemplateArgs,
4562 DeclarationName());
4563 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4564 IsCall, Outputs);
4565}
4566
4569 const MultiLevelTemplateArgumentList &TemplateArgs) {
4570 if (!NNS)
4571 return NestedNameSpecifierLoc();
4572
4573 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4574 DeclarationName());
4575 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4576}
4577
4580 const MultiLevelTemplateArgumentList &TemplateArgs) {
4581 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4582 NameInfo.getName());
4583 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4584}
4585
4588 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4589 SourceLocation NameLoc,
4590 const MultiLevelTemplateArgumentList &TemplateArgs) {
4591 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4592 DeclarationName());
4593 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4594 NameLoc);
4595}
4596
4597static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4598 // When storing ParmVarDecls in the local instantiation scope, we always
4599 // want to use the ParmVarDecl from the canonical function declaration,
4600 // since the map is then valid for any redeclaration or definition of that
4601 // function.
4602 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4603 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4604 unsigned i = PV->getFunctionScopeIndex();
4605 // This parameter might be from a freestanding function type within the
4606 // function and isn't necessarily referring to one of FD's parameters.
4607 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4608 return FD->getCanonicalDecl()->getParamDecl(i);
4609 }
4610 }
4611 return D;
4612}
4613
4614llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4617 for (LocalInstantiationScope *Current = this; Current;
4618 Current = Current->Outer) {
4619
4620 // Check if we found something within this scope.
4621 const Decl *CheckD = D;
4622 do {
4623 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4624 if (Found != Current->LocalDecls.end())
4625 return &Found->second;
4626
4627 // If this is a tag declaration, it's possible that we need to look for
4628 // a previous declaration.
4629 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4630 CheckD = Tag->getPreviousDecl();
4631 else
4632 CheckD = nullptr;
4633 } while (CheckD);
4634
4635 // If we aren't combined with our outer scope, we're done.
4636 if (!Current->CombineWithOuterScope)
4637 break;
4638 }
4639
4640 return nullptr;
4641}
4642
4643llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4646 if (Result)
4647 return Result;
4648 // If we're performing a partial substitution during template argument
4649 // deduction, we may not have values for template parameters yet.
4652 return nullptr;
4653
4654 // Local types referenced prior to definition may require instantiation.
4655 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4656 if (RD->isLocalClass())
4657 return nullptr;
4658
4659 // Enumeration types referenced prior to definition may appear as a result of
4660 // error recovery.
4661 if (isa<EnumDecl>(D))
4662 return nullptr;
4663
4664 // Materialized typedefs/type alias for implicit deduction guides may require
4665 // instantiation.
4666 if (isa<TypedefNameDecl>(D) &&
4668 return nullptr;
4669
4670 // If we didn't find the decl, then we either have a sema bug, or we have a
4671 // forward reference to a label declaration. Return null to indicate that
4672 // we have an uninstantiated label.
4673 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4674 return nullptr;
4675}
4676
4679 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4680 if (Stored.isNull()) {
4681#ifndef NDEBUG
4682 // It should not be present in any surrounding scope either.
4683 LocalInstantiationScope *Current = this;
4684 while (Current->CombineWithOuterScope && Current->Outer) {
4685 Current = Current->Outer;
4686 assert(!Current->LocalDecls.contains(D) &&
4687 "Instantiated local in inner and outer scopes");
4688 }
4689#endif
4690 Stored = Inst;
4691 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4692 Pack->push_back(cast<ValueDecl>(Inst));
4693 } else {
4694 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4695 }
4696}
4697
4699 VarDecl *Inst) {
4701 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4702 Pack->push_back(Inst);
4703}
4704
4706#ifndef NDEBUG
4707 // This should be the first time we've been told about this decl.
4708 for (LocalInstantiationScope *Current = this;
4709 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4710 assert(!Current->LocalDecls.contains(D) &&
4711 "Creating local pack after instantiation of local");
4712#endif
4713
4715 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4717 Stored = Pack;
4718 ArgumentPacks.push_back(Pack);
4719}
4720
4722 for (DeclArgumentPack *Pack : ArgumentPacks)
4723 if (llvm::is_contained(*Pack, D))
4724 return true;
4725 return false;
4726}
4727
4729 const TemplateArgument *ExplicitArgs,
4730 unsigned NumExplicitArgs) {
4731 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4732 "Already have a partially-substituted pack");
4733 assert((!PartiallySubstitutedPack
4734 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4735 "Wrong number of arguments in partially-substituted pack");
4736 PartiallySubstitutedPack = Pack;
4737 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4738 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4739}
4740
4742 const TemplateArgument **ExplicitArgs,
4743 unsigned *NumExplicitArgs) const {
4744 if (ExplicitArgs)
4745 *ExplicitArgs = nullptr;
4746 if (NumExplicitArgs)
4747 *NumExplicitArgs = 0;
4748
4749 for (const LocalInstantiationScope *Current = this; Current;
4750 Current = Current->Outer) {
4751 if (Current->PartiallySubstitutedPack) {
4752 if (ExplicitArgs)
4753 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4754 if (NumExplicitArgs)
4755 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4756
4757 return Current->PartiallySubstitutedPack;
4758 }
4759
4760 if (!Current->CombineWithOuterScope)
4761 break;
4762 }
4763
4764 return nullptr;
4765}
Defines the clang::ASTContext interface.
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.
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.
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:226
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:850
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:3512
QualType getElementType() const
Definition TypeBase.h:3742
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:5076
Opcode getOpcode() const
Definition Expr.h:4086
QualType getPointeeType() const
Definition TypeBase.h:3562
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:1345
const ParmVarDecl * getParam() const
Definition ExprCXX.h:1313
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
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...
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:1449
bool isFileContext() const
Definition DeclBase.h:2180
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
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:2373
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:1061
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:1226
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:454
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:588
SourceLocation getLocation() const
Definition DeclBase.h:439
void setLocation(SourceLocation L)
Definition DeclBase.h:440
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition DeclBase.h:949
DeclContext * getDeclContext()
Definition DeclBase.h:448
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:918
bool hasAttr() const
Definition DeclBase.h:577
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition DeclBase.h:870
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:4013
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4285
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5155
EnumDecl * getDefinition() const
Definition Decl.h:4125
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:3160
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4726
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Represents a function declaration or definition.
Definition Decl.h:2000
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
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:4265
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4314
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
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:4883
ValueDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition ExprCXX.h:4875
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4868
iterator end() const
Definition ExprCXX.h:4877
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4880
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4871
iterator begin() const
Definition ExprCXX.h:4876
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5315
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5604
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:4537
QualType getReturnType() const
Definition TypeBase.h:4851
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:1969
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:372
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope=false, bool InstantiatingLambdaOrBlock=false)
Definition Template.h:440
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:375
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:512
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:578
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:6210
QualType getPointeeType() const
Definition TypeBase.h:3679
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:144
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:272
std::pair< Decl *, bool > getAssociatedDecl(unsigned Depth) const
A template-like entity which owns the whole pattern being substituted.
Definition Template.h:164
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition Template.h:129
unsigned getNewDepth(unsigned OldDepth) const
Determine how many of the OldDepth outermost template parameter lists would be removed by substitutin...
Definition Template.h:145
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition Template.h:200
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:1846
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition Decl.cpp:1672
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:3319
Represents a parameter to a function.
Definition Decl.h:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
SourceLocation getExplicitObjectParamThisLoc() const
Definition Decl.h:1886
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1931
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1919
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3048
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1923
bool hasInheritedDefaultArg() const
Definition Decl.h:1935
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
Expr * getDefaultArg()
Definition Decl.cpp:3011
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3053
unsigned getFunctionScopeDepth() const
Definition Decl.h:1840
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1939
QualType getPointeeType() const
Definition TypeBase.h:3346
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:3624
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1162
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:4327
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
QualType getPointeeTypeAsWritten() const
Definition TypeBase.h:3597
Represents the body of a requires-expression.
Definition DeclCXX.h:2105
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:13721
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8499
A RAII object to temporarily push a declaration context.
Definition Sema.h:3518
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6405
DefaultedComparisonKind asComparison() const
Definition Sema.h:6437
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6434
A helper class for building up ExtParameterInfos.
Definition Sema.h:13085
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12517
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:13676
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:13660
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:13114
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:2308
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:14042
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:1300
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:13751
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:1204
bool pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:272
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition Sema.h: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:11833
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
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:13126
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:1438
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:14091
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:13691
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:14031
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:13715
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:1301
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6780
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6790
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13699
bool inParameterMappingSubstitution() const
Definition Sema.h:14036
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8218
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8368
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:1302
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:1580
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13671
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:625
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:651
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8710
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:1485
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:3717
void setTagKind(TagKind TK)
Definition Decl.h:3921
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4907
void setBraceRange(SourceRange R)
Definition Decl.h:3795
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
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:687
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition Template.h:690
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:3548
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:8359
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:8370
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:1839
bool isVoidType() const
Definition TypeBase.h:8991
bool isReferenceType() const
Definition TypeBase.h:8649
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2798
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2411
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2808
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9218
bool isRecordType() const
Definition TypeBase.h:8752
QualType getUnderlyingType() const
Definition Decl.h:3617
A reference to a name which we were able to look up during parsing but could not resolve to a specifi...
Definition ExprCXX.h:3391
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:5594
Represents a variable declaration or definition.
Definition Decl.h:926
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2378
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2784
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:2919
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1168
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2910
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:4197
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.
#define bool
Definition gpuintrin.h:32
Defines the clang::TargetInfo interface.
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:151
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:124
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.
@ 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:132
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_XValue
An x-value expression is a reference to an object with independent storage but which can be "moved",...
Definition Specifiers.h:144
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
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:188
@ TSK_ExplicitInstantiationDefinition
This template specialization was instantiated from a template due to an explicit instantiation defini...
Definition Specifiers.h:206
@ TSK_ExplicitInstantiationDeclaration
This template specialization was instantiated from a template due to an explicit instantiation declar...
Definition Specifiers.h:202
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition Specifiers.h:198
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition Specifiers.h:194
@ TSK_Undeclared
This template specialization was formed from a template-id but has not yet been declared,...
Definition Specifiers.h:191
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5928
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:5372
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5374
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:13165
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13336
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:13309
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13296
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13167
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13259
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13177
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13186
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13205
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13256
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13213
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13220
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13263
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13231
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13269
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13196
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13275
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13272
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13278
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13193
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13201
@ SYCLKernelLaunchOverloadResolution
We are performing overload resolution for a call to a function template or variable template named 's...
Definition Sema.h:13286
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13209
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13170
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13223
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13227
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13182
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13253
@ SYCLKernelLaunchLookup
We are performing name lookup for a function template or variable template named 'sycl_kernel_launch'...
Definition Sema.h:13282
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13216
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13299
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:13359
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13512
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