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 Inst.InParameterMappingSubstitution =
633 if (!SemaRef.CodeSynthesisContexts.empty()) {
634 Inst.InConstraintSubstitution |=
635 SemaRef.CodeSynthesisContexts.back().InConstraintSubstitution;
636 Inst.InParameterMappingSubstitution |=
637 SemaRef.CodeSynthesisContexts.back().InParameterMappingSubstitution;
638 }
639
640 Invalid = SemaRef.pushCodeSynthesisContext(Inst);
641 if (!Invalid) {
642 AlreadyInstantiating =
643 !Inst.Entity
644 ? false
645 : !SemaRef.InstantiatingSpecializations
646 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
647 .second;
649 }
650}
651
653 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
654 SourceRange InstantiationRange)
655 : InstantiatingTemplate(SemaRef,
656 CodeSynthesisContext::TemplateInstantiation,
657 PointOfInstantiation, InstantiationRange, Entity) {}
658
660 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
661 ExceptionSpecification, SourceRange InstantiationRange)
663 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
664 PointOfInstantiation, InstantiationRange, Entity) {}
665
667 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
669 SourceRange InstantiationRange)
671 SemaRef,
672 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
673 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
674 Template, TemplateArgs) {}
675
677 Sema &SemaRef, SourceLocation PointOfInstantiation,
679 ArrayRef<TemplateArgument> TemplateArgs,
681 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
682 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
683 InstantiationRange, FunctionTemplate, nullptr,
684 TemplateArgs, &DeductionInfo) {
688}
689
691 Sema &SemaRef, SourceLocation PointOfInstantiation,
693 ArrayRef<TemplateArgument> TemplateArgs,
694 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
696 SemaRef,
697 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
698 PointOfInstantiation, InstantiationRange, Template, nullptr,
699 TemplateArgs, &DeductionInfo) {}
700
702 Sema &SemaRef, SourceLocation PointOfInstantiation,
704 ArrayRef<TemplateArgument> TemplateArgs,
705 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
707 SemaRef,
708 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
709 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
710 TemplateArgs, &DeductionInfo) {}
711
713 Sema &SemaRef, SourceLocation PointOfInstantiation,
715 ArrayRef<TemplateArgument> TemplateArgs,
716 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
718 SemaRef,
719 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
720 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
721 TemplateArgs, &DeductionInfo) {}
722
724 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
725 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
727 SemaRef,
728 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
729 PointOfInstantiation, InstantiationRange, Param, nullptr,
730 TemplateArgs) {}
731
733 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
735 SourceRange InstantiationRange)
737 SemaRef,
738 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
739 PointOfInstantiation, InstantiationRange, Param, Template,
740 TemplateArgs) {}
741
743 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
745 SourceRange InstantiationRange)
747 SemaRef,
748 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
749 PointOfInstantiation, InstantiationRange, Param, Template,
750 TemplateArgs) {}
751
753 Sema &SemaRef, SourceLocation PointOfInstantiation,
755 SourceRange InstantiationRange)
757 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
758 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
759 /*Template=*/nullptr, TemplateArgs) {}
760
762 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
763 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
764 SourceRange InstantiationRange)
766 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
767 PointOfInstantiation, InstantiationRange, Param, Template,
768 TemplateArgs) {}
769
771 Sema &SemaRef, SourceLocation PointOfInstantiation,
773 SourceRange InstantiationRange)
775 SemaRef, CodeSynthesisContext::RequirementInstantiation,
776 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
777 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
778
780 Sema &SemaRef, SourceLocation PointOfInstantiation,
782 SourceRange InstantiationRange)
784 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
785 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
786 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
787
789 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
790 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
792 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
793 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
794 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
795
797 Sema &SemaRef, SourceLocation PointOfInstantiation,
799 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
802 PointOfInstantiation, InstantiationRange, Template, nullptr,
803 TemplateArgs) {}
804
806 Sema &SemaRef, SourceLocation PointOfInstantiation,
808 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
811 PointOfInstantiation, InstantiationRange, Template, nullptr,
812 {}, &DeductionInfo) {}
813
815 Sema &SemaRef, SourceLocation PointOfInstantiation,
817 SourceRange InstantiationRange)
820 PointOfInstantiation, InstantiationRange, Template) {}
821
823 Sema &SemaRef, SourceLocation PointOfInstantiation,
825 SourceRange InstantiationRange)
828 PointOfInstantiation, InstantiationRange, Template) {}
829
831 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
832 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
834 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
835 PointOfInstantiation, InstantiationRange, Entity) {}
836
838 Sema &SemaRef, SourceLocation ArgLoc, PartialOrderingTTP,
839 TemplateDecl *PArg, SourceRange InstantiationRange)
841 ArgLoc, InstantiationRange, PArg) {}
842
846
847 if (!Ctx.isInstantiationRecord()) {
849 } else {
850 assert(SemaRef.NonInstantiationEntries <=
851 SemaRef.CodeSynthesisContexts.size());
852 if ((SemaRef.CodeSynthesisContexts.size() -
853 SemaRef.NonInstantiationEntries) >
854 SemaRef.getLangOpts().InstantiationDepth) {
856 diag::err_template_recursion_depth_exceeded)
857 << SemaRef.getLangOpts().InstantiationDepth << Ctx.InstantiationRange;
859 diag::note_template_recursion_depth)
860 << SemaRef.getLangOpts().InstantiationDepth;
861 return true;
862 }
863 }
864
865 CodeSynthesisContexts.push_back(Ctx);
866
867 // Check to see if we're low on stack space. We can't do anything about this
868 // from here, but we can at least warn the user.
869 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
870 return false;
871}
872
874 auto &Active = CodeSynthesisContexts.back();
875 if (!Active.isInstantiationRecord()) {
876 assert(NonInstantiationEntries > 0);
878 }
879
880 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
881
882 // Name lookup no longer looks in this template's defining module.
883 assert(CodeSynthesisContexts.size() >=
885 "forgot to remove a lookup module for a template instantiation");
886 if (CodeSynthesisContexts.size() ==
889 LookupModulesCache.erase(M);
891 }
892
893 // If we've left the code synthesis context for the current context stack,
894 // stop remembering that we've emitted that stack.
895 if (CodeSynthesisContexts.size() ==
898
899 CodeSynthesisContexts.pop_back();
900}
901
903 if (!Invalid) {
904 if (!AlreadyInstantiating) {
905 auto &Active = SemaRef.CodeSynthesisContexts.back();
906 if (Active.Entity)
907 SemaRef.InstantiatingSpecializations.erase(
908 {Active.Entity->getCanonicalDecl(), Active.Kind});
909 }
910
911 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
912 SemaRef.CodeSynthesisContexts.back());
913
914 SemaRef.popCodeSynthesisContext();
915 Invalid = true;
916 }
917}
918
919static std::string convertCallArgsToString(Sema &S,
921 std::string Result;
922 llvm::raw_string_ostream OS(Result);
923 llvm::ListSeparator Comma;
924 for (const Expr *Arg : Args) {
925 OS << Comma;
926 Arg->IgnoreParens()->printPretty(OS, nullptr,
928 }
929 return Result;
930}
931
933 // Determine which template instantiations to skip, if any.
934 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
935 unsigned Limit = Diags.getTemplateBacktraceLimit();
936 if (Limit && Limit < CodeSynthesisContexts.size()) {
937 SkipStart = Limit / 2 + Limit % 2;
938 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
939 }
940
941 // FIXME: In all of these cases, we need to show the template arguments
942 unsigned InstantiationIdx = 0;
944 Active = CodeSynthesisContexts.rbegin(),
945 ActiveEnd = CodeSynthesisContexts.rend();
946 Active != ActiveEnd;
947 ++Active, ++InstantiationIdx) {
948 // Skip this instantiation?
949 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
950 if (InstantiationIdx == SkipStart) {
951 // Note that we're skipping instantiations.
952 DiagFunc(Active->PointOfInstantiation,
953 PDiag(diag::note_instantiation_contexts_suppressed)
954 << unsigned(CodeSynthesisContexts.size() - Limit));
955 }
956 continue;
957 }
958
959 switch (Active->Kind) {
961 Decl *D = Active->Entity;
962 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
963 unsigned DiagID = diag::note_template_member_class_here;
965 DiagID = diag::note_template_class_instantiation_here;
966 DiagFunc(Active->PointOfInstantiation,
967 PDiag(DiagID) << Record << Active->InstantiationRange);
968 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
969 unsigned DiagID;
970 if (Function->getPrimaryTemplate())
971 DiagID = diag::note_function_template_spec_here;
972 else
973 DiagID = diag::note_template_member_function_here;
974 DiagFunc(Active->PointOfInstantiation,
975 PDiag(DiagID) << Function << Active->InstantiationRange);
976 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
977 DiagFunc(Active->PointOfInstantiation,
978 PDiag(VD->isStaticDataMember()
979 ? diag::note_template_static_data_member_def_here
980 : diag::note_template_variable_def_here)
981 << VD << Active->InstantiationRange);
982 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
983 DiagFunc(Active->PointOfInstantiation,
984 PDiag(diag::note_template_enum_def_here)
985 << ED << Active->InstantiationRange);
986 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
987 DiagFunc(Active->PointOfInstantiation,
988 PDiag(diag::note_template_nsdmi_here)
989 << FD << Active->InstantiationRange);
990 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
991 DiagFunc(Active->PointOfInstantiation,
992 PDiag(diag::note_template_class_instantiation_here)
993 << CTD << Active->InstantiationRange);
994 }
995 break;
996 }
997
999 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
1000 SmallString<128> TemplateArgsStr;
1001 llvm::raw_svector_ostream OS(TemplateArgsStr);
1002 Template->printName(OS, getPrintingPolicy());
1003 printTemplateArgumentList(OS, Active->template_arguments(),
1005 DiagFunc(Active->PointOfInstantiation,
1006 PDiag(diag::note_default_arg_instantiation_here)
1007 << OS.str() << Active->InstantiationRange);
1008 break;
1009 }
1010
1012 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
1013 DiagFunc(Active->PointOfInstantiation,
1014 PDiag(diag::note_explicit_template_arg_substitution_here)
1015 << FnTmpl
1017 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1018 Active->NumTemplateArgs)
1019 << Active->InstantiationRange);
1020 break;
1021 }
1022
1024 if (FunctionTemplateDecl *FnTmpl =
1025 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1026 DiagFunc(
1027 Active->PointOfInstantiation,
1028 PDiag(diag::note_function_template_deduction_instantiation_here)
1029 << FnTmpl
1031 FnTmpl->getTemplateParameters(), Active->TemplateArgs,
1032 Active->NumTemplateArgs)
1033 << Active->InstantiationRange);
1034 } else {
1035 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1036 isa<VarTemplateSpecializationDecl>(Active->Entity);
1037 bool IsTemplate = false;
1038 TemplateParameterList *Params;
1039 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1040 IsTemplate = true;
1041 Params = D->getTemplateParameters();
1042 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1043 Active->Entity)) {
1044 Params = D->getTemplateParameters();
1045 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1046 Active->Entity)) {
1047 Params = D->getTemplateParameters();
1048 } else {
1049 llvm_unreachable("unexpected template kind");
1050 }
1051
1052 DiagFunc(Active->PointOfInstantiation,
1053 PDiag(diag::note_deduced_template_arg_substitution_here)
1054 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1056 Active->TemplateArgs,
1057 Active->NumTemplateArgs)
1058 << Active->InstantiationRange);
1059 }
1060 break;
1061 }
1062
1064 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1065 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1066
1067 SmallString<128> TemplateArgsStr;
1068 llvm::raw_svector_ostream OS(TemplateArgsStr);
1070 printTemplateArgumentList(OS, Active->template_arguments(),
1072 DiagFunc(Active->PointOfInstantiation,
1073 PDiag(diag::note_default_function_arg_instantiation_here)
1074 << OS.str() << Active->InstantiationRange);
1075 break;
1076 }
1077
1079 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1080 std::string Name;
1081 if (!Parm->getName().empty())
1082 Name = std::string(" '") + Parm->getName().str() + "'";
1083
1084 TemplateParameterList *TemplateParams = nullptr;
1085 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1086 TemplateParams = Template->getTemplateParameters();
1087 else
1088 TemplateParams =
1090 ->getTemplateParameters();
1091 DiagFunc(Active->PointOfInstantiation,
1092 PDiag(diag::note_prior_template_arg_substitution)
1093 << isa<TemplateTemplateParmDecl>(Parm) << Name
1094 << getTemplateArgumentBindingsText(TemplateParams,
1095 Active->TemplateArgs,
1096 Active->NumTemplateArgs)
1097 << Active->InstantiationRange);
1098 break;
1099 }
1100
1102 TemplateParameterList *TemplateParams = nullptr;
1103 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1104 TemplateParams = Template->getTemplateParameters();
1105 else
1106 TemplateParams =
1108 ->getTemplateParameters();
1109
1110 DiagFunc(Active->PointOfInstantiation,
1111 PDiag(diag::note_template_default_arg_checking)
1112 << getTemplateArgumentBindingsText(TemplateParams,
1113 Active->TemplateArgs,
1114 Active->NumTemplateArgs)
1115 << Active->InstantiationRange);
1116 break;
1117 }
1118
1120 DiagFunc(Active->PointOfInstantiation,
1121 PDiag(diag::note_evaluating_exception_spec_here)
1122 << cast<FunctionDecl>(Active->Entity));
1123 break;
1124
1126 DiagFunc(Active->PointOfInstantiation,
1127 PDiag(diag::note_template_exception_spec_instantiation_here)
1128 << cast<FunctionDecl>(Active->Entity)
1129 << Active->InstantiationRange);
1130 break;
1131
1133 DiagFunc(Active->PointOfInstantiation,
1134 PDiag(diag::note_template_requirement_instantiation_here)
1135 << Active->InstantiationRange);
1136 break;
1138 DiagFunc(Active->PointOfInstantiation,
1139 PDiag(diag::note_template_requirement_params_instantiation_here)
1140 << Active->InstantiationRange);
1141 break;
1142
1144 DiagFunc(Active->PointOfInstantiation,
1145 PDiag(diag::note_nested_requirement_here)
1146 << Active->InstantiationRange);
1147 break;
1148
1150 DiagFunc(Active->PointOfInstantiation,
1151 PDiag(diag::note_in_declaration_of_implicit_special_member)
1152 << cast<CXXRecordDecl>(Active->Entity)
1153 << Active->SpecialMember);
1154 break;
1155
1157 DiagFunc(
1158 Active->Entity->getLocation(),
1159 PDiag(diag::note_in_declaration_of_implicit_equality_comparison));
1160 break;
1161
1163 // FIXME: For synthesized functions that are not defaulted,
1164 // produce a note.
1165 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1166 // Note: if FD is nullptr currently setting DFK to DefaultedFunctionKind()
1167 // will ensure that DFK.isComparison() is false. This is important because
1168 // we will uncondtionally dereference FD in the else if.
1171 if (DFK.isSpecialMember()) {
1172 auto *MD = cast<CXXMethodDecl>(FD);
1173 DiagFunc(Active->PointOfInstantiation,
1174 PDiag(diag::note_member_synthesized_at)
1175 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
1176 << Context.getCanonicalTagType(MD->getParent()));
1177 } else if (DFK.isComparison()) {
1178 QualType RecordType = FD->getParamDecl(0)
1179 ->getType()
1180 .getNonReferenceType()
1181 .getUnqualifiedType();
1182 DiagFunc(Active->PointOfInstantiation,
1183 PDiag(diag::note_comparison_synthesized_at)
1184 << (int)DFK.asComparison() << RecordType);
1185 }
1186 break;
1187 }
1188
1190 DiagFunc(Active->Entity->getLocation(),
1191 PDiag(diag::note_rewriting_operator_as_spaceship));
1192 break;
1193
1195 DiagFunc(Active->PointOfInstantiation,
1196 PDiag(diag::note_in_binding_decl_init)
1197 << cast<BindingDecl>(Active->Entity));
1198 break;
1199
1201 DiagFunc(Active->PointOfInstantiation,
1202 PDiag(diag::note_due_to_dllexported_class)
1203 << cast<CXXRecordDecl>(Active->Entity)
1204 << !getLangOpts().CPlusPlus11);
1205 break;
1206
1208 DiagFunc(Active->PointOfInstantiation,
1209 PDiag(diag::note_building_builtin_dump_struct_call)
1211 *this, llvm::ArrayRef(Active->CallArgs,
1212 Active->NumCallArgs)));
1213 break;
1214
1216 break;
1217
1219 DiagFunc(Active->PointOfInstantiation,
1220 PDiag(diag::note_lambda_substitution_here));
1221 break;
1223 unsigned DiagID = 0;
1224 if (!Active->Entity) {
1225 DiagFunc(Active->PointOfInstantiation,
1226 PDiag(diag::note_nested_requirement_here)
1227 << Active->InstantiationRange);
1228 break;
1229 }
1230 if (isa<ConceptDecl>(Active->Entity))
1231 DiagID = diag::note_concept_specialization_here;
1232 else if (isa<TemplateDecl>(Active->Entity))
1233 DiagID = diag::note_checking_constraints_for_template_id_here;
1234 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1235 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1236 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1237 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1238 else {
1239 assert(isa<FunctionDecl>(Active->Entity));
1240 DiagID = diag::note_checking_constraints_for_function_here;
1241 }
1242 SmallString<128> TemplateArgsStr;
1243 llvm::raw_svector_ostream OS(TemplateArgsStr);
1244 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1245 if (!isa<FunctionDecl>(Active->Entity)) {
1246 printTemplateArgumentList(OS, Active->template_arguments(),
1248 }
1249 DiagFunc(Active->PointOfInstantiation,
1250 PDiag(DiagID) << OS.str() << Active->InstantiationRange);
1251 break;
1252 }
1254 DiagFunc(Active->PointOfInstantiation,
1255 PDiag(diag::note_constraint_substitution_here)
1256 << Active->InstantiationRange);
1257 break;
1259 DiagFunc(Active->PointOfInstantiation,
1260 PDiag(diag::note_constraint_normalization_here)
1261 << cast<NamedDecl>(Active->Entity)
1262 << Active->InstantiationRange);
1263 break;
1265 DiagFunc(Active->PointOfInstantiation,
1266 PDiag(diag::note_parameter_mapping_substitution_here)
1267 << Active->InstantiationRange);
1268 break;
1270 DiagFunc(Active->PointOfInstantiation,
1271 PDiag(diag::note_building_deduction_guide_here));
1272 break;
1274 // Workaround for a workaround: don't produce a note if we are merely
1275 // instantiating some other template which contains this alias template.
1276 // This would be redundant either with the error itself, or some other
1277 // context note attached to it.
1278 if (Active->NumTemplateArgs == 0)
1279 break;
1280 DiagFunc(Active->PointOfInstantiation,
1281 PDiag(diag::note_template_type_alias_instantiation_here)
1282 << cast<TypeAliasTemplateDecl>(Active->Entity)
1283 << Active->InstantiationRange);
1284 break;
1286 DiagFunc(Active->PointOfInstantiation,
1287 PDiag(diag::note_template_arg_template_params_mismatch));
1288 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1289 ParamLoc.isValid())
1290 DiagFunc(ParamLoc, PDiag(diag::note_template_prev_declaration)
1291 << /*isTemplateTemplateParam=*/true
1292 << Active->InstantiationRange);
1293 break;
1294 }
1295 }
1296}
1297
1298std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1300 return std::optional<TemplateDeductionInfo *>(nullptr);
1301
1303 Active = CodeSynthesisContexts.rbegin(),
1304 ActiveEnd = CodeSynthesisContexts.rend();
1305 Active != ActiveEnd;
1306 ++Active)
1307 {
1308 switch (Active->Kind) {
1310 // An instantiation of an alias template may or may not be a SFINAE
1311 // context, depending on what else is on the stack.
1312 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1313 break;
1314 [[fallthrough]];
1322 // This is a template instantiation, so there is no SFINAE.
1323 return std::nullopt;
1325 // [temp.deduct]p9
1326 // A lambda-expression appearing in a function type or a template
1327 // parameter is not considered part of the immediate context for the
1328 // purposes of template argument deduction.
1329 // CWG2672: A lambda-expression body is never in the immediate context.
1330 return std::nullopt;
1331
1337 // A default template argument instantiation and substitution into
1338 // template parameters with arguments for prior parameters may or may
1339 // not be a SFINAE context; look further up the stack.
1340 break;
1341
1344 // We're either substituting explicitly-specified template arguments,
1345 // deduced template arguments. SFINAE applies unless we are in a lambda
1346 // body, see [temp.deduct]p9.
1350 // SFINAE always applies in a constraint expression or a requirement
1351 // in a requires expression.
1352 assert(Active->DeductionInfo && "Missing deduction info pointer");
1353 return Active->DeductionInfo;
1354
1362 // This happens in a context unrelated to template instantiation, so
1363 // there is no SFINAE.
1364 return std::nullopt;
1365
1367 // FIXME: This should not be treated as a SFINAE context, because
1368 // we will cache an incorrect exception specification. However, clang
1369 // bootstrap relies this! See PR31692.
1370 break;
1371
1373 break;
1374 }
1375
1376 // The inner context was transparent for SFINAE. If it occurred within a
1377 // non-instantiation SFINAE context, then SFINAE applies.
1378 if (Active->SavedInNonInstantiationSFINAEContext)
1379 return std::optional<TemplateDeductionInfo *>(nullptr);
1380 }
1381
1382 return std::nullopt;
1383}
1384
1385//===----------------------------------------------------------------------===/
1386// Template Instantiation for Types
1387//===----------------------------------------------------------------------===/
1388namespace {
1389
1390 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1391 const MultiLevelTemplateArgumentList &TemplateArgs;
1392 SourceLocation Loc;
1393 DeclarationName Entity;
1394 // Whether to evaluate the C++20 constraints or simply substitute into them.
1395 bool EvaluateConstraints = true;
1396 // Whether Substitution was Incomplete, that is, we tried to substitute in
1397 // any user provided template arguments which were null.
1398 bool IsIncomplete = false;
1399 // Whether an incomplete substituion should be treated as an error.
1400 bool BailOutOnIncomplete;
1401
1402 // Whether to rebuild pack expansion types; We don't do that when
1403 // rebuilding the parameter mapping of a fold expression appearing
1404 // in a constraint expression.
1405 bool BuildPackExpansionTypes = true;
1406
1407 // CWG2770: Function parameters should be instantiated when they are
1408 // needed by a satisfaction check of an atomic constraint or
1409 // (recursively) by another function parameter.
1410 bool maybeInstantiateFunctionParameterToScope(ParmVarDecl *OldParm);
1411
1412 public:
1413 typedef TreeTransform<TemplateInstantiator> inherited;
1414
1415 TemplateInstantiator(Sema &SemaRef,
1416 const MultiLevelTemplateArgumentList &TemplateArgs,
1417 SourceLocation Loc, DeclarationName Entity,
1418 bool BailOutOnIncomplete = false)
1419 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1420 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1421
1422 void setEvaluateConstraints(bool B) {
1423 EvaluateConstraints = B;
1424 }
1425 bool getEvaluateConstraints() {
1426 return EvaluateConstraints;
1427 }
1428
1429 inline static struct ForParameterMappingSubstitution_t {
1430 } ForParameterMappingSubstitution;
1431
1432 TemplateInstantiator(ForParameterMappingSubstitution_t, Sema &SemaRef,
1433 SourceLocation Loc,
1434 const MultiLevelTemplateArgumentList &TemplateArgs,
1435 bool BuildPackExpansionTypes)
1436 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1437 BailOutOnIncomplete(false),
1438 BuildPackExpansionTypes(BuildPackExpansionTypes) {}
1439
1440 /// Determine whether the given type \p T has already been
1441 /// transformed.
1442 ///
1443 /// For the purposes of template instantiation, a type has already been
1444 /// transformed if it is NULL or if it is not dependent.
1445 bool AlreadyTransformed(QualType T);
1446
1447 /// Returns the location of the entity being instantiated, if known.
1448 SourceLocation getBaseLocation() { return Loc; }
1449
1450 /// Returns the name of the entity being instantiated, if any.
1451 DeclarationName getBaseEntity() { return Entity; }
1452
1453 /// Returns whether any substitution so far was incomplete.
1454 bool getIsIncomplete() const { return IsIncomplete; }
1455
1456 /// Sets the "base" location and entity when that
1457 /// information is known based on another transformation.
1458 void setBase(SourceLocation Loc, DeclarationName Entity) {
1459 this->Loc = Loc;
1460 this->Entity = Entity;
1461 }
1462
1463 unsigned TransformTemplateDepth(unsigned Depth) {
1464 return TemplateArgs.getNewDepth(Depth);
1465 }
1466
1467 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1468 SourceRange PatternRange,
1469 ArrayRef<UnexpandedParameterPack> Unexpanded,
1470 bool FailOnPackProducingTemplates,
1471 bool &ShouldExpand, bool &RetainExpansion,
1472 UnsignedOrNone &NumExpansions) {
1473 if (SemaRef.CurrentInstantiationScope &&
1474 (SemaRef.inConstraintSubstitution() ||
1475 SemaRef.inParameterMappingSubstitution())) {
1476 for (UnexpandedParameterPack ParmPack : Unexpanded) {
1477 NamedDecl *VD = ParmPack.first.dyn_cast<NamedDecl *>();
1478 if (auto *PVD = dyn_cast_if_present<ParmVarDecl>(VD);
1479 PVD && maybeInstantiateFunctionParameterToScope(PVD))
1480 return true;
1481 }
1482 }
1483
1484 return getSema().CheckParameterPacksForExpansion(
1485 EllipsisLoc, PatternRange, Unexpanded, TemplateArgs,
1486 FailOnPackProducingTemplates, ShouldExpand, RetainExpansion,
1487 NumExpansions);
1488 }
1489
1490 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1492 }
1493
1494 TemplateArgument ForgetPartiallySubstitutedPack() {
1495 TemplateArgument Result;
1496 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1498 MultiLevelTemplateArgumentList &TemplateArgs =
1499 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1500 unsigned Depth, Index;
1501 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1502 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1503 Result = TemplateArgs(Depth, Index);
1504 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1505 } else {
1506 IsIncomplete = true;
1507 if (BailOutOnIncomplete)
1508 return TemplateArgument();
1509 }
1510 }
1511
1512 return Result;
1513 }
1514
1515 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1516 if (Arg.isNull())
1517 return;
1518
1519 if (NamedDecl *PartialPack = SemaRef.CurrentInstantiationScope
1521 MultiLevelTemplateArgumentList &TemplateArgs =
1522 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1523 unsigned Depth, Index;
1524 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1525 TemplateArgs.setArgument(Depth, Index, Arg);
1526 }
1527 }
1528
1529 MultiLevelTemplateArgumentList ForgetSubstitution() {
1530 MultiLevelTemplateArgumentList New;
1531 New.addOuterRetainedLevels(this->TemplateArgs.getNumLevels());
1532
1533 MultiLevelTemplateArgumentList Old =
1534 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1535 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) =
1536 std::move(New);
1537 return Old;
1538 }
1539
1540 void RememberSubstitution(MultiLevelTemplateArgumentList Old) {
1541 const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs) = Old;
1542 }
1543
1544 TemplateArgument
1545 getTemplateArgumentPackPatternForRewrite(const TemplateArgument &TA) {
1546 if (TA.getKind() != TemplateArgument::Pack)
1547 return TA;
1548 if (SemaRef.ArgPackSubstIndex)
1549 return SemaRef.getPackSubstitutedTemplateArgument(TA);
1550 assert(TA.pack_size() == 1 && TA.pack_begin()->isPackExpansion() &&
1551 "unexpected pack arguments in template rewrite");
1552 TemplateArgument Arg = *TA.pack_begin();
1553 if (Arg.isPackExpansion())
1554 Arg = Arg.getPackExpansionPattern();
1555 return Arg;
1556 }
1557
1558 /// Transform the given declaration by instantiating a reference to
1559 /// this declaration.
1560 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1561
1562 void transformAttrs(Decl *Old, Decl *New) {
1563 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1564 }
1565
1566 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1567 if (Old->isParameterPack() &&
1568 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1570 for (auto *New : NewDecls)
1572 Old, cast<VarDecl>(New));
1573 return;
1574 }
1575
1576 assert(NewDecls.size() == 1 &&
1577 "should only have multiple expansions for a pack");
1578 Decl *New = NewDecls.front();
1579
1580 // If we've instantiated the call operator of a lambda or the call
1581 // operator template of a generic lambda, update the "instantiation of"
1582 // information.
1583 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1584 if (NewMD && isLambdaCallOperator(NewMD)) {
1585 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1586 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1587 NewTD->setInstantiatedFromMemberTemplate(
1588 OldMD->getDescribedFunctionTemplate());
1589 else
1590 NewMD->setInstantiationOfMemberFunction(OldMD,
1592 }
1593
1595
1596 // We recreated a local declaration, but not by instantiating it. There
1597 // may be pending dependent diagnostics to produce.
1598 if (auto *DC = dyn_cast<DeclContext>(Old);
1599 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1600 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1601 }
1602
1603 /// Transform the definition of the given declaration by
1604 /// instantiating it.
1605 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1606
1607 /// Transform the first qualifier within a scope by instantiating the
1608 /// declaration.
1609 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1610
1611 bool TransformExceptionSpec(SourceLocation Loc,
1612 FunctionProtoType::ExceptionSpecInfo &ESI,
1613 SmallVectorImpl<QualType> &Exceptions,
1614 bool &Changed);
1615
1616 /// Rebuild the exception declaration and register the declaration
1617 /// as an instantiated local.
1618 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1619 TypeSourceInfo *Declarator,
1620 SourceLocation StartLoc,
1621 SourceLocation NameLoc,
1622 IdentifierInfo *Name);
1623
1624 /// Rebuild the Objective-C exception declaration and register the
1625 /// declaration as an instantiated local.
1626 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1627 TypeSourceInfo *TSInfo, QualType T);
1628
1630 TransformTemplateName(NestedNameSpecifierLoc &QualifierLoc,
1631 SourceLocation TemplateKWLoc, TemplateName Name,
1632 SourceLocation NameLoc,
1633 QualType ObjectType = QualType(),
1634 NamedDecl *FirstQualifierInScope = nullptr,
1635 bool AllowInjectedClassName = false);
1636
1637 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1638 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1639 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1640 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1641 const Stmt *InstS,
1642 const NoInlineAttr *A);
1643 const AlwaysInlineAttr *
1644 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1645 const AlwaysInlineAttr *A);
1646 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1647 const OpenACCRoutineDeclAttr *
1648 TransformOpenACCRoutineDeclAttr(const OpenACCRoutineDeclAttr *A);
1649 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1650 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1651 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1652
1653 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1654 NonTypeTemplateParmDecl *D);
1655
1656 /// Rebuild a DeclRefExpr for a VarDecl reference.
1657 ExprResult RebuildVarDeclRefExpr(ValueDecl *PD, SourceLocation Loc);
1658
1659 /// Transform a reference to a function or init-capture parameter pack.
1660 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, ValueDecl *PD);
1661
1662 /// Transform a FunctionParmPackExpr which was built when we couldn't
1663 /// expand a function parameter pack reference which refers to an expanded
1664 /// pack.
1665 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1666
1667 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1668 FunctionProtoTypeLoc TL) {
1669 // Call the base version; it will forward to our overridden version below.
1670 return inherited::TransformFunctionProtoType(TLB, TL);
1671 }
1672
1673 QualType TransformTagType(TypeLocBuilder &TLB, TagTypeLoc TL) {
1674 auto Type = inherited::TransformTagType(TLB, TL);
1675 if (!Type.isNull())
1676 return Type;
1677 // Special case for transforming a deduction guide, we return a
1678 // transformed TemplateSpecializationType.
1679 // FIXME: Why is this hack necessary?
1680 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(TL.getTypePtr());
1681 ICNT && SemaRef.CodeSynthesisContexts.back().Kind ==
1683 Type = inherited::TransformType(
1684 ICNT->getOriginalDecl()->getCanonicalTemplateSpecializationType(
1685 SemaRef.Context));
1686 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1687 }
1688 return Type;
1689 }
1690 // Override the default version to handle a rewrite-template-arg-pack case
1691 // for building a deduction guide.
1692 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1693 TemplateArgumentLoc &Output,
1694 bool Uneval = false) {
1695 const TemplateArgument &Arg = Input.getArgument();
1696 std::vector<TemplateArgument> TArgs;
1697 switch (Arg.getKind()) {
1699 assert(SemaRef.CodeSynthesisContexts.empty() ||
1700 SemaRef.CodeSynthesisContexts.back().Kind ==
1702 // Literally rewrite the template argument pack, instead of unpacking
1703 // it.
1704 for (auto &pack : Arg.getPackAsArray()) {
1705 TemplateArgumentLoc Input = SemaRef.getTrivialTemplateArgumentLoc(
1706 pack, QualType(), SourceLocation{});
1707 TemplateArgumentLoc Output;
1708 if (TransformTemplateArgument(Input, Output, Uneval))
1709 return true; // fails
1710 TArgs.push_back(Output.getArgument());
1711 }
1712 Output = SemaRef.getTrivialTemplateArgumentLoc(
1713 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1714 QualType(), SourceLocation{});
1715 return false;
1716 default:
1717 break;
1718 }
1719 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1720 }
1721
1722 // This has to be here to allow its overload.
1723 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
1724 UnsignedOrNone NumExpansions) {
1725 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
1726 NumExpansions);
1727 }
1728
1729 TemplateArgumentLoc RebuildPackExpansion(TemplateArgumentLoc Pattern,
1730 SourceLocation EllipsisLoc,
1731 UnsignedOrNone NumExpansions) {
1732 // We don't rewrite a PackExpansion type when we want to normalize a
1733 // CXXFoldExpr constraint. We'll expand it when evaluating the constraint.
1734 if (BuildPackExpansionTypes)
1735 return inherited::RebuildPackExpansion(Pattern, EllipsisLoc,
1736 NumExpansions);
1737 return Pattern;
1738 }
1739
1741 QualType
1742 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
1743 TemplateSpecializationTypeLoc TL) {
1744 auto *T = TL.getTypePtr();
1745 if (!getSema().ArgPackSubstIndex || !T->isSugared() ||
1746 !isPackProducingBuiltinTemplateName(T->getTemplateName()))
1748 // Look through sugar to get to the SubstBuiltinTemplatePackType that we
1749 // need to substitute into.
1750
1751 // `TransformType` code below will handle picking the element from a pack
1752 // with the index `ArgPackSubstIndex`.
1753 // FIXME: add ability to represent sugarred type for N-th element of a
1754 // builtin pack and produce the sugar here.
1755 QualType R = TransformType(T->desugar());
1756 TLB.pushTrivial(getSema().getASTContext(), R, TL.getBeginLoc());
1757 return R;
1758 }
1759
1760 UnsignedOrNone ComputeSizeOfPackExprWithoutSubstitution(
1761 ArrayRef<TemplateArgument> PackArgs) {
1762 // Don't do this when rewriting template parameters for CTAD:
1763 // 1) The heuristic needs the unpacked Subst* nodes to figure out the
1764 // expanded size, but this never applies since Subst* nodes are not
1765 // created in rewrite scenarios.
1766 //
1767 // 2) The heuristic substitutes into the pattern with pack expansion
1768 // suppressed, which does not meet the requirements for argument
1769 // rewriting when template arguments include a non-pack matching against
1770 // a pack, particularly when rewriting an alias CTAD.
1771 if (TemplateArgs.isRewrite())
1772 return std::nullopt;
1773
1774 return inherited::ComputeSizeOfPackExprWithoutSubstitution(PackArgs);
1775 }
1776
1777 template<typename Fn>
1778 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1779 FunctionProtoTypeLoc TL,
1780 CXXRecordDecl *ThisContext,
1781 Qualifiers ThisTypeQuals,
1782 Fn TransformExceptionSpec);
1783
1784 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
1785 int indexAdjustment,
1786 UnsignedOrNone NumExpansions,
1787 bool ExpectParameterPack);
1788
1789 using inherited::TransformTemplateTypeParmType;
1790 /// Transforms a template type parameter type by performing
1791 /// substitution of the corresponding template type argument.
1792 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1793 TemplateTypeParmTypeLoc TL,
1794 bool SuppressObjCLifetime);
1795
1796 QualType BuildSubstTemplateTypeParmType(
1797 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1798 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
1799 TemplateArgument Arg, SourceLocation NameLoc);
1800
1801 /// Transforms an already-substituted template type parameter pack
1802 /// into either itself (if we aren't substituting into its pack expansion)
1803 /// or the appropriate substituted argument.
1804 using inherited::TransformSubstTemplateTypeParmPackType;
1805 QualType
1806 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1807 SubstTemplateTypeParmPackTypeLoc TL,
1808 bool SuppressObjCLifetime);
1809 QualType
1810 TransformSubstBuiltinTemplatePackType(TypeLocBuilder &TLB,
1811 SubstBuiltinTemplatePackTypeLoc TL);
1812
1814 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1815 if (auto TypeAlias =
1816 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1817 getSema());
1818 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1819 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1820 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1821 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1822 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1823 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1824 if (TA.isDependent())
1825 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1826 }
1827 return inherited::ComputeLambdaDependency(LSI);
1828 }
1829
1830 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1831 // Do not rebuild lambdas to avoid creating a new type.
1832 // Lambdas have already been processed inside their eval contexts.
1834 return E;
1835 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1836 /*InstantiatingLambdaOrBlock=*/true);
1837 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1838
1839 return inherited::TransformLambdaExpr(E);
1840 }
1841
1842 ExprResult TransformBlockExpr(BlockExpr *E) {
1843 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1844 /*InstantiatingLambdaOrBlock=*/true);
1845 return inherited::TransformBlockExpr(E);
1846 }
1847
1848 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1849 LambdaScopeInfo *LSI) {
1850 CXXMethodDecl *MD = LSI->CallOperator;
1851 for (ParmVarDecl *PVD : MD->parameters()) {
1852 assert(PVD && "null in a parameter list");
1853 if (!PVD->hasDefaultArg())
1854 continue;
1855 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1856 // FIXME: Obtain the source location for the '=' token.
1857 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1858 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1859 // If substitution fails, the default argument is set to a
1860 // RecoveryExpr that wraps the uninstantiated default argument so
1861 // that downstream diagnostics are omitted.
1862 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1863 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1864 UninstExpr->getType());
1865 if (ErrorResult.isUsable())
1866 PVD->setDefaultArg(ErrorResult.get());
1867 }
1868 }
1869 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1870 }
1871
1872 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1873 // Currently, we instantiate the body when instantiating the lambda
1874 // expression. However, `EvaluateConstraints` is disabled during the
1875 // instantiation of the lambda expression, causing the instantiation
1876 // failure of the return type requirement in the body. If p0588r1 is fully
1877 // implemented, the body will be lazily instantiated, and this problem
1878 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1879 // `true` to temporarily fix this issue.
1880 // FIXME: This temporary fix can be removed after fully implementing
1881 // p0588r1.
1882 llvm::SaveAndRestore _(EvaluateConstraints, true);
1883 return inherited::TransformLambdaBody(E, Body);
1884 }
1885
1886 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1887 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1888 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1889 if (TransReq.isInvalid())
1890 return TransReq;
1891 assert(TransReq.get() != E &&
1892 "Do not change value of isSatisfied for the existing expression. "
1893 "Create a new expression instead.");
1894 if (E->getBody()->isDependentContext()) {
1895 Sema::SFINAETrap Trap(SemaRef);
1896 // We recreate the RequiresExpr body, but not by instantiating it.
1897 // Produce pending diagnostics for dependent access check.
1898 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1899 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1900 if (Trap.hasErrorOccurred())
1901 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1902 }
1903 return TransReq;
1904 }
1905
1906 bool TransformRequiresExprRequirements(
1907 ArrayRef<concepts::Requirement *> Reqs,
1908 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1909 bool SatisfactionDetermined = false;
1910 for (concepts::Requirement *Req : Reqs) {
1911 concepts::Requirement *TransReq = nullptr;
1912 if (!SatisfactionDetermined) {
1913 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1914 TransReq = TransformTypeRequirement(TypeReq);
1915 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1916 TransReq = TransformExprRequirement(ExprReq);
1917 else
1918 TransReq = TransformNestedRequirement(
1920 if (!TransReq)
1921 return true;
1922 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1923 // [expr.prim.req]p6
1924 // [...] The substitution and semantic constraint checking
1925 // proceeds in lexical order and stops when a condition that
1926 // determines the result of the requires-expression is
1927 // encountered. [..]
1928 SatisfactionDetermined = true;
1929 } else
1930 TransReq = Req;
1931 Transformed.push_back(TransReq);
1932 }
1933 return false;
1934 }
1935
1936 TemplateParameterList *TransformTemplateParameterList(
1937 TemplateParameterList *OrigTPL) {
1938 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1939
1940 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1941 TemplateDeclInstantiator DeclInstantiator(getSema(),
1942 /* DeclContext *Owner */ Owner, TemplateArgs);
1943 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1944 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1945 }
1946
1947 concepts::TypeRequirement *
1948 TransformTypeRequirement(concepts::TypeRequirement *Req);
1949 concepts::ExprRequirement *
1950 TransformExprRequirement(concepts::ExprRequirement *Req);
1951 concepts::NestedRequirement *
1952 TransformNestedRequirement(concepts::NestedRequirement *Req);
1953 ExprResult TransformRequiresTypeParams(
1954 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1955 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1956 SmallVectorImpl<QualType> &PTypes,
1957 SmallVectorImpl<ParmVarDecl *> &TransParams,
1958 Sema::ExtParameterInfoBuilder &PInfos);
1959 };
1960}
1961
1962bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1963 if (T.isNull())
1964 return true;
1965
1968 return false;
1969
1970 getSema().MarkDeclarationsReferencedInType(Loc, T);
1971 return true;
1972}
1973
1974Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1975 if (!D)
1976 return nullptr;
1977
1978 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1979 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1980 // If the corresponding template argument is NULL or non-existent, it's
1981 // because we are performing instantiation from explicitly-specified
1982 // template arguments in a function template, but there were some
1983 // arguments left unspecified.
1984 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1985 TTP->getPosition())) {
1986 IsIncomplete = true;
1987 return BailOutOnIncomplete ? nullptr : D;
1988 }
1989
1990 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1991
1992 if (TTP->isParameterPack()) {
1993 assert(Arg.getKind() == TemplateArgument::Pack &&
1994 "Missing argument pack");
1995 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
1996 }
1997
1999 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
2000 "Wrong kind of template template argument");
2001 return Template.getAsTemplateDecl();
2002 }
2003
2004 // Fall through to find the instantiated declaration for this template
2005 // template parameter.
2006 }
2007
2008 if (ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(D);
2009 PVD && SemaRef.CurrentInstantiationScope &&
2010 (SemaRef.inConstraintSubstitution() ||
2011 SemaRef.inParameterMappingSubstitution()) &&
2012 maybeInstantiateFunctionParameterToScope(PVD))
2013 return nullptr;
2014
2015 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
2016}
2017
2018bool TemplateInstantiator::maybeInstantiateFunctionParameterToScope(
2019 ParmVarDecl *OldParm) {
2020 if (SemaRef.CurrentInstantiationScope->getInstantiationOfIfExists(OldParm))
2021 return false;
2022
2023 if (!OldParm->isParameterPack())
2024 return !TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2025 /*NumExpansions=*/std::nullopt,
2026 /*ExpectParameterPack=*/false);
2027
2028 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2029
2030 // Find the parameter packs that could be expanded.
2031 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
2032 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
2033 TypeLoc Pattern = ExpansionTL.getPatternLoc();
2034 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2035 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?");
2036
2037 bool ShouldExpand = false;
2038 bool RetainExpansion = false;
2039 UnsignedOrNone OrigNumExpansions =
2040 ExpansionTL.getTypePtr()->getNumExpansions();
2041 UnsignedOrNone NumExpansions = OrigNumExpansions;
2042 if (TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
2043 Pattern.getSourceRange(), Unexpanded,
2044 /*FailOnPackProducingTemplates=*/true,
2045 ShouldExpand, RetainExpansion, NumExpansions))
2046 return true;
2047
2048 assert(ShouldExpand && !RetainExpansion &&
2049 "Shouldn't preserve pack expansion when evaluating constraints");
2050 ExpandingFunctionParameterPack(OldParm);
2051 for (unsigned I = 0; I != *NumExpansions; ++I) {
2052 Sema::ArgPackSubstIndexRAII SubstIndex(getSema(), I);
2053 if (!TransformFunctionTypeParam(OldParm, /*indexAdjustment=*/0,
2054 /*NumExpansions=*/OrigNumExpansions,
2055 /*ExpectParameterPack=*/false))
2056 return true;
2057 }
2058 return false;
2059}
2060
2061Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
2062 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
2063 if (!Inst)
2064 return nullptr;
2065
2066 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2067 return Inst;
2068}
2069
2070bool TemplateInstantiator::TransformExceptionSpec(
2071 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
2072 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
2073 if (ESI.Type == EST_Uninstantiated) {
2074 ESI.instantiate();
2075 Changed = true;
2076 }
2077 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
2078}
2079
2080NamedDecl *
2081TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
2082 SourceLocation Loc) {
2083 // If the first part of the nested-name-specifier was a template type
2084 // parameter, instantiate that type parameter down to a tag type.
2085 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
2086 const TemplateTypeParmType *TTP
2087 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
2088
2089 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2090 // FIXME: This needs testing w/ member access expressions.
2091 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
2092
2093 if (TTP->isParameterPack()) {
2094 assert(Arg.getKind() == TemplateArgument::Pack &&
2095 "Missing argument pack");
2096
2097 if (!getSema().ArgPackSubstIndex)
2098 return nullptr;
2099
2100 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2101 }
2102
2103 QualType T = Arg.getAsType();
2104 if (T.isNull())
2105 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2106
2107 if (const TagType *Tag = T->getAs<TagType>())
2108 return Tag->getOriginalDecl();
2109
2110 // The resulting type is not a tag; complain.
2111 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
2112 return nullptr;
2113 }
2114 }
2115
2116 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
2117}
2118
2119VarDecl *
2120TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
2121 TypeSourceInfo *Declarator,
2122 SourceLocation StartLoc,
2123 SourceLocation NameLoc,
2124 IdentifierInfo *Name) {
2125 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
2126 StartLoc, NameLoc, Name);
2127 if (Var)
2128 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2129 return Var;
2130}
2131
2132VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2133 TypeSourceInfo *TSInfo,
2134 QualType T) {
2135 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2136 if (Var)
2137 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2138 return Var;
2139}
2140
2141TemplateName TemplateInstantiator::TransformTemplateName(
2142 NestedNameSpecifierLoc &QualifierLoc, SourceLocation TemplateKWLoc,
2143 TemplateName Name, SourceLocation NameLoc, QualType ObjectType,
2144 NamedDecl *FirstQualifierInScope, bool AllowInjectedClassName) {
2145 if (Name.getKind() == TemplateName::Template) {
2146 assert(!QualifierLoc && "Unexpected qualifier");
2147 if (auto *TTP =
2148 dyn_cast<TemplateTemplateParmDecl>(Name.getAsTemplateDecl());
2149 TTP && TTP->getDepth() < TemplateArgs.getNumLevels()) {
2150 // If the corresponding template argument is NULL or non-existent, it's
2151 // because we are performing instantiation from explicitly-specified
2152 // template arguments in a function template, but there were some
2153 // arguments left unspecified.
2154 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2155 TTP->getPosition())) {
2156 IsIncomplete = true;
2157 return BailOutOnIncomplete ? TemplateName() : Name;
2158 }
2159
2160 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2161
2162 if (TemplateArgs.isRewrite()) {
2163 // We're rewriting the template parameter as a reference to another
2164 // template parameter.
2165 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2166 assert(Arg.getKind() == TemplateArgument::Template &&
2167 "unexpected nontype template argument kind in template rewrite");
2168 return Arg.getAsTemplate();
2169 }
2170
2171 auto [AssociatedDecl, Final] =
2172 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2173 UnsignedOrNone PackIndex = std::nullopt;
2174 if (TTP->isParameterPack()) {
2175 assert(Arg.getKind() == TemplateArgument::Pack &&
2176 "Missing argument pack");
2177
2178 if (!getSema().ArgPackSubstIndex) {
2179 // We have the template argument pack to substitute, but we're not
2180 // actually expanding the enclosing pack expansion yet. So, just
2181 // keep the entire argument pack.
2182 return getSema().Context.getSubstTemplateTemplateParmPack(
2183 Arg, AssociatedDecl, TTP->getIndex(), Final);
2184 }
2185
2186 PackIndex = SemaRef.getPackIndex(Arg);
2187 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2188 }
2189
2191 assert(!Template.isNull() && "Null template template argument");
2192 return getSema().Context.getSubstTemplateTemplateParm(
2193 Template, AssociatedDecl, TTP->getIndex(), PackIndex, Final);
2194 }
2195 }
2196
2197 if (SubstTemplateTemplateParmPackStorage *SubstPack
2199 if (!getSema().ArgPackSubstIndex)
2200 return Name;
2201
2202 TemplateArgument Pack = SubstPack->getArgumentPack();
2204 SemaRef.getPackSubstitutedTemplateArgument(Pack).getAsTemplate();
2205 return getSema().Context.getSubstTemplateTemplateParm(
2206 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2207 SemaRef.getPackIndex(Pack), SubstPack->getFinal());
2208 }
2209
2210 return inherited::TransformTemplateName(
2211 QualifierLoc, TemplateKWLoc, Name, NameLoc, ObjectType,
2212 FirstQualifierInScope, AllowInjectedClassName);
2213}
2214
2216TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2217 if (!E->isTypeDependent())
2218 return E;
2219
2220 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2221}
2222
2224TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2225 NonTypeTemplateParmDecl *NTTP) {
2226 // If the corresponding template argument is NULL or non-existent, it's
2227 // because we are performing instantiation from explicitly-specified
2228 // template arguments in a function template, but there were some
2229 // arguments left unspecified.
2230 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2231 NTTP->getPosition())) {
2232 IsIncomplete = true;
2233 return BailOutOnIncomplete ? ExprError() : E;
2234 }
2235
2236 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2237
2238 if (TemplateArgs.isRewrite()) {
2239 // We're rewriting the template parameter as a reference to another
2240 // template parameter.
2241 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2242 assert(Arg.getKind() == TemplateArgument::Expression &&
2243 "unexpected nontype template argument kind in template rewrite");
2244 // FIXME: This can lead to the same subexpression appearing multiple times
2245 // in a complete expression.
2246 return Arg.getAsExpr();
2247 }
2248
2249 auto [AssociatedDecl, Final] =
2250 TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2251 UnsignedOrNone PackIndex = std::nullopt;
2252 if (NTTP->isParameterPack()) {
2253 assert(Arg.getKind() == TemplateArgument::Pack &&
2254 "Missing argument pack");
2255
2256 if (!getSema().ArgPackSubstIndex) {
2257 // We have an argument pack, but we can't select a particular argument
2258 // out of it yet. Therefore, we'll build an expression to hold on to that
2259 // argument pack.
2260 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2261 E->getLocation(),
2262 NTTP->getDeclName());
2263 if (TargetType.isNull())
2264 return ExprError();
2265
2266 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2267 if (TargetType->isRecordType())
2268 ExprType.addConst();
2269 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
2270 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2271 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition(), Final);
2272 }
2273 PackIndex = SemaRef.getPackIndex(Arg);
2274 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2275 }
2276 return SemaRef.BuildSubstNonTypeTemplateParmExpr(
2277 AssociatedDecl, NTTP, E->getLocation(), Arg, PackIndex, Final);
2278}
2279
2280const AnnotateAttr *
2281TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2282 SmallVector<Expr *> Args;
2283 for (Expr *Arg : AA->args()) {
2284 ExprResult Res = getDerived().TransformExpr(Arg);
2285 if (Res.isUsable())
2286 Args.push_back(Res.get());
2287 }
2288 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2289 Args.data(), Args.size(), AA->getRange());
2290}
2291
2292const CXXAssumeAttr *
2293TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2294 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2295 if (!Res.isUsable())
2296 return AA;
2297
2298 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2299 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2300 AA->getRange());
2301 if (!Res.isUsable())
2302 return AA;
2303 }
2304
2305 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2306 AA->getRange());
2307}
2308
2309const LoopHintAttr *
2310TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2311 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2312
2313 if (TransformedExpr == LH->getValue())
2314 return LH;
2315
2316 // Generate error if there is a problem with the value.
2317 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2318 LH->getSemanticSpelling() ==
2319 LoopHintAttr::Pragma_unroll))
2320 return LH;
2321
2322 LoopHintAttr::OptionType Option = LH->getOption();
2323 LoopHintAttr::LoopHintState State = LH->getState();
2324
2325 llvm::APSInt ValueAPS =
2326 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2327 // The values of 0 and 1 block any unrolling of the loop.
2328 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2329 Option = LoopHintAttr::Unroll;
2330 State = LoopHintAttr::Disable;
2331 }
2332
2333 // Create new LoopHintValueAttr with integral expression in place of the
2334 // non-type template parameter.
2335 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2336 TransformedExpr, *LH);
2337}
2338const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2339 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2340 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2341 return nullptr;
2342
2343 return A;
2344}
2345const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2346 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2347 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2348 return nullptr;
2349
2350 return A;
2351}
2352
2353const CodeAlignAttr *
2354TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2355 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2356 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2357}
2358const OpenACCRoutineDeclAttr *
2359TemplateInstantiator::TransformOpenACCRoutineDeclAttr(
2360 const OpenACCRoutineDeclAttr *A) {
2361 llvm_unreachable("RoutineDecl should only be a declaration attribute, as it "
2362 "applies to a Function Decl (and a few places for VarDecl)");
2363}
2364
2365ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(ValueDecl *PD,
2366 SourceLocation Loc) {
2367 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2368 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2369}
2370
2372TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2373 if (getSema().ArgPackSubstIndex) {
2374 // We can expand this parameter pack now.
2375 ValueDecl *D = E->getExpansion(*getSema().ArgPackSubstIndex);
2376 ValueDecl *VD = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), D));
2377 if (!VD)
2378 return ExprError();
2379 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2380 }
2381
2382 QualType T = TransformType(E->getType());
2383 if (T.isNull())
2384 return ExprError();
2385
2386 // Transform each of the parameter expansions into the corresponding
2387 // parameters in the instantiation of the function decl.
2388 SmallVector<ValueDecl *, 8> Vars;
2389 Vars.reserve(E->getNumExpansions());
2390 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2391 I != End; ++I) {
2392 ValueDecl *D = cast_or_null<ValueDecl>(TransformDecl(E->getExprLoc(), *I));
2393 if (!D)
2394 return ExprError();
2395 Vars.push_back(D);
2396 }
2397
2398 auto *PackExpr =
2400 E->getParameterPackLocation(), Vars);
2401 getSema().MarkFunctionParmPackReferenced(PackExpr);
2402 return PackExpr;
2403}
2404
2406TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2407 ValueDecl *PD) {
2408 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2409 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2410 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2411 assert(Found && "no instantiation for parameter pack");
2412
2413 Decl *TransformedDecl;
2414 if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(*Found)) {
2415 // If this is a reference to a function parameter pack which we can
2416 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2417 if (!getSema().ArgPackSubstIndex) {
2418 QualType T = TransformType(E->getType());
2419 if (T.isNull())
2420 return ExprError();
2421 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2422 E->getExprLoc(), *Pack);
2423 getSema().MarkFunctionParmPackReferenced(PackExpr);
2424 return PackExpr;
2425 }
2426
2427 TransformedDecl = (*Pack)[*getSema().ArgPackSubstIndex];
2428 } else {
2429 TransformedDecl = cast<Decl *>(*Found);
2430 }
2431
2432 // We have either an unexpanded pack or a specific expansion.
2433 return RebuildVarDeclRefExpr(cast<ValueDecl>(TransformedDecl),
2434 E->getExprLoc());
2435}
2436
2438TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2439 NamedDecl *D = E->getDecl();
2440
2441 // Handle references to non-type template parameters and non-type template
2442 // parameter packs.
2443 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2444 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2445 return TransformTemplateParmRefExpr(E, NTTP);
2446
2447 // We have a non-type template parameter that isn't fully substituted;
2448 // FindInstantiatedDecl will find it in the local instantiation scope.
2449 }
2450
2451 // Handle references to function parameter packs.
2452 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2453 if (PD->isParameterPack())
2454 return TransformFunctionParmPackRefExpr(E, PD);
2455
2456 return inherited::TransformDeclRefExpr(E);
2457}
2458
2459ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2460 CXXDefaultArgExpr *E) {
2461 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2462 getDescribedFunctionTemplate() &&
2463 "Default arg expressions are never formed in dependent cases.");
2464 return SemaRef.BuildCXXDefaultArgExpr(
2466 E->getParam());
2467}
2468
2469template<typename Fn>
2470QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2471 FunctionProtoTypeLoc TL,
2472 CXXRecordDecl *ThisContext,
2473 Qualifiers ThisTypeQuals,
2474 Fn TransformExceptionSpec) {
2475 // If this is a lambda or block, the transformation MUST be done in the
2476 // CurrentInstantiationScope since it introduces a mapping of
2477 // the original to the newly created transformed parameters.
2478 //
2479 // In that case, TemplateInstantiator::TransformLambdaExpr will
2480 // have already pushed a scope for this prototype, so don't create
2481 // a second one.
2482 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2483 std::optional<LocalInstantiationScope> Scope;
2484 if (!Current || !Current->isLambdaOrBlock())
2485 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2486
2487 return inherited::TransformFunctionProtoType(
2488 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2489}
2490
2491ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2492 ParmVarDecl *OldParm, int indexAdjustment, UnsignedOrNone NumExpansions,
2493 bool ExpectParameterPack) {
2494 auto NewParm = SemaRef.SubstParmVarDecl(
2495 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2496 ExpectParameterPack, EvaluateConstraints);
2497 if (NewParm && SemaRef.getLangOpts().OpenCL)
2498 SemaRef.deduceOpenCLAddressSpace(NewParm);
2499 return NewParm;
2500}
2501
2502QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2503 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2504 Decl *AssociatedDecl, unsigned Index, UnsignedOrNone PackIndex,
2505 TemplateArgument Arg, SourceLocation NameLoc) {
2506 QualType Replacement = Arg.getAsType();
2507
2508 // If the template parameter had ObjC lifetime qualifiers,
2509 // then any such qualifiers on the replacement type are ignored.
2510 if (SuppressObjCLifetime) {
2511 Qualifiers RQs;
2512 RQs = Replacement.getQualifiers();
2513 RQs.removeObjCLifetime();
2514 Replacement =
2515 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2516 }
2517
2518 // TODO: only do this uniquing once, at the start of instantiation.
2519 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2520 Replacement, AssociatedDecl, Index, PackIndex, Final);
2521 SubstTemplateTypeParmTypeLoc NewTL =
2522 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2523 NewTL.setNameLoc(NameLoc);
2524 return Result;
2525}
2526
2527QualType
2528TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2529 TemplateTypeParmTypeLoc TL,
2530 bool SuppressObjCLifetime) {
2531 const TemplateTypeParmType *T = TL.getTypePtr();
2532 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2533 // Replace the template type parameter with its corresponding
2534 // template argument.
2535
2536 // If the corresponding template argument is NULL or doesn't exist, it's
2537 // because we are performing instantiation from explicitly-specified
2538 // template arguments in a function template class, but there were some
2539 // arguments left unspecified.
2540 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2541 IsIncomplete = true;
2542 if (BailOutOnIncomplete)
2543 return QualType();
2544
2545 TemplateTypeParmTypeLoc NewTL
2546 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2547 NewTL.setNameLoc(TL.getNameLoc());
2548 return TL.getType();
2549 }
2550
2551 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2552
2553 if (TemplateArgs.isRewrite()) {
2554 // We're rewriting the template parameter as a reference to another
2555 // template parameter.
2556 Arg = getTemplateArgumentPackPatternForRewrite(Arg);
2557 assert(Arg.getKind() == TemplateArgument::Type &&
2558 "unexpected nontype template argument kind in template rewrite");
2559 QualType NewT = Arg.getAsType();
2560 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2561 return NewT;
2562 }
2563
2564 auto [AssociatedDecl, Final] =
2565 TemplateArgs.getAssociatedDecl(T->getDepth());
2566 UnsignedOrNone PackIndex = std::nullopt;
2567 if (T->isParameterPack()) {
2568 assert(Arg.getKind() == TemplateArgument::Pack &&
2569 "Missing argument pack");
2570
2571 if (!getSema().ArgPackSubstIndex) {
2572 // We have the template argument pack, but we're not expanding the
2573 // enclosing pack expansion yet. Just save the template argument
2574 // pack for later substitution.
2575 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2576 AssociatedDecl, T->getIndex(), Final, Arg);
2577 SubstTemplateTypeParmPackTypeLoc NewTL
2578 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2579 NewTL.setNameLoc(TL.getNameLoc());
2580 return Result;
2581 }
2582
2583 // PackIndex starts from last element.
2584 PackIndex = SemaRef.getPackIndex(Arg);
2585 Arg = SemaRef.getPackSubstitutedTemplateArgument(Arg);
2586 }
2587
2588 assert(Arg.getKind() == TemplateArgument::Type &&
2589 "Template argument kind mismatch");
2590
2591 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2592 AssociatedDecl, T->getIndex(),
2593 PackIndex, Arg, TL.getNameLoc());
2594 }
2595
2596 // The template type parameter comes from an inner template (e.g.,
2597 // the template parameter list of a member template inside the
2598 // template we are instantiating). Create a new template type
2599 // parameter with the template "level" reduced by one.
2600 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2601 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2602 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2603 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2604 QualType Result = getSema().Context.getTemplateTypeParmType(
2605 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2606 T->isParameterPack(), NewTTPDecl);
2607 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2608 NewTL.setNameLoc(TL.getNameLoc());
2609 return Result;
2610}
2611
2612QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2613 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2614 bool SuppressObjCLifetime) {
2615 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2616
2617 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2618
2619 if (!getSema().ArgPackSubstIndex) {
2620 // We aren't expanding the parameter pack, so just return ourselves.
2621 QualType Result = TL.getType();
2622 if (NewReplaced != T->getAssociatedDecl())
2623 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2624 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2625 SubstTemplateTypeParmPackTypeLoc NewTL =
2626 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2627 NewTL.setNameLoc(TL.getNameLoc());
2628 return Result;
2629 }
2630
2631 TemplateArgument Pack = T->getArgumentPack();
2632 TemplateArgument Arg = SemaRef.getPackSubstitutedTemplateArgument(Pack);
2633 return BuildSubstTemplateTypeParmType(
2634 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2635 SemaRef.getPackIndex(Pack), Arg, TL.getNameLoc());
2636}
2637
2638QualType TemplateInstantiator::TransformSubstBuiltinTemplatePackType(
2639 TypeLocBuilder &TLB, SubstBuiltinTemplatePackTypeLoc TL) {
2640 if (!getSema().ArgPackSubstIndex)
2641 return TreeTransform::TransformSubstBuiltinTemplatePackType(TLB, TL);
2642 TemplateArgument Result = SemaRef.getPackSubstitutedTemplateArgument(
2643 TL.getTypePtr()->getArgumentPack());
2644 TLB.pushTrivial(SemaRef.getASTContext(), Result.getAsType(),
2645 TL.getBeginLoc());
2646 return Result.getAsType();
2647}
2648
2649static concepts::Requirement::SubstitutionDiagnostic *
2651 Sema::EntityPrinter Printer) {
2652 SmallString<128> Message;
2653 SourceLocation ErrorLoc;
2654 if (Info.hasSFINAEDiagnostic()) {
2657 Info.takeSFINAEDiagnostic(PDA);
2658 PDA.second.EmitToString(S.getDiagnostics(), Message);
2659 ErrorLoc = PDA.first;
2660 } else {
2661 ErrorLoc = Info.getLocation();
2662 }
2663 SmallString<128> Entity;
2664 llvm::raw_svector_ostream OS(Entity);
2665 Printer(OS);
2666 const ASTContext &C = S.Context;
2668 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2669}
2670
2671concepts::Requirement::SubstitutionDiagnostic *
2673 SmallString<128> Entity;
2674 llvm::raw_svector_ostream OS(Entity);
2675 Printer(OS);
2676 const ASTContext &C = Context;
2678 /*SubstitutedEntity=*/C.backupStr(Entity),
2679 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2680}
2681
2682ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2683 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2686 SmallVectorImpl<ParmVarDecl *> &TransParams,
2688
2689 TemplateDeductionInfo Info(KWLoc);
2690 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2691 RE, Info,
2692 SourceRange{KWLoc, RBraceLoc});
2694
2695 unsigned ErrorIdx;
2696 if (getDerived().TransformFunctionTypeParams(
2697 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2698 &TransParams, PInfos, &ErrorIdx) ||
2699 Trap.hasErrorOccurred()) {
2701 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2702 // Add a 'failed' Requirement to contain the error that caused the failure
2703 // here.
2704 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2705 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2706 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2707 TransParams, RE->getRParenLoc(),
2708 TransReqs, RBraceLoc);
2709 }
2710
2711 return ExprResult{};
2712}
2713
2714concepts::TypeRequirement *
2715TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2716 if (!Req->isDependent() && !AlwaysRebuild())
2717 return Req;
2718 if (Req->isSubstitutionFailure()) {
2719 if (AlwaysRebuild())
2720 return RebuildTypeRequirement(
2722 return Req;
2723 }
2724
2725 Sema::SFINAETrap Trap(SemaRef);
2726 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2727 Sema::InstantiatingTemplate TypeInst(SemaRef,
2728 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2729 Req->getType()->getTypeLoc().getSourceRange());
2730 if (TypeInst.isInvalid())
2731 return nullptr;
2732 TypeSourceInfo *TransType = TransformType(Req->getType());
2733 if (!TransType || Trap.hasErrorOccurred())
2734 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2735 [&] (llvm::raw_ostream& OS) {
2736 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2737 }));
2738 return RebuildTypeRequirement(TransType);
2739}
2740
2741concepts::ExprRequirement *
2742TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2743 if (!Req->isDependent() && !AlwaysRebuild())
2744 return Req;
2745
2746 Sema::SFINAETrap Trap(SemaRef);
2747
2748 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2749 TransExpr;
2750 if (Req->isExprSubstitutionFailure())
2751 TransExpr = Req->getExprSubstitutionDiagnostic();
2752 else {
2753 Expr *E = Req->getExpr();
2754 TemplateDeductionInfo Info(E->getBeginLoc());
2755 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2756 E->getSourceRange());
2757 if (ExprInst.isInvalid())
2758 return nullptr;
2759 ExprResult TransExprRes = TransformExpr(E);
2760 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2761 TransExprRes.get()->hasPlaceholderType())
2762 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2763 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2764 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2765 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2766 });
2767 else
2768 TransExpr = TransExprRes.get();
2769 }
2770
2771 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2772 const auto &RetReq = Req->getReturnTypeRequirement();
2773 if (RetReq.isEmpty())
2774 TransRetReq.emplace();
2775 else if (RetReq.isSubstitutionFailure())
2776 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2777 else if (RetReq.isTypeConstraint()) {
2778 TemplateParameterList *OrigTPL =
2779 RetReq.getTypeConstraintTemplateParameterList();
2780 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2781 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2782 Req, Info, OrigTPL->getSourceRange());
2783 if (TPLInst.isInvalid())
2784 return nullptr;
2785 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2786 if (!TPL || Trap.hasErrorOccurred())
2787 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2788 [&] (llvm::raw_ostream& OS) {
2789 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2790 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2791 }));
2792 else {
2793 TPLInst.Clear();
2794 TransRetReq.emplace(TPL);
2795 }
2796 }
2797 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2798 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2799 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2800 std::move(*TransRetReq));
2801 return RebuildExprRequirement(
2803 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2804}
2805
2806concepts::NestedRequirement *
2807TemplateInstantiator::TransformNestedRequirement(
2808 concepts::NestedRequirement *Req) {
2809
2810 ASTContext &C = SemaRef.Context;
2811
2812 Expr *Constraint = Req->getConstraintExpr();
2813 ConstraintSatisfaction Satisfaction;
2814
2815 auto NestedReqWithDiag = [&C, this](Expr *E,
2816 ConstraintSatisfaction Satisfaction) {
2817 Satisfaction.IsSatisfied = false;
2818 SmallString<128> Entity;
2819 llvm::raw_svector_ostream OS(Entity);
2820 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2821 return new (C) concepts::NestedRequirement(
2822 SemaRef.Context, C.backupStr(Entity), std::move(Satisfaction));
2823 };
2824
2825 if (Req->hasInvalidConstraint()) {
2826 if (AlwaysRebuild())
2827 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2829 return Req;
2830 }
2831
2832 if (!getEvaluateConstraints()) {
2833 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2834 if (TransConstraint.isInvalid() || !TransConstraint.get())
2835 return nullptr;
2836 if (TransConstraint.get()->isInstantiationDependent())
2837 return new (SemaRef.Context)
2838 concepts::NestedRequirement(TransConstraint.get());
2839 ConstraintSatisfaction Satisfaction;
2840 return new (SemaRef.Context) concepts::NestedRequirement(
2841 SemaRef.Context, TransConstraint.get(), Satisfaction);
2842 }
2843
2844 bool Success;
2845 Expr *NewConstraint;
2846 TemplateDeductionInfo Info(Constraint->getBeginLoc());
2847 {
2848 EnterExpressionEvaluationContext ContextRAII(
2850
2851 Sema::InstantiatingTemplate ConstrInst(
2852 SemaRef, Constraint->getBeginLoc(), Req,
2853 Sema::InstantiatingTemplate::ConstraintsCheck(),
2854 Constraint->getSourceRange());
2855
2856 if (ConstrInst.isInvalid())
2857 return nullptr;
2858
2859 Sema::SFINAETrap Trap(SemaRef);
2860
2861 Success = !SemaRef.CheckConstraintSatisfaction(
2862 Req, AssociatedConstraint(Constraint, SemaRef.ArgPackSubstIndex),
2863 TemplateArgs, Constraint->getSourceRange(), Satisfaction,
2864 /*TopLevelConceptId=*/nullptr, &NewConstraint);
2865
2866 assert(!Success || !Trap.hasErrorOccurred() &&
2867 "Substitution failures must be handled "
2868 "by CheckConstraintSatisfaction.");
2869 }
2870
2871 if (!Success || Satisfaction.HasSubstitutionFailure())
2872 return NestedReqWithDiag(Constraint, Satisfaction);
2873
2874 // FIXME: const correctness
2875 // MLTAL might be dependent.
2876 if (!NewConstraint) {
2877 if (!Satisfaction.IsSatisfied)
2878 return NestedReqWithDiag(Constraint, Satisfaction);
2879
2880 NewConstraint = Constraint;
2881 }
2882 return new (C) concepts::NestedRequirement(C, NewConstraint, Satisfaction);
2883}
2884
2887 SourceLocation Loc,
2888 DeclarationName Entity,
2889 bool AllowDeducedTST) {
2890 assert(!CodeSynthesisContexts.empty() &&
2891 "Cannot perform an instantiation without some context on the "
2892 "instantiation stack");
2893
2894 if (!T->getType()->isInstantiationDependentType() &&
2895 !T->getType()->isVariablyModifiedType())
2896 return T;
2897
2898 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2899 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2900 : Instantiator.TransformType(T);
2901}
2902
2905 SourceLocation Loc,
2906 DeclarationName Entity) {
2907 assert(!CodeSynthesisContexts.empty() &&
2908 "Cannot perform an instantiation without some context on the "
2909 "instantiation stack");
2910
2911 if (TL.getType().isNull())
2912 return nullptr;
2913
2916 // FIXME: Make a copy of the TypeLoc data here, so that we can
2917 // return a new TypeSourceInfo. Inefficient!
2918 TypeLocBuilder TLB;
2919 TLB.pushFullCopy(TL);
2920 return TLB.getTypeSourceInfo(Context, TL.getType());
2921 }
2922
2923 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2924 TypeLocBuilder TLB;
2925 TLB.reserve(TL.getFullDataSize());
2926 QualType Result = Instantiator.TransformType(TLB, TL);
2927 if (Result.isNull())
2928 return nullptr;
2929
2930 return TLB.getTypeSourceInfo(Context, Result);
2931}
2932
2933/// Deprecated form of the above.
2935 const MultiLevelTemplateArgumentList &TemplateArgs,
2936 SourceLocation Loc, DeclarationName Entity,
2937 bool *IsIncompleteSubstitution) {
2938 assert(!CodeSynthesisContexts.empty() &&
2939 "Cannot perform an instantiation without some context on the "
2940 "instantiation stack");
2941
2942 // If T is not a dependent type or a variably-modified type, there
2943 // is nothing to do.
2944 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2945 return T;
2946
2947 TemplateInstantiator Instantiator(
2948 *this, TemplateArgs, Loc, Entity,
2949 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2950 QualType QT = Instantiator.TransformType(T);
2951 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2952 *IsIncompleteSubstitution = true;
2953 return QT;
2954}
2955
2957 if (T->getType()->isInstantiationDependentType() ||
2958 T->getType()->isVariablyModifiedType())
2959 return true;
2960
2961 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2962 if (!TL.getAs<FunctionProtoTypeLoc>())
2963 return false;
2964
2966 for (ParmVarDecl *P : FP.getParams()) {
2967 // This must be synthesized from a typedef.
2968 if (!P) continue;
2969
2970 // If there are any parameters, a new TypeSourceInfo that refers to the
2971 // instantiated parameters must be built.
2972 return true;
2973 }
2974
2975 return false;
2976}
2977
2980 SourceLocation Loc,
2981 DeclarationName Entity,
2982 CXXRecordDecl *ThisContext,
2983 Qualifiers ThisTypeQuals,
2984 bool EvaluateConstraints) {
2985 assert(!CodeSynthesisContexts.empty() &&
2986 "Cannot perform an instantiation without some context on the "
2987 "instantiation stack");
2988
2990 return T;
2991
2992 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2993 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2994
2995 TypeLocBuilder TLB;
2996
2997 TypeLoc TL = T->getTypeLoc();
2998 TLB.reserve(TL.getFullDataSize());
2999
3001
3002 if (FunctionProtoTypeLoc Proto =
3004 // Instantiate the type, other than its exception specification. The
3005 // exception specification is instantiated in InitFunctionInstantiation
3006 // once we've built the FunctionDecl.
3007 // FIXME: Set the exception specification to EST_Uninstantiated here,
3008 // instead of rebuilding the function type again later.
3009 Result = Instantiator.TransformFunctionProtoType(
3010 TLB, Proto, ThisContext, ThisTypeQuals,
3012 bool &Changed) { return false; });
3013 } else {
3014 Result = Instantiator.TransformType(TLB, TL);
3015 }
3016 // When there are errors resolving types, clang may use IntTy as a fallback,
3017 // breaking our assumption that function declarations have function types.
3018 if (Result.isNull() || !Result->isFunctionType())
3019 return nullptr;
3020
3021 return TLB.getTypeSourceInfo(Context, Result);
3022}
3023
3026 SmallVectorImpl<QualType> &ExceptionStorage,
3027 const MultiLevelTemplateArgumentList &Args) {
3028 bool Changed = false;
3029 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3030 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3031 Changed);
3032}
3033
3035 const MultiLevelTemplateArgumentList &Args) {
3038
3039 SmallVector<QualType, 4> ExceptionStorage;
3040 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
3041 ESI, ExceptionStorage, Args))
3042 // On error, recover by dropping the exception specification.
3043 ESI.Type = EST_None;
3044
3046}
3047
3048namespace {
3049
3050 struct GetContainedInventedTypeParmVisitor :
3051 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3052 TemplateTypeParmDecl *> {
3053 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3054 TemplateTypeParmDecl *>::Visit;
3055
3057 if (T.isNull())
3058 return nullptr;
3059 return Visit(T.getTypePtr());
3060 }
3061 // The deduced type itself.
3062 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3063 const TemplateTypeParmType *T) {
3064 if (!T->getDecl() || !T->getDecl()->isImplicit())
3065 return nullptr;
3066 return T->getDecl();
3067 }
3068
3069 // Only these types can contain 'auto' types, and subsequently be replaced
3070 // by references to invented parameters.
3071
3072 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3073 return Visit(T->getPointeeType());
3074 }
3075
3076 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3077 return Visit(T->getPointeeType());
3078 }
3079
3080 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3081 return Visit(T->getPointeeTypeAsWritten());
3082 }
3083
3084 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3085 return Visit(T->getPointeeType());
3086 }
3087
3088 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3089 return Visit(T->getElementType());
3090 }
3091
3092 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3093 const DependentSizedExtVectorType *T) {
3094 return Visit(T->getElementType());
3095 }
3096
3097 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3098 return Visit(T->getElementType());
3099 }
3100
3101 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3102 return VisitFunctionType(T);
3103 }
3104
3105 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3106 return Visit(T->getReturnType());
3107 }
3108
3109 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3110 return Visit(T->getInnerType());
3111 }
3112
3113 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3114 return Visit(T->getModifiedType());
3115 }
3116
3117 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3118 return Visit(T->getUnderlyingType());
3119 }
3120
3121 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3122 return Visit(T->getOriginalType());
3123 }
3124
3125 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3126 return Visit(T->getPattern());
3127 }
3128 };
3129
3130} // namespace
3131
3133 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3134 const MultiLevelTemplateArgumentList &TemplateArgs,
3135 bool EvaluateConstraints) {
3136 const ASTTemplateArgumentListInfo *TemplArgInfo =
3138
3139 if (!EvaluateConstraints && !inParameterMappingSubstitution()) {
3141 if (!Index)
3142 Index = SemaRef.ArgPackSubstIndex;
3145 return false;
3146 }
3147
3148 TemplateArgumentListInfo InstArgs;
3149
3150 if (TemplArgInfo) {
3151 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3152 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3153 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3154 InstArgs))
3155 return true;
3156 }
3157 return AttachTypeConstraint(
3159 TC->getNamedConcept(),
3160 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3161 Inst->isParameterPack()
3163 ->getEllipsisLoc()
3164 : SourceLocation());
3165}
3166
3169 const MultiLevelTemplateArgumentList &TemplateArgs,
3170 int indexAdjustment, UnsignedOrNone NumExpansions,
3171 bool ExpectParameterPack, bool EvaluateConstraint) {
3172 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3173 TypeSourceInfo *NewDI = nullptr;
3174
3175 TypeLoc OldTL = OldDI->getTypeLoc();
3176 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3177
3178 // We have a function parameter pack. Substitute into the pattern of the
3179 // expansion.
3180 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3181 OldParm->getLocation(), OldParm->getDeclName());
3182 if (!NewDI)
3183 return nullptr;
3184
3185 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3186 // We still have unexpanded parameter packs, which means that
3187 // our function parameter is still a function parameter pack.
3188 // Therefore, make its type a pack expansion type.
3189 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3190 NumExpansions);
3191 } else if (ExpectParameterPack) {
3192 // We expected to get a parameter pack but didn't (because the type
3193 // itself is not a pack expansion type), so complain. This can occur when
3194 // the substitution goes through an alias template that "loses" the
3195 // pack expansion.
3196 Diag(OldParm->getLocation(),
3197 diag::err_function_parameter_pack_without_parameter_packs)
3198 << NewDI->getType();
3199 return nullptr;
3200 }
3201 } else {
3202 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3203 OldParm->getDeclName());
3204 }
3205
3206 if (!NewDI)
3207 return nullptr;
3208
3209 if (NewDI->getType()->isVoidType()) {
3210 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3211 return nullptr;
3212 }
3213
3214 // In abbreviated templates, TemplateTypeParmDecls with possible
3215 // TypeConstraints are created when the parameter list is originally parsed.
3216 // The TypeConstraints can therefore reference other functions parameters in
3217 // the abbreviated function template, which is why we must instantiate them
3218 // here, when the instantiated versions of those referenced parameters are in
3219 // scope.
3220 if (TemplateTypeParmDecl *TTP =
3221 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3222 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3223 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3224 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3225 // We will first get here when instantiating the abbreviated function
3226 // template's described function, but we might also get here later.
3227 // Make sure we do not instantiate the TypeConstraint more than once.
3228 if (Inst && !Inst->getTypeConstraint()) {
3229 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3230 return nullptr;
3231 }
3232 }
3233 }
3234
3235 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
3236 OldParm->getInnerLocStart(),
3237 OldParm->getLocation(),
3238 OldParm->getIdentifier(),
3239 NewDI->getType(), NewDI,
3240 OldParm->getStorageClass());
3241 if (!NewParm)
3242 return nullptr;
3243
3244 // Mark the (new) default argument as uninstantiated (if any).
3245 if (OldParm->hasUninstantiatedDefaultArg()) {
3246 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3247 NewParm->setUninstantiatedDefaultArg(Arg);
3248 } else if (OldParm->hasUnparsedDefaultArg()) {
3249 NewParm->setUnparsedDefaultArg();
3250 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3251 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3252 // Default arguments cannot be substituted until the declaration context
3253 // for the associated function or lambda capture class is available.
3254 // This is necessary for cases like the following where construction of
3255 // the lambda capture class for the outer lambda is dependent on the
3256 // parameter types but where the default argument is dependent on the
3257 // outer lambda's declaration context.
3258 // template <typename T>
3259 // auto f() {
3260 // return [](T = []{ return T{}; }()) { return 0; };
3261 // }
3262 NewParm->setUninstantiatedDefaultArg(Arg);
3263 }
3264
3268
3269 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3270 // Add the new parameter to the instantiated parameter pack.
3271 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
3272 } else {
3273 // Introduce an Old -> New mapping
3274 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
3275 }
3276
3277 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3278 // can be anything, is this right ?
3279 NewParm->setDeclContext(CurContext);
3280
3281 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3282 OldParm->getFunctionScopeIndex() + indexAdjustment);
3283
3284 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3285
3286 return NewParm;
3287}
3288
3291 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3292 const MultiLevelTemplateArgumentList &TemplateArgs,
3293 SmallVectorImpl<QualType> &ParamTypes,
3295 ExtParameterInfoBuilder &ParamInfos) {
3296 assert(!CodeSynthesisContexts.empty() &&
3297 "Cannot perform an instantiation without some context on the "
3298 "instantiation stack");
3299
3300 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3301 DeclarationName());
3302 return Instantiator.TransformFunctionTypeParams(
3303 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3304}
3305
3307 SourceLocation Loc,
3308 ParmVarDecl *Param,
3309 const MultiLevelTemplateArgumentList &TemplateArgs,
3310 bool ForCallExpr) {
3311 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3312 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3313
3316
3317 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3318 if (Inst.isInvalid())
3319 return true;
3320 if (Inst.isAlreadyInstantiating()) {
3321 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3322 Param->setInvalidDecl();
3323 return true;
3324 }
3325
3327 // C++ [dcl.fct.default]p5:
3328 // The names in the [default argument] expression are bound, and
3329 // the semantic constraints are checked, at the point where the
3330 // default argument expression appears.
3331 ContextRAII SavedContext(*this, FD);
3332 {
3333 std::optional<LocalInstantiationScope> LIS;
3334
3335 if (ForCallExpr) {
3336 // When instantiating a default argument due to use in a call expression,
3337 // an instantiation scope that includes the parameters of the callee is
3338 // required to satisfy references from the default argument. For example:
3339 // template<typename T> void f(T a, int = decltype(a)());
3340 // void g() { f(0); }
3341 LIS.emplace(*this);
3343 /*ForDefinition*/ false);
3344 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3345 return true;
3346 }
3347
3349 Result = SubstInitializer(PatternExpr, TemplateArgs,
3350 /*DirectInit*/ false);
3351 });
3352 }
3353 if (Result.isInvalid())
3354 return true;
3355
3356 if (ForCallExpr) {
3357 // Check the expression as an initializer for the parameter.
3358 InitializedEntity Entity
3361 Param->getLocation(),
3362 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3363 Expr *ResultE = Result.getAs<Expr>();
3364
3365 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3366 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3367 if (Result.isInvalid())
3368 return true;
3369
3370 Result =
3371 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
3372 /*DiscardedValue*/ false);
3373 } else {
3374 // FIXME: Obtain the source location for the '=' token.
3375 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3376 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3377 }
3378 if (Result.isInvalid())
3379 return true;
3380
3381 // Remember the instantiated default argument.
3382 Param->setDefaultArg(Result.getAs<Expr>());
3383
3384 return false;
3385}
3386
3387// See TreeTransform::PreparePackForExpansion for the relevant comment.
3388// This function implements the same concept for base specifiers.
3389static bool
3391 const MultiLevelTemplateArgumentList &TemplateArgs,
3392 TypeSourceInfo *&Out, UnexpandedInfo &Info) {
3393 SourceRange BaseSourceRange = Base.getSourceRange();
3394 SourceLocation BaseEllipsisLoc = Base.getEllipsisLoc();
3395 Info.Ellipsis = Base.getEllipsisLoc();
3396 auto ComputeInfo = [&S, &TemplateArgs, BaseSourceRange, BaseEllipsisLoc](
3397 TypeSourceInfo *BaseTypeInfo,
3398 bool IsLateExpansionAttempt, UnexpandedInfo &Info) {
3399 // This is a pack expansion. See whether we should expand it now, or
3400 // wait until later.
3402 S.collectUnexpandedParameterPacks(BaseTypeInfo->getTypeLoc(), Unexpanded);
3403 if (IsLateExpansionAttempt) {
3404 // Request expansion only when there is an opportunity to expand a pack
3405 // that required a substituion first.
3406 bool SawPackTypes =
3407 llvm::any_of(Unexpanded, [](UnexpandedParameterPack P) {
3408 return P.first.dyn_cast<const SubstBuiltinTemplatePackType *>();
3409 });
3410 if (!SawPackTypes) {
3411 Info.Expand = false;
3412 return false;
3413 }
3414 }
3415
3416 // Determine whether the set of unexpanded parameter packs can and should be
3417 // expanded.
3418 Info.Expand = false;
3419 Info.RetainExpansion = false;
3420 Info.NumExpansions = std::nullopt;
3422 BaseEllipsisLoc, BaseSourceRange, Unexpanded, TemplateArgs,
3423 /*FailOnPackProducingTemplates=*/false, Info.Expand,
3424 Info.RetainExpansion, Info.NumExpansions);
3425 };
3426
3427 if (ComputeInfo(Base.getTypeSourceInfo(), false, Info))
3428 return true;
3429
3430 if (Info.Expand) {
3431 Out = Base.getTypeSourceInfo();
3432 return false;
3433 }
3434
3435 // The resulting base specifier will (still) be a pack expansion.
3436 {
3437 Sema::ArgPackSubstIndexRAII SubstIndex(S, std::nullopt);
3438 Out = S.SubstType(Base.getTypeSourceInfo(), TemplateArgs,
3439 BaseSourceRange.getBegin(), DeclarationName());
3440 }
3441 if (!Out->getType()->containsUnexpandedParameterPack())
3442 return false;
3443
3444 // Some packs will learn their length after substitution.
3445 // We may need to request their expansion.
3446 if (ComputeInfo(Out, /*IsLateExpansionAttempt=*/true, Info))
3447 return true;
3448 if (Info.Expand)
3449 Info.ExpandUnderForgetSubstitions = true;
3450 return false;
3451}
3452
3453bool
3455 CXXRecordDecl *Pattern,
3456 const MultiLevelTemplateArgumentList &TemplateArgs) {
3457 bool Invalid = false;
3458 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3459 for (const auto &Base : Pattern->bases()) {
3460 if (!Base.getType()->isDependentType()) {
3461 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3462 if (RD->isInvalidDecl())
3463 Instantiation->setInvalidDecl();
3464 }
3465 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3466 continue;
3467 }
3468
3469 SourceLocation EllipsisLoc;
3470 TypeSourceInfo *BaseTypeLoc = nullptr;
3471 if (Base.isPackExpansion()) {
3472 UnexpandedInfo Info;
3473 if (PreparePackForExpansion(*this, Base, TemplateArgs, BaseTypeLoc,
3474 Info)) {
3475 Invalid = true;
3476 continue;
3477 }
3478
3479 // If we should expand this pack expansion now, do so.
3481 const MultiLevelTemplateArgumentList *ArgsForSubst = &TemplateArgs;
3483 ArgsForSubst = &EmptyList;
3484
3485 if (Info.Expand) {
3486 for (unsigned I = 0; I != *Info.NumExpansions; ++I) {
3487 Sema::ArgPackSubstIndexRAII SubstIndex(*this, I);
3488
3489 TypeSourceInfo *Expanded =
3490 SubstType(BaseTypeLoc, *ArgsForSubst,
3491 Base.getSourceRange().getBegin(), DeclarationName());
3492 if (!Expanded) {
3493 Invalid = true;
3494 continue;
3495 }
3496
3497 if (CXXBaseSpecifier *InstantiatedBase = CheckBaseSpecifier(
3498 Instantiation, Base.getSourceRange(), Base.isVirtual(),
3499 Base.getAccessSpecifierAsWritten(), Expanded,
3500 SourceLocation()))
3501 InstantiatedBases.push_back(InstantiatedBase);
3502 else
3503 Invalid = true;
3504 }
3505
3506 continue;
3507 }
3508
3509 // The resulting base specifier will (still) be a pack expansion.
3510 EllipsisLoc = Base.getEllipsisLoc();
3511 Sema::ArgPackSubstIndexRAII SubstIndex(*this, std::nullopt);
3512 BaseTypeLoc =
3513 SubstType(BaseTypeLoc, *ArgsForSubst,
3514 Base.getSourceRange().getBegin(), DeclarationName());
3515 } else {
3516 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3517 TemplateArgs,
3518 Base.getSourceRange().getBegin(),
3519 DeclarationName());
3520 }
3521
3522 if (!BaseTypeLoc) {
3523 Invalid = true;
3524 continue;
3525 }
3526
3527 if (CXXBaseSpecifier *InstantiatedBase
3528 = CheckBaseSpecifier(Instantiation,
3529 Base.getSourceRange(),
3530 Base.isVirtual(),
3531 Base.getAccessSpecifierAsWritten(),
3532 BaseTypeLoc,
3533 EllipsisLoc))
3534 InstantiatedBases.push_back(InstantiatedBase);
3535 else
3536 Invalid = true;
3537 }
3538
3539 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3540 Invalid = true;
3541
3542 return Invalid;
3543}
3544
3545// Defined via #include from SemaTemplateInstantiateDecl.cpp
3546namespace clang {
3547 namespace sema {
3549 const MultiLevelTemplateArgumentList &TemplateArgs);
3551 const Attr *At, ASTContext &C, Sema &S,
3552 const MultiLevelTemplateArgumentList &TemplateArgs);
3553 }
3554}
3555
3556bool
3558 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3559 const MultiLevelTemplateArgumentList &TemplateArgs,
3561 bool Complain) {
3562 CXXRecordDecl *PatternDef
3563 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3564 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3565 Instantiation->getInstantiatedFromMemberClass(),
3566 Pattern, PatternDef, TSK, Complain))
3567 return true;
3568
3569 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3570 llvm::TimeTraceMetadata M;
3571 llvm::raw_string_ostream OS(M.Detail);
3572 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3573 /*Qualified=*/true);
3574 if (llvm::isTimeTraceVerbose()) {
3575 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3576 M.File = SourceMgr.getFilename(Loc);
3577 M.Line = SourceMgr.getExpansionLineNumber(Loc);
3578 }
3579 return M;
3580 });
3581
3582 Pattern = PatternDef;
3583
3584 // Record the point of instantiation.
3585 if (MemberSpecializationInfo *MSInfo
3586 = Instantiation->getMemberSpecializationInfo()) {
3587 MSInfo->setTemplateSpecializationKind(TSK);
3588 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3589 } else if (ClassTemplateSpecializationDecl *Spec
3590 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3591 Spec->setTemplateSpecializationKind(TSK);
3592 Spec->setPointOfInstantiation(PointOfInstantiation);
3593 }
3594
3595 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3596 if (Inst.isInvalid())
3597 return true;
3598 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3599 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3600 "instantiating class definition");
3601
3602 // Enter the scope of this instantiation. We don't use
3603 // PushDeclContext because we don't have a scope.
3604 ContextRAII SavedContext(*this, Instantiation);
3607
3608 // If this is an instantiation of a local class, merge this local
3609 // instantiation scope with the enclosing scope. Otherwise, every
3610 // instantiation of a class has its own local instantiation scope.
3611 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3612 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3613
3614 // Some class state isn't processed immediately but delayed till class
3615 // instantiation completes. We may not be ready to handle any delayed state
3616 // already on the stack as it might correspond to a different class, so save
3617 // it now and put it back later.
3618 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3619
3620 // Pull attributes from the pattern onto the instantiation.
3621 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3622
3623 // Start the definition of this instantiation.
3624 Instantiation->startDefinition();
3625
3626 // The instantiation is visible here, even if it was first declared in an
3627 // unimported module.
3628 Instantiation->setVisibleDespiteOwningModule();
3629
3630 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3631 Instantiation->setTagKind(Pattern->getTagKind());
3632
3633 // Do substitution on the base class specifiers.
3634 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3635 Instantiation->setInvalidDecl();
3636
3637 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3638 Instantiator.setEvaluateConstraints(false);
3639 SmallVector<Decl*, 4> Fields;
3640 // Delay instantiation of late parsed attributes.
3641 LateInstantiatedAttrVec LateAttrs;
3642 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3643
3644 bool MightHaveConstexprVirtualFunctions = false;
3645 for (auto *Member : Pattern->decls()) {
3646 // Don't instantiate members not belonging in this semantic context.
3647 // e.g. for:
3648 // @code
3649 // template <int i> class A {
3650 // class B *g;
3651 // };
3652 // @endcode
3653 // 'class B' has the template as lexical context but semantically it is
3654 // introduced in namespace scope.
3655 if (Member->getDeclContext() != Pattern)
3656 continue;
3657
3658 // BlockDecls can appear in a default-member-initializer. They must be the
3659 // child of a BlockExpr, so we only know how to instantiate them from there.
3660 // Similarly, lambda closure types are recreated when instantiating the
3661 // corresponding LambdaExpr.
3662 if (isa<BlockDecl>(Member) ||
3664 continue;
3665
3666 if (Member->isInvalidDecl()) {
3667 Instantiation->setInvalidDecl();
3668 continue;
3669 }
3670
3671 Decl *NewMember = Instantiator.Visit(Member);
3672 if (NewMember) {
3673 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3674 Fields.push_back(Field);
3675 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3676 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3677 // specialization causes the implicit instantiation of the definitions
3678 // of unscoped member enumerations.
3679 // Record a point of instantiation for this implicit instantiation.
3680 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3681 Enum->isCompleteDefinition()) {
3682 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3683 assert(MSInfo && "no spec info for member enum specialization");
3685 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3686 }
3687 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3688 if (SA->isFailed()) {
3689 // A static_assert failed. Bail out; instantiating this
3690 // class is probably not meaningful.
3691 Instantiation->setInvalidDecl();
3692 break;
3693 }
3694 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3695 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3696 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3697 MightHaveConstexprVirtualFunctions = true;
3698 }
3699
3700 if (NewMember->isInvalidDecl())
3701 Instantiation->setInvalidDecl();
3702 } else {
3703 // FIXME: Eventually, a NULL return will mean that one of the
3704 // instantiations was a semantic disaster, and we'll want to mark the
3705 // declaration invalid.
3706 // For now, we expect to skip some members that we can't yet handle.
3707 }
3708 }
3709
3710 // Finish checking fields.
3711 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3713 CheckCompletedCXXClass(nullptr, Instantiation);
3714
3715 // Default arguments are parsed, if not instantiated. We can go instantiate
3716 // default arg exprs for default constructors if necessary now. Unless we're
3717 // parsing a class, in which case wait until that's finished.
3718 if (ParsingClassDepth == 0)
3720
3721 // Instantiate late parsed attributes, and attach them to their decls.
3722 // See Sema::InstantiateAttrs
3723 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3724 E = LateAttrs.end(); I != E; ++I) {
3725 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3726 CurrentInstantiationScope = I->Scope;
3727
3728 // Allow 'this' within late-parsed attributes.
3729 auto *ND = cast<NamedDecl>(I->NewDecl);
3730 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3731 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3732 ND->isCXXInstanceMember());
3733
3734 Attr *NewAttr =
3735 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3736 if (NewAttr)
3737 I->NewDecl->addAttr(NewAttr);
3739 Instantiator.getStartingScope());
3740 }
3741 Instantiator.disableLateAttributeInstantiation();
3742 LateAttrs.clear();
3743
3745
3746 // FIXME: We should do something similar for explicit instantiations so they
3747 // end up in the right module.
3748 if (TSK == TSK_ImplicitInstantiation) {
3749 Instantiation->setLocation(Pattern->getLocation());
3750 Instantiation->setLocStart(Pattern->getInnerLocStart());
3751 Instantiation->setBraceRange(Pattern->getBraceRange());
3752 }
3753
3754 if (!Instantiation->isInvalidDecl()) {
3755 // Perform any dependent diagnostics from the pattern.
3756 if (Pattern->isDependentContext())
3757 PerformDependentDiagnostics(Pattern, TemplateArgs);
3758
3759 // Instantiate any out-of-line class template partial
3760 // specializations now.
3762 P = Instantiator.delayed_partial_spec_begin(),
3763 PEnd = Instantiator.delayed_partial_spec_end();
3764 P != PEnd; ++P) {
3766 P->first, P->second)) {
3767 Instantiation->setInvalidDecl();
3768 break;
3769 }
3770 }
3771
3772 // Instantiate any out-of-line variable template partial
3773 // specializations now.
3775 P = Instantiator.delayed_var_partial_spec_begin(),
3776 PEnd = Instantiator.delayed_var_partial_spec_end();
3777 P != PEnd; ++P) {
3779 P->first, P->second)) {
3780 Instantiation->setInvalidDecl();
3781 break;
3782 }
3783 }
3784 }
3785
3786 // Exit the scope of this instantiation.
3787 SavedContext.pop();
3788
3789 if (!Instantiation->isInvalidDecl()) {
3790 // Always emit the vtable for an explicit instantiation definition
3791 // of a polymorphic class template specialization. Otherwise, eagerly
3792 // instantiate only constexpr virtual functions in preparation for their use
3793 // in constant evaluation.
3795 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3796 else if (MightHaveConstexprVirtualFunctions)
3797 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3798 /*ConstexprOnly*/ true);
3799 }
3800
3801 Consumer.HandleTagDeclDefinition(Instantiation);
3802
3803 return Instantiation->isInvalidDecl();
3804}
3805
3806bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3807 EnumDecl *Instantiation, EnumDecl *Pattern,
3808 const MultiLevelTemplateArgumentList &TemplateArgs,
3810 EnumDecl *PatternDef = Pattern->getDefinition();
3811 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3812 Instantiation->getInstantiatedFromMemberEnum(),
3813 Pattern, PatternDef, TSK,/*Complain*/true))
3814 return true;
3815 Pattern = PatternDef;
3816
3817 // Record the point of instantiation.
3818 if (MemberSpecializationInfo *MSInfo
3819 = Instantiation->getMemberSpecializationInfo()) {
3820 MSInfo->setTemplateSpecializationKind(TSK);
3821 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3822 }
3823
3824 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3825 if (Inst.isInvalid())
3826 return true;
3827 if (Inst.isAlreadyInstantiating())
3828 return false;
3829 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3830 "instantiating enum definition");
3831
3832 // The instantiation is visible here, even if it was first declared in an
3833 // unimported module.
3834 Instantiation->setVisibleDespiteOwningModule();
3835
3836 // Enter the scope of this instantiation. We don't use
3837 // PushDeclContext because we don't have a scope.
3838 ContextRAII SavedContext(*this, Instantiation);
3841
3842 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3843
3844 // Pull attributes from the pattern onto the instantiation.
3845 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3846
3847 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3848 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3849
3850 // Exit the scope of this instantiation.
3851 SavedContext.pop();
3852
3853 return Instantiation->isInvalidDecl();
3854}
3855
3857 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3858 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3859 // If there is no initializer, we don't need to do anything.
3860 if (!Pattern->hasInClassInitializer())
3861 return false;
3862
3863 assert(Instantiation->getInClassInitStyle() ==
3864 Pattern->getInClassInitStyle() &&
3865 "pattern and instantiation disagree about init style");
3866
3867 // Error out if we haven't parsed the initializer of the pattern yet because
3868 // we are waiting for the closing brace of the outer class.
3869 Expr *OldInit = Pattern->getInClassInitializer();
3870 if (!OldInit) {
3871 RecordDecl *PatternRD = Pattern->getParent();
3872 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3873 Diag(PointOfInstantiation,
3874 diag::err_default_member_initializer_not_yet_parsed)
3875 << OutermostClass << Pattern;
3876 Diag(Pattern->getEndLoc(),
3877 diag::note_default_member_initializer_not_yet_parsed);
3878 Instantiation->setInvalidDecl();
3879 return true;
3880 }
3881
3882 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3883 if (Inst.isInvalid())
3884 return true;
3885 if (Inst.isAlreadyInstantiating()) {
3886 // Error out if we hit an instantiation cycle for this initializer.
3887 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3888 << Instantiation;
3889 return true;
3890 }
3891 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3892 "instantiating default member init");
3893
3894 // Enter the scope of this instantiation. We don't use PushDeclContext because
3895 // we don't have a scope.
3896 ContextRAII SavedContext(*this, Instantiation->getParent());
3899 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3900 PointOfInstantiation, Instantiation, CurContext};
3901
3902 LocalInstantiationScope Scope(*this, true);
3903
3904 // Instantiate the initializer.
3906 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3907
3908 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3909 /*CXXDirectInit=*/false);
3910 Expr *Init = NewInit.get();
3911 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3913 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3914
3915 if (auto *L = getASTMutationListener())
3916 L->DefaultMemberInitializerInstantiated(Instantiation);
3917
3918 // Return true if the in-class initializer is still missing.
3919 return !Instantiation->getInClassInitializer();
3920}
3921
3922namespace {
3923 /// A partial specialization whose template arguments have matched
3924 /// a given template-id.
3925 struct PartialSpecMatchResult {
3928 };
3929}
3930
3932 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3933 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3935 return true;
3936
3938 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
3939 CTD->getPartialSpecializations(PartialSpecs);
3940 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
3941 // C++ [temp.spec.partial.member]p2:
3942 // If the primary member template is explicitly specialized for a given
3943 // (implicit) specialization of the enclosing class template, the partial
3944 // specializations of the member template are ignored for this
3945 // specialization of the enclosing class template. If a partial
3946 // specialization of the member template is explicitly specialized for a
3947 // given (implicit) specialization of the enclosing class template, the
3948 // primary member template and its other partial specializations are still
3949 // considered for this specialization of the enclosing class template.
3951 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
3952 continue;
3953
3954 TemplateDeductionInfo Info(Loc);
3955 if (DeduceTemplateArguments(CTPSD,
3956 ClassTemplateSpec->getTemplateArgs().asArray(),
3958 return true;
3959 }
3960
3961 return false;
3962}
3963
3964/// Get the instantiation pattern to use to instantiate the definition of a
3965/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3966/// template or of a partial specialization).
3968 Sema &S, SourceLocation PointOfInstantiation,
3969 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3970 TemplateSpecializationKind TSK, bool PrimaryStrictPackMatch) {
3971 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3972 if (Inst.isInvalid())
3973 return {/*Invalid=*/true};
3974 if (Inst.isAlreadyInstantiating())
3975 return {/*Invalid=*/false};
3976
3977 llvm::PointerUnion<ClassTemplateDecl *,
3979 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3981 // Find best matching specialization.
3982 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3983
3984 // C++ [temp.class.spec.match]p1:
3985 // When a class template is used in a context that requires an
3986 // instantiation of the class, it is necessary to determine
3987 // whether the instantiation is to be generated using the primary
3988 // template or one of the partial specializations. This is done by
3989 // matching the template arguments of the class template
3990 // specialization with the template argument lists of the partial
3991 // specializations.
3992 typedef PartialSpecMatchResult MatchResult;
3993 SmallVector<MatchResult, 4> Matched, ExtraMatched;
3995 Template->getPartialSpecializations(PartialSpecs);
3996 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3997 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
3998 // C++ [temp.spec.partial.member]p2:
3999 // If the primary member template is explicitly specialized for a given
4000 // (implicit) specialization of the enclosing class template, the
4001 // partial specializations of the member template are ignored for this
4002 // specialization of the enclosing class template. If a partial
4003 // specialization of the member template is explicitly specialized for a
4004 // given (implicit) specialization of the enclosing class template, the
4005 // primary member template and its other partial specializations are
4006 // still considered for this specialization of the enclosing class
4007 // template.
4008 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4009 !Partial->getMostRecentDecl()->isMemberSpecialization())
4010 continue;
4011
4012 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4014 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4016 // Store the failed-deduction information for use in diagnostics, later.
4017 // TODO: Actually use the failed-deduction info?
4018 FailedCandidates.addCandidate().set(
4020 MakeDeductionFailureInfo(S.Context, Result, Info));
4021 (void)Result;
4022 } else {
4023 auto &List = Info.hasStrictPackMatch() ? ExtraMatched : Matched;
4024 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4025 }
4026 }
4027 if (Matched.empty() && PrimaryStrictPackMatch)
4028 Matched = std::move(ExtraMatched);
4029
4030 // If we're dealing with a member template where the template parameters
4031 // have been instantiated, this provides the original template parameters
4032 // from which the member template's parameters were instantiated.
4033
4034 if (Matched.size() >= 1) {
4035 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4036 if (Matched.size() == 1) {
4037 // -- If exactly one matching specialization is found, the
4038 // instantiation is generated from that specialization.
4039 // We don't need to do anything for this.
4040 } else {
4041 // -- If more than one matching specialization is found, the
4042 // partial order rules (14.5.4.2) are used to determine
4043 // whether one of the specializations is more specialized
4044 // than the others. If none of the specializations is more
4045 // specialized than all of the other matching
4046 // specializations, then the use of the class template is
4047 // ambiguous and the program is ill-formed.
4049 PEnd = Matched.end();
4050 P != PEnd; ++P) {
4052 P->Partial, Best->Partial, PointOfInstantiation) ==
4053 P->Partial)
4054 Best = P;
4055 }
4056
4057 // Determine if the best partial specialization is more specialized than
4058 // the others.
4059 bool Ambiguous = false;
4060 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4061 PEnd = Matched.end();
4062 P != PEnd; ++P) {
4063 if (P != Best && S.getMoreSpecializedPartialSpecialization(
4064 P->Partial, Best->Partial,
4065 PointOfInstantiation) != Best->Partial) {
4066 Ambiguous = true;
4067 break;
4068 }
4069 }
4070
4071 if (Ambiguous) {
4072 // Partial ordering did not produce a clear winner. Complain.
4073 Inst.Clear();
4074 S.Diag(PointOfInstantiation,
4075 diag::err_partial_spec_ordering_ambiguous)
4076 << ClassTemplateSpec;
4077
4078 // Print the matching partial specializations.
4079 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4080 PEnd = Matched.end();
4081 P != PEnd; ++P)
4082 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4084 P->Partial->getTemplateParameters(), *P->Args);
4085
4086 return {/*Invalid=*/true};
4087 }
4088 }
4089
4090 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4091 } else {
4092 // -- If no matches are found, the instantiation is generated
4093 // from the primary template.
4094 }
4095 }
4096
4097 CXXRecordDecl *Pattern = nullptr;
4098 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4099 if (auto *PartialSpec =
4100 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4101 // Instantiate using the best class template partial specialization.
4102 while (PartialSpec->getInstantiatedFromMember()) {
4103 // If we've found an explicit specialization of this class template,
4104 // stop here and use that as the pattern.
4105 if (PartialSpec->isMemberSpecialization())
4106 break;
4107
4108 PartialSpec = PartialSpec->getInstantiatedFromMember();
4109 }
4110 Pattern = PartialSpec;
4111 } else {
4112 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4113 while (Template->getInstantiatedFromMemberTemplate()) {
4114 // If we've found an explicit specialization of this class template,
4115 // stop here and use that as the pattern.
4116 if (Template->isMemberSpecialization())
4117 break;
4118
4119 Template = Template->getInstantiatedFromMemberTemplate();
4120 }
4121 Pattern = Template->getTemplatedDecl();
4122 }
4123
4124 return Pattern;
4125}
4126
4128 SourceLocation PointOfInstantiation,
4129 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4130 TemplateSpecializationKind TSK, bool Complain,
4131 bool PrimaryStrictPackMatch) {
4132 // Perform the actual instantiation on the canonical declaration.
4133 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4134 ClassTemplateSpec->getCanonicalDecl());
4135 if (ClassTemplateSpec->isInvalidDecl())
4136 return true;
4137
4138 bool HadAvaibilityWarning =
4139 ShouldDiagnoseAvailabilityOfDecl(ClassTemplateSpec, nullptr, nullptr)
4140 .first != AR_Available;
4141
4143 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
4144 ClassTemplateSpec, TSK,
4145 PrimaryStrictPackMatch);
4146
4147 if (!Pattern.isUsable())
4148 return Pattern.isInvalid();
4149
4150 bool Err = InstantiateClass(
4151 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4152 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4153
4154 // If we haven't already warn on avaibility, consider the avaibility
4155 // attributes of the partial specialization.
4156 // Note that - because we need to have deduced the partial specialization -
4157 // We can only emit these warnings when the specialization is instantiated.
4158 if (!Err && !HadAvaibilityWarning) {
4159 assert(ClassTemplateSpec->getTemplateSpecializationKind() !=
4161 DiagnoseAvailabilityOfDecl(ClassTemplateSpec, PointOfInstantiation);
4162 }
4163 return Err;
4164}
4165
4166void
4168 CXXRecordDecl *Instantiation,
4169 const MultiLevelTemplateArgumentList &TemplateArgs,
4171 // FIXME: We need to notify the ASTMutationListener that we did all of these
4172 // things, in case we have an explicit instantiation definition in a PCM, a
4173 // module, or preamble, and the declaration is in an imported AST.
4174 assert(
4177 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4178 "Unexpected template specialization kind!");
4179 for (auto *D : Instantiation->decls()) {
4180 bool SuppressNew = false;
4181 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4182 if (FunctionDecl *Pattern =
4183 Function->getInstantiatedFromMemberFunction()) {
4184
4185 if (Function->getTrailingRequiresClause()) {
4186 ConstraintSatisfaction Satisfaction;
4187 if (CheckFunctionConstraints(Function, Satisfaction) ||
4188 !Satisfaction.IsSatisfied) {
4189 continue;
4190 }
4191 }
4192
4193 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4194 continue;
4195
4197 Function->getTemplateSpecializationKind();
4198 if (PrevTSK == TSK_ExplicitSpecialization)
4199 continue;
4200
4202 PointOfInstantiation, TSK, Function, PrevTSK,
4203 Function->getPointOfInstantiation(), SuppressNew) ||
4204 SuppressNew)
4205 continue;
4206
4207 // C++11 [temp.explicit]p8:
4208 // An explicit instantiation definition that names a class template
4209 // specialization explicitly instantiates the class template
4210 // specialization and is only an explicit instantiation definition
4211 // of members whose definition is visible at the point of
4212 // instantiation.
4213 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4214 continue;
4215
4216 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4217
4218 if (Function->isDefined()) {
4219 // Let the ASTConsumer know that this function has been explicitly
4220 // instantiated now, and its linkage might have changed.
4221 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
4222 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4223 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4224 } else if (TSK == TSK_ImplicitInstantiation) {
4226 std::make_pair(Function, PointOfInstantiation));
4227 }
4228 }
4229 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4231 continue;
4232
4233 if (Var->isStaticDataMember()) {
4234 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4235 continue;
4236
4238 assert(MSInfo && "No member specialization information?");
4239 if (MSInfo->getTemplateSpecializationKind()
4241 continue;
4242
4243 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4244 Var,
4246 MSInfo->getPointOfInstantiation(),
4247 SuppressNew) ||
4248 SuppressNew)
4249 continue;
4250
4252 // C++0x [temp.explicit]p8:
4253 // An explicit instantiation definition that names a class template
4254 // specialization explicitly instantiates the class template
4255 // specialization and is only an explicit instantiation definition
4256 // of members whose definition is visible at the point of
4257 // instantiation.
4259 continue;
4260
4261 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4262 InstantiateVariableDefinition(PointOfInstantiation, Var);
4263 } else {
4264 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4265 }
4266 }
4267 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4268 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4269 continue;
4270
4271 // Always skip the injected-class-name, along with any
4272 // redeclarations of nested classes, since both would cause us
4273 // to try to instantiate the members of a class twice.
4274 // Skip closure types; they'll get instantiated when we instantiate
4275 // the corresponding lambda-expression.
4276 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4277 Record->isLambda())
4278 continue;
4279
4280 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4281 assert(MSInfo && "No member specialization information?");
4282
4283 if (MSInfo->getTemplateSpecializationKind()
4285 continue;
4286
4287 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4289 // On Windows, explicit instantiation decl of the outer class doesn't
4290 // affect the inner class. Typically extern template declarations are
4291 // used in combination with dll import/export annotations, but those
4292 // are not propagated from the outer class templates to inner classes.
4293 // Therefore, do not instantiate inner classes on this platform, so
4294 // that users don't end up with undefined symbols during linking.
4295 continue;
4296 }
4297
4298 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4299 Record,
4301 MSInfo->getPointOfInstantiation(),
4302 SuppressNew) ||
4303 SuppressNew)
4304 continue;
4305
4306 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
4307 assert(Pattern && "Missing instantiated-from-template information");
4308
4309 if (!Record->getDefinition()) {
4310 if (!Pattern->getDefinition()) {
4311 // C++0x [temp.explicit]p8:
4312 // An explicit instantiation definition that names a class template
4313 // specialization explicitly instantiates the class template
4314 // specialization and is only an explicit instantiation definition
4315 // of members whose definition is visible at the point of
4316 // instantiation.
4318 MSInfo->setTemplateSpecializationKind(TSK);
4319 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4320 }
4321
4322 continue;
4323 }
4324
4325 InstantiateClass(PointOfInstantiation, Record, Pattern,
4326 TemplateArgs,
4327 TSK);
4328 } else {
4330 Record->getTemplateSpecializationKind() ==
4332 Record->setTemplateSpecializationKind(TSK);
4333 MarkVTableUsed(PointOfInstantiation, Record, true);
4334 }
4335 }
4336
4337 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4338 if (Pattern)
4339 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4340 TSK);
4341 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4342 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4343 assert(MSInfo && "No member specialization information?");
4344
4345 if (MSInfo->getTemplateSpecializationKind()
4347 continue;
4348
4350 PointOfInstantiation, TSK, Enum,
4352 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4353 SuppressNew)
4354 continue;
4355
4356 if (Enum->getDefinition())
4357 continue;
4358
4359 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4360 assert(Pattern && "Missing instantiated-from-template information");
4361
4363 if (!Pattern->getDefinition())
4364 continue;
4365
4366 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4367 } else {
4368 MSInfo->setTemplateSpecializationKind(TSK);
4369 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4370 }
4371 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4372 // No need to instantiate in-class initializers during explicit
4373 // instantiation.
4374 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4375 // Handle local classes which could have substituted template params.
4376 CXXRecordDecl *ClassPattern =
4377 Instantiation->isLocalClass()
4378 ? Instantiation->getInstantiatedFromMemberClass()
4379 : Instantiation->getTemplateInstantiationPattern();
4380
4382 ClassPattern->lookup(Field->getDeclName());
4383 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4384 assert(Pattern);
4385 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4386 TemplateArgs);
4387 }
4388 }
4389 }
4390}
4391
4392void
4394 SourceLocation PointOfInstantiation,
4395 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4397 // C++0x [temp.explicit]p7:
4398 // An explicit instantiation that names a class template
4399 // specialization is an explicit instantion of the same kind
4400 // (declaration or definition) of each of its members (not
4401 // including members inherited from base classes) that has not
4402 // been previously explicitly specialized in the translation unit
4403 // containing the explicit instantiation, except as described
4404 // below.
4405 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4406 getTemplateInstantiationArgs(ClassTemplateSpec),
4407 TSK);
4408}
4409
4412 if (!S)
4413 return S;
4414
4415 TemplateInstantiator Instantiator(*this, TemplateArgs,
4417 DeclarationName());
4418 return Instantiator.TransformStmt(S);
4419}
4420
4422 const TemplateArgumentLoc &Input,
4423 const MultiLevelTemplateArgumentList &TemplateArgs,
4425 const DeclarationName &Entity) {
4426 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4427 return Instantiator.TransformTemplateArgument(Input, Output);
4428}
4429
4432 const MultiLevelTemplateArgumentList &TemplateArgs,
4434 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4435 DeclarationName());
4436 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4437}
4438
4441 const MultiLevelTemplateArgumentList &TemplateArgs,
4442 TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes) {
4443 TemplateInstantiator Instantiator(
4444 TemplateInstantiator::ForParameterMappingSubstitution, *this, BaseLoc,
4445 TemplateArgs, BuildPackExpansionTypes);
4446 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4447}
4448
4451 if (!E)
4452 return E;
4453
4454 TemplateInstantiator Instantiator(*this, TemplateArgs,
4456 DeclarationName());
4457 return Instantiator.TransformExpr(E);
4458}
4459
4462 const MultiLevelTemplateArgumentList &TemplateArgs) {
4463 if (!E)
4464 return E;
4465
4466 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4467 DeclarationName());
4468 return Instantiator.TransformAddressOfOperand(E);
4469}
4470
4473 const MultiLevelTemplateArgumentList &TemplateArgs) {
4474 // FIXME: should call SubstExpr directly if this function is equivalent or
4475 // should it be different?
4476 return SubstExpr(E, TemplateArgs);
4477}
4478
4480 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4481 if (!E)
4482 return E;
4483
4484 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4485 DeclarationName());
4486 Instantiator.setEvaluateConstraints(false);
4487 return Instantiator.TransformExpr(E);
4488}
4489
4491 const MultiLevelTemplateArgumentList &TemplateArgs,
4492 bool CXXDirectInit) {
4493 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4494 DeclarationName());
4495 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4496}
4497
4498bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4499 const MultiLevelTemplateArgumentList &TemplateArgs,
4500 SmallVectorImpl<Expr *> &Outputs) {
4501 if (Exprs.empty())
4502 return false;
4503
4504 TemplateInstantiator Instantiator(*this, TemplateArgs,
4506 DeclarationName());
4507 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4508 IsCall, Outputs);
4509}
4510
4513 const MultiLevelTemplateArgumentList &TemplateArgs) {
4514 if (!NNS)
4515 return NestedNameSpecifierLoc();
4516
4517 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4518 DeclarationName());
4519 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4520}
4521
4524 const MultiLevelTemplateArgumentList &TemplateArgs) {
4525 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4526 NameInfo.getName());
4527 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4528}
4529
4532 NestedNameSpecifierLoc &QualifierLoc, TemplateName Name,
4533 SourceLocation NameLoc,
4534 const MultiLevelTemplateArgumentList &TemplateArgs) {
4535 TemplateInstantiator Instantiator(*this, TemplateArgs, NameLoc,
4536 DeclarationName());
4537 return Instantiator.TransformTemplateName(QualifierLoc, TemplateKWLoc, Name,
4538 NameLoc);
4539}
4540
4541static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4542 // When storing ParmVarDecls in the local instantiation scope, we always
4543 // want to use the ParmVarDecl from the canonical function declaration,
4544 // since the map is then valid for any redeclaration or definition of that
4545 // function.
4546 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4547 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4548 unsigned i = PV->getFunctionScopeIndex();
4549 // This parameter might be from a freestanding function type within the
4550 // function and isn't necessarily referring to one of FD's parameters.
4551 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4552 return FD->getCanonicalDecl()->getParamDecl(i);
4553 }
4554 }
4555 return D;
4556}
4557
4558llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4561 for (LocalInstantiationScope *Current = this; Current;
4562 Current = Current->Outer) {
4563
4564 // Check if we found something within this scope.
4565 const Decl *CheckD = D;
4566 do {
4567 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4568 if (Found != Current->LocalDecls.end())
4569 return &Found->second;
4570
4571 // If this is a tag declaration, it's possible that we need to look for
4572 // a previous declaration.
4573 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4574 CheckD = Tag->getPreviousDecl();
4575 else
4576 CheckD = nullptr;
4577 } while (CheckD);
4578
4579 // If we aren't combined with our outer scope, we're done.
4580 if (!Current->CombineWithOuterScope)
4581 break;
4582 }
4583
4584 return nullptr;
4585}
4586
4587llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4590 if (Result)
4591 return Result;
4592 // If we're performing a partial substitution during template argument
4593 // deduction, we may not have values for template parameters yet.
4596 return nullptr;
4597
4598 // Local types referenced prior to definition may require instantiation.
4599 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4600 if (RD->isLocalClass())
4601 return nullptr;
4602
4603 // Enumeration types referenced prior to definition may appear as a result of
4604 // error recovery.
4605 if (isa<EnumDecl>(D))
4606 return nullptr;
4607
4608 // Materialized typedefs/type alias for implicit deduction guides may require
4609 // instantiation.
4610 if (isa<TypedefNameDecl>(D) &&
4612 return nullptr;
4613
4614 // If we didn't find the decl, then we either have a sema bug, or we have a
4615 // forward reference to a label declaration. Return null to indicate that
4616 // we have an uninstantiated label.
4617 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4618 return nullptr;
4619}
4620
4623 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4624 if (Stored.isNull()) {
4625#ifndef NDEBUG
4626 // It should not be present in any surrounding scope either.
4627 LocalInstantiationScope *Current = this;
4628 while (Current->CombineWithOuterScope && Current->Outer) {
4629 Current = Current->Outer;
4630 assert(!Current->LocalDecls.contains(D) &&
4631 "Instantiated local in inner and outer scopes");
4632 }
4633#endif
4634 Stored = Inst;
4635 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4636 Pack->push_back(cast<ValueDecl>(Inst));
4637 } else {
4638 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4639 }
4640}
4641
4643 VarDecl *Inst) {
4645 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4646 Pack->push_back(Inst);
4647}
4648
4650#ifndef NDEBUG
4651 // This should be the first time we've been told about this decl.
4652 for (LocalInstantiationScope *Current = this;
4653 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4654 assert(!Current->LocalDecls.contains(D) &&
4655 "Creating local pack after instantiation of local");
4656#endif
4657
4659 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4661 Stored = Pack;
4662 ArgumentPacks.push_back(Pack);
4663}
4664
4666 for (DeclArgumentPack *Pack : ArgumentPacks)
4667 if (llvm::is_contained(*Pack, D))
4668 return true;
4669 return false;
4670}
4671
4673 const TemplateArgument *ExplicitArgs,
4674 unsigned NumExplicitArgs) {
4675 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4676 "Already have a partially-substituted pack");
4677 assert((!PartiallySubstitutedPack
4678 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4679 "Wrong number of arguments in partially-substituted pack");
4680 PartiallySubstitutedPack = Pack;
4681 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4682 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4683}
4684
4686 const TemplateArgument **ExplicitArgs,
4687 unsigned *NumExplicitArgs) const {
4688 if (ExplicitArgs)
4689 *ExplicitArgs = nullptr;
4690 if (NumExplicitArgs)
4691 *NumExplicitArgs = 0;
4692
4693 for (const LocalInstantiationScope *Current = this; Current;
4694 Current = Current->Outer) {
4695 if (Current->PartiallySubstitutedPack) {
4696 if (ExplicitArgs)
4697 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4698 if (NumExplicitArgs)
4699 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4700
4701 return Current->PartiallySubstitutedPack;
4702 }
4703
4704 if (!Current->CombineWithOuterScope)
4705 break;
4706 }
4707
4708 return nullptr;
4709}
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:197
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:47
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1449
bool isFileContext() const
Definition DeclBase.h:2180
DeclContextLookupResult lookup_result
Definition DeclBase.h:2577
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2373
ValueDecl * getDecl()
Definition Expr.h: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:822
NestedNameSpecifier getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition Decl.h:837
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:809
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition Decl.h:4007
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition Decl.h:4270
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition Decl.cpp:5080
EnumDecl * getDefinition() const
Definition Decl.h:4110
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:3160
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition Decl.cpp:4713
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition Decl.h:3340
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition Decl.h:3334
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3396
Represents a function declaration or definition.
Definition Decl.h:2000
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2774
FunctionDecl * getTemplateInstantiationPattern(bool ForDefinition=true) const
Retrieve the function declaration from which this function could be instantiated, if it is an instant...
Definition Decl.cpp:4252
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4301
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2470
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition Decl.h:2344
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, ValueDecl *ParamPack, SourceLocation NameLoc, ArrayRef< ValueDecl * > Params)
Definition ExprCXX.cpp:1816
ValueDecl * getExpansion(unsigned I) const
Get an expansion of the parameter pack by index.
Definition ExprCXX.h:4884
ValueDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition ExprCXX.h:4876
ValueDecl * getParameterPack() const
Get the parameter pack which this expression refers to.
Definition ExprCXX.h:4869
iterator end() const
Definition ExprCXX.h:4878
unsigned getNumExpansions() const
Get the number of parameters in this parameter pack.
Definition ExprCXX.h:4881
SourceLocation getParameterPackLocation() const
Get the location of the parameter pack.
Definition ExprCXX.h:4872
iterator begin() const
Definition ExprCXX.h:4877
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:369
LocalInstantiationScope(Sema &SemaRef, bool CombineWithOuterScope=false, bool InstantiatingLambdaOrBlock=false)
Definition Template.h:437
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:372
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:509
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:575
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:269
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:274
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:295
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:301
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
virtual void getNameForDiagnostic(raw_ostream &OS, const PrintingPolicy &Policy, bool Qualified) const
Appends a human-readable name for this declaration into the given stream.
Definition Decl.cpp: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:1790
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition Decl.h:1850
SourceLocation getExplicitObjectParamThisLoc() const
Definition Decl.h:1886
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition Decl.h:1931
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition Decl.h:1919
void setUninstantiatedDefaultArg(Expr *arg)
Definition Decl.cpp:3039
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition Decl.h:1823
bool hasUninstantiatedDefaultArg() const
Definition Decl.h:1923
bool hasInheritedDefaultArg() const
Definition Decl.h:1935
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition Decl.h:1882
Expr * getDefaultArg()
Definition Decl.cpp:3002
Expr * getUninstantiatedDefaultArg()
Definition Decl.cpp:3044
unsigned getFunctionScopeDepth() const
Definition Decl.h:1840
void setHasInheritedDefaultArg(bool I=true)
Definition Decl.h:1939
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:4312
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:13552
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition Sema.h:8401
A RAII object to temporarily push a declaration context.
Definition Sema.h:3476
For a defaulted function, the kind of defaulted function that it is.
Definition Sema.h:6321
DefaultedComparisonKind asComparison() const
Definition Sema.h:6353
CXXSpecialMemberKind asSpecialMember() const
Definition Sema.h:6350
A helper class for building up ExtParameterInfos.
Definition Sema.h:12955
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition Sema.h:12392
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:854
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition Sema.h:13502
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:13486
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition Sema.h:12984
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:2285
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:13863
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:1283
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:13513
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition Sema.h:922
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
void PrintInstantiationStack()
Definition Sema.h:13580
ASTContext & getASTContext() const
Definition Sema.h:925
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:14025
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition Sema.h:1191
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:918
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:13538
TemplateArgument getPackSubstitutedTemplateArgument(TemplateArgument Arg) const
Definition Sema.h:11724
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:12996
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:1418
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:13912
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:13522
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:13852
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:13546
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:1284
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6696
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6706
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition Sema.h:13530
bool inParameterMappingSubstitution() const
Definition Sema.h:13857
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:8120
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:8270
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:1286
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:1285
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:1560
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition Sema.h:13497
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
bool SubstTemplateArgumentsInParameterMapping(ArrayRef< TemplateArgumentLoc > Args, SourceLocation BaseLoc, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Out, bool BuildPackExpansionTypes)
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:8609
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:3717
void setTagKind(TagKind TK)
Definition Decl.h:3915
SourceRange getBraceRange() const
Definition Decl.h:3788
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition Decl.h:3793
void startDefinition()
Starts the definition of this tag declaration.
Definition Decl.cpp:4894
TagKind getTagKind() const
Definition Decl.h:3911
void setBraceRange(SourceRange R)
Definition Decl.h:3789
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:671
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition Template.h:684
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition Template.h:710
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition Template.h:694
void setEvaluateConstraints(bool B)
Definition Template.h:612
LocalInstantiationScope * getStartingScope() const
Definition Template.h:682
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:687
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:706
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition Template.h:698
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:227
const ASTTemplateArgumentListInfo * getTemplateArgsAsWritten() const
Definition ASTConcept.h:266
UnsignedOrNone getArgPackSubstIndex() const
Definition ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition ASTConcept.h:244
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition ASTConcept.h:276
TemplateDecl * getNamedConcept() const
Definition ASTConcept.h:254
const DeclarationNameInfo & getConceptNameInfo() const
Definition ASTConcept.h:280
ConceptReference * getConceptReference() const
Definition ASTConcept.h:248
void setLocStart(SourceLocation L)
Definition Decl.h:3548
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
void pushFullCopy(TypeLoc L)
Pushes a copy of the given TypeLoc onto this builder.
void reserve(size_t Requested)
Ensures that this buffer has at least as much capacity as described.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
void pushTrivial(ASTContext &Context, QualType T, SourceLocation Loc)
Pushes 'T' with all locations pointing to 'Loc'.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
QualType getType() const
Get the type for which this source info wrapper provides information.
Definition TypeLoc.h:133
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
TypeLoc IgnoreParens() const
Definition TypeLoc.h: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:8261
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:8272
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:8883
bool isReferenceType() const
Definition TypeBase.h:8551
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:9103
bool isRecordType() const
Definition TypeBase.h:8654
QualType getUnderlyingType() const
Definition Decl.h:3617
QualType getType() const
Definition Decl.h:723
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5512
Represents a variable declaration or definition.
Definition Decl.h:926
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1283
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp: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:1168
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:236
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:562
@ 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:367
@ Success
Template argument deduction was successful.
Definition Sema.h:369
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:13001
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition Sema.h:13171
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition Sema.h:13118
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition Sema.h:13140
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition Sema.h:13166
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition Sema.h:13127
SynthesisKind
The kind of template instantiation we are performing.
Definition Sema.h:13003
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition Sema.h:13095
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition Sema.h:13013
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition Sema.h:13022
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition Sema.h:13041
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition Sema.h:13092
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition Sema.h:13049
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition Sema.h:13056
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition Sema.h:13099
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition Sema.h:13067
@ Memoization
Added for Template instantiation observation.
Definition Sema.h:13105
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition Sema.h:13032
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition Sema.h:13111
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition Sema.h:13108
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition Sema.h:13114
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition Sema.h:13029
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition Sema.h:13037
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition Sema.h:13045
@ TemplateInstantiation
We are instantiating a template declaration.
Definition Sema.h:13006
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition Sema.h:13059
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition Sema.h:13063
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition Sema.h:13018
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition Sema.h:13089
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition Sema.h:13052
Decl * Entity
The entity that is being synthesized.
Definition Sema.h:13130
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:13197
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition Sema.h:13357
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:13361
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
SourceLocation Ellipsis
UnsignedOrNone NumExpansions