Thanks to visit codestin.com
Credit goes to clang.llvm.org

clang 22.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
21#include "clang/AST/Expr.h"
24#include "clang/AST/Type.h"
25#include "clang/AST/TypeLoc.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Sema.h"
35#include "clang/Sema/Template.h"
38#include "llvm/ADT/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
604
607 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
608 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
609 sema::TemplateDeductionInfo *DeductionInfo)
610 : SemaRef(SemaRef) {
611 // Don't allow further instantiation if a fatal error and an uncompilable
612 // error have occurred. Any diagnostics we might have raised will not be
613 // visible, and we do not need to construct a correct AST.
614 if (SemaRef.Diags.hasFatalErrorOccurred() &&
615 SemaRef.hasUncompilableErrorOccurred()) {
616 Invalid = true;
617 return;
618 }
619
621 Inst.Kind = Kind;
622 Inst.PointOfInstantiation = PointOfInstantiation;
623 Inst.Entity = Entity;
624 Inst.Template = Template;
625 Inst.TemplateArgs = TemplateArgs.data();
626 Inst.NumTemplateArgs = TemplateArgs.size();
627 Inst.DeductionInfo = DeductionInfo;
628 Inst.InstantiationRange = InstantiationRange;
629 Inst.InConstraintSubstitution =
631 if (!SemaRef.CodeSynthesisContexts.empty())
632 Inst.InConstraintSubstitution |=
633 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
634
635 Invalid = SemaRef.pushCodeSynthesisContext(Inst);
636 if (!Invalid) {
637 AlreadyInstantiating =
638 !Inst.Entity
639 ? false
640 : !SemaRef.InstantiatingSpecializations
641 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
642 .second;
644 }
645}
646
648 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
649 SourceRange InstantiationRange)
650 : InstantiatingTemplate(SemaRef,
651 CodeSynthesisContext::TemplateInstantiation,
652 PointOfInstantiation, InstantiationRange, Entity) {}
653
655 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
656 ExceptionSpecification, SourceRange InstantiationRange)
658 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
659 PointOfInstantiation, InstantiationRange, Entity) {}
660
662 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
664 SourceRange InstantiationRange)
666 SemaRef,
667 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
668 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
669 Template, TemplateArgs) {}
670
672 Sema &SemaRef, SourceLocation PointOfInstantiation,
674 ArrayRef<TemplateArgument> TemplateArgs,
676 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
677 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
678 InstantiationRange, FunctionTemplate, nullptr,
679 TemplateArgs, &DeductionInfo) {
683}
684
686 Sema &SemaRef, SourceLocation PointOfInstantiation,
688 ArrayRef<TemplateArgument> TemplateArgs,
689 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
691 SemaRef,
692 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
693 PointOfInstantiation, InstantiationRange, Template, nullptr,
694 TemplateArgs, &DeductionInfo) {}
695
697 Sema &SemaRef, SourceLocation PointOfInstantiation,
699 ArrayRef<TemplateArgument> TemplateArgs,
700 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
702 SemaRef,
703 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
704 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
705 TemplateArgs, &DeductionInfo) {}
706
708 Sema &SemaRef, SourceLocation PointOfInstantiation,
710 ArrayRef<TemplateArgument> TemplateArgs,
711 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
713 SemaRef,
714 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
715 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
716 TemplateArgs, &DeductionInfo) {}
717
719 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
720 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
722 SemaRef,
723 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
724 PointOfInstantiation, InstantiationRange, Param, nullptr,
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, NamedDecl *Template,
740 SourceRange InstantiationRange)
742 SemaRef,
743 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
744 PointOfInstantiation, InstantiationRange, Param, Template,
745 TemplateArgs) {}
746
748 Sema &SemaRef, SourceLocation PointOfInstantiation,
750 SourceRange InstantiationRange)
752 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
753 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
754 /*Template=*/nullptr, TemplateArgs) {}
755
757 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
758 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
759 SourceRange InstantiationRange)
761 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
762 PointOfInstantiation, InstantiationRange, Param, Template,
763 TemplateArgs) {}
764
766 Sema &SemaRef, SourceLocation PointOfInstantiation,
768 SourceRange InstantiationRange)
770 SemaRef, CodeSynthesisContext::RequirementInstantiation,
771 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
772 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
773
775 Sema &SemaRef, SourceLocation PointOfInstantiation,
777 SourceRange InstantiationRange)
779 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
780 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
781 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
782
784 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
785 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
787 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
788 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
789 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
790
792 Sema &SemaRef, SourceLocation PointOfInstantiation,
794 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
797 PointOfInstantiation, InstantiationRange, Template, nullptr,
798 TemplateArgs) {}
799
801 Sema &SemaRef, SourceLocation PointOfInstantiation,
803 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
806 PointOfInstantiation, InstantiationRange, Template, nullptr,
807 {}, &DeductionInfo) {}
808
810 Sema &SemaRef, SourceLocation PointOfInstantiation,
812 SourceRange InstantiationRange)
815 PointOfInstantiation, InstantiationRange, Template) {}
816
818 Sema &SemaRef, SourceLocation PointOfInstantiation,
820 SourceRange InstantiationRange)
823 PointOfInstantiation, InstantiationRange, Template) {}
824
826 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
827 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
829 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
830 PointOfInstantiation, InstantiationRange, Entity) {}
831
833 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
834 TemplateDecl *PArg, SourceRange InstantiationRange)
836 ArgLoc, InstantiationRange, PArg) {}
837
841
842 if (!Ctx.isInstantiationRecord()) {
844 } else {
845 assert(SemaRef.NonInstantiationEntries <=
846 SemaRef.CodeSynthesisContexts.size());
847 if ((SemaRef.CodeSynthesisContexts.size() -
848 SemaRef.NonInstantiationEntries) >
849 SemaRef.getLangOpts().InstantiationDepth) {
851 diag::err_template_recursion_depth_exceeded)
852 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
854 diag::note_template_recursion_depth)
855 << SemaRef.getLangOpts().InstantiationDepth;
856 return true;
857 }
858 }
859
860 CodeSynthesisContexts.push_back(Ctx);
861
862 // Check to see if we're low on stack space. We can't do anything about this
863 // from here, but we can at least warn the user.
864 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
865 return false;
866}
867
869 auto &Active = CodeSynthesisContexts.back();
870 if (!Active.isInstantiationRecord()) {
871 assert(NonInstantiationEntries > 0);
873 }
874
875 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
876
877 // Name lookup no longer looks in this template's defining module.
878 assert(CodeSynthesisContexts.size() >=
880 "forgot to remove a lookup module for a template instantiation");
881 if (CodeSynthesisContexts.size() ==
884 LookupModulesCache.erase(M);
886 }
887
888 // If we've left the code synthesis context for the current context stack,
889 // stop remembering that we've emitted that stack.
890 if (CodeSynthesisContexts.size() ==
893
894 CodeSynthesisContexts.pop_back();
895}
896
898 if (!Invalid) {
899 if (!AlreadyInstantiating) {
900 auto &Active = SemaRef.CodeSynthesisContexts.back();
901 if (Active.Entity)
902 SemaRef.InstantiatingSpecializations.erase(
903 {Active.Entity->getCanonicalDecl(), Active.Kind});
904 }
905
906 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
907 SemaRef.CodeSynthesisContexts.back());
908
909 SemaRef.popCodeSynthesisContext();
910 Invalid = true;
911 }
912}
913
914static std::string convertCallArgsToString(Sema &S,
916 std::string Result;
917 llvm::raw_string_ostream OS(Result);
918 llvm::ListSeparator Comma;
919 for (const Expr *Arg : Args) {
920 OS << Comma;
921 Arg->IgnoreParens()->printPretty(OS, nullptr,
923 }
924 return Result;
925}
926
928 // Determine which template instantiations to skip, if any.
929 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
930 unsigned Limit = Diags.getTemplateBacktraceLimit();
931 if (Limit && Limit < CodeSynthesisContexts.size()) {
932 SkipStart = Limit / 2 + Limit % 2;
933 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
934 }
935
936 // FIXME: In all of these cases, we need to show the template arguments
937 unsigned InstantiationIdx = 0;
939 Active = CodeSynthesisContexts.rbegin(),
940 ActiveEnd = CodeSynthesisContexts.rend();
941 Active != ActiveEnd;
942 ++Active, ++InstantiationIdx) {
943 // Skip this instantiation?
944 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
945 if (InstantiationIdx == SkipStart) {
946 // Note that we're skipping instantiations.
947 DiagFunc(Active->PointOfInstantiation,
948 PDiag(diag::note_instantiation_contexts_suppressed)
949 << unsigned(CodeSynthesisContexts.size() - Limit));
950 }
951 continue;
952 }
953
954 switch (Active->Kind) {
956 Decl *D = Active->Entity;
957 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
958 unsigned DiagID = diag::note_template_member_class_here;
960 DiagID = diag::note_template_class_instantiation_here;
961 DiagFunc(Active->PointOfInstantiation,
962 PDiag(DiagID) << Record << Active->InstantiationRange);
963 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
964 unsigned DiagID;
965 if (Function->getPrimaryTemplate())
966 DiagID = diag::note_function_template_spec_here;
967 else
968 DiagID = diag::note_template_member_function_here;
969 DiagFunc(Active->PointOfInstantiation,
970 PDiag(DiagID) << Function << Active->InstantiationRange);
971 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
972 DiagFunc(Active->PointOfInstantiation,
973 PDiag(VD->isStaticDataMember()
974 ? diag::note_template_static_data_member_def_here
975 : diag::note_template_variable_def_here)
976 << VD << Active->InstantiationRange);
977 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
978 DiagFunc(Active->PointOfInstantiation,
979 PDiag(diag::note_template_enum_def_here)
980 << ED << Active->InstantiationRange);
981 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
982 DiagFunc(Active->PointOfInstantiation,
983 PDiag(diag::note_template_nsdmi_here)
984 << FD << Active->InstantiationRange);
985 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
986 DiagFunc(Active->PointOfInstantiation,
987 PDiag(diag::note_template_class_instantiation_here)
988 << CTD << Active->InstantiationRange);
989 }
990 break;
991 }
992
994 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
995 SmallString<128> TemplateArgsStr;
996 llvm::raw_svector_ostream OS(TemplateArgsStr);
997 Template->printName(OS, getPrintingPolicy());
998 printTemplateArgumentList(OS, Active->template_arguments(),
1000 DiagFunc(Active->PointOfInstantiation,
1001 PDiag(diag::note_default_arg_instantiation_here)
1002 << OS.str() << Active->InstantiationRange);
1003 break;
1004 }
1005
1007 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1008 DiagFunc(Active->PointOfInstantiation,
1009 PDiag(diag::note_explicit_template_arg_substitution_here)
1010 << FnTmpl
1012 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1013 Active->NumTemplateArgs)
1014 << Active->InstantiationRange);
1015 break;
1016 }
1017
1019 if (FunctionTemplateDecl *FnTmpl =
1020 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1021 DiagFunc(
1022 Active->PointOfInstantiation,
1023 PDiag(diag::note_function_template_deduction_instantiation_here)
1024 << FnTmpl
1026 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1027 Active->NumTemplateArgs)
1028 << Active->InstantiationRange);
1029 } else {
1030 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1031 isa<VarTemplateSpecializationDecl>(Active->Entity);
1032 bool IsTemplate = false;
1033 TemplateParameterList *Params;
1034 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1035 IsTemplate = true;
1036 Params = D->getTemplateParameters();
1037 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1038 Active->Entity)) {
1039 Params = D->getTemplateParameters();
1040 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1041 Active->Entity)) {
1042 Params = D->getTemplateParameters();
1043 } else {
1044 llvm_unreachable("unexpected template kind");
1045 }
1046
1047 DiagFunc(Active->PointOfInstantiation,
1048 PDiag(diag::note_deduced_template_arg_substitution_here)
1049 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1051 Active->TemplateArgs,
1052 Active->NumTemplateArgs)
1053 << Active->InstantiationRange);
1054 }
1055 break;
1056 }
1057
1059 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1060 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1061
1062 SmallString<128> TemplateArgsStr;
1063 llvm::raw_svector_ostream OS(TemplateArgsStr);
1065 printTemplateArgumentList(OS, Active->template_arguments(),
1067 DiagFunc(Active->PointOfInstantiation,
1068 PDiag(diag::note_default_function_arg_instantiation_here)
1069 << OS.str() << Active->InstantiationRange);
1070 break;
1071 }
1072
1074 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1075 std::string Name;
1076 if (!Parm->getName().empty())
1077 Name = std::string(" '") + Parm->getName().str() + "'";
1078
1079 TemplateParameterList *TemplateParams = nullptr;
1080 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1081 TemplateParams = Template->getTemplateParameters();
1082 else
1083 TemplateParams =
1085 ->getTemplateParameters();
1086 DiagFunc(Active->PointOfInstantiation,
1087 PDiag(diag::note_prior_template_arg_substitution)
1088 << isa<TemplateTemplateParmDecl>(Parm) << Name
1089 << getTemplateArgumentBindingsText(TemplateParams,
1090 Active->TemplateArgs,
1091 Active->NumTemplateArgs)
1092 << Active->InstantiationRange);
1093 break;
1094 }
1095
1097 TemplateParameterList *TemplateParams = nullptr;
1098 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1099 TemplateParams = Template->getTemplateParameters();
1100 else
1101 TemplateParams =
1103 ->getTemplateParameters();
1104
1105 DiagFunc(Active->PointOfInstantiation,
1106 PDiag(diag::note_template_default_arg_checking)
1107 << getTemplateArgumentBindingsText(TemplateParams,
1108 Active->TemplateArgs,
1109 Active->NumTemplateArgs)
1110 << Active->InstantiationRange);
1111 break;
1112 }
1113
1115 DiagFunc(Active->PointOfInstantiation,
1116 PDiag(diag::note_evaluating_exception_spec_here)
1117 << cast<FunctionDecl>(Active->Entity));
1118 break;
1119
1121 DiagFunc(Active->PointOfInstantiation,
1122 PDiag(diag::note_template_exception_spec_instantiation_here)
1123 << cast<FunctionDecl>(Active->Entity)
1124 << Active->InstantiationRange);
1125 break;
1126
1128 DiagFunc(Active->PointOfInstantiation,
1129 PDiag(diag::note_template_requirement_instantiation_here)
1130 << Active->InstantiationRange);
1131 break;
1133 DiagFunc(Active->PointOfInstantiation,
1134 PDiag(diag::note_template_requirement_params_instantiation_here)
1135 << Active->InstantiationRange);
1136 break;
1137
1139 DiagFunc(Active->PointOfInstantiation,
1140 PDiag(diag::note_nested_requirement_here)
1141 << Active->InstantiationRange);
1142 break;
1143
1145 DiagFunc(Active->PointOfInstantiation,
1146 PDiag(diag::note_in_declaration_of_implicit_special_member)
1147 << cast<CXXRecordDecl>(Active->Entity)
1148 << Active->SpecialMember);
1149 break;
1150
1152 DiagFunc(
1153 Active->Entity->getLocation(),
1154 PDiag(diag::note_in_declaration_of_implicit_equality_comparison));
1155 break;
1156
1158 // FIXME: For synthesized functions that are not defaulted,
1159 // produce a note.
1160 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1161 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1162 // will ensure that DFK.isComparison() is false. This is important because
1163 // we will uncondtionally dereference FD in the else if.
1166 if (DFK.isSpecialMember()) {
1167 auto *MD = cast<CXXMethodDecl>(FD);
1168 DiagFunc(Active->PointOfInstantiation,
1169 PDiag(diag::note_member_synthesized_at)
1170 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1171 << Context.getCanonicalTagType(MD->getParent()));
1172 } else if (DFK.isComparison()) {
1173 QualType RecordType = FD->getParamDecl(0)
1174 ->getType()
1175 .getNonReferenceType()
1176 .getUnqualifiedType();
1177 DiagFunc(Active->PointOfInstantiation,
1178 PDiag(diag::note_comparison_synthesized_at)
1179 << (int)DFK.asComparison() << RecordType);
1180 }
1181 break;
1182 }
1183
1185 DiagFunc(Active->Entity->getLocation(),
1186 PDiag(diag::note_rewriting_operator_as_spaceship));
1187 break;
1188
1190 DiagFunc(Active->PointOfInstantiation,
1191 PDiag(diag::note_in_binding_decl_init)
1192 << cast<BindingDecl>(Active->Entity));
1193 break;
1194
1196 DiagFunc(Active->PointOfInstantiation,
1197 PDiag(diag::note_due_to_dllexported_class)
1198 << cast<CXXRecordDecl>(Active->Entity)
1199 << !getLangOpts().CPlusPlus11);
1200 break;
1201
1203 DiagFunc(Active->PointOfInstantiation,
1204 PDiag(diag::note_building_builtin_dump_struct_call)
1206 *this, llvm::ArrayRef(Active->CallArgs,
1207 Active->NumCallArgs)));
1208 break;
1209
1211 break;
1212
1214 DiagFunc(Active->PointOfInstantiation,
1215 PDiag(diag::note_lambda_substitution_here));
1216 break;
1218 unsigned DiagID = 0;
1219 if (!Active->Entity) {
1220 DiagFunc(Active->PointOfInstantiation,
1221 PDiag(diag::note_nested_requirement_here)
1222 << Active->InstantiationRange);
1223 break;
1224 }
1225 if (isa<ConceptDecl>(Active->Entity))
1226 DiagID = diag::note_concept_specialization_here;
1227 else if (isa<TemplateDecl>(Active->Entity))
1228 DiagID = diag::note_checking_constraints_for_template_id_here;
1229 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1230 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1231 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1232 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1233 else {
1234 assert(isa<FunctionDecl>(Active->Entity));
1235 DiagID = diag::note_checking_constraints_for_function_here;
1236 }
1237 SmallString<128> TemplateArgsStr;
1238 llvm::raw_svector_ostream OS(TemplateArgsStr);
1239 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1240 if (!isa<FunctionDecl>(Active->Entity)) {
1241 printTemplateArgumentList(OS, Active->template_arguments(),
1243 }
1244 DiagFunc(Active->PointOfInstantiation,
1245 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1246 break;
1247 }
1249 DiagFunc(Active->PointOfInstantiation,
1250 PDiag(diag::note_constraint_substitution_here)
1251 << Active->InstantiationRange);
1252 break;
1254 DiagFunc(Active->PointOfInstantiation,
1255 PDiag(diag::note_constraint_normalization_here)
1256 << cast<NamedDecl>(Active->Entity)
1257 << Active->InstantiationRange);
1258 break;
1260 DiagFunc(Active->PointOfInstantiation,
1261 PDiag(diag::note_parameter_mapping_substitution_here)
1262 << Active->InstantiationRange);
1263 break;
1265 DiagFunc(Active->PointOfInstantiation,
1266 PDiag(diag::note_building_deduction_guide_here));
1267 break;
1269 DiagFunc(Active->PointOfInstantiation,
1270 PDiag(diag::note_template_type_alias_instantiation_here)
1271 << cast<TypeAliasTemplateDecl>(Active->Entity)
1272 << Active->InstantiationRange);
1273 break;
1275 DiagFunc(Active->PointOfInstantiation,
1276 PDiag(diag::note_template_arg_template_params_mismatch));
1277 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1278 ParamLoc.isValid())
1279 DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration)
1280 << /*isTemplateTemplateParam=*/true
1281 << Active->InstantiationRange);
1282 break;
1283 }
1284 }
1285}
1286
1287std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1289 return std::optional<TemplateDeductionInfo *>(nullptr);
1290
1292 Active = CodeSynthesisContexts.rbegin(),
1293 ActiveEnd = CodeSynthesisContexts.rend();
1294 Active != ActiveEnd;
1295 ++Active)
1296 {
1297 switch (Active->Kind) {
1299 // An instantiation of an alias template may or may not be a SFINAE
1300 // context, depending on what else is on the stack.
1301 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1302 break;
1303 [[fallthrough]];
1311 // This is a template instantiation, so there is no SFINAE.
1312 return std::nullopt;
1314 // [temp.deduct]p9
1315 // A lambda-expression appearing in a function type or a template
1316 // parameter is not considered part of the immediate context for the
1317 // purposes of template argument deduction.
1318 // CWG2672: A lambda-expression body is never in the immediate context.
1319 return std::nullopt;
1320
1326 // A default template argument instantiation and substitution into
1327 // template parameters with arguments for prior parameters may or may
1328 // not be a SFINAE context; look further up the stack.
1329 break;
1330
1333 // We're either substituting explicitly-specified template arguments,
1334 // deduced template arguments. SFINAE applies unless we are in a lambda
1335 // body, see [temp.deduct]p9.
1339 // SFINAE always applies in a constraint expression or a requirement
1340 // in a requires expression.
1341 assert(Active->DeductionInfo && "Missing deduction info pointer");
1342 return Active->DeductionInfo;
1343
1351 // This happens in a context unrelated to template instantiation, so
1352 // there is no SFINAE.
1353 return std::nullopt;
1354
1356 // FIXME: This should not be treated as a SFINAE context, because
1357 // we will cache an incorrect exception specification. However, clang
1358 // bootstrap relies this! See PR31692.
1359 break;
1360
1362 break;
1363 }
1364
1365 // The inner context was transparent for SFINAE. If it occurred within a
1366 // non-instantiation SFINAE context, then SFINAE applies.
1367 if (Active->SavedInNonInstantiationSFINAEContext)
1368 return std::optional<TemplateDeductionInfo *>(nullptr);
1369 }
1370
1371 return std::nullopt;
1372}
1373
1374//===----------------------------------------------------------------------===/
1375// Template Instantiation for Types
1376//===----------------------------------------------------------------------===/
1377namespace {
1378 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1379 const MultiLevelTemplateArgumentList &TemplateArgs;
1380 SourceLocation Loc;
1381 DeclarationName Entity;
1382 // Whether to evaluate the C++20 constraints or simply substitute into them.
1383 bool EvaluateConstraints = true;
1384 // Whether Substitution was Incomplete, that is, we tried to substitute in
1385 // any user provided template arguments which were null.
1386 bool IsIncomplete = false;
1387 // Whether an incomplete substituion should be treated as an error.
1388 bool BailOutOnIncomplete;
1389
1390 private:
1391 // CWG2770: Function parameters should be instantiated when they are
1392 // needed by a satisfaction check of an atomic constraint or
1393 // (recursively) by another function parameter.
1394 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1395
1396 public:
1397 typedef TreeTransform<TemplateInstantiator> inherited;
1398
1399 TemplateInstantiator(Sema &SemaRef,
1400 const MultiLevelTemplateArgumentList &TemplateArgs,
1401 SourceLocation Loc, DeclarationName Entity,
1402 bool BailOutOnIncomplete = false)
1403 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1404 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1405
1406 void setEvaluateConstraints(bool B) {
1407 EvaluateConstraints = B;
1408 }
1409 bool getEvaluateConstraints() {
1410 return EvaluateConstraints;
1411 }
1412
1413 /// Determine whether the given type \p T has already been
1414 /// transformed.
1415 ///
1416 /// For the purposes of template instantiation, a type has already been
1417 /// transformed if it is NULL or if it is not dependent.
1418 bool AlreadyTransformed(QualType T);
1419
1420 /// Returns the location of the entity being instantiated, if known.
1421 SourceLocation getBaseLocation() { return Loc; }
1422
1423 /// Returns the name of the entity being instantiated, if any.
1424 DeclarationName getBaseEntity() { return Entity; }
1425
1426 /// Returns whether any substitution so far was incomplete.
1427 bool getIsIncomplete() const { return IsIncomplete; }
1428
1429 /// Sets the "base" location and entity when that
1430 /// information is known based on another transformation.
1431 void setBase(SourceLocation Loc, DeclarationName Entity) {
1432 this->Loc = Loc;
1433 this->Entity = Entity;
1434 }
1435
1436 unsigned TransformTemplateDepth(unsigned Depth) {
1437 return TemplateArgs.getNewDepth(Depth);
1438 }
1439
1440 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1441 SourceRange PatternRange,
1442 ArrayRef<UnexpandedParameterPack> Unexpanded,
1443 bool FailOnPackProducingTemplates,
1444 bool &ShouldExpand, bool &RetainExpansion,
1445 UnsignedOrNone &NumExpansions) {
1446 if (SemaRef.CurrentInstantiationScope &&
1447 SemaRef.inConstraintSubstitution()) {
1448 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1449 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1450 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);
1451 PVD && maybeInstantiateFunctionParameterToScope(PVD))
1452 return true;
1453 }
1454 }
1455
1456 return getSema().CheckParameterPacksForExpansion(
1457 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1458 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1459 NumExpansions);
1460 }
1461
1462 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1464 }
1465
1466 TemplateArgument ForgetPartiallySubstitutedPack() {
1467 TemplateArgument Result;
1468 if (NamedDecl *PartialPack
1470 MultiLevelTemplateArgumentList &TemplateArgs
1471 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1472 unsigned Depth, Index;
1473 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1474 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1475 Result = TemplateArgs(Depth, Index);
1476 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1477 } else {
1478 IsIncomplete = true;
1479 if (BailOutOnIncomplete)
1480 return TemplateArgument();
1481 }
1482 }
1483
1484 return Result;
1485 }
1486
1487 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1488 if (Arg.isNull())
1489 return;
1490
1491 if (NamedDecl *PartialPack
1493 MultiLevelTemplateArgumentList &TemplateArgs
1494 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1495 unsigned Depth, Index;
1496 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1497 TemplateArgs.setArgument(Depth, Index, Arg);
1498 }
1499 }
1500
1501 MultiLevelTemplateArgumentList ForgetSubstitution() {
1502 MultiLevelTemplateArgumentList New;
1503 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1504
1505 MultiLevelTemplateArgumentList Old =
1506 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1507 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1508 std::move(New);
1509 return Old;
1510 }
1511 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1512 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1513 std::move(Old);
1514 }
1515
1516 TemplateArgument
1517 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1518 if (TA.getKind() != TemplateArgument::Pack)
1519 return TA;
1520 if (SemaRef.ArgPackSubstIndex)
1521 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1522 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1523 "unexpected pack arguments in template rewrite");
1524 TemplateArgument Arg = *TA.pack_begin();
1525 if (Arg.isPackExpansion())
1526 Arg = Arg.getPackExpansionPattern();
1527 return Arg;
1528 }
1529
1530 /// Transform the given declaration by instantiating a reference to
1531 /// this declaration.
1532 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1533
1534 void transformAttrs(Decl *Old, Decl *New) {
1535 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1536 }
1537
1538 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1539 if (Old->isParameterPack() &&
1540 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1542 for (auto *New : NewDecls)
1544 Old, cast<VarDecl>(New));
1545 return;
1546 }
1547
1548 assert(NewDecls.size() == 1 &&
1549 "should only have multiple expansions for a pack");
1550 Decl *New = NewDecls.front();
1551
1552 // If we've instantiated the call operator of a lambda or the call
1553 // operator template of a generic lambda, update the "instantiation of"
1554 // information.
1555 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1556 if (NewMD && isLambdaCallOperator(NewMD)) {
1557 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1558 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1559 NewTD->setInstantiatedFromMemberTemplate(
1560 OldMD->getDescribedFunctionTemplate());
1561 else
1562 NewMD->setInstantiationOfMemberFunction(OldMD,
1564 }
1565
1567
1568 // We recreated a local declaration, but not by instantiating it. There
1569 // may be pending dependent diagnostics to produce.
1570 if (auto *DC = dyn_cast<DeclContext>(Old);
1571 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1572 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1573 }
1574
1575 /// Transform the definition of the given declaration by
1576 /// instantiating it.
1577 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1578
1579 /// Transform the first qualifier within a scope by instantiating the
1580 /// declaration.
1581 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1582
1583 bool TransformExceptionSpec(SourceLocation Loc,
1584 FunctionProtoType::ExceptionSpecInfo &ESI,
1585 SmallVectorImpl<QualType> &Exceptions,
1586 bool &Changed);
1587
1588 /// Rebuild the exception declaration and register the declaration
1589 /// as an instantiated local.
1590 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1591 TypeSourceInfo *Declarator,
1592 SourceLocation StartLoc,
1593 SourceLocation NameLoc,
1594 IdentifierInfo *Name);
1595
1596 /// Rebuild the Objective-C exception declaration and register the
1597 /// declaration as an instantiated local.
1598 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1599 TypeSourceInfo *TSInfo, QualType T);
1600
1602 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1603 SourceLocation TemplateKWLoc, TemplateName Name,
1604 SourceLocation NameLoc,
1605 QualType ObjectType = QualType(),
1606 NamedDecl *FirstQualifierInScope = nullptr,
1607 bool AllowInjectedClassName = false);
1608
1609 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1610 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1611 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1612 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1613 const Stmt *InstS,
1614 const NoInlineAttr *A);
1615 const AlwaysInlineAttr *
1616 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1617 const AlwaysInlineAttr *A);
1618 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1619 const OpenACCRoutineDeclAttr *
1620 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1621 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1622 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1623 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1624
1625 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1626 NonTypeTemplateParmDecl *D);
1627
1628 /// Rebuild a DeclRefExpr for a VarDecl reference.
1629 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1630
1631 /// Transform a reference to a function or init-capture parameter pack.
1632 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1633
1634 /// Transform a FunctionParmPackExpr which was built when we couldn't
1635 /// expand a function parameter pack reference which refers to an expanded
1636 /// pack.
1637 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1638
1639 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1640 FunctionProtoTypeLoc TL) {
1641 // Call the base version; it will forward to our overridden version below.
1642 return inherited::TransformFunctionProtoType(TLB, TL);
1643 }
1644
1645 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1646 auto Type = inherited::TransformTagType(TLB, TL);
1647 if (!Type.isNull())
1648 return Type;
1649 // Special case for transforming a deduction guide, we return a
1650 // transformed TemplateSpecializationType.
1651 // FIXME: Why is this hack necessary?
1652 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1653 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1655 Type = inherited::TransformType(
1656 ICNT->getOriginalDecl()->getCanonicalTemplateSpecializationType(
1657 SemaRef.Context));
1658 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1659 }
1660 return Type;
1661 }
1662 // Override the default version to handle a rewrite-template-arg-pack case
1663 // for building a deduction guide.
1664 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1665 TemplateArgumentLoc &Output,
1666 bool Uneval = false) {
1667 const TemplateArgument &Arg = Input.getArgument();
1668 std::vector<TemplateArgument> TArgs;
1669 switch (Arg.getKind()) {
1671 assert(SemaRef.CodeSynthesisContexts.empty() ||
1672 SemaRef.CodeSynthesisContexts.back().Kind ==
1674 // Literally rewrite the template argument pack, instead of unpacking
1675 // it.
1676 for (auto &pack : Arg.getPackAsArray()) {
1677 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1678 pack, QualType(), SourceLocation{});
1679 TemplateArgumentLoc Output;
1680 if (TransformTemplateArgument(Input, Output, Uneval))
1681 return true; // fails
1682 TArgs.push_back(Output.getArgument());
1683 }
1684 Output = SemaRef.getTrivialTemplateArgumentLoc(
1685 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1686 QualType(), SourceLocation{});
1687 return false;
1688 default:
1689 break;
1690 }
1691 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1692 }
1693
1695 QualType
1696 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1697 TemplateSpecializationTypeLoc TL) {
1698 auto *T = TL.getTypePtr();
1699 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1700 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1702 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1703 // need to substitute into.
1704
1705 // `TransformType` code below will handle picking the element from a pack
1706 // with the index `ArgPackSubstIndex`.
1707 // FIXME: add ability to represent sugarred type for N-th element of a
1708 // builtin pack and produce the sugar here.
1709 QualType R = TransformType(T->desugar());
1710 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1711 return R;
1712 }
1713
1714 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1715 ArrayRef<TemplateArgument> PackArgs) {
1716 // Don't do this when rewriting template parameters for CTAD:
1717 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1718 // expanded size, but this never applies since Subst* nodes are not
1719 // created in rewrite scenarios.
1720 //
1721 // 2) The heuristic substitutes into the pattern with pack expansion
1722 // suppressed, which does not meet the requirements for argument
1723 // rewriting when template arguments include a non-pack matching against
1724 // a pack, particularly when rewriting an alias CTAD.
1725 if (TemplateArgs.isRewrite())
1726 return std::nullopt;
1727
1728 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1729 }
1730
1731 template<typename Fn>
1732 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1733 FunctionProtoTypeLoc TL,
1734 CXXRecordDecl *ThisContext,
1735 Qualifiers ThisTypeQuals,
1736 Fn TransformExceptionSpec);
1737
1738 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1739 int indexAdjustment,
1740 UnsignedOrNone NumExpansions,
1741 bool ExpectParameterPack);
1742
1743 using inherited::TransformTemplateTypeParmType;
1744 /// Transforms a template type parameter type by performing
1745 /// substitution of the corresponding template type argument.
1746 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1747 TemplateTypeParmTypeLoc TL,
1748 bool SuppressObjCLifetime);
1749
1750 QualType BuildSubstTemplateTypeParmType(
1751 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1752 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1753 TemplateArgument Arg, SourceLocation NameLoc);
1754
1755 /// Transforms an already-substituted template type parameter pack
1756 /// into either itself (if we aren't substituting into its pack expansion)
1757 /// or the appropriate substituted argument.
1758 using inherited::TransformSubstTemplateTypeParmPackType;
1759 QualType
1760 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1761 SubstTemplateTypeParmPackTypeLoc TL,
1762 bool SuppressObjCLifetime);
1763 QualType
1764 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1765 SubstBuiltinTemplatePackTypeLoc TL);
1766
1768 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1769 if (auto TypeAlias =
1770 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1771 getSema());
1772 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1773 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1774 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1775 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1776 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1777 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1778 if (TA.isDependent())
1779 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1780 }
1781 return inherited::ComputeLambdaDependency(LSI);
1782 }
1783
1784 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1785 // Do not rebuild lambdas to avoid creating a new type.
1786 // Lambdas have already been processed inside their eval contexts.
1788 return E;
1789 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1790 /*InstantiatingLambdaOrBlock=*/true);
1791 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1792
1793 return inherited::TransformLambdaExpr(E);
1794 }
1795
1796 ExprResult TransformBlockExpr(BlockExpr *E) {
1797 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1798 /*InstantiatingLambdaOrBlock=*/true);
1799 return inherited::TransformBlockExpr(E);
1800 }
1801
1802 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1803 LambdaScopeInfo *LSI) {
1804 CXXMethodDecl *MD = LSI->CallOperator;
1805 for (ParmVarDecl *PVD : MD->parameters()) {
1806 assert(PVD && "null in a parameter list");
1807 if (!PVD->hasDefaultArg())
1808 continue;
1809 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1810 // FIXME: Obtain the source location for the '=' token.
1811 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1812 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1813 // If substitution fails, the default argument is set to a
1814 // RecoveryExpr that wraps the uninstantiated default argument so
1815 // that downstream diagnostics are omitted.
1816 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1817 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1818 UninstExpr->getType());
1819 if (ErrorResult.isUsable())
1820 PVD->setDefaultArg(ErrorResult.get());
1821 }
1822 }
1823 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1824 }
1825
1826 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1827 // Currently, we instantiate the body when instantiating the lambda
1828 // expression. However, `EvaluateConstraints` is disabled during the
1829 // instantiation of the lambda expression, causing the instantiation
1830 // failure of the return type requirement in the body. If p0588r1 is fully
1831 // implemented, the body will be lazily instantiated, and this problem
1832 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1833 // `true` to temporarily fix this issue.
1834 // FIXME: This temporary fix can be removed after fully implementing
1835 // p0588r1.
1836 llvm::SaveAndRestore _(EvaluateConstraints, true);
1837 return inherited::TransformLambdaBody(E, Body);
1838 }
1839
1840 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1841 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1842 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1843 if (TransReq.isInvalid())
1844 return TransReq;
1845 assert(TransReq.get() != E &&
1846 "Do not change value of isSatisfied for the existing expression. "
1847 "Create a new expression instead.");
1848 if (E->getBody()->isDependentContext()) {
1849 Sema::SFINAETrap Trap(SemaRef);
1850 // We recreate the RequiresExpr body, but not by instantiating it.
1851 // Produce pending diagnostics for dependent access check.
1852 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1853 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1854 if (Trap.hasErrorOccurred())
1855 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1856 }
1857 return TransReq;
1858 }
1859
1860 bool TransformRequiresExprRequirements(
1861 ArrayRef<concepts::Requirement *> Reqs,
1862 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1863 bool SatisfactionDetermined = false;
1864 for (concepts::Requirement *Req : Reqs) {
1865 concepts::Requirement *TransReq = nullptr;
1866 if (!SatisfactionDetermined) {
1867 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1868 TransReq = TransformTypeRequirement(TypeReq);
1869 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1870 TransReq = TransformExprRequirement(ExprReq);
1871 else
1872 TransReq = TransformNestedRequirement(
1874 if (!TransReq)
1875 return true;
1876 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1877 // [expr.prim.req]p6
1878 // [...] The substitution and semantic constraint checking
1879 // proceeds in lexical order and stops when a condition that
1880 // determines the result of the requires-expression is
1881 // encountered. [..]
1882 SatisfactionDetermined = true;
1883 } else
1884 TransReq = Req;
1885 Transformed.push_back(TransReq);
1886 }
1887 return false;
1888 }
1889
1890 TemplateParameterList *TransformTemplateParameterList(
1891 TemplateParameterList *OrigTPL) {
1892 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1893
1894 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1895 TemplateDeclInstantiator DeclInstantiator(getSema(),
1896 /* DeclContext *Owner */ Owner, TemplateArgs);
1897 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1898 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1899 }
1900
1901 concepts::TypeRequirement *
1902 TransformTypeRequirement(concepts::TypeRequirement *Req);
1903 concepts::ExprRequirement *
1904 TransformExprRequirement(concepts::ExprRequirement *Req);
1905 concepts::NestedRequirement *
1906 TransformNestedRequirement(concepts::NestedRequirement *Req);
1907 ExprResult TransformRequiresTypeParams(
1908 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1909 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1910 SmallVectorImpl<QualType> &PTypes,
1911 SmallVectorImpl<ParmVarDecl *> &TransParams,
1912 Sema::ExtParameterInfoBuilder &PInfos);
1913 };
1914}
1915
1916bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1917 if (T.isNull())
1918 return true;
1919
1922 return false;
1923
1924 getSema().MarkDeclarationsReferencedInType(Loc, T);
1925 return true;
1926}
1927
1928Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1929 if (!D)
1930 return nullptr;
1931
1932 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1933 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1934 // If the corresponding template argument is NULL or non-existent, it's
1935 // because we are performing instantiation from explicitly-specified
1936 // template arguments in a function template, but there were some
1937 // arguments left unspecified.
1938 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1939 TTP->getPosition())) {
1940 IsIncomplete = true;
1941 return BailOutOnIncomplete ? nullptr : D;
1942 }
1943
1944 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1945
1946 if (TTP->isParameterPack()) {
1947 assert(Arg.getKind() == TemplateArgument::Pack &&
1948 "Missing argument pack");
1949 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1950 }
1951
1953 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1954 "Wrong kind of template template argument");
1955 return Template.getAsTemplateDecl();
1956 }
1957
1958 // Fall through to find the instantiated declaration for this template
1959 // template parameter.
1960 }
1961
1962 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);
1963 PVD && SemaRef.CurrentInstantiationScope &&
1964 SemaRef.inConstraintSubstitution() &&
1965 maybeInstantiateFunctionParameterToScope(PVD))
1966 return nullptr;
1967
1968 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1969}
1970
1971bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
1972 ParmVarDecl *OldParm) {
1973 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))
1974 return false;
1975
1976 if (!OldParm->isParameterPack())
1977 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
1978 /*NumExpansions=*/std::nullopt,
1979 /*ExpectParameterPack=*/false);
1980
1981 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
1982
1983 // Find the parameter packs that could be expanded.
1984 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
1985 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
1986 TypeLoc Pattern = ExpansionTL.getPatternLoc();
1987 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
1988 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
1989
1990 bool ShouldExpand = false;
1991 bool RetainExpansion = false;
1992 UnsignedOrNone OrigNumExpansions =
1993 ExpansionTL.getTypePtr()->getNumExpansions();
1994 UnsignedOrNone NumExpansions = OrigNumExpansions;
1995 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
1996 Pattern.getSourceRange(), Unexpanded,
1997 /*FailOnPackProducingTemplates=*/true,
1998 ShouldExpand, RetainExpansion, NumExpansions))
1999 return true;
2000
2001 assert(ShouldExpand && !RetainExpansion &&
2002 "Shouldn't preserve pack expansion when evaluating constraints");
2003 ExpandingFunctionParameterPack(OldParm);
2004 for (unsigned I = 0; I != *NumExpansions; ++I) {
2005 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2006 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2007 /*NumExpansions=*/OrigNumExpansions,
2008 /*ExpectParameterPack=*/false))
2009 return true;
2010 }
2011 return false;
2012}
2013
2014Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2015 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
2016 if (!Inst)
2017 return nullptr;
2018
2019 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2020 return Inst;
2021}
2022
2023bool TemplateInstantiator::TransformExceptionSpec(
2024 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2025 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2026 if (ESI.Type == EST_Uninstantiated) {
2027 ESI.instantiate();
2028 Changed = true;
2029 }
2030 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2031}
2032
2033NamedDecl *
2034TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2035 SourceLocation Loc) {
2036 // If the first part of the nested-name-specifier was a template type
2037 // parameter, instantiate that type parameter down to a tag type.
2038 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
2039 const TemplateTypeParmType *TTP
2040 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
2041
2042 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2043 // FIXME: This needs testing w/ member access expressions.
2044 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2045
2046 if (TTP->isParameterPack()) {
2047 assert(Arg.getKind() == TemplateArgument::Pack &&
2048 "Missing argument pack");
2049
2050 if (!getSema().ArgPackSubstIndex)
2051 return nullptr;
2052
2053 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2054 }
2055
2056 QualType T = Arg.getAsType();
2057 if (T.isNull())
2058 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2059
2060 if (const TagType *Tag = T->getAs<TagType>())
2061 return Tag->getOriginalDecl();
2062
2063 // The resulting type is not a tag; complain.
2064 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2065 return nullptr;
2066 }
2067 }
2068
2069 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2070}
2071
2072VarDecl *
2073TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2074 TypeSourceInfo *Declarator,
2075 SourceLocation StartLoc,
2076 SourceLocation NameLoc,
2077 IdentifierInfo *Name) {
2078 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2079 StartLoc, NameLoc, Name);
2080 if (Var)
2081 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2082 return Var;
2083}
2084
2085VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2086 TypeSourceInfo *TSInfo,
2087 QualType T) {
2088 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2089 if (Var)
2090 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2091 return Var;
2092}
2093
2094TemplateName TemplateInstantiator::TransformTemplateName(
2095 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2096 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2097 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2098 if (Name.getKind() == TemplateName::Template) {
2099 assert(!QualifierLoc && "Unexpected qualifier");
2100 if (auto *TTP =
2101 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2102 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2103 // If the corresponding template argument is NULL or non-existent, it's
2104 // because we are performing instantiation from explicitly-specified
2105 // template arguments in a function template, but there were some
2106 // arguments left unspecified.
2107 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2108 TTP->getPosition())) {
2109 IsIncomplete = true;
2110 return BailOutOnIncomplete ? TemplateName() : Name;
2111 }
2112
2113 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2114
2115 if (TemplateArgs.isRewrite()) {
2116 // We're rewriting the template parameter as a reference to another
2117 // template parameter.
2118 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2119 assert(Arg.getKind() == TemplateArgument::Template &&
2120 "unexpected nontype template argument kind in template rewrite");
2121 return Arg.getAsTemplate();
2122 }
2123
2124 auto [AssociatedDecl, Final] =
2125 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2126 UnsignedOrNone PackIndex = std::nullopt;
2127 if (TTP->isParameterPack()) {
2128 assert(Arg.getKind() == TemplateArgument::Pack &&
2129 "Missing argument pack");
2130
2131 if (!getSema().ArgPackSubstIndex) {
2132 // We have the template argument pack to substitute, but we're not
2133 // actually expanding the enclosing pack expansion yet. So, just
2134 // keep the entire argument pack.
2135 return getSema().Context.getSubstTemplateTemplateParmPack(
2136 Arg, AssociatedDecl, TTP->getIndex(), Final);
2137 }
2138
2139 PackIndex = SemaRef.getPackIndex(Arg);
2140 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2141 }
2142
2144 assert(!Template.isNull() && "Null template template argument");
2145 return getSema().Context.getSubstTemplateTemplateParm(
2146 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2147 }
2148 }
2149
2150 if (SubstTemplateTemplateParmPackStorage *SubstPack
2152 if (!getSema().ArgPackSubstIndex)
2153 return Name;
2154
2155 TemplateArgument Pack = SubstPack->getArgumentPack();
2157 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2158 return getSema().Context.getSubstTemplateTemplateParm(
2159 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2160 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2161 }
2162
2163 return inherited::TransformTemplateName(
2164 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2165 FirstQualifierInScope, AllowInjectedClassName);
2166}
2167
2169TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2170 if (!E->isTypeDependent())
2171 return E;
2172
2173 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2174}
2175
2177TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2178 NonTypeTemplateParmDecl *NTTP) {
2179 // If the corresponding template argument is NULL or non-existent, it's
2180 // because we are performing instantiation from explicitly-specified
2181 // template arguments in a function template, but there were some
2182 // arguments left unspecified.
2183 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2184 NTTP->getPosition())) {
2185 IsIncomplete = true;
2186 return BailOutOnIncomplete ? ExprError() : E;
2187 }
2188
2189 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2190
2191 if (TemplateArgs.isRewrite()) {
2192 // We're rewriting the template parameter as a reference to another
2193 // template parameter.
2194 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2195 assert(Arg.getKind() == TemplateArgument::Expression &&
2196 "unexpected nontype template argument kind in template rewrite");
2197 // FIXME: This can lead to the same subexpression appearing multiple times
2198 // in a complete expression.
2199 return Arg.getAsExpr();
2200 }
2201
2202 auto [AssociatedDecl, Final] =
2203 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2204 UnsignedOrNone PackIndex = std::nullopt;
2205 if (NTTP->isParameterPack()) {
2206 assert(Arg.getKind() == TemplateArgument::Pack &&
2207 "Missing argument pack");
2208
2209 if (!getSema().ArgPackSubstIndex) {
2210 // We have an argument pack, but we can't select a particular argument
2211 // out of it yet. Therefore, we'll build an expression to hold on to that
2212 // argument pack.
2213 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2214 E->getLocation(),
2215 NTTP->getDeclName());
2216 if (TargetType.isNull())
2217 return ExprError();
2218
2219 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2220 if (TargetType->isRecordType())
2221 ExprType.addConst();
2222 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2223 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2224 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2225 }
2226 PackIndex = SemaRef.getPackIndex(Arg);
2227 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2228 }
2229 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2230 AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);
2231}
2232
2233const AnnotateAttr *
2234TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2235 SmallVector<Expr *> Args;
2236 for (Expr *Arg : AA->args()) {
2237 ExprResult Res = getDerived().TransformExpr(Arg);
2238 if (Res.isUsable())
2239 Args.push_back(Res.get());
2240 }
2241 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2242 Args.data(), Args.size(), AA->getRange());
2243}
2244
2245const CXXAssumeAttr *
2246TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2247 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2248 if (!Res.isUsable())
2249 return AA;
2250
2251 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2252 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2253 AA->getRange());
2254 if (!Res.isUsable())
2255 return AA;
2256 }
2257
2258 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2259 AA->getRange());
2260}
2261
2262const LoopHintAttr *
2263TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2264 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2265
2266 if (TransformedExpr == LH->getValue())
2267 return LH;
2268
2269 // Generate error if there is a problem with the value.
2270 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2271 LH->getSemanticSpelling() ==
2272 LoopHintAttr::Pragma_unroll))
2273 return LH;
2274
2275 LoopHintAttr::OptionType Option = LH->getOption();
2276 LoopHintAttr::LoopHintState State = LH->getState();
2277
2278 llvm::APSInt ValueAPS =
2279 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2280 // The values of 0 and 1 block any unrolling of the loop.
2281 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2282 Option = LoopHintAttr::Unroll;
2283 State = LoopHintAttr::Disable;
2284 }
2285
2286 // Create new LoopHintValueAttr with integral expression in place of the
2287 // non-type template parameter.
2288 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2289 TransformedExpr, *LH);
2290}
2291const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2292 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2293 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2294 return nullptr;
2295
2296 return A;
2297}
2298const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2299 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2300 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2301 return nullptr;
2302
2303 return A;
2304}
2305
2306const CodeAlignAttr *
2307TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2308 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2309 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2310}
2311const OpenACCRoutineDeclAttr *
2312TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2313 const OpenACCRoutineDeclAttr *A) {
2314 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2315 "applies to a Function Decl (and a few places for VarDecl)");
2316}
2317
2318ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2319 SourceLocation Loc) {
2320 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2321 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2322}
2323
2325TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2326 if (getSema().ArgPackSubstIndex) {
2327 // We can expand this parameter pack now.
2328 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2329 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2330 if (!VD)
2331 return ExprError();
2332 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2333 }
2334
2335 QualType T = TransformType(E->getType());
2336 if (T.isNull())
2337 return ExprError();
2338
2339 // Transform each of the parameter expansions into the corresponding
2340 // parameters in the instantiation of the function decl.
2341 SmallVector<ValueDecl *, 8> Vars;
2342 Vars.reserve(E->getNumExpansions());
2343 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2344 I != End; ++I) {
2345 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2346 if (!D)
2347 return ExprError();
2348 Vars.push_back(D);
2349 }
2350
2351 auto *PackExpr =
2353 E->getParameterPackLocation(), Vars);
2354 getSema().MarkFunctionParmPackReferenced(PackExpr);
2355 return PackExpr;
2356}
2357
2359TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2360 ValueDecl *PD) {
2361 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2362 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2363 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2364 assert(Found && "no instantiation for parameter pack");
2365
2366 Decl *TransformedDecl;
2367 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2368 // If this is a reference to a function parameter pack which we can
2369 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2370 if (!getSema().ArgPackSubstIndex) {
2371 QualType T = TransformType(E->getType());
2372 if (T.isNull())
2373 return ExprError();
2374 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2375 E->getExprLoc(), *Pack);
2376 getSema().MarkFunctionParmPackReferenced(PackExpr);
2377 return PackExpr;
2378 }
2379
2380 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2381 } else {
2382 TransformedDecl = cast<Decl *>(*Found);
2383 }
2384
2385 // We have either an unexpanded pack or a specific expansion.
2386 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2387 E->getExprLoc());
2388}
2389
2391TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2392 NamedDecl *D = E->getDecl();
2393
2394 // Handle references to non-type template parameters and non-type template
2395 // parameter packs.
2396 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2397 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2398 return TransformTemplateParmRefExpr(E, NTTP);
2399
2400 // We have a non-type template parameter that isn't fully substituted;
2401 // FindInstantiatedDecl will find it in the local instantiation scope.
2402 }
2403
2404 // Handle references to function parameter packs.
2405 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2406 if (PD->isParameterPack())
2407 return TransformFunctionParmPackRefExpr(E, PD);
2408
2409 return inherited::TransformDeclRefExpr(E);
2410}
2411
2412ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2413 CXXDefaultArgExpr *E) {
2414 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2415 getDescribedFunctionTemplate() &&
2416 "Default arg expressions are never formed in dependent cases.");
2417 return SemaRef.BuildCXXDefaultArgExpr(
2419 E->getParam());
2420}
2421
2422template<typename Fn>
2423QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2424 FunctionProtoTypeLoc TL,
2425 CXXRecordDecl *ThisContext,
2426 Qualifiers ThisTypeQuals,
2427 Fn TransformExceptionSpec) {
2428 // If this is a lambda or block, the transformation MUST be done in the
2429 // CurrentInstantiationScope since it introduces a mapping of
2430 // the original to the newly created transformed parameters.
2431 //
2432 // In that case, TemplateInstantiator::TransformLambdaExpr will
2433 // have already pushed a scope for this prototype, so don't create
2434 // a second one.
2435 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2436 std::optional<LocalInstantiationScope> Scope;
2437 if (!Current || !Current->isLambdaOrBlock())
2438 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2439
2440 return inherited::TransformFunctionProtoType(
2441 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2442}
2443
2444ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2445 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2446 bool ExpectParameterPack) {
2447 auto NewParm = SemaRef.SubstParmVarDecl(
2448 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2449 ExpectParameterPack, EvaluateConstraints);
2450 if (NewParm && SemaRef.getLangOpts().OpenCL)
2451 SemaRef.deduceOpenCLAddressSpace(NewParm);
2452 return NewParm;
2453}
2454
2455QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2456 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2457 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2458 TemplateArgument Arg, SourceLocation NameLoc) {
2459 QualType Replacement = Arg.getAsType();
2460
2461 // If the template parameter had ObjC lifetime qualifiers,
2462 // then any such qualifiers on the replacement type are ignored.
2463 if (SuppressObjCLifetime) {
2464 Qualifiers RQs;
2465 RQs = Replacement.getQualifiers();
2466 RQs.removeObjCLifetime();
2467 Replacement =
2468 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2469 }
2470
2471 // TODO: only do this uniquing once, at the start of instantiation.
2472 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2473 Replacement, AssociatedDecl, Index, PackIndex, Final);
2474 SubstTemplateTypeParmTypeLoc NewTL =
2475 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2476 NewTL.setNameLoc(NameLoc);
2477 return Result;
2478}
2479
2480QualType
2481TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2482 TemplateTypeParmTypeLoc TL,
2483 bool SuppressObjCLifetime) {
2484 const TemplateTypeParmType *T = TL.getTypePtr();
2485 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2486 // Replace the template type parameter with its corresponding
2487 // template argument.
2488
2489 // If the corresponding template argument is NULL or doesn't exist, it's
2490 // because we are performing instantiation from explicitly-specified
2491 // template arguments in a function template class, but there were some
2492 // arguments left unspecified.
2493 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2494 IsIncomplete = true;
2495 if (BailOutOnIncomplete)
2496 return QualType();
2497
2498 TemplateTypeParmTypeLoc NewTL
2499 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2500 NewTL.setNameLoc(TL.getNameLoc());
2501 return TL.getType();
2502 }
2503
2504 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2505
2506 if (TemplateArgs.isRewrite()) {
2507 // We're rewriting the template parameter as a reference to another
2508 // template parameter.
2509 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2510 assert(Arg.getKind() == TemplateArgument::Type &&
2511 "unexpected nontype template argument kind in template rewrite");
2512 QualType NewT = Arg.getAsType();
2513 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2514 return NewT;
2515 }
2516
2517 auto [AssociatedDecl, Final] =
2518 TemplateArgs.getAssociatedDecl(T->getDepth());
2519 UnsignedOrNone PackIndex = std::nullopt;
2520 if (T->isParameterPack()) {
2521 assert(Arg.getKind() == TemplateArgument::Pack &&
2522 "Missing argument pack");
2523
2524 if (!getSema().ArgPackSubstIndex) {
2525 // We have the template argument pack, but we're not expanding the
2526 // enclosing pack expansion yet. Just save the template argument
2527 // pack for later substitution.
2528 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2529 AssociatedDecl, T->getIndex(), Final, Arg);
2530 SubstTemplateTypeParmPackTypeLoc NewTL
2531 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2532 NewTL.setNameLoc(TL.getNameLoc());
2533 return Result;
2534 }
2535
2536 // PackIndex starts from last element.
2537 PackIndex = SemaRef.getPackIndex(Arg);
2538 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2539 }
2540
2541 assert(Arg.getKind() == TemplateArgument::Type &&
2542 "Template argument kind mismatch");
2543
2544 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2545 AssociatedDecl, T->getIndex(),
2546 PackIndex, Arg, TL.getNameLoc());
2547 }
2548
2549 // The template type parameter comes from an inner template (e.g.,
2550 // the template parameter list of a member template inside the
2551 // template we are instantiating). Create a new template type
2552 // parameter with the template "level" reduced by one.
2553 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2554 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2555 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2556 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2557 QualType Result = getSema().Context.getTemplateTypeParmType(
2558 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2559 T->isParameterPack(), NewTTPDecl);
2560 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2561 NewTL.setNameLoc(TL.getNameLoc());
2562 return Result;
2563}
2564
2565QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2566 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2567 bool SuppressObjCLifetime) {
2568 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2569
2570 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2571
2572 if (!getSema().ArgPackSubstIndex) {
2573 // We aren't expanding the parameter pack, so just return ourselves.
2574 QualType Result = TL.getType();
2575 if (NewReplaced != T->getAssociatedDecl())
2576 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2577 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2578 SubstTemplateTypeParmPackTypeLoc NewTL =
2579 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2580 NewTL.setNameLoc(TL.getNameLoc());
2581 return Result;
2582 }
2583
2584 TemplateArgument Pack = T->getArgumentPack();
2585 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2586 return BuildSubstTemplateTypeParmType(
2587 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2588 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2589}
2590
2591QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2592 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2593 if (!getSema().ArgPackSubstIndex)
2594 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2595 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2596 TL.getTypePtr()->getArgumentPack());
2597 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2598 TL.getBeginLoc());
2599 return Result.getAsType();
2600}
2601
2602static concepts::Requirement::SubstitutionDiagnostic *
2604 Sema::EntityPrinter Printer) {
2605 SmallString<128> Message;
2606 SourceLocation ErrorLoc;
2607 if (Info.hasSFINAEDiagnostic()) {
2610 Info.takeSFINAEDiagnostic(PDA);
2611 PDA.second.EmitToString(S.getDiagnostics(), Message);
2612 ErrorLoc = PDA.first;
2613 } else {
2614 ErrorLoc = Info.getLocation();
2615 }
2616 SmallString<128> Entity;
2617 llvm::raw_svector_ostream OS(Entity);
2618 Printer(OS);
2619 const ASTContext &C = S.Context;
2621 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2622}
2623
2624concepts::Requirement::SubstitutionDiagnostic *
2626 SmallString<128> Entity;
2627 llvm::raw_svector_ostream OS(Entity);
2628 Printer(OS);
2629 const ASTContext &C = Context;
2631 /*SubstitutedEntity=*/C.backupStr(Entity),
2632 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2633}
2634
2635ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2636 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2639 SmallVectorImpl<ParmVarDecl *> &TransParams,
2641
2642 TemplateDeductionInfo Info(KWLoc);
2643 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2644 RE, Info,
2645 SourceRange{KWLoc, RBraceLoc});
2647
2648 unsigned ErrorIdx;
2649 if (getDerived().TransformFunctionTypeParams(
2650 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2651 &TransParams, PInfos, &ErrorIdx) ||
2652 Trap.hasErrorOccurred()) {
2654 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2655 // Add a 'failed' Requirement to contain the error that caused the failure
2656 // here.
2657 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2658 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2659 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2660 TransParams, RE->getRParenLoc(),
2661 TransReqs, RBraceLoc);
2662 }
2663
2664 return ExprResult{};
2665}
2666
2667concepts::TypeRequirement *
2668TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2669 if (!Req->isDependent() && !AlwaysRebuild())
2670 return Req;
2671 if (Req->isSubstitutionFailure()) {
2672 if (AlwaysRebuild())
2673 return RebuildTypeRequirement(
2675 return Req;
2676 }
2677
2678 Sema::SFINAETrap Trap(SemaRef);
2679 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2680 Sema::InstantiatingTemplate TypeInst(SemaRef,
2681 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2682 Req->getType()->getTypeLoc().getSourceRange());
2683 if (TypeInst.isInvalid())
2684 return nullptr;
2685 TypeSourceInfo *TransType = TransformType(Req->getType());
2686 if (!TransType || Trap.hasErrorOccurred())
2687 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2688 [&] (llvm::raw_ostream& OS) {
2689 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2690 }));
2691 return RebuildTypeRequirement(TransType);
2692}
2693
2694concepts::ExprRequirement *
2695TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2696 if (!Req->isDependent() && !AlwaysRebuild())
2697 return Req;
2698
2699 Sema::SFINAETrap Trap(SemaRef);
2700
2701 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2702 TransExpr;
2703 if (Req->isExprSubstitutionFailure())
2704 TransExpr = Req->getExprSubstitutionDiagnostic();
2705 else {
2706 Expr *E = Req->getExpr();
2707 TemplateDeductionInfo Info(E->getBeginLoc());
2708 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2709 E->getSourceRange());
2710 if (ExprInst.isInvalid())
2711 return nullptr;
2712 ExprResult TransExprRes = TransformExpr(E);
2713 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2714 TransExprRes.get()->hasPlaceholderType())
2715 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2716 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2717 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2718 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2719 });
2720 else
2721 TransExpr = TransExprRes.get();
2722 }
2723
2724 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2725 const auto &RetReq = Req->getReturnTypeRequirement();
2726 if (RetReq.isEmpty())
2727 TransRetReq.emplace();
2728 else if (RetReq.isSubstitutionFailure())
2729 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2730 else if (RetReq.isTypeConstraint()) {
2731 TemplateParameterList *OrigTPL =
2732 RetReq.getTypeConstraintTemplateParameterList();
2733 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2734 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2735 Req, Info, OrigTPL->getSourceRange());
2736 if (TPLInst.isInvalid())
2737 return nullptr;
2738 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2739 if (!TPL || Trap.hasErrorOccurred())
2740 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2741 [&] (llvm::raw_ostream& OS) {
2742 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2743 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2744 }));
2745 else {
2746 TPLInst.Clear();
2747 TransRetReq.emplace(TPL);
2748 }
2749 }
2750 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2751 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2752 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2753 std::move(*TransRetReq));
2754 return RebuildExprRequirement(
2756 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2757}
2758
2759concepts::NestedRequirement *
2760TemplateInstantiator::TransformNestedRequirement(
2761 concepts::NestedRequirement *Req) {
2762 if (!Req->isDependent() && !AlwaysRebuild())
2763 return Req;
2764 if (Req->hasInvalidConstraint()) {
2765 if (AlwaysRebuild())
2766 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2768 return Req;
2769 }
2770 Sema::InstantiatingTemplate ReqInst(SemaRef,
2771 Req->getConstraintExpr()->getBeginLoc(), Req,
2772 Sema::InstantiatingTemplate::ConstraintsCheck{},
2774 if (!getEvaluateConstraints()) {
2775 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2776 if (TransConstraint.isInvalid() || !TransConstraint.get())
2777 return nullptr;
2778 if (TransConstraint.get()->isInstantiationDependent())
2779 return new (SemaRef.Context)
2780 concepts::NestedRequirement(TransConstraint.get());
2781 ConstraintSatisfaction Satisfaction;
2782 return new (SemaRef.Context) concepts::NestedRequirement(
2783 SemaRef.Context, TransConstraint.get(), Satisfaction);
2784 }
2785
2786 ExprResult TransConstraint;
2787 ConstraintSatisfaction Satisfaction;
2788 TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2789 {
2790 EnterExpressionEvaluationContext ContextRAII(
2792 Sema::SFINAETrap Trap(SemaRef);
2793 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2794 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2796 if (ConstrInst.isInvalid())
2797 return nullptr;
2798 llvm::SmallVector<Expr *> Result;
2799 if (!SemaRef.CheckConstraintSatisfaction(
2800 nullptr,
2801 AssociatedConstraint(Req->getConstraintExpr(),
2802 SemaRef.ArgPackSubstIndex),
2803 Result, TemplateArgs, Req->getConstraintExpr()->getSourceRange(),
2804 Satisfaction) &&
2805 !Result.empty())
2806 TransConstraint = Result[0];
2807 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2808 "by CheckConstraintSatisfaction.");
2809 }
2810 ASTContext &C = SemaRef.Context;
2811 if (TransConstraint.isUsable() &&
2812 TransConstraint.get()->isInstantiationDependent())
2813 return new (C) concepts::NestedRequirement(TransConstraint.get());
2814 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2815 Satisfaction.HasSubstitutionFailure()) {
2816 SmallString<128> Entity;
2817 llvm::raw_svector_ostream OS(Entity);
2818 Req->getConstraintExpr()->printPretty(OS, nullptr,
2819 SemaRef.getPrintingPolicy());
2820 return new (C) concepts::NestedRequirement(
2821 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2822 }
2823 return new (C)
2824 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2825}
2826
2829 SourceLocation Loc,
2830 DeclarationName Entity,
2831 bool AllowDeducedTST) {
2832 assert(!CodeSynthesisContexts.empty() &&
2833 "Cannot perform an instantiation without some context on the "
2834 "instantiation stack");
2835
2836 if (!T->getType()->isInstantiationDependentType() &&
2837 !T->getType()->isVariablyModifiedType())
2838 return T;
2839
2840 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2841 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2842 : Instantiator.TransformType(T);
2843}
2844
2847 SourceLocation Loc,
2848 DeclarationName Entity) {
2849 assert(!CodeSynthesisContexts.empty() &&
2850 "Cannot perform an instantiation without some context on the "
2851 "instantiation stack");
2852
2853 if (TL.getType().isNull())
2854 return nullptr;
2855
2858 // FIXME: Make a copy of the TypeLoc data here, so that we can
2859 // return a new TypeSourceInfo. Inefficient!
2860 TypeLocBuilder TLB;
2861 TLB.pushFullCopy(TL);
2862 return TLB.getTypeSourceInfo(Context, TL.getType());
2863 }
2864
2865 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2866 TypeLocBuilder TLB;
2867 TLB.reserve(TL.getFullDataSize());
2868 QualType Result = Instantiator.TransformType(TLB, TL);
2869 if (Result.isNull())
2870 return nullptr;
2871
2872 return TLB.getTypeSourceInfo(Context, Result);
2873}
2874
2875/// Deprecated form of the above.
2877 const MultiLevelTemplateArgumentList &TemplateArgs,
2878 SourceLocation Loc, DeclarationName Entity,
2879 bool *IsIncompleteSubstitution) {
2880 assert(!CodeSynthesisContexts.empty() &&
2881 "Cannot perform an instantiation without some context on the "
2882 "instantiation stack");
2883
2884 // If T is not a dependent type or a variably-modified type, there
2885 // is nothing to do.
2886 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2887 return T;
2888
2889 TemplateInstantiator Instantiator(
2890 *this, TemplateArgs, Loc, Entity,
2891 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2892 QualType QT = Instantiator.TransformType(T);
2893 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2894 *IsIncompleteSubstitution = true;
2895 return QT;
2896}
2897
2899 if (T->getType()->isInstantiationDependentType() ||
2900 T->getType()->isVariablyModifiedType())
2901 return true;
2902
2903 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2904 if (!TL.getAs<FunctionProtoTypeLoc>())
2905 return false;
2906
2908 for (ParmVarDecl *P : FP.getParams()) {
2909 // This must be synthesized from a typedef.
2910 if (!P) continue;
2911
2912 // If there are any parameters, a new TypeSourceInfo that refers to the
2913 // instantiated parameters must be built.
2914 return true;
2915 }
2916
2917 return false;
2918}
2919
2922 SourceLocation Loc,
2923 DeclarationName Entity,
2924 CXXRecordDecl *ThisContext,
2925 Qualifiers ThisTypeQuals,
2926 bool EvaluateConstraints) {
2927 assert(!CodeSynthesisContexts.empty() &&
2928 "Cannot perform an instantiation without some context on the "
2929 "instantiation stack");
2930
2932 return T;
2933
2934 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2935 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2936
2937 TypeLocBuilder TLB;
2938
2939 TypeLoc TL = T->getTypeLoc();
2940 TLB.reserve(TL.getFullDataSize());
2941
2943
2944 if (FunctionProtoTypeLoc Proto =
2946 // Instantiate the type, other than its exception specification. The
2947 // exception specification is instantiated in InitFunctionInstantiation
2948 // once we've built the FunctionDecl.
2949 // FIXME: Set the exception specification to EST_Uninstantiated here,
2950 // instead of rebuilding the function type again later.
2951 Result = Instantiator.TransformFunctionProtoType(
2952 TLB, Proto, ThisContext, ThisTypeQuals,
2954 bool &Changed) { return false; });
2955 } else {
2956 Result = Instantiator.TransformType(TLB, TL);
2957 }
2958 // When there are errors resolving types, clang may use IntTy as a fallback,
2959 // breaking our assumption that function declarations have function types.
2960 if (Result.isNull() || !Result->isFunctionType())
2961 return nullptr;
2962
2963 return TLB.getTypeSourceInfo(Context, Result);
2964}
2965
2968 SmallVectorImpl<QualType> &ExceptionStorage,
2969 const MultiLevelTemplateArgumentList &Args) {
2970 bool Changed = false;
2971 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2972 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2973 Changed);
2974}
2975
2977 const MultiLevelTemplateArgumentList &Args) {
2980
2981 SmallVector<QualType, 4> ExceptionStorage;
2982 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2983 ESI, ExceptionStorage, Args))
2984 // On error, recover by dropping the exception specification.
2985 ESI.Type = EST_None;
2986
2988}
2989
2990namespace {
2991
2992 struct GetContainedInventedTypeParmVisitor :
2993 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2994 TemplateTypeParmDecl *> {
2995 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2996 TemplateTypeParmDecl *>::Visit;
2997
2999 if (T.isNull())
3000 return nullptr;
3001 return Visit(T.getTypePtr());
3002 }
3003 // The deduced type itself.
3004 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3005 const TemplateTypeParmType *T) {
3006 if (!T->getDecl() || !T->getDecl()->isImplicit())
3007 return nullptr;
3008 return T->getDecl();
3009 }
3010
3011 // Only these types can contain 'auto' types, and subsequently be replaced
3012 // by references to invented parameters.
3013
3014 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3015 return Visit(T->getPointeeType());
3016 }
3017
3018 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3019 return Visit(T->getPointeeType());
3020 }
3021
3022 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3023 return Visit(T->getPointeeTypeAsWritten());
3024 }
3025
3026 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3027 return Visit(T->getPointeeType());
3028 }
3029
3030 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3031 return Visit(T->getElementType());
3032 }
3033
3034 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3035 const DependentSizedExtVectorType *T) {
3036 return Visit(T->getElementType());
3037 }
3038
3039 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3040 return Visit(T->getElementType());
3041 }
3042
3043 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3044 return VisitFunctionType(T);
3045 }
3046
3047 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3048 return Visit(T->getReturnType());
3049 }
3050
3051 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3052 return Visit(T->getInnerType());
3053 }
3054
3055 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3056 return Visit(T->getModifiedType());
3057 }
3058
3059 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3060 return Visit(T->getUnderlyingType());
3061 }
3062
3063 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3064 return Visit(T->getOriginalType());
3065 }
3066
3067 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3068 return Visit(T->getPattern());
3069 }
3070 };
3071
3072} // namespace
3073
3075 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3076 const MultiLevelTemplateArgumentList &TemplateArgs,
3077 bool EvaluateConstraints) {
3078 const ASTTemplateArgumentListInfo *TemplArgInfo =
3080
3081 if (!EvaluateConstraints) {
3083 if (!Index)
3084 Index = SemaRef.ArgPackSubstIndex;
3087 return false;
3088 }
3089
3090 TemplateArgumentListInfo InstArgs;
3091
3092 if (TemplArgInfo) {
3093 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3094 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3095 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3096 InstArgs))
3097 return true;
3098 }
3099 return AttachTypeConstraint(
3101 TC->getNamedConcept(),
3102 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3103 Inst->isParameterPack()
3105 ->getEllipsisLoc()
3106 : SourceLocation());
3107}
3108
3111 const MultiLevelTemplateArgumentList &TemplateArgs,
3112 int indexAdjustment, UnsignedOrNone NumExpansions,
3113 bool ExpectParameterPack, bool EvaluateConstraint) {
3114 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3115 TypeSourceInfo *NewDI = nullptr;
3116
3117 TypeLoc OldTL = OldDI->getTypeLoc();
3118 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3119
3120 // We have a function parameter pack. Substitute into the pattern of the
3121 // expansion.
3122 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3123 OldParm->getLocation(), OldParm->getDeclName());
3124 if (!NewDI)
3125 return nullptr;
3126
3127 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3128 // We still have unexpanded parameter packs, which means that
3129 // our function parameter is still a function parameter pack.
3130 // Therefore, make its type a pack expansion type.
3131 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3132 NumExpansions);
3133 } else if (ExpectParameterPack) {
3134 // We expected to get a parameter pack but didn't (because the type
3135 // itself is not a pack expansion type), so complain. This can occur when
3136 // the substitution goes through an alias template that "loses" the
3137 // pack expansion.
3138 Diag(OldParm->getLocation(),
3139 diag::err_function_parameter_pack_without_parameter_packs)
3140 << NewDI->getType();
3141 return nullptr;
3142 }
3143 } else {
3144 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3145 OldParm->getDeclName());
3146 }
3147
3148 if (!NewDI)
3149 return nullptr;
3150
3151 if (NewDI->getType()->isVoidType()) {
3152 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3153 return nullptr;
3154 }
3155
3156 // In abbreviated templates, TemplateTypeParmDecls with possible
3157 // TypeConstraints are created when the parameter list is originally parsed.
3158 // The TypeConstraints can therefore reference other functions parameters in
3159 // the abbreviated function template, which is why we must instantiate them
3160 // here, when the instantiated versions of those referenced parameters are in
3161 // scope.
3162 if (TemplateTypeParmDecl *TTP =
3163 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3164 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3165 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3166 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3167 // We will first get here when instantiating the abbreviated function
3168 // template's described function, but we might also get here later.
3169 // Make sure we do not instantiate the TypeConstraint more than once.
3170 if (Inst && !Inst->getTypeConstraint()) {
3171 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3172 return nullptr;
3173 }
3174 }
3175 }
3176
3177 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
3178 OldParm->getInnerLocStart(),
3179 OldParm->getLocation(),
3180 OldParm->getIdentifier(),
3181 NewDI->getType(), NewDI,
3182 OldParm->getStorageClass());
3183 if (!NewParm)
3184 return nullptr;
3185
3186 // Mark the (new) default argument as uninstantiated (if any).
3187 if (OldParm->hasUninstantiatedDefaultArg()) {
3188 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3189 NewParm->setUninstantiatedDefaultArg(Arg);
3190 } else if (OldParm->hasUnparsedDefaultArg()) {
3191 NewParm->setUnparsedDefaultArg();
3192 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3193 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3194 // Default arguments cannot be substituted until the declaration context
3195 // for the associated function or lambda capture class is available.
3196 // This is necessary for cases like the following where construction of
3197 // the lambda capture class for the outer lambda is dependent on the
3198 // parameter types but where the default argument is dependent on the
3199 // outer lambda's declaration context.
3200 // template <typename T>
3201 // auto f() {
3202 // return [](T = []{ return T{}; }()) { return 0; };
3203 // }
3204 NewParm->setUninstantiatedDefaultArg(Arg);
3205 }
3206
3210
3211 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3212 // Add the new parameter to the instantiated parameter pack.
3213 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3214 } else {
3215 // Introduce an Old -> New mapping
3216 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3217 }
3218
3219 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3220 // can be anything, is this right ?
3221 NewParm->setDeclContext(CurContext);
3222
3223 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3224 OldParm->getFunctionScopeIndex() + indexAdjustment);
3225
3226 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3227
3228 return NewParm;
3229}
3230
3233 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3234 const MultiLevelTemplateArgumentList &TemplateArgs,
3235 SmallVectorImpl<QualType> &ParamTypes,
3237 ExtParameterInfoBuilder &ParamInfos) {
3238 assert(!CodeSynthesisContexts.empty() &&
3239 "Cannot perform an instantiation without some context on the "
3240 "instantiation stack");
3241
3242 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3243 DeclarationName());
3244 return Instantiator.TransformFunctionTypeParams(
3245 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3246}
3247
3249 SourceLocation Loc,
3250 ParmVarDecl *Param,
3251 const MultiLevelTemplateArgumentList &TemplateArgs,
3252 bool ForCallExpr) {
3253 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3254 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3255
3258
3259 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3260 if (Inst.isInvalid())
3261 return true;
3262 if (Inst.isAlreadyInstantiating()) {
3263 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3264 Param->setInvalidDecl();
3265 return true;
3266 }
3267
3269 // C++ [dcl.fct.default]p5:
3270 // The names in the [default argument] expression are bound, and
3271 // the semantic constraints are checked, at the point where the
3272 // default argument expression appears.
3273 ContextRAII SavedContext(*this, FD);
3274 {
3275 std::optional<LocalInstantiationScope> LIS;
3276
3277 if (ForCallExpr) {
3278 // When instantiating a default argument due to use in a call expression,
3279 // an instantiation scope that includes the parameters of the callee is
3280 // required to satisfy references from the default argument. For example:
3281 // template<typename T> void f(T a, int = decltype(a)());
3282 // void g() { f(0); }
3283 LIS.emplace(*this);
3285 /*ForDefinition*/ false);
3286 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3287 return true;
3288 }
3289
3291 Result = SubstInitializer(PatternExpr, TemplateArgs,
3292 /*DirectInit*/ false);
3293 });
3294 }
3295 if (Result.isInvalid())
3296 return true;
3297
3298 if (ForCallExpr) {
3299 // Check the expression as an initializer for the parameter.
3300 InitializedEntity Entity
3303 Param->getLocation(),
3304 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3305 Expr *ResultE = Result.getAs<Expr>();
3306
3307 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3308 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3309 if (Result.isInvalid())
3310 return true;
3311
3312 Result =
3313 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3314 /*DiscardedValue*/ false);
3315 } else {
3316 // FIXME: Obtain the source location for the '=' token.
3317 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3318 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3319 }
3320 if (Result.isInvalid())
3321 return true;
3322
3323 // Remember the instantiated default argument.
3324 Param->setDefaultArg(Result.getAs<Expr>());
3325
3326 return false;
3327}
3328
3329// See TreeTransform::PreparePackForExpansion for the relevant comment.
3330// This function implements the same concept for base specifiers.
3331static bool
3333 const MultiLevelTemplateArgumentList &TemplateArgs,
3334 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3335 SourceRange BaseSourceRange = Base.getSourceRange();
3336 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3337 Info.Ellipsis = Base.getEllipsisLoc();
3338 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3339 TypeSourceInfo *BaseTypeInfo,
3340 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3341 // This is a pack expansion. See whether we should expand it now, or
3342 // wait until later.
3344 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3345 if (IsLateExpansionAttempt) {
3346 // Request expansion only when there is an opportunity to expand a pack
3347 // that required a substituion first.
3348 bool SawPackTypes =
3349 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3350 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3351 });
3352 if (!SawPackTypes) {
3353 Info.Expand = false;
3354 return false;
3355 }
3356 }
3357
3358 // Determine whether the set of unexpanded parameter packs can and should be
3359 // expanded.
3360 Info.Expand = false;
3361 Info.RetainExpansion = false;
3362 Info.NumExpansions = std::nullopt;
3364 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3365 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3366 Info.RetainExpansion, Info.NumExpansions);
3367 };
3368
3369 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3370 return true;
3371
3372 if (Info.Expand) {
3373 Out = Base.getTypeSourceInfo();
3374 return false;
3375 }
3376
3377 // The resulting base specifier will (still) be a pack expansion.
3378 {
3379 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3380 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3381 BaseSourceRange.getBegin(), DeclarationName());
3382 }
3383 if (!Out->getType()->containsUnexpandedParameterPack())
3384 return false;
3385
3386 // Some packs will learn their length after substitution.
3387 // We may need to request their expansion.
3388 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3389 return true;
3390 if (Info.Expand)
3391 Info.ExpandUnderForgetSubstitions = true;
3392 return false;
3393}
3394
3395bool
3397 CXXRecordDecl *Pattern,
3398 const MultiLevelTemplateArgumentList &TemplateArgs) {
3399 bool Invalid = false;
3400 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3401 for (const auto &Base : Pattern->bases()) {
3402 if (!Base.getType()->isDependentType()) {
3403 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3404 if (RD->isInvalidDecl())
3405 Instantiation->setInvalidDecl();
3406 }
3407 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3408 continue;
3409 }
3410
3411 SourceLocation EllipsisLoc;
3412 TypeSourceInfo *BaseTypeLoc = nullptr;
3413 if (Base.isPackExpansion()) {
3414 UnexpandedInfo Info;
3415 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3416 Info)) {
3417 Invalid = true;
3418 continue;
3419 }
3420
3421 // If we should expand this pack expansion now, do so.
3423 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3425 ArgsForSubst = &EmptyList;
3426
3427 if (Info.Expand) {
3428 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3429 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3430
3431 TypeSourceInfo *Expanded =
3432 SubstType(BaseTypeLoc, *ArgsForSubst,
3433 Base.getSourceRange().getBegin(), DeclarationName());
3434 if (!Expanded) {
3435 Invalid = true;
3436 continue;
3437 }
3438
3439 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3440 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3441 Base.getAccessSpecifierAsWritten(), Expanded,
3442 SourceLocation()))
3443 InstantiatedBases.push_back(InstantiatedBase);
3444 else
3445 Invalid = true;
3446 }
3447
3448 continue;
3449 }
3450
3451 // The resulting base specifier will (still) be a pack expansion.
3452 EllipsisLoc = Base.getEllipsisLoc();
3453 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3454 BaseTypeLoc =
3455 SubstType(BaseTypeLoc, *ArgsForSubst,
3456 Base.getSourceRange().getBegin(), DeclarationName());
3457 } else {
3458 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3459 TemplateArgs,
3460 Base.getSourceRange().getBegin(),
3461 DeclarationName());
3462 }
3463
3464 if (!BaseTypeLoc) {
3465 Invalid = true;
3466 continue;
3467 }
3468
3469 if (CXXBaseSpecifier *InstantiatedBase
3470 = CheckBaseSpecifier(Instantiation,
3471 Base.getSourceRange(),
3472 Base.isVirtual(),
3473 Base.getAccessSpecifierAsWritten(),
3474 BaseTypeLoc,
3475 EllipsisLoc))
3476 InstantiatedBases.push_back(InstantiatedBase);
3477 else
3478 Invalid = true;
3479 }
3480
3481 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3482 Invalid = true;
3483
3484 return Invalid;
3485}
3486
3487// Defined via #include from SemaTemplateInstantiateDecl.cpp
3488namespace clang {
3489 namespace sema {
3491 const MultiLevelTemplateArgumentList &TemplateArgs);
3493 const Attr *At, ASTContext &C, Sema &S,
3494 const MultiLevelTemplateArgumentList &TemplateArgs);
3495 }
3496}
3497
3498bool
3500 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3501 const MultiLevelTemplateArgumentList &TemplateArgs,
3503 bool Complain) {
3504 CXXRecordDecl *PatternDef
3505 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3506 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3507 Instantiation->getInstantiatedFromMemberClass(),
3508 Pattern, PatternDef, TSK, Complain))
3509 return true;
3510
3511 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3512 llvm::TimeTraceMetadata M;
3513 llvm::raw_string_ostream OS(M.Detail);
3514 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3515 /*Qualified=*/true);
3516 if (llvm::isTimeTraceVerbose()) {
3517 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3518 M.File = SourceMgr.getFilename(Loc);
3519 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3520 }
3521 return M;
3522 });
3523
3524 Pattern = PatternDef;
3525
3526 // Record the point of instantiation.
3527 if (MemberSpecializationInfo *MSInfo
3528 = Instantiation->getMemberSpecializationInfo()) {
3529 MSInfo->setTemplateSpecializationKind(TSK);
3530 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3531 } else if (ClassTemplateSpecializationDecl *Spec
3532 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3533 Spec->setTemplateSpecializationKind(TSK);
3534 Spec->setPointOfInstantiation(PointOfInstantiation);
3535 }
3536
3537 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3538 if (Inst.isInvalid())
3539 return true;
3540 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3541 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3542 "instantiating class definition");
3543
3544 // Enter the scope of this instantiation. We don't use
3545 // PushDeclContext because we don't have a scope.
3546 ContextRAII SavedContext(*this, Instantiation);
3549
3550 // If this is an instantiation of a local class, merge this local
3551 // instantiation scope with the enclosing scope. Otherwise, every
3552 // instantiation of a class has its own local instantiation scope.
3553 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3554 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3555
3556 // Some class state isn't processed immediately but delayed till class
3557 // instantiation completes. We may not be ready to handle any delayed state
3558 // already on the stack as it might correspond to a different class, so save
3559 // it now and put it back later.
3560 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3561
3562 // Pull attributes from the pattern onto the instantiation.
3563 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3564
3565 // Start the definition of this instantiation.
3566 Instantiation->startDefinition();
3567
3568 // The instantiation is visible here, even if it was first declared in an
3569 // unimported module.
3570 Instantiation->setVisibleDespiteOwningModule();
3571
3572 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3573 Instantiation->setTagKind(Pattern->getTagKind());
3574
3575 // Do substitution on the base class specifiers.
3576 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3577 Instantiation->setInvalidDecl();
3578
3579 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3580 Instantiator.setEvaluateConstraints(false);
3581 SmallVector<Decl*, 4> Fields;
3582 // Delay instantiation of late parsed attributes.
3583 LateInstantiatedAttrVec LateAttrs;
3584 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3585
3586 bool MightHaveConstexprVirtualFunctions = false;
3587 for (auto *Member : Pattern->decls()) {
3588 // Don't instantiate members not belonging in this semantic context.
3589 // e.g. for:
3590 // @code
3591 // template <int i> class A {
3592 // class B *g;
3593 // };
3594 // @endcode
3595 // 'class B' has the template as lexical context but semantically it is
3596 // introduced in namespace scope.
3597 if (Member->getDeclContext() != Pattern)
3598 continue;
3599
3600 // BlockDecls can appear in a default-member-initializer. They must be the
3601 // child of a BlockExpr, so we only know how to instantiate them from there.
3602 // Similarly, lambda closure types are recreated when instantiating the
3603 // corresponding LambdaExpr.
3604 if (isa<BlockDecl>(Member) ||
3606 continue;
3607
3608 if (Member->isInvalidDecl()) {
3609 Instantiation->setInvalidDecl();
3610 continue;
3611 }
3612
3613 Decl *NewMember = Instantiator.Visit(Member);
3614 if (NewMember) {
3615 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3616 Fields.push_back(Field);
3617 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3618 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3619 // specialization causes the implicit instantiation of the definitions
3620 // of unscoped member enumerations.
3621 // Record a point of instantiation for this implicit instantiation.
3622 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3623 Enum->isCompleteDefinition()) {
3624 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3625 assert(MSInfo && "no spec info for member enum specialization");
3627 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3628 }
3629 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3630 if (SA->isFailed()) {
3631 // A static_assert failed. Bail out; instantiating this
3632 // class is probably not meaningful.
3633 Instantiation->setInvalidDecl();
3634 break;
3635 }
3636 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3637 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3638 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3639 MightHaveConstexprVirtualFunctions = true;
3640 }
3641
3642 if (NewMember->isInvalidDecl())
3643 Instantiation->setInvalidDecl();
3644 } else {
3645 // FIXME: Eventually, a NULL return will mean that one of the
3646 // instantiations was a semantic disaster, and we'll want to mark the
3647 // declaration invalid.
3648 // For now, we expect to skip some members that we can't yet handle.
3649 }
3650 }
3651
3652 // Finish checking fields.
3653 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3655 CheckCompletedCXXClass(nullptr, Instantiation);
3656
3657 // Default arguments are parsed, if not instantiated. We can go instantiate
3658 // default arg exprs for default constructors if necessary now. Unless we're
3659 // parsing a class, in which case wait until that's finished.
3660 if (ParsingClassDepth == 0)
3662
3663 // Instantiate late parsed attributes, and attach them to their decls.
3664 // See Sema::InstantiateAttrs
3665 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3666 E = LateAttrs.end(); I != E; ++I) {
3667 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3668 CurrentInstantiationScope = I->Scope;
3669
3670 // Allow 'this' within late-parsed attributes.
3671 auto *ND = cast<NamedDecl>(I->NewDecl);
3672 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3673 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3674 ND->isCXXInstanceMember());
3675
3676 Attr *NewAttr =
3677 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3678 if (NewAttr)
3679 I->NewDecl->addAttr(NewAttr);
3681 Instantiator.getStartingScope());
3682 }
3683 Instantiator.disableLateAttributeInstantiation();
3684 LateAttrs.clear();
3685
3687
3688 // FIXME: We should do something similar for explicit instantiations so they
3689 // end up in the right module.
3690 if (TSK == TSK_ImplicitInstantiation) {
3691 Instantiation->setLocation(Pattern->getLocation());
3692 Instantiation->setLocStart(Pattern->getInnerLocStart());
3693 Instantiation->setBraceRange(Pattern->getBraceRange());
3694 }
3695
3696 if (!Instantiation->isInvalidDecl()) {
3697 // Perform any dependent diagnostics from the pattern.
3698 if (Pattern->isDependentContext())
3699 PerformDependentDiagnostics(Pattern, TemplateArgs);
3700
3701 // Instantiate any out-of-line class template partial
3702 // specializations now.
3704 P = Instantiator.delayed_partial_spec_begin(),
3705 PEnd = Instantiator.delayed_partial_spec_end();
3706 P != PEnd; ++P) {
3708 P->first, P->second)) {
3709 Instantiation->setInvalidDecl();
3710 break;
3711 }
3712 }
3713
3714 // Instantiate any out-of-line variable template partial
3715 // specializations now.
3717 P = Instantiator.delayed_var_partial_spec_begin(),
3718 PEnd = Instantiator.delayed_var_partial_spec_end();
3719 P != PEnd; ++P) {
3721 P->first, P->second)) {
3722 Instantiation->setInvalidDecl();
3723 break;
3724 }
3725 }
3726 }
3727
3728 // Exit the scope of this instantiation.
3729 SavedContext.pop();
3730
3731 if (!Instantiation->isInvalidDecl()) {
3732 // Always emit the vtable for an explicit instantiation definition
3733 // of a polymorphic class template specialization. Otherwise, eagerly
3734 // instantiate only constexpr virtual functions in preparation for their use
3735 // in constant evaluation.
3737 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3738 else if (MightHaveConstexprVirtualFunctions)
3739 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3740 /*ConstexprOnly*/ true);
3741 }
3742
3743 Consumer.HandleTagDeclDefinition(Instantiation);
3744
3745 return Instantiation->isInvalidDecl();
3746}
3747
3748bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3749 EnumDecl *Instantiation, EnumDecl *Pattern,
3750 const MultiLevelTemplateArgumentList &TemplateArgs,
3752 EnumDecl *PatternDef = Pattern->getDefinition();
3753 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3754 Instantiation->getInstantiatedFromMemberEnum(),
3755 Pattern, PatternDef, TSK,/*Complain*/true))
3756 return true;
3757 Pattern = PatternDef;
3758
3759 // Record the point of instantiation.
3760 if (MemberSpecializationInfo *MSInfo
3761 = Instantiation->getMemberSpecializationInfo()) {
3762 MSInfo->setTemplateSpecializationKind(TSK);
3763 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3764 }
3765
3766 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3767 if (Inst.isInvalid())
3768 return true;
3769 if (Inst.isAlreadyInstantiating())
3770 return false;
3771 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3772 "instantiating enum definition");
3773
3774 // The instantiation is visible here, even if it was first declared in an
3775 // unimported module.
3776 Instantiation->setVisibleDespiteOwningModule();
3777
3778 // Enter the scope of this instantiation. We don't use
3779 // PushDeclContext because we don't have a scope.
3780 ContextRAII SavedContext(*this, Instantiation);
3783
3784 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3785
3786 // Pull attributes from the pattern onto the instantiation.
3787 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3788
3789 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3790 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3791
3792 // Exit the scope of this instantiation.
3793 SavedContext.pop();
3794
3795 return Instantiation->isInvalidDecl();
3796}
3797
3799 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3800 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3801 // If there is no initializer, we don't need to do anything.
3802 if (!Pattern->hasInClassInitializer())
3803 return false;
3804
3805 assert(Instantiation->getInClassInitStyle() ==
3806 Pattern->getInClassInitStyle() &&
3807 "pattern and instantiation disagree about init style");
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 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3825 if (Inst.isInvalid())
3826 return true;
3827 if (Inst.isAlreadyInstantiating()) {
3828 // Error out if we hit an instantiation cycle for this initializer.
3829 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3830 << Instantiation;
3831 return true;
3832 }
3833 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3834 "instantiating default member init");
3835
3836 // Enter the scope of this instantiation. We don't use PushDeclContext because
3837 // we don't have a scope.
3838 ContextRAII SavedContext(*this, Instantiation->getParent());
3841 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3842 PointOfInstantiation, Instantiation, CurContext};
3843
3844 LocalInstantiationScope Scope(*this, true);
3845
3846 // Instantiate the initializer.
3848 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3849
3850 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3851 /*CXXDirectInit=*/false);
3852 Expr *Init = NewInit.get();
3853 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3855 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3856
3857 if (auto *L = getASTMutationListener())
3858 L->DefaultMemberInitializerInstantiated(Instantiation);
3859
3860 // Return true if the in-class initializer is still missing.
3861 return !Instantiation->getInClassInitializer();
3862}
3863
3864namespace {
3865 /// A partial specialization whose template arguments have matched
3866 /// a given template-id.
3867 struct PartialSpecMatchResult {
3870 };
3871}
3872
3874 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3875 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3877 return true;
3878
3880 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3881 CTD->getPartialSpecializations(PartialSpecs);
3882 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3883 // C++ [temp.spec.partial.member]p2:
3884 // If the primary member template is explicitly specialized for a given
3885 // (implicit) specialization of the enclosing class template, the partial
3886 // specializations of the member template are ignored for this
3887 // specialization of the enclosing class template. If a partial
3888 // specialization of the member template is explicitly specialized for a
3889 // given (implicit) specialization of the enclosing class template, the
3890 // primary member template and its other partial specializations are still
3891 // considered for this specialization of the enclosing class template.
3893 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3894 continue;
3895
3896 TemplateDeductionInfo Info(Loc);
3897 if (DeduceTemplateArguments(CTPSD,
3898 ClassTemplateSpec->getTemplateArgs().asArray(),
3900 return true;
3901 }
3902
3903 return false;
3904}
3905
3906/// Get the instantiation pattern to use to instantiate the definition of a
3907/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3908/// template or of a partial specialization).
3910 Sema &S, SourceLocation PointOfInstantiation,
3911 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3912 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3913 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3914 if (Inst.isInvalid())
3915 return {/*Invalid=*/true};
3916 if (Inst.isAlreadyInstantiating())
3917 return {/*Invalid=*/false};
3918
3919 llvm::PointerUnion<ClassTemplateDecl *,
3921 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3923 // Find best matching specialization.
3924 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3925
3926 // C++ [temp.class.spec.match]p1:
3927 // When a class template is used in a context that requires an
3928 // instantiation of the class, it is necessary to determine
3929 // whether the instantiation is to be generated using the primary
3930 // template or one of the partial specializations. This is done by
3931 // matching the template arguments of the class template
3932 // specialization with the template argument lists of the partial
3933 // specializations.
3934 typedef PartialSpecMatchResult MatchResult;
3935 SmallVector<MatchResult, 4> Matched, ExtraMatched;
3937 Template->getPartialSpecializations(PartialSpecs);
3938 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3939 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
3940 // C++ [temp.spec.partial.member]p2:
3941 // If the primary member template is explicitly specialized for a given
3942 // (implicit) specialization of the enclosing class template, the
3943 // partial specializations of the member template are ignored for this
3944 // specialization of the enclosing class template. If a partial
3945 // specialization of the member template is explicitly specialized for a
3946 // given (implicit) specialization of the enclosing class template, the
3947 // primary member template and its other partial specializations are
3948 // still considered for this specialization of the enclosing class
3949 // template.
3950 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
3951 !Partial->getMostRecentDecl()->isMemberSpecialization())
3952 continue;
3953
3954 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3956 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3958 // Store the failed-deduction information for use in diagnostics, later.
3959 // TODO: Actually use the failed-deduction info?
3960 FailedCandidates.addCandidate().set(
3962 MakeDeductionFailureInfo(S.Context, Result, Info));
3963 (void)Result;
3964 } else {
3965 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
3966 List.push_back(MatchResult{Partial, Info.takeCanonical()});
3967 }
3968 }
3969 if (Matched.empty() && PrimaryStrictPackMatch)
3970 Matched = std::move(ExtraMatched);
3971
3972 // If we're dealing with a member template where the template parameters
3973 // have been instantiated, this provides the original template parameters
3974 // from which the member template's parameters were instantiated.
3975
3976 if (Matched.size() >= 1) {
3977 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3978 if (Matched.size() == 1) {
3979 // -- If exactly one matching specialization is found, the
3980 // instantiation is generated from that specialization.
3981 // We don't need to do anything for this.
3982 } else {
3983 // -- If more than one matching specialization is found, the
3984 // partial order rules (14.5.4.2) are used to determine
3985 // whether one of the specializations is more specialized
3986 // than the others. If none of the specializations is more
3987 // specialized than all of the other matching
3988 // specializations, then the use of the class template is
3989 // ambiguous and the program is ill-formed.
3991 PEnd = Matched.end();
3992 P != PEnd; ++P) {
3994 P->Partial, Best->Partial, PointOfInstantiation) ==
3995 P->Partial)
3996 Best = P;
3997 }
3998
3999 // Determine if the best partial specialization is more specialized than
4000 // the others.
4001 bool Ambiguous = false;
4002 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4003 PEnd = Matched.end();
4004 P != PEnd; ++P) {
4005 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4006 P->Partial, Best->Partial,
4007 PointOfInstantiation) != Best->Partial) {
4008 Ambiguous = true;
4009 break;
4010 }
4011 }
4012
4013 if (Ambiguous) {
4014 // Partial ordering did not produce a clear winner. Complain.
4015 Inst.Clear();
4016 S.Diag(PointOfInstantiation,
4017 diag::err_partial_spec_ordering_ambiguous)
4018 << ClassTemplateSpec;
4019
4020 // Print the matching partial specializations.
4021 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4022 PEnd = Matched.end();
4023 P != PEnd; ++P)
4024 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4026 P->Partial->getTemplateParameters(), *P->Args);
4027
4028 return {/*Invalid=*/true};
4029 }
4030 }
4031
4032 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4033 } else {
4034 // -- If no matches are found, the instantiation is generated
4035 // from the primary template.
4036 }
4037 }
4038
4039 CXXRecordDecl *Pattern = nullptr;
4040 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4041 if (auto *PartialSpec =
4042 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4043 // Instantiate using the best class template partial specialization.
4044 while (PartialSpec->getInstantiatedFromMember()) {
4045 // If we've found an explicit specialization of this class template,
4046 // stop here and use that as the pattern.
4047 if (PartialSpec->isMemberSpecialization())
4048 break;
4049
4050 PartialSpec = PartialSpec->getInstantiatedFromMember();
4051 }
4052 Pattern = PartialSpec;
4053 } else {
4054 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4055 while (Template->getInstantiatedFromMemberTemplate()) {
4056 // If we've found an explicit specialization of this class template,
4057 // stop here and use that as the pattern.
4058 if (Template->isMemberSpecialization())
4059 break;
4060
4061 Template = Template->getInstantiatedFromMemberTemplate();
4062 }
4063 Pattern = Template->getTemplatedDecl();
4064 }
4065
4066 return Pattern;
4067}
4068
4070 SourceLocation PointOfInstantiation,
4071 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4072 TemplateSpecializationKind TSK, bool Complain,
4073 bool PrimaryStrictPackMatch) {
4074 // Perform the actual instantiation on the canonical declaration.
4075 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4076 ClassTemplateSpec->getCanonicalDecl());
4077 if (ClassTemplateSpec->isInvalidDecl())
4078 return true;
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 = InstantiateClass(
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 if (!E)
4384 return E;
4385
4386 TemplateInstantiator Instantiator(*this, TemplateArgs,
4388 DeclarationName());
4389 return Instantiator.TransformExpr(E);
4390}
4391
4394 const MultiLevelTemplateArgumentList &TemplateArgs) {
4395 if (!E)
4396 return E;
4397
4398 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4399 DeclarationName());
4400 return Instantiator.TransformAddressOfOperand(E);
4401}
4402
4405 const MultiLevelTemplateArgumentList &TemplateArgs) {
4406 // FIXME: should call SubstExpr directly if this function is equivalent or
4407 // should it be different?
4408 return SubstExpr(E, TemplateArgs);
4409}
4410
4412 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4413 if (!E)
4414 return E;
4415
4416 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4417 DeclarationName());
4418 Instantiator.setEvaluateConstraints(false);
4419 return Instantiator.TransformExpr(E);
4420}
4421
4423 const MultiLevelTemplateArgumentList &TemplateArgs,
4424 bool CXXDirectInit) {
4425 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4426 DeclarationName());
4427 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4428}
4429
4430bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4431 const MultiLevelTemplateArgumentList &TemplateArgs,
4432 SmallVectorImpl<Expr *> &Outputs) {
4433 if (Exprs.empty())
4434 return false;
4435
4436 TemplateInstantiator Instantiator(*this, TemplateArgs,
4438 DeclarationName());
4439 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4440 IsCall, Outputs);
4441}
4442
4445 const MultiLevelTemplateArgumentList &TemplateArgs) {
4446 if (!NNS)
4447 return NestedNameSpecifierLoc();
4448
4449 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4450 DeclarationName());
4451 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4452}
4453
4456 const MultiLevelTemplateArgumentList &TemplateArgs) {
4457 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4458 NameInfo.getName());
4459 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4460}
4461
4464 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4465 SourceLocation NameLoc,
4466 const MultiLevelTemplateArgumentList &TemplateArgs) {
4467 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4468 DeclarationName());
4469 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4470 NameLoc);
4471}
4472
4473static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4474 // When storing ParmVarDecls in the local instantiation scope, we always
4475 // want to use the ParmVarDecl from the canonical function declaration,
4476 // since the map is then valid for any redeclaration or definition of that
4477 // function.
4478 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4479 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4480 unsigned i = PV->getFunctionScopeIndex();
4481 // This parameter might be from a freestanding function type within the
4482 // function and isn't necessarily referring to one of FD's parameters.
4483 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4484 return FD->getCanonicalDecl()->getParamDecl(i);
4485 }
4486 }
4487 return D;
4488}
4489
4490llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4493 for (LocalInstantiationScope *Current = this; Current;
4494 Current = Current->Outer) {
4495
4496 // Check if we found something within this scope.
4497 const Decl *CheckD = D;
4498 do {
4499 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4500 if (Found != Current->LocalDecls.end())
4501 return &Found->second;
4502
4503 // If this is a tag declaration, it's possible that we need to look for
4504 // a previous declaration.
4505 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4506 CheckD = Tag->getPreviousDecl();
4507 else
4508 CheckD = nullptr;
4509 } while (CheckD);
4510
4511 // If we aren't combined with our outer scope, we're done.
4512 if (!Current->CombineWithOuterScope)
4513 break;
4514 }
4515
4516 return nullptr;
4517}
4518
4519llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4522 if (Result)
4523 return Result;
4524 // If we're performing a partial substitution during template argument
4525 // deduction, we may not have values for template parameters yet.
4528 return nullptr;
4529
4530 // Local types referenced prior to definition may require instantiation.
4531 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4532 if (RD->isLocalClass())
4533 return nullptr;
4534
4535 // Enumeration types referenced prior to definition may appear as a result of
4536 // error recovery.
4537 if (isa<EnumDecl>(D))
4538 return nullptr;
4539
4540 // Materialized typedefs/type alias for implicit deduction guides may require
4541 // instantiation.
4542 if (isa<TypedefNameDecl>(D) &&
4544 return nullptr;
4545
4546 // If we didn't find the decl, then we either have a sema bug, or we have a
4547 // forward reference to a label declaration. Return null to indicate that
4548 // we have an uninstantiated label.
4549 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4550 return nullptr;
4551}
4552
4555 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4556 if (Stored.isNull()) {
4557#ifndef NDEBUG
4558 // It should not be present in any surrounding scope either.
4559 LocalInstantiationScope *Current = this;
4560 while (Current->CombineWithOuterScope && Current->Outer) {
4561 Current = Current->Outer;
4562 assert(!Current->LocalDecls.contains(D) &&
4563 "Instantiated local in inner and outer scopes");
4564 }
4565#endif
4566 Stored = Inst;
4567 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4568 Pack->push_back(cast<ValueDecl>(Inst));
4569 } else {
4570 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4571 }
4572}
4573
4575 VarDecl *Inst) {
4577 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4578 Pack->push_back(Inst);
4579}
4580
4582#ifndef NDEBUG
4583 // This should be the first time we've been told about this decl.
4584 for (LocalInstantiationScope *Current = this;
4585 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4586 assert(!Current->LocalDecls.contains(D) &&
4587 "Creating local pack after instantiation of local");
4588#endif
4589
4591 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4593 Stored = Pack;
4594 ArgumentPacks.push_back(Pack);
4595}
4596
4598 for (DeclArgumentPack *Pack : ArgumentPacks)
4599 if (llvm::is_contained(*Pack, D))
4600 return true;
4601 return false;
4602}
4603
4605 const TemplateArgument *ExplicitArgs,
4606 unsigned NumExplicitArgs) {
4607 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4608 "Already have a partially-substituted pack");
4609 assert((!PartiallySubstitutedPack
4610 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4611 "Wrong number of arguments in partially-substituted pack");
4612 PartiallySubstitutedPack = Pack;
4613 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4614 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4615}
4616
4618 const TemplateArgument **ExplicitArgs,
4619 unsigned *NumExplicitArgs) const {
4620 if (ExplicitArgs)
4621 *ExplicitArgs = nullptr;
4622 if (NumExplicitArgs)
4623 *NumExplicitArgs = 0;
4624
4625 for (const LocalInstantiationScope *Current = this; Current;
4626 Current = Current->Outer) {
4627 if (Current->PartiallySubstitutedPack) {
4628 if (ExplicitArgs)
4629 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4630 if (NumExplicitArgs)
4631 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4632
4633 return Current->PartiallySubstitutedPack;
4634 }
4635
4636 if (!Current->CombineWithOuterScope)
4637 break;
4638 }
4639
4640 return nullptr;
4641}
This file provides AST data structures related to concepts.
Defines the clang::ASTContext interface.
This file provides some common utility functions for processing Lambda related AST Constructs.
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 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:220
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:825
The result of parsing/analyzing an expression, statement etc.
Definition Ownership.h:154
PtrTy get() const
Definition Ownership.h:171
bool isInvalid() const
Definition Ownership.h:167
bool isUsable() const
Definition Ownership.h:169
Attr - This represents one attribute.
Definition Attr.h:44
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 static or instance method of a struct/union/class.
Definition DeclCXX.h:2129
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:1828
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition DeclCXX.h:1554
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:2020
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:2075
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition DeclCXX.cpp:2050
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition DeclCXX.cpp:2042
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition DeclCXX.cpp:2027
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1736
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:193
const TypeClass * getTypePtr() const
Definition TypeLoc.h:438
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition ASTConcept.h:37
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:1338
SourceLocation getLocation() const
Definition Expr.h:1346
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:263
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:244
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:156
bool isFileContextDecl() const
Definition DeclBase.cpp:432
static Decl * castFromDeclContext(const DeclContext *)
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition DeclBase.cpp:298
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:360
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:821
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:836
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:808
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4004
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4267
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5033
EnumDecl * getDefinition() const
Definition Decl.h:4107
This represents one expression.
Definition Expr.h:112
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:273
QualType getType() const
Definition Expr.h:144
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition Expr.h:523
ExprDependence getDependence() const
Definition Expr.h:164
Represents a member of a struct/union/class.
Definition Decl.h:3157
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4666
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3337
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3331
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3393
Represents a function declaration or definition.
Definition Decl.h:1999
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2771
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:4205
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4254
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2469
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2343
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:4876
ValueDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition ExprCXX.h:4868
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4861
iterator end() const
Definition ExprCXX.h:4870
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4873
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4864
iterator begin() const
Definition ExprCXX.h:4869
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5266
QualType desugar() const
Definition TypeBase.h:5847
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5555
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition TypeLoc.h:1687
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition TypeBase.h:4488
QualType getReturnType() const
Definition TypeBase.h:4802
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition TypeLoc.h:531
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:1970
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:365
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope=false, bool InstantiatingLambdaOrBlock=false)
Definition Template.h:433
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:368
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:505
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:571
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Provides information a specialization of a member of a class template, which may be a member function...
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Describes a module or submodule.
Definition Module.h: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:265
std::pair< Decl *, bool > getAssociatedDecl(unsigned Depth) const
A template-like entity which owns the whole pattern being substituted.
Definition Template.h:164
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition Template.h:129
unsigned getNewDepth(unsigned OldDepth) const
Determine how many of the OldDepth outermost template parameter lists would be removed by substitutin...
Definition Template.h:145
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition Template.h:197
bool isRewrite() const
Determine whether we are rewriting template parameters rather than substituting for them.
Definition Template.h:117
This represents a decl that may have a name.
Definition Decl.h:273
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:294
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:300
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:339
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:1834
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:2609
TypeLoc getPatternLoc() const
Definition TypeLoc.h:2625
Represents a parameter to a function.
Definition Decl.h:1789
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1849
SourceLocation getExplicitObjectParamThisLoc() const
Definition Decl.h:1885
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1930
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1918
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3039
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1822
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1922
bool hasInheritedDefaultArg() const
Definition Decl.h:1934
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1881
Expr * getDefaultArg()
Definition Decl.cpp:3002
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3044
unsigned getFunctionScopeDepth() const
Definition Decl.h:1839
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1938
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2040
SourceLocation getLocation() const
Definition Expr.h:2046
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:3556
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1156
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:4309
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Represents the body of a requires-expression.
Definition DeclCXX.h:2098
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
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition SemaBase.cpp:61
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition SemaBase.cpp:33
Sema & SemaRef
Definition SemaBase.h:40
RAII object used to change the argument pack substitution index within a Sema object.
Definition Sema.h:13518
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8400
A RAII object to temporarily push a declaration context.
Definition Sema.h:3475
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6320
DefaultedComparisonKind asComparison() const
Definition Sema.h:6352
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6349
A helper class for building up ExtParameterInfos.
Definition Sema.h:12931
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12383
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:853
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13468
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:13452
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12960
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.
void ActOnFinishCXXNonNestedClass()
NamedDecl * FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, bool FindingInstantiatedContext=false)
Find the instantiation of the given declaration within the current instantiation.
void ActOnFinishDelayedMemberInitializers(Decl *Record)
llvm::function_ref< void(SourceLocation, PartialDiagnostic)> InstantiationContextDiagFuncRef
Definition Sema.h:2284
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:13823
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:1282
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain, bool PrimaryStrictPackMatch)
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition Sema.h:13479
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:921
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void PrintInstantiationStack()
Definition Sema.h:13546
ASTContext & getASTContext() const
Definition Sema.h:924
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.
SmallVector< LateInstantiatedAttribute, 1 > LateInstantiatedAttrVec
Definition Sema.h:13985
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1190
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:917
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
void InstantiateClassMembers(SourceLocation PointOfInstantiation, CXXRecordDecl *Instantiation, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateSpecializationKind TSK)
Instantiates the definitions of all of the member of the given class, which is an instantiation of a ...
void MarkVirtualMembersReferenced(SourceLocation Loc, const CXXRecordDecl *RD, bool ConstexprOnly=false)
MarkVirtualMembersReferenced - Will mark all members of the given CXXRecordDecl referenced.
DeclarationNameInfo SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo, const MultiLevelTemplateArgumentList &TemplateArgs)
Do template substitution on declaration name info.
void MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class, bool DefinitionRequired=false)
Note that the vtable for the given class was used at the given location.
std::vector< std::unique_ptr< TemplateInstantiationCallback > > TemplateInstCallbacks
The template instantiation callbacks to trace or track instantiations (objects can be chained).
Definition Sema.h:13504
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11722
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
std::optional< sema::TemplateDeductionInfo * > isSFINAEContext() const
Determines whether we are currently in a context where template argument substitution failures are no...
CXXBaseSpecifier * CheckBaseSpecifier(CXXRecordDecl *Class, SourceRange SpecifierRange, bool Virtual, AccessSpecifier Access, TypeSourceInfo *TInfo, SourceLocation EllipsisLoc)
Check the validity of a C++ base class specifier.
UnparsedDefaultArgInstantiationsMap UnparsedDefaultArgInstantiations
A mapping from parameters with unparsed default arguments to the set of instantiations of each parame...
Definition Sema.h:12972
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:1417
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:13872
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:13488
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:13818
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:13512
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:1283
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6695
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6705
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13496
NestedNameSpecifierLoc SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS, const MultiLevelTemplateArgumentList &TemplateArgs)
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition Sema.h:8119
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8269
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...
SourceManager & SourceMgr
Definition Sema.h:1285
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool FailOnPackProducingTemplates, bool &ShouldExpand, bool &RetainExpansion, UnsignedOrNone &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
DiagnosticsEngine & Diags
Definition Sema.h:1284
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:1559
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13463
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:627
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:653
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8608
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
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4136
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:358
void printPretty(raw_ostream &OS, PrinterHelper *Helper, const PrintingPolicy &Policy, unsigned Indentation=0, StringRef NewlineSymbol="\n", const ASTContext *Context=nullptr) const
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:334
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Stmt.cpp:346
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3714
void setTagKind(TagKind TK)
Definition Decl.h:3912
SourceRange getBraceRange() const
Definition Decl.h:3785
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3790
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4847
TagKind getTagKind() const
Definition Decl.h:3908
void setBraceRange(SourceRange R)
Definition Decl.h:3786
SourceLocation getNameLoc() const
Definition TypeLoc.h:827
A convenient class for passing around template argument information.
void setLAngleLoc(SourceLocation Loc)
void setRAngleLoc(SourceLocation Loc)
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.
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.
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition Template.h:667
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition Template.h:680
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition Template.h:706
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition Template.h:690
void setEvaluateConstraints(bool B)
Definition Template.h:608
LocalInstantiationScope * getStartingScope() const
Definition Template.h:678
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition Template.h:683
delayed_partial_spec_iterator delayed_partial_spec_end()
Return an iterator to the end of the set of "delayed" partial specializations, which must be passed t...
Definition Template.h:702
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition Template.h:694
ClassTemplatePartialSpecializationDecl * InstantiateClassTemplatePartialSpecialization(ClassTemplateDecl *ClassTemplate, ClassTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a class template partial specialization.
The base class of all kinds of template declarations (e.g., class, function, etc.).
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:223
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:262
UnsignedOrNone getArgPackSubstIndex() const
Definition ASTConcept.h:246
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:240
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:272
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:250
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:276
ConceptReference * getConceptReference() const
Definition ASTConcept.h:244
void setLocStart(SourceLocation L)
Definition Decl.h:3545
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:1417
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:8258
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:272
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8269
SourceLocation getNameLoc() const
Definition TypeLoc.h:552
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:556
An operation on a type.
Definition TypeVisitor.h:64
The base class of the type hierarchy.
Definition TypeBase.h:1833
bool isVoidType() const
Definition TypeBase.h:8880
bool isReferenceType() const
Definition TypeBase.h:8548
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:752
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition TypeBase.h:2790
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2405
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2800
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9100
bool isRecordType() const
Definition TypeBase.h:8651
QualType getUnderlyingType() const
Definition Decl.h:3614
QualType getType() const
Definition Decl.h:722
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5465
Represents a variable declaration or definition.
Definition Decl.h:925
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1282
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2366
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition Decl.cpp:2772
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:2907
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1167
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition Decl.cpp:2898
Declaration of a variable template.
Represents a variable template specialization, which refers to a variable template with a given set o...
const TemplateArgumentList & getTemplateInstantiationArgs() const
Retrieve the set of template arguments that should be used to instantiate the initializer of the vari...
llvm::PointerUnion< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > getSpecializedTemplateOrPartial() const
Retrieve the variable template or variable template partial specialization which was specialized by t...
TemplateSpecializationKind getSpecializationKind() const
Determine the kind of specialization that this declaration represents.
VarTemplateDecl * getSpecializedTemplate() const
Retrieve the template that this specialization specializes.
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
const ReturnTypeRequirement & getReturnTypeRequirement() const
SourceLocation getNoexceptLoc() const
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
A static requirement that can be used in a requires-expression to check properties of types and expre...
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
TypeSourceInfo * getType() const
RetTy Visit(PTR(Decl) D)
Definition DeclVisitor.h:38
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:874
Provides information about an attempted template argument deduction, whose success or failure was des...
TemplateArgumentList * takeCanonical()
SourceLocation getLocation() const
Returns the location at which template argument is occurring.
bool hasSFINAEDiagnostic() const
Is a SFINAE diagnostic available?
void takeSFINAEDiagnostic(PartialDiagnosticAt &PD)
Take ownership of the SFINAE diagnostic.
#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)
std::pair< llvm::PointerUnion< const TemplateTypeParmType *, NamedDecl *, const TemplateSpecializationType *, const SubstBuiltinTemplatePackType * >, SourceLocation > UnexpandedParameterPack
Definition Sema.h:235
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.
const FunctionProtoType * T
@ Template
We are parsing a template declaration.
Definition Parser.h:81
DeductionFailureInfo MakeDeductionFailureInfo(ASTContext &Context, TemplateDeductionResult TDK, sema::TemplateDeductionInfo &Info)
Convert from Sema's representation of template deduction information to the form used in overload-can...
ExprResult ExprError()
Definition Ownership.h:265
@ Type
The name was classified as a type.
Definition Sema.h:561
@ AR_Available
Definition DeclBase.h:73
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:135
@ VK_LValue
An l-value expression is a reference to an object with independent storage.
Definition Specifiers.h:139
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:366
@ Success
Template argument deduction was successful.
Definition Sema.h:368
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:5879
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 ('>').
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
ArrayRef< TemplateArgumentLoc > arguments() 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:5323
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5325
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition Sema.h:12977
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13144
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition Sema.h:13094
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13113
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition Sema.h:13139
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13100
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:12979
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13071
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:12989
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:12998
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13017
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13068
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13025
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13032
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13075
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13043
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13081
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13008
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13087
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13084
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13090
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13005
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13013
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13021
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:12982
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13035
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13039
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:12994
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13065
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13028
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13103
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:13168
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13328
InstantiatingTemplate(Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity, SourceRange InstantiationRange=SourceRange())
Note that we are instantiating a class template, function template, variable template,...
void Clear()
Note that we have finished instantiating this template.
bool isAlreadyInstantiating() const
Determine whether we are already instantiating this specialization in some surrounding active instant...
Definition Sema.h:13332
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation Ellipsis
UnsignedOrNone NumExpansions