clang 20.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/STLForwardCompat.h"
39#include "llvm/ADT/StringExtras.h"
40#include "llvm/Support/ErrorHandling.h"
41#include "llvm/Support/SaveAndRestore.h"
42#include "llvm/Support/TimeProfiler.h"
43#include <optional>
44
45using namespace clang;
46using namespace sema;
47
48//===----------------------------------------------------------------------===/
49// Template Instantiation Support
50//===----------------------------------------------------------------------===/
51
52namespace {
54struct Response {
55 const Decl *NextDecl = nullptr;
56 bool IsDone = false;
57 bool ClearRelativeToPrimary = true;
58 static Response Done() {
59 Response R;
60 R.IsDone = true;
61 return R;
62 }
63 static Response ChangeDecl(const Decl *ND) {
64 Response R;
65 R.NextDecl = ND;
66 return R;
67 }
68 static Response ChangeDecl(const DeclContext *Ctx) {
69 Response R;
70 R.NextDecl = Decl::castFromDeclContext(Ctx);
71 return R;
72 }
73
74 static Response UseNextDecl(const Decl *CurDecl) {
75 return ChangeDecl(CurDecl->getDeclContext());
76 }
77
78 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
79 Response R = Response::UseNextDecl(CurDecl);
80 R.ClearRelativeToPrimary = false;
81 return R;
82 }
83};
84
85// Retrieve the primary template for a lambda call operator. It's
86// unfortunate that we only have the mappings of call operators rather
87// than lambda classes.
88const FunctionDecl *
89getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
90 if (!isLambdaCallOperator(LambdaCallOperator))
91 return LambdaCallOperator;
92 while (true) {
93 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
94 LambdaCallOperator->getDescribedTemplate());
95 FTD && FTD->getInstantiatedFromMemberTemplate()) {
96 LambdaCallOperator =
97 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
98 } else if (LambdaCallOperator->getPrimaryTemplate()) {
99 // Cases where the lambda operator is instantiated in
100 // TemplateDeclInstantiator::VisitCXXMethodDecl.
101 LambdaCallOperator =
102 LambdaCallOperator->getPrimaryTemplate()->getTemplatedDecl();
103 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
104 ->getInstantiatedFromMemberFunction())
105 LambdaCallOperator = Prev;
106 else
107 break;
108 }
109 return LambdaCallOperator;
110}
111
112struct EnclosingTypeAliasTemplateDetails {
113 TypeAliasTemplateDecl *Template = nullptr;
114 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
115 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
116
117 explicit operator bool() noexcept { return Template; }
118};
119
120// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
121// well as its primary template and instantiating template arguments.
122EnclosingTypeAliasTemplateDetails
123getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
124 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
126 TypeAliasTemplateInstantiation)
127 continue;
128 EnclosingTypeAliasTemplateDetails Result;
129 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
130 *Next = TATD->getInstantiatedFromMemberTemplate();
131 Result = {
132 /*Template=*/TATD,
133 /*PrimaryTypeAliasDecl=*/TATD,
134 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
135 };
136 while (Next) {
137 Result.PrimaryTypeAliasDecl = Next;
138 Next = Next->getInstantiatedFromMemberTemplate();
139 }
140 return Result;
141 }
142 return {};
143}
144
145// Check if we are currently inside of a lambda expression that is
146// surrounded by a using alias declaration. e.g.
147// template <class> using type = decltype([](auto) { ^ }());
148// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
149// a DeclContext, nor does it have an associated specialization Decl from which
150// we could collect these template arguments.
151bool isLambdaEnclosedByTypeAliasDecl(
152 const FunctionDecl *LambdaCallOperator,
153 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
154 struct Visitor : DynamicRecursiveASTVisitor {
155 Visitor(const FunctionDecl *CallOperator) : CallOperator(CallOperator) {}
156 bool VisitLambdaExpr(LambdaExpr *LE) override {
157 // Return true to bail out of the traversal, implying the Decl contains
158 // the lambda.
159 return getPrimaryTemplateOfGenericLambda(LE->getCallOperator()) !=
160 CallOperator;
161 }
162 const FunctionDecl *CallOperator;
163 };
164
165 QualType Underlying =
166 PrimaryTypeAliasDecl->getTemplatedDecl()->getUnderlyingType();
167
168 return !Visitor(getPrimaryTemplateOfGenericLambda(LambdaCallOperator))
169 .TraverseType(Underlying);
170}
171
172// Add template arguments from a variable template instantiation.
173Response
174HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
176 bool SkipForSpecialization) {
177 // For a class-scope explicit specialization, there are no template arguments
178 // at this level, but there may be enclosing template arguments.
179 if (VarTemplSpec->isClassScopeExplicitSpecialization())
180 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
181
182 // We're done when we hit an explicit specialization.
183 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
184 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
185 return Response::Done();
186
187 // If this variable template specialization was instantiated from a
188 // specialized member that is a variable template, we're done.
189 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
190 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
191 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
193 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
194 if (!SkipForSpecialization)
195 Result.addOuterTemplateArguments(
196 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
197 /*Final=*/false);
198 if (Partial->isMemberSpecialization())
199 return Response::Done();
200 } else {
201 VarTemplateDecl *Tmpl = cast<VarTemplateDecl *>(Specialized);
202 if (!SkipForSpecialization)
203 Result.addOuterTemplateArguments(
204 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
205 /*Final=*/false);
206 if (Tmpl->isMemberSpecialization())
207 return Response::Done();
208 }
209 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
210}
211
212// If we have a template template parameter with translation unit context,
213// then we're performing substitution into a default template argument of
214// this template template parameter before we've constructed the template
215// that will own this template template parameter. In this case, we
216// use empty template parameter lists for all of the outer templates
217// to avoid performing any substitutions.
218Response
219HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
221 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
222 Result.addOuterTemplateArguments(std::nullopt);
223 return Response::Done();
224}
225
226Response HandlePartialClassTemplateSpec(
227 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
228 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
229 if (!SkipForSpecialization)
230 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
231 return Response::Done();
232}
233
234// Add template arguments from a class template instantiation.
235Response
236HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
238 bool SkipForSpecialization) {
239 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
240 // We're done when we hit an explicit specialization.
241 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
242 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
243 return Response::Done();
244
245 if (!SkipForSpecialization)
246 Result.addOuterTemplateArguments(
247 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
248 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
249 /*Final=*/false);
250
251 // If this class template specialization was instantiated from a
252 // specialized member that is a class template, we're done.
253 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
254 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
255 return Response::Done();
256
257 // If this was instantiated from a partial template specialization, we need
258 // to get the next level of declaration context from the partial
259 // specialization, as the ClassTemplateSpecializationDecl's
260 // DeclContext/LexicalDeclContext will be for the primary template.
261 if (auto *InstFromPartialTempl =
262 ClassTemplSpec->getSpecializedTemplateOrPartial()
264 return Response::ChangeDecl(
265 InstFromPartialTempl->getLexicalDeclContext());
266 }
267 return Response::UseNextDecl(ClassTemplSpec);
268}
269
270Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
272 const FunctionDecl *Pattern, bool RelativeToPrimary,
273 bool ForConstraintInstantiation,
274 bool ForDefaultArgumentSubstitution) {
275 // Add template arguments from a function template specialization.
276 if (!RelativeToPrimary &&
277 Function->getTemplateSpecializationKindForInstantiation() ==
279 return Response::Done();
280
281 if (!RelativeToPrimary &&
282 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
283 // This is an implicit instantiation of an explicit specialization. We
284 // don't get any template arguments from this function but might get
285 // some from an enclosing template.
286 return Response::UseNextDecl(Function);
287 } else if (const TemplateArgumentList *TemplateArgs =
288 Function->getTemplateSpecializationArgs()) {
289 // Add the template arguments for this specialization.
290 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
291 TemplateArgs->asArray(),
292 /*Final=*/false);
293
294 if (RelativeToPrimary &&
295 (Function->getTemplateSpecializationKind() ==
297 (Function->getFriendObjectKind() &&
298 !Function->getPrimaryTemplate()->getFriendObjectKind())))
299 return Response::UseNextDecl(Function);
300
301 // If this function was instantiated from a specialized member that is
302 // a function template, we're done.
303 assert(Function->getPrimaryTemplate() && "No function template?");
304 if (!ForDefaultArgumentSubstitution &&
305 Function->getPrimaryTemplate()->isMemberSpecialization())
306 return Response::Done();
307
308 // If this function is a generic lambda specialization, we are done.
309 if (!ForConstraintInstantiation &&
311 return Response::Done();
312
313 } else if (Function->getDescribedFunctionTemplate()) {
314 assert(
315 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
316 "Outer template not instantiated?");
317 }
318 // If this is a friend or local declaration and it declares an entity at
319 // namespace scope, take arguments from its lexical parent
320 // instead of its semantic parent, unless of course the pattern we're
321 // instantiating actually comes from the file's context!
322 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
323 Function->getNonTransparentDeclContext()->isFileContext() &&
324 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
325 return Response::ChangeDecl(Function->getLexicalDeclContext());
326 }
327
328 if (ForConstraintInstantiation && Function->getFriendObjectKind())
329 return Response::ChangeDecl(Function->getLexicalDeclContext());
330 return Response::UseNextDecl(Function);
331}
332
333Response HandleFunctionTemplateDecl(Sema &SemaRef,
334 const FunctionTemplateDecl *FTD,
336 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
337 Result.addOuterTemplateArguments(
338 const_cast<FunctionTemplateDecl *>(FTD),
339 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(
340 SemaRef.Context),
341 /*Final=*/false);
342
344
345 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
346 if (NNS->isInstantiationDependent()) {
347 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
348 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
349 // Prefer template arguments from the injected-class-type if possible.
350 // For example,
351 // ```cpp
352 // template <class... Pack> struct S {
353 // template <class T> void foo();
354 // };
355 // template <class... Pack> template <class T>
356 // ^^^^^^^^^^^^^ InjectedTemplateArgs
357 // They're of kind TemplateArgument::Pack, not of
358 // TemplateArgument::Type.
359 // void S<Pack...>::foo() {}
360 // ^^^^^^^
361 // TSTy->template_arguments() (which are of PackExpansionType)
362 // ```
363 // This meets the contract in
364 // TreeTransform::TryExpandParameterPacks that the template arguments
365 // for unexpanded parameters should be of a Pack kind.
366 if (TSTy->isCurrentInstantiation()) {
367 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
368 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
369 Arguments = CTD->getInjectedTemplateArgs(SemaRef.Context);
370 else if (auto *Specialization =
371 dyn_cast<ClassTemplateSpecializationDecl>(RD))
372 Arguments =
373 Specialization->getTemplateInstantiationArgs().asArray();
374 }
375 Result.addOuterTemplateArguments(
376 TSTy->getTemplateName().getAsTemplateDecl(), Arguments,
377 /*Final=*/false);
378 }
379 }
380
381 NNS = NNS->getPrefix();
382 }
383 }
384
385 return Response::ChangeDecl(FTD->getLexicalDeclContext());
386}
387
388Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
390 ASTContext &Context,
391 bool ForConstraintInstantiation) {
392 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
393 assert(
394 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
395 "Outer template not instantiated?");
396 if (ClassTemplate->isMemberSpecialization())
397 return Response::Done();
398 if (ForConstraintInstantiation)
399 Result.addOuterTemplateArguments(
400 const_cast<CXXRecordDecl *>(Rec),
401 ClassTemplate->getInjectedTemplateArgs(SemaRef.Context),
402 /*Final=*/false);
403 }
404
405 if (const MemberSpecializationInfo *MSInfo =
407 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
408 return Response::Done();
409
410 bool IsFriend = Rec->getFriendObjectKind() ||
413 if (ForConstraintInstantiation && IsFriend &&
415 return Response::ChangeDecl(Rec->getLexicalDeclContext());
416 }
417
418 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
419 // TypeAliasTemplateDecl that this lambda is defined inside of.
420 if (Rec->isLambda()) {
421 if (const Decl *LCD = Rec->getLambdaContextDecl())
422 return Response::ChangeDecl(LCD);
423 // Retrieve the template arguments for a using alias declaration.
424 // This is necessary for constraint checking, since we always keep
425 // constraints relative to the primary template.
426 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef);
427 ForConstraintInstantiation && TypeAlias) {
428 if (isLambdaEnclosedByTypeAliasDecl(Rec->getLambdaCallOperator(),
429 TypeAlias.PrimaryTypeAliasDecl)) {
430 Result.addOuterTemplateArguments(TypeAlias.Template,
431 TypeAlias.AssociatedTemplateArguments,
432 /*Final=*/false);
433 // Visit the parent of the current type alias declaration rather than
434 // the lambda thereof.
435 // E.g., in the following example:
436 // struct S {
437 // template <class> using T = decltype([]<Concept> {} ());
438 // };
439 // void foo() {
440 // S::T var;
441 // }
442 // The instantiated lambda expression (which we're visiting at 'var')
443 // has a function DeclContext 'foo' rather than the Record DeclContext
444 // S. This seems to be an oversight to me that we may want to set a
445 // Sema Context from the CXXScopeSpec before substituting into T.
446 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
447 }
448 }
449 }
450
451 return Response::UseNextDecl(Rec);
452}
453
454Response HandleImplicitConceptSpecializationDecl(
457 Result.addOuterTemplateArguments(
458 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
460 /*Final=*/false);
461 return Response::UseNextDecl(CSD);
462}
463
464Response HandleGenericDeclContext(const Decl *CurDecl) {
465 return Response::UseNextDecl(CurDecl);
466}
467} // namespace TemplateInstArgsHelpers
468} // namespace
469
471 const NamedDecl *ND, const DeclContext *DC, bool Final,
472 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
473 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
474 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
475 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
476 // Accumulate the set of template argument lists in this structure.
478
479 using namespace TemplateInstArgsHelpers;
480 const Decl *CurDecl = ND;
481
482 if (!CurDecl)
483 CurDecl = Decl::castFromDeclContext(DC);
484
485 if (Innermost) {
486 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
487 Final);
488 // Populate placeholder template arguments for TemplateTemplateParmDecls.
489 // This is essential for the case e.g.
490 //
491 // template <class> concept Concept = false;
492 // template <template <Concept C> class T> void foo(T<int>)
493 //
494 // where parameter C has a depth of 1 but the substituting argument `int`
495 // has a depth of 0.
496 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
497 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
498 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
499 }
500
501 while (!CurDecl->isFileContextDecl()) {
502 Response R;
503 if (const auto *VarTemplSpec =
504 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
505 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
506 } else if (const auto *PartialClassTemplSpec =
507 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
508 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
509 SkipForSpecialization);
510 } else if (const auto *ClassTemplSpec =
511 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
512 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
513 SkipForSpecialization);
514 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
515 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
516 ForConstraintInstantiation,
517 ForDefaultArgumentSubstitution);
518 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
519 R = HandleRecordDecl(*this, Rec, Result, Context,
520 ForConstraintInstantiation);
521 } else if (const auto *CSD =
522 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
523 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
524 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
525 R = HandleFunctionTemplateDecl(*this, FTD, Result);
526 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
527 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
528 } else if (!isa<DeclContext>(CurDecl)) {
529 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
530 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
531 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
532 }
533 } else {
534 R = HandleGenericDeclContext(CurDecl);
535 }
536
537 if (R.IsDone)
538 return Result;
539 if (R.ClearRelativeToPrimary)
540 RelativeToPrimary = false;
541 assert(R.NextDecl);
542 CurDecl = R.NextDecl;
543 }
544
545 return Result;
546}
547
549 switch (Kind) {
557 case ConstraintsCheck:
559 return true;
560
579 return false;
580
581 // This function should never be called when Kind's value is Memoization.
582 case Memoization:
583 break;
584 }
585
586 llvm_unreachable("Invalid SynthesisKind!");
587}
588
591 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
592 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
593 sema::TemplateDeductionInfo *DeductionInfo)
594 : SemaRef(SemaRef) {
595 // Don't allow further instantiation if a fatal error and an uncompilable
596 // error have occurred. Any diagnostics we might have raised will not be
597 // visible, and we do not need to construct a correct AST.
600 Invalid = true;
601 return;
602 }
603 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
604 if (!Invalid) {
606 Inst.Kind = Kind;
607 Inst.PointOfInstantiation = PointOfInstantiation;
608 Inst.Entity = Entity;
609 Inst.Template = Template;
610 Inst.TemplateArgs = TemplateArgs.data();
611 Inst.NumTemplateArgs = TemplateArgs.size();
612 Inst.DeductionInfo = DeductionInfo;
613 Inst.InstantiationRange = InstantiationRange;
615
616 AlreadyInstantiating = !Inst.Entity ? false :
618 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
619 .second;
621 }
622}
623
625 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
626 SourceRange InstantiationRange)
628 CodeSynthesisContext::TemplateInstantiation,
629 PointOfInstantiation, InstantiationRange, Entity) {}
630
632 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
633 ExceptionSpecification, SourceRange InstantiationRange)
635 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
636 PointOfInstantiation, InstantiationRange, Entity) {}
637
639 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
640 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
641 SourceRange InstantiationRange)
643 SemaRef,
644 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
645 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
646 Template, TemplateArgs) {}
647
649 Sema &SemaRef, SourceLocation PointOfInstantiation,
651 ArrayRef<TemplateArgument> TemplateArgs,
653 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
654 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
655 InstantiationRange, FunctionTemplate, nullptr,
656 TemplateArgs, &DeductionInfo) {
660}
661
663 Sema &SemaRef, SourceLocation PointOfInstantiation,
664 TemplateDecl *Template,
665 ArrayRef<TemplateArgument> TemplateArgs,
666 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
668 SemaRef,
669 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
670 PointOfInstantiation, InstantiationRange, Template, nullptr,
671 TemplateArgs, &DeductionInfo) {}
672
674 Sema &SemaRef, SourceLocation PointOfInstantiation,
676 ArrayRef<TemplateArgument> TemplateArgs,
677 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
679 SemaRef,
680 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
681 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
682 TemplateArgs, &DeductionInfo) {}
683
685 Sema &SemaRef, SourceLocation PointOfInstantiation,
687 ArrayRef<TemplateArgument> TemplateArgs,
688 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
690 SemaRef,
691 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
692 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
693 TemplateArgs, &DeductionInfo) {}
694
696 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
697 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
699 SemaRef,
700 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
701 PointOfInstantiation, InstantiationRange, Param, nullptr,
702 TemplateArgs) {}
703
705 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
707 SourceRange InstantiationRange)
709 SemaRef,
710 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
711 PointOfInstantiation, InstantiationRange, Param, Template,
712 TemplateArgs) {}
713
715 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
717 SourceRange InstantiationRange)
719 SemaRef,
720 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
721 PointOfInstantiation, InstantiationRange, Param, Template,
722 TemplateArgs) {}
723
725 Sema &SemaRef, SourceLocation PointOfInstantiation,
727 SourceRange InstantiationRange)
729 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
730 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
731 /*Template=*/nullptr, TemplateArgs) {}
732
734 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
735 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
736 SourceRange InstantiationRange)
738 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
739 PointOfInstantiation, InstantiationRange, Param, Template,
740 TemplateArgs) {}
741
743 Sema &SemaRef, SourceLocation PointOfInstantiation,
745 SourceRange InstantiationRange)
747 SemaRef, CodeSynthesisContext::RequirementInstantiation,
748 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
749 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
750
752 Sema &SemaRef, SourceLocation PointOfInstantiation,
754 SourceRange InstantiationRange)
756 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
757 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
758 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
759
761 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
762 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
764 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
765 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
766 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
767
769 Sema &SemaRef, SourceLocation PointOfInstantiation,
770 ConstraintsCheck, NamedDecl *Template,
771 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
774 PointOfInstantiation, InstantiationRange, Template, nullptr,
775 TemplateArgs) {}
776
778 Sema &SemaRef, SourceLocation PointOfInstantiation,
780 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
783 PointOfInstantiation, InstantiationRange, Template, nullptr,
784 {}, &DeductionInfo) {}
785
787 Sema &SemaRef, SourceLocation PointOfInstantiation,
789 SourceRange InstantiationRange)
792 PointOfInstantiation, InstantiationRange, Template) {}
793
795 Sema &SemaRef, SourceLocation PointOfInstantiation,
797 SourceRange InstantiationRange)
800 PointOfInstantiation, InstantiationRange, Template) {}
801
803 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
804 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
806 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
807 PointOfInstantiation, InstantiationRange, Entity) {}
808
811 TemplateDecl *PArg, SourceRange InstantiationRange)
813 ArgLoc, InstantiationRange, PArg) {}
814
816 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
818
819 CodeSynthesisContexts.push_back(Ctx);
820
821 if (!Ctx.isInstantiationRecord())
823
824 // Check to see if we're low on stack space. We can't do anything about this
825 // from here, but we can at least warn the user.
826 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
827}
828
830 auto &Active = CodeSynthesisContexts.back();
831 if (!Active.isInstantiationRecord()) {
832 assert(NonInstantiationEntries > 0);
834 }
835
836 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
837
838 // Name lookup no longer looks in this template's defining module.
839 assert(CodeSynthesisContexts.size() >=
841 "forgot to remove a lookup module for a template instantiation");
842 if (CodeSynthesisContexts.size() ==
845 LookupModulesCache.erase(M);
847 }
848
849 // If we've left the code synthesis context for the current context stack,
850 // stop remembering that we've emitted that stack.
851 if (CodeSynthesisContexts.size() ==
854
855 CodeSynthesisContexts.pop_back();
856}
857
859 if (!Invalid) {
860 if (!AlreadyInstantiating) {
861 auto &Active = SemaRef.CodeSynthesisContexts.back();
862 if (Active.Entity)
864 {Active.Entity->getCanonicalDecl(), Active.Kind});
865 }
866
869
871 Invalid = true;
872 }
873}
874
875static std::string convertCallArgsToString(Sema &S,
877 std::string Result;
878 llvm::raw_string_ostream OS(Result);
879 llvm::ListSeparator Comma;
880 for (const Expr *Arg : Args) {
881 OS << Comma;
882 Arg->IgnoreParens()->printPretty(OS, nullptr,
884 }
885 return Result;
886}
887
888bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
889 SourceLocation PointOfInstantiation,
890 SourceRange InstantiationRange) {
893 if ((SemaRef.CodeSynthesisContexts.size() -
895 <= SemaRef.getLangOpts().InstantiationDepth)
896 return false;
897
898 SemaRef.Diag(PointOfInstantiation,
899 diag::err_template_recursion_depth_exceeded)
900 << SemaRef.getLangOpts().InstantiationDepth
901 << InstantiationRange;
902 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
903 << SemaRef.getLangOpts().InstantiationDepth;
904 return true;
905}
906
908 // Determine which template instantiations to skip, if any.
909 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
910 unsigned Limit = Diags.getTemplateBacktraceLimit();
911 if (Limit && Limit < CodeSynthesisContexts.size()) {
912 SkipStart = Limit / 2 + Limit % 2;
913 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
914 }
915
916 // FIXME: In all of these cases, we need to show the template arguments
917 unsigned InstantiationIdx = 0;
919 Active = CodeSynthesisContexts.rbegin(),
920 ActiveEnd = CodeSynthesisContexts.rend();
921 Active != ActiveEnd;
922 ++Active, ++InstantiationIdx) {
923 // Skip this instantiation?
924 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
925 if (InstantiationIdx == SkipStart) {
926 // Note that we're skipping instantiations.
927 Diags.Report(Active->PointOfInstantiation,
928 diag::note_instantiation_contexts_suppressed)
929 << unsigned(CodeSynthesisContexts.size() - Limit);
930 }
931 continue;
932 }
933
934 switch (Active->Kind) {
936 Decl *D = Active->Entity;
937 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
938 unsigned DiagID = diag::note_template_member_class_here;
939 if (isa<ClassTemplateSpecializationDecl>(Record))
940 DiagID = diag::note_template_class_instantiation_here;
941 Diags.Report(Active->PointOfInstantiation, DiagID)
942 << Record << Active->InstantiationRange;
943 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
944 unsigned DiagID;
945 if (Function->getPrimaryTemplate())
946 DiagID = diag::note_function_template_spec_here;
947 else
948 DiagID = diag::note_template_member_function_here;
949 Diags.Report(Active->PointOfInstantiation, DiagID)
950 << Function
951 << Active->InstantiationRange;
952 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
953 Diags.Report(Active->PointOfInstantiation,
954 VD->isStaticDataMember()?
955 diag::note_template_static_data_member_def_here
956 : diag::note_template_variable_def_here)
957 << VD
958 << Active->InstantiationRange;
959 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
960 Diags.Report(Active->PointOfInstantiation,
961 diag::note_template_enum_def_here)
962 << ED
963 << Active->InstantiationRange;
964 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
965 Diags.Report(Active->PointOfInstantiation,
966 diag::note_template_nsdmi_here)
967 << FD << Active->InstantiationRange;
968 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
969 Diags.Report(Active->PointOfInstantiation,
970 diag::note_template_class_instantiation_here)
971 << CTD << Active->InstantiationRange;
972 }
973 break;
974 }
975
977 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
978 SmallString<128> TemplateArgsStr;
979 llvm::raw_svector_ostream OS(TemplateArgsStr);
980 Template->printName(OS, getPrintingPolicy());
981 printTemplateArgumentList(OS, Active->template_arguments(),
983 Diags.Report(Active->PointOfInstantiation,
984 diag::note_default_arg_instantiation_here)
985 << OS.str()
986 << Active->InstantiationRange;
987 break;
988 }
989
991 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
992 Diags.Report(Active->PointOfInstantiation,
993 diag::note_explicit_template_arg_substitution_here)
994 << FnTmpl
996 Active->TemplateArgs,
997 Active->NumTemplateArgs)
998 << Active->InstantiationRange;
999 break;
1000 }
1001
1003 if (FunctionTemplateDecl *FnTmpl =
1004 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1005 Diags.Report(Active->PointOfInstantiation,
1006 diag::note_function_template_deduction_instantiation_here)
1007 << FnTmpl
1008 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1009 Active->TemplateArgs,
1010 Active->NumTemplateArgs)
1011 << Active->InstantiationRange;
1012 } else {
1013 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1014 isa<VarTemplateSpecializationDecl>(Active->Entity);
1015 bool IsTemplate = false;
1016 TemplateParameterList *Params;
1017 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1018 IsTemplate = true;
1019 Params = D->getTemplateParameters();
1020 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1021 Active->Entity)) {
1022 Params = D->getTemplateParameters();
1023 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1024 Active->Entity)) {
1025 Params = D->getTemplateParameters();
1026 } else {
1027 llvm_unreachable("unexpected template kind");
1028 }
1029
1030 Diags.Report(Active->PointOfInstantiation,
1031 diag::note_deduced_template_arg_substitution_here)
1032 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1033 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1034 Active->NumTemplateArgs)
1035 << Active->InstantiationRange;
1036 }
1037 break;
1038 }
1039
1041 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1042 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1043
1044 SmallString<128> TemplateArgsStr;
1045 llvm::raw_svector_ostream OS(TemplateArgsStr);
1047 printTemplateArgumentList(OS, Active->template_arguments(),
1049 Diags.Report(Active->PointOfInstantiation,
1050 diag::note_default_function_arg_instantiation_here)
1051 << OS.str()
1052 << Active->InstantiationRange;
1053 break;
1054 }
1055
1057 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1058 std::string Name;
1059 if (!Parm->getName().empty())
1060 Name = std::string(" '") + Parm->getName().str() + "'";
1061
1062 TemplateParameterList *TemplateParams = nullptr;
1063 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1064 TemplateParams = Template->getTemplateParameters();
1065 else
1066 TemplateParams =
1067 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1068 ->getTemplateParameters();
1069 Diags.Report(Active->PointOfInstantiation,
1070 diag::note_prior_template_arg_substitution)
1071 << isa<TemplateTemplateParmDecl>(Parm)
1072 << Name
1073 << getTemplateArgumentBindingsText(TemplateParams,
1074 Active->TemplateArgs,
1075 Active->NumTemplateArgs)
1076 << Active->InstantiationRange;
1077 break;
1078 }
1079
1081 TemplateParameterList *TemplateParams = nullptr;
1082 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1083 TemplateParams = Template->getTemplateParameters();
1084 else
1085 TemplateParams =
1086 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1087 ->getTemplateParameters();
1088
1089 Diags.Report(Active->PointOfInstantiation,
1090 diag::note_template_default_arg_checking)
1091 << getTemplateArgumentBindingsText(TemplateParams,
1092 Active->TemplateArgs,
1093 Active->NumTemplateArgs)
1094 << Active->InstantiationRange;
1095 break;
1096 }
1097
1099 Diags.Report(Active->PointOfInstantiation,
1100 diag::note_evaluating_exception_spec_here)
1101 << cast<FunctionDecl>(Active->Entity);
1102 break;
1103
1105 Diags.Report(Active->PointOfInstantiation,
1106 diag::note_template_exception_spec_instantiation_here)
1107 << cast<FunctionDecl>(Active->Entity)
1108 << Active->InstantiationRange;
1109 break;
1110
1112 Diags.Report(Active->PointOfInstantiation,
1113 diag::note_template_requirement_instantiation_here)
1114 << Active->InstantiationRange;
1115 break;
1117 Diags.Report(Active->PointOfInstantiation,
1118 diag::note_template_requirement_params_instantiation_here)
1119 << Active->InstantiationRange;
1120 break;
1121
1123 Diags.Report(Active->PointOfInstantiation,
1124 diag::note_nested_requirement_here)
1125 << Active->InstantiationRange;
1126 break;
1127
1129 Diags.Report(Active->PointOfInstantiation,
1130 diag::note_in_declaration_of_implicit_special_member)
1131 << cast<CXXRecordDecl>(Active->Entity)
1132 << llvm::to_underlying(Active->SpecialMember);
1133 break;
1134
1136 Diags.Report(Active->Entity->getLocation(),
1137 diag::note_in_declaration_of_implicit_equality_comparison);
1138 break;
1139
1141 // FIXME: For synthesized functions that are not defaulted,
1142 // produce a note.
1143 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1146 if (DFK.isSpecialMember()) {
1147 auto *MD = cast<CXXMethodDecl>(FD);
1148 Diags.Report(Active->PointOfInstantiation,
1149 diag::note_member_synthesized_at)
1150 << MD->isExplicitlyDefaulted()
1151 << llvm::to_underlying(DFK.asSpecialMember())
1152 << Context.getTagDeclType(MD->getParent());
1153 } else if (DFK.isComparison()) {
1154 QualType RecordType = FD->getParamDecl(0)
1155 ->getType()
1156 .getNonReferenceType()
1157 .getUnqualifiedType();
1158 Diags.Report(Active->PointOfInstantiation,
1159 diag::note_comparison_synthesized_at)
1160 << (int)DFK.asComparison() << RecordType;
1161 }
1162 break;
1163 }
1164
1166 Diags.Report(Active->Entity->getLocation(),
1167 diag::note_rewriting_operator_as_spaceship);
1168 break;
1169
1171 Diags.Report(Active->PointOfInstantiation,
1172 diag::note_in_binding_decl_init)
1173 << cast<BindingDecl>(Active->Entity);
1174 break;
1175
1177 Diags.Report(Active->PointOfInstantiation,
1178 diag::note_due_to_dllexported_class)
1179 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1180 break;
1181
1183 Diags.Report(Active->PointOfInstantiation,
1184 diag::note_building_builtin_dump_struct_call)
1186 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1187 break;
1188
1190 break;
1191
1193 Diags.Report(Active->PointOfInstantiation,
1194 diag::note_lambda_substitution_here);
1195 break;
1197 unsigned DiagID = 0;
1198 if (!Active->Entity) {
1199 Diags.Report(Active->PointOfInstantiation,
1200 diag::note_nested_requirement_here)
1201 << Active->InstantiationRange;
1202 break;
1203 }
1204 if (isa<ConceptDecl>(Active->Entity))
1205 DiagID = diag::note_concept_specialization_here;
1206 else if (isa<TemplateDecl>(Active->Entity))
1207 DiagID = diag::note_checking_constraints_for_template_id_here;
1208 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1209 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1210 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1211 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1212 else {
1213 assert(isa<FunctionDecl>(Active->Entity));
1214 DiagID = diag::note_checking_constraints_for_function_here;
1215 }
1216 SmallString<128> TemplateArgsStr;
1217 llvm::raw_svector_ostream OS(TemplateArgsStr);
1218 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1219 if (!isa<FunctionDecl>(Active->Entity)) {
1220 printTemplateArgumentList(OS, Active->template_arguments(),
1222 }
1223 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1224 << Active->InstantiationRange;
1225 break;
1226 }
1228 Diags.Report(Active->PointOfInstantiation,
1229 diag::note_constraint_substitution_here)
1230 << Active->InstantiationRange;
1231 break;
1233 Diags.Report(Active->PointOfInstantiation,
1234 diag::note_constraint_normalization_here)
1235 << cast<NamedDecl>(Active->Entity) << Active->InstantiationRange;
1236 break;
1238 Diags.Report(Active->PointOfInstantiation,
1239 diag::note_parameter_mapping_substitution_here)
1240 << Active->InstantiationRange;
1241 break;
1243 Diags.Report(Active->PointOfInstantiation,
1244 diag::note_building_deduction_guide_here);
1245 break;
1247 Diags.Report(Active->PointOfInstantiation,
1248 diag::note_template_type_alias_instantiation_here)
1249 << cast<TypeAliasTemplateDecl>(Active->Entity)
1250 << Active->InstantiationRange;
1251 break;
1253 Diags.Report(Active->PointOfInstantiation,
1254 diag::note_template_arg_template_params_mismatch);
1255 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1256 ParamLoc.isValid())
1257 Diags.Report(ParamLoc, diag::note_template_prev_declaration)
1258 << /*isTemplateTemplateParam=*/true << Active->InstantiationRange;
1259 break;
1260 }
1261 }
1262}
1263
1264std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1266 return std::optional<TemplateDeductionInfo *>(nullptr);
1267
1269 Active = CodeSynthesisContexts.rbegin(),
1270 ActiveEnd = CodeSynthesisContexts.rend();
1271 Active != ActiveEnd;
1272 ++Active)
1273 {
1274 switch (Active->Kind) {
1276 // An instantiation of an alias template may or may not be a SFINAE
1277 // context, depending on what else is on the stack.
1278 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1279 break;
1280 [[fallthrough]];
1288 // This is a template instantiation, so there is no SFINAE.
1289 return std::nullopt;
1291 // [temp.deduct]p9
1292 // A lambda-expression appearing in a function type or a template
1293 // parameter is not considered part of the immediate context for the
1294 // purposes of template argument deduction.
1295 // CWG2672: A lambda-expression body is never in the immediate context.
1296 return std::nullopt;
1297
1303 // A default template argument instantiation and substitution into
1304 // template parameters with arguments for prior parameters may or may
1305 // not be a SFINAE context; look further up the stack.
1306 break;
1307
1310 // We're either substituting explicitly-specified template arguments,
1311 // deduced template arguments. SFINAE applies unless we are in a lambda
1312 // body, see [temp.deduct]p9.
1316 // SFINAE always applies in a constraint expression or a requirement
1317 // in a requires expression.
1318 assert(Active->DeductionInfo && "Missing deduction info pointer");
1319 return Active->DeductionInfo;
1320
1328 // This happens in a context unrelated to template instantiation, so
1329 // there is no SFINAE.
1330 return std::nullopt;
1331
1333 // FIXME: This should not be treated as a SFINAE context, because
1334 // we will cache an incorrect exception specification. However, clang
1335 // bootstrap relies this! See PR31692.
1336 break;
1337
1339 break;
1340 }
1341
1342 // The inner context was transparent for SFINAE. If it occurred within a
1343 // non-instantiation SFINAE context, then SFINAE applies.
1344 if (Active->SavedInNonInstantiationSFINAEContext)
1345 return std::optional<TemplateDeductionInfo *>(nullptr);
1346 }
1347
1348 return std::nullopt;
1349}
1350
1351//===----------------------------------------------------------------------===/
1352// Template Instantiation for Types
1353//===----------------------------------------------------------------------===/
1354namespace {
1355 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1356 const MultiLevelTemplateArgumentList &TemplateArgs;
1358 DeclarationName Entity;
1359 // Whether to evaluate the C++20 constraints or simply substitute into them.
1360 bool EvaluateConstraints = true;
1361 // Whether Substitution was Incomplete, that is, we tried to substitute in
1362 // any user provided template arguments which were null.
1363 bool IsIncomplete = false;
1364 // Whether an incomplete substituion should be treated as an error.
1365 bool BailOutOnIncomplete;
1366
1367 public:
1368 typedef TreeTransform<TemplateInstantiator> inherited;
1369
1370 TemplateInstantiator(Sema &SemaRef,
1371 const MultiLevelTemplateArgumentList &TemplateArgs,
1373 bool BailOutOnIncomplete = false)
1374 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1375 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1376
1377 void setEvaluateConstraints(bool B) {
1378 EvaluateConstraints = B;
1379 }
1380 bool getEvaluateConstraints() {
1381 return EvaluateConstraints;
1382 }
1383
1384 /// Determine whether the given type \p T has already been
1385 /// transformed.
1386 ///
1387 /// For the purposes of template instantiation, a type has already been
1388 /// transformed if it is NULL or if it is not dependent.
1389 bool AlreadyTransformed(QualType T);
1390
1391 /// Returns the location of the entity being instantiated, if known.
1392 SourceLocation getBaseLocation() { return Loc; }
1393
1394 /// Returns the name of the entity being instantiated, if any.
1395 DeclarationName getBaseEntity() { return Entity; }
1396
1397 /// Returns whether any substitution so far was incomplete.
1398 bool getIsIncomplete() const { return IsIncomplete; }
1399
1400 /// Sets the "base" location and entity when that
1401 /// information is known based on another transformation.
1402 void setBase(SourceLocation Loc, DeclarationName Entity) {
1403 this->Loc = Loc;
1404 this->Entity = Entity;
1405 }
1406
1407 unsigned TransformTemplateDepth(unsigned Depth) {
1408 return TemplateArgs.getNewDepth(Depth);
1409 }
1410
1411 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1412 int Index = getSema().ArgumentPackSubstitutionIndex;
1413 if (Index == -1)
1414 return std::nullopt;
1415 return Pack.pack_size() - 1 - Index;
1416 }
1417
1418 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1419 SourceRange PatternRange,
1421 bool &ShouldExpand, bool &RetainExpansion,
1422 std::optional<unsigned> &NumExpansions) {
1423 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1424 PatternRange, Unexpanded,
1425 TemplateArgs,
1426 ShouldExpand,
1427 RetainExpansion,
1428 NumExpansions);
1429 }
1430
1431 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1433 }
1434
1435 TemplateArgument ForgetPartiallySubstitutedPack() {
1436 TemplateArgument Result;
1437 if (NamedDecl *PartialPack
1439 MultiLevelTemplateArgumentList &TemplateArgs
1440 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1441 unsigned Depth, Index;
1442 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1443 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1444 Result = TemplateArgs(Depth, Index);
1445 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1446 } else {
1447 IsIncomplete = true;
1448 if (BailOutOnIncomplete)
1449 return TemplateArgument();
1450 }
1451 }
1452
1453 return Result;
1454 }
1455
1456 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1457 if (Arg.isNull())
1458 return;
1459
1460 if (NamedDecl *PartialPack
1462 MultiLevelTemplateArgumentList &TemplateArgs
1463 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1464 unsigned Depth, Index;
1465 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1466 TemplateArgs.setArgument(Depth, Index, Arg);
1467 }
1468 }
1469
1470 /// Transform the given declaration by instantiating a reference to
1471 /// this declaration.
1472 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1473
1474 void transformAttrs(Decl *Old, Decl *New) {
1475 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1476 }
1477
1478 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1479 if (Old->isParameterPack() &&
1480 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1482 for (auto *New : NewDecls)
1484 Old, cast<VarDecl>(New));
1485 return;
1486 }
1487
1488 assert(NewDecls.size() == 1 &&
1489 "should only have multiple expansions for a pack");
1490 Decl *New = NewDecls.front();
1491
1492 // If we've instantiated the call operator of a lambda or the call
1493 // operator template of a generic lambda, update the "instantiation of"
1494 // information.
1495 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1496 if (NewMD && isLambdaCallOperator(NewMD)) {
1497 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1498 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1499 NewTD->setInstantiatedFromMemberTemplate(
1500 OldMD->getDescribedFunctionTemplate());
1501 else
1502 NewMD->setInstantiationOfMemberFunction(OldMD,
1504 }
1505
1507
1508 // We recreated a local declaration, but not by instantiating it. There
1509 // may be pending dependent diagnostics to produce.
1510 if (auto *DC = dyn_cast<DeclContext>(Old);
1511 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1512 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1513 }
1514
1515 /// Transform the definition of the given declaration by
1516 /// instantiating it.
1517 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1518
1519 /// Transform the first qualifier within a scope by instantiating the
1520 /// declaration.
1521 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1522
1523 bool TransformExceptionSpec(SourceLocation Loc,
1525 SmallVectorImpl<QualType> &Exceptions,
1526 bool &Changed);
1527
1528 /// Rebuild the exception declaration and register the declaration
1529 /// as an instantiated local.
1530 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1532 SourceLocation StartLoc,
1533 SourceLocation NameLoc,
1534 IdentifierInfo *Name);
1535
1536 /// Rebuild the Objective-C exception declaration and register the
1537 /// declaration as an instantiated local.
1538 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1539 TypeSourceInfo *TSInfo, QualType T);
1540
1541 /// Check for tag mismatches when instantiating an
1542 /// elaborated type.
1543 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1544 ElaboratedTypeKeyword Keyword,
1545 NestedNameSpecifierLoc QualifierLoc,
1546 QualType T);
1547
1549 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1550 SourceLocation NameLoc,
1551 QualType ObjectType = QualType(),
1552 NamedDecl *FirstQualifierInScope = nullptr,
1553 bool AllowInjectedClassName = false);
1554
1555 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1556 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1557 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1558 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1559 const Stmt *InstS,
1560 const NoInlineAttr *A);
1561 const AlwaysInlineAttr *
1562 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1563 const AlwaysInlineAttr *A);
1564 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1565 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1566 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1567 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1568
1569 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1571 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1573 ExprResult TransformSubstNonTypeTemplateParmExpr(
1575
1576 /// Rebuild a DeclRefExpr for a VarDecl reference.
1577 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1578
1579 /// Transform a reference to a function or init-capture parameter pack.
1580 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1581
1582 /// Transform a FunctionParmPackExpr which was built when we couldn't
1583 /// expand a function parameter pack reference which refers to an expanded
1584 /// pack.
1585 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1586
1587 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1589 // Call the base version; it will forward to our overridden version below.
1590 return inherited::TransformFunctionProtoType(TLB, TL);
1591 }
1592
1593 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1595 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1596 // Special case for transforming a deduction guide, we return a
1597 // transformed TemplateSpecializationType.
1598 if (Type.isNull() &&
1599 SemaRef.CodeSynthesisContexts.back().Kind ==
1601 // Return a TemplateSpecializationType for transforming a deduction
1602 // guide.
1603 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1604 auto Type =
1605 inherited::TransformType(ICT->getInjectedSpecializationType());
1606 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1607 return Type;
1608 }
1609 }
1610 return Type;
1611 }
1612 // Override the default version to handle a rewrite-template-arg-pack case
1613 // for building a deduction guide.
1614 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1615 TemplateArgumentLoc &Output,
1616 bool Uneval = false) {
1617 const TemplateArgument &Arg = Input.getArgument();
1618 std::vector<TemplateArgument> TArgs;
1619 switch (Arg.getKind()) {
1621 // Literally rewrite the template argument pack, instead of unpacking
1622 // it.
1623 for (auto &pack : Arg.getPackAsArray()) {
1625 pack, QualType(), SourceLocation{});
1626 TemplateArgumentLoc Output;
1627 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1628 return true; // fails
1629 TArgs.push_back(Output.getArgument());
1630 }
1631 Output = SemaRef.getTrivialTemplateArgumentLoc(
1632 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1634 return false;
1635 default:
1636 break;
1637 }
1638 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1639 }
1640
1641 template<typename Fn>
1642 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1644 CXXRecordDecl *ThisContext,
1645 Qualifiers ThisTypeQuals,
1646 Fn TransformExceptionSpec);
1647
1648 ParmVarDecl *
1649 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1650 std::optional<unsigned> NumExpansions,
1651 bool ExpectParameterPack);
1652
1653 using inherited::TransformTemplateTypeParmType;
1654 /// Transforms a template type parameter type by performing
1655 /// substitution of the corresponding template type argument.
1656 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1658 bool SuppressObjCLifetime);
1659
1660 QualType BuildSubstTemplateTypeParmType(
1661 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1662 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1663 TemplateArgument Arg, SourceLocation NameLoc);
1664
1665 /// Transforms an already-substituted template type parameter pack
1666 /// into either itself (if we aren't substituting into its pack expansion)
1667 /// or the appropriate substituted argument.
1668 using inherited::TransformSubstTemplateTypeParmPackType;
1669 QualType
1670 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1672 bool SuppressObjCLifetime);
1673
1674 QualType
1675 TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
1678 if (Type->getSubstitutionFlag() !=
1679 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace)
1680 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1681
1682 assert(Type->getPackIndex());
1683 TemplateArgument TA = TemplateArgs(
1684 Type->getReplacedParameter()->getDepth(), Type->getIndex());
1685 assert(*Type->getPackIndex() + 1 <= TA.pack_size());
1687 SemaRef, TA.pack_size() - 1 - *Type->getPackIndex());
1688
1689 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1690 }
1691
1693 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1694 if (auto TypeAlias =
1695 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1696 getSema());
1697 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1698 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1699 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1700 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1701 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1702 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1703 if (TA.isDependent())
1704 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1705 }
1706 return inherited::ComputeLambdaDependency(LSI);
1707 }
1708
1709 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1710 // Do not rebuild lambdas to avoid creating a new type.
1711 // Lambdas have already been processed inside their eval contexts.
1713 return E;
1714 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1715 /*InstantiatingLambdaOrBlock=*/true);
1717
1718 return inherited::TransformLambdaExpr(E);
1719 }
1720
1721 ExprResult TransformBlockExpr(BlockExpr *E) {
1722 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1723 /*InstantiatingLambdaOrBlock=*/true);
1724 return inherited::TransformBlockExpr(E);
1725 }
1726
1727 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1728 LambdaScopeInfo *LSI) {
1729 CXXMethodDecl *MD = LSI->CallOperator;
1730 for (ParmVarDecl *PVD : MD->parameters()) {
1731 assert(PVD && "null in a parameter list");
1732 if (!PVD->hasDefaultArg())
1733 continue;
1734 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1735 // FIXME: Obtain the source location for the '=' token.
1736 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1737 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1738 // If substitution fails, the default argument is set to a
1739 // RecoveryExpr that wraps the uninstantiated default argument so
1740 // that downstream diagnostics are omitted.
1741 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1742 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1743 UninstExpr->getType());
1744 if (ErrorResult.isUsable())
1745 PVD->setDefaultArg(ErrorResult.get());
1746 }
1747 }
1748 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1749 }
1750
1751 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1752 // Currently, we instantiate the body when instantiating the lambda
1753 // expression. However, `EvaluateConstraints` is disabled during the
1754 // instantiation of the lambda expression, causing the instantiation
1755 // failure of the return type requirement in the body. If p0588r1 is fully
1756 // implemented, the body will be lazily instantiated, and this problem
1757 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1758 // `true` to temporarily fix this issue.
1759 // FIXME: This temporary fix can be removed after fully implementing
1760 // p0588r1.
1761 llvm::SaveAndRestore _(EvaluateConstraints, true);
1762 return inherited::TransformLambdaBody(E, Body);
1763 }
1764
1765 ExprResult TransformSizeOfPackExpr(SizeOfPackExpr *E) {
1766 ExprResult Transformed = inherited::TransformSizeOfPackExpr(E);
1767 if (!Transformed.isUsable())
1768 return Transformed;
1769 auto *TransformedExpr = cast<SizeOfPackExpr>(Transformed.get());
1770 if (SemaRef.CodeSynthesisContexts.back().Kind ==
1772 TransformedExpr->getPack() == E->getPack()) {
1773 Decl *NewPack =
1774 TransformDecl(E->getPackLoc(), TransformedExpr->getPack());
1775 if (!NewPack)
1776 return ExprError();
1777 TransformedExpr->setPack(cast<NamedDecl>(NewPack));
1778 }
1779 return TransformedExpr;
1780 }
1781
1782 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1783 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1784 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1785 if (TransReq.isInvalid())
1786 return TransReq;
1787 assert(TransReq.get() != E &&
1788 "Do not change value of isSatisfied for the existing expression. "
1789 "Create a new expression instead.");
1790 if (E->getBody()->isDependentContext()) {
1791 Sema::SFINAETrap Trap(SemaRef);
1792 // We recreate the RequiresExpr body, but not by instantiating it.
1793 // Produce pending diagnostics for dependent access check.
1794 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1795 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1796 if (Trap.hasErrorOccurred())
1797 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1798 }
1799 return TransReq;
1800 }
1801
1802 bool TransformRequiresExprRequirements(
1805 bool SatisfactionDetermined = false;
1806 for (concepts::Requirement *Req : Reqs) {
1807 concepts::Requirement *TransReq = nullptr;
1808 if (!SatisfactionDetermined) {
1809 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1810 TransReq = TransformTypeRequirement(TypeReq);
1811 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1812 TransReq = TransformExprRequirement(ExprReq);
1813 else
1814 TransReq = TransformNestedRequirement(
1815 cast<concepts::NestedRequirement>(Req));
1816 if (!TransReq)
1817 return true;
1818 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1819 // [expr.prim.req]p6
1820 // [...] The substitution and semantic constraint checking
1821 // proceeds in lexical order and stops when a condition that
1822 // determines the result of the requires-expression is
1823 // encountered. [..]
1824 SatisfactionDetermined = true;
1825 } else
1826 TransReq = Req;
1827 Transformed.push_back(TransReq);
1828 }
1829 return false;
1830 }
1831
1832 TemplateParameterList *TransformTemplateParameterList(
1833 TemplateParameterList *OrigTPL) {
1834 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1835
1836 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1837 TemplateDeclInstantiator DeclInstantiator(getSema(),
1838 /* DeclContext *Owner */ Owner, TemplateArgs);
1839 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1840 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1841 }
1842
1844 TransformTypeRequirement(concepts::TypeRequirement *Req);
1846 TransformExprRequirement(concepts::ExprRequirement *Req);
1848 TransformNestedRequirement(concepts::NestedRequirement *Req);
1849 ExprResult TransformRequiresTypeParams(
1850 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1853 SmallVectorImpl<ParmVarDecl *> &TransParams,
1855
1856 private:
1858 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1859 const NonTypeTemplateParmDecl *parm,
1861 std::optional<unsigned> PackIndex);
1862 };
1863}
1864
1865bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1866 if (T.isNull())
1867 return true;
1868
1870 return false;
1871
1872 getSema().MarkDeclarationsReferencedInType(Loc, T);
1873 return true;
1874}
1875
1876static TemplateArgument
1878 assert(S.ArgumentPackSubstitutionIndex >= 0);
1879 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1881 if (Arg.isPackExpansion())
1882 Arg = Arg.getPackExpansionPattern();
1883 return Arg;
1884}
1885
1886Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1887 if (!D)
1888 return nullptr;
1889
1890 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1891 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1892 // If the corresponding template argument is NULL or non-existent, it's
1893 // because we are performing instantiation from explicitly-specified
1894 // template arguments in a function template, but there were some
1895 // arguments left unspecified.
1896 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1897 TTP->getPosition())) {
1898 IsIncomplete = true;
1899 return BailOutOnIncomplete ? nullptr : D;
1900 }
1901
1902 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1903
1904 if (TTP->isParameterPack()) {
1905 // We might not have an index for pack expansion when normalizing
1906 // constraint expressions. In that case, resort to instantiation scopes
1907 // for the transformed declarations.
1909 SemaRef.CodeSynthesisContexts.back().Kind ==
1911 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D),
1912 TemplateArgs);
1913 }
1914 assert(Arg.getKind() == TemplateArgument::Pack &&
1915 "Missing argument pack");
1916 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1917 }
1918
1919 TemplateName Template = Arg.getAsTemplate();
1920 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1921 "Wrong kind of template template argument");
1922 return Template.getAsTemplateDecl();
1923 }
1924
1925 // Fall through to find the instantiated declaration for this template
1926 // template parameter.
1927 }
1928
1929 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1930}
1931
1932Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1933 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1934 if (!Inst)
1935 return nullptr;
1936
1937 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1938 return Inst;
1939}
1940
1941bool TemplateInstantiator::TransformExceptionSpec(
1943 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1944 if (ESI.Type == EST_Uninstantiated) {
1945 ESI.instantiate();
1946 Changed = true;
1947 }
1948 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1949}
1950
1951NamedDecl *
1952TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1954 // If the first part of the nested-name-specifier was a template type
1955 // parameter, instantiate that type parameter down to a tag type.
1956 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1957 const TemplateTypeParmType *TTP
1958 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1959
1960 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1961 // FIXME: This needs testing w/ member access expressions.
1962 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1963
1964 if (TTP->isParameterPack()) {
1965 assert(Arg.getKind() == TemplateArgument::Pack &&
1966 "Missing argument pack");
1967
1968 if (getSema().ArgumentPackSubstitutionIndex == -1)
1969 return nullptr;
1970
1971 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1972 }
1973
1974 QualType T = Arg.getAsType();
1975 if (T.isNull())
1976 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1977
1978 if (const TagType *Tag = T->getAs<TagType>())
1979 return Tag->getDecl();
1980
1981 // The resulting type is not a tag; complain.
1982 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1983 return nullptr;
1984 }
1985 }
1986
1987 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1988}
1989
1990VarDecl *
1991TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1993 SourceLocation StartLoc,
1994 SourceLocation NameLoc,
1995 IdentifierInfo *Name) {
1996 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1997 StartLoc, NameLoc, Name);
1998 if (Var)
1999 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2000 return Var;
2001}
2002
2003VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
2004 TypeSourceInfo *TSInfo,
2005 QualType T) {
2006 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
2007 if (Var)
2008 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
2009 return Var;
2010}
2011
2013TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
2014 ElaboratedTypeKeyword Keyword,
2015 NestedNameSpecifierLoc QualifierLoc,
2016 QualType T) {
2017 if (const TagType *TT = T->getAs<TagType>()) {
2018 TagDecl* TD = TT->getDecl();
2019
2020 SourceLocation TagLocation = KeywordLoc;
2021
2023
2024 // TODO: should we even warn on struct/class mismatches for this? Seems
2025 // like it's likely to produce a lot of spurious errors.
2026 if (Id && Keyword != ElaboratedTypeKeyword::None &&
2029 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
2030 TagLocation, Id)) {
2031 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
2032 << Id
2034 TD->getKindName());
2035 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
2036 }
2037 }
2038 }
2039
2040 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
2041}
2042
2043TemplateName TemplateInstantiator::TransformTemplateName(
2044 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
2045 QualType ObjectType, NamedDecl *FirstQualifierInScope,
2046 bool AllowInjectedClassName) {
2048 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
2049 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2050 // If the corresponding template argument is NULL or non-existent, it's
2051 // because we are performing instantiation from explicitly-specified
2052 // template arguments in a function template, but there were some
2053 // arguments left unspecified.
2054 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2055 TTP->getPosition())) {
2056 IsIncomplete = true;
2057 return BailOutOnIncomplete ? TemplateName() : Name;
2058 }
2059
2060 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2061
2062 if (TemplateArgs.isRewrite()) {
2063 // We're rewriting the template parameter as a reference to another
2064 // template parameter.
2065 if (Arg.getKind() == TemplateArgument::Pack) {
2066 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2067 "unexpected pack arguments in template rewrite");
2068 Arg = Arg.pack_begin()->getPackExpansionPattern();
2069 }
2070 assert(Arg.getKind() == TemplateArgument::Template &&
2071 "unexpected nontype template argument kind in template rewrite");
2072 return Arg.getAsTemplate();
2073 }
2074
2075 auto [AssociatedDecl, Final] =
2076 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2077 std::optional<unsigned> PackIndex;
2078 if (TTP->isParameterPack()) {
2079 assert(Arg.getKind() == TemplateArgument::Pack &&
2080 "Missing argument pack");
2081
2082 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2083 // We have the template argument pack to substitute, but we're not
2084 // actually expanding the enclosing pack expansion yet. So, just
2085 // keep the entire argument pack.
2086 return getSema().Context.getSubstTemplateTemplateParmPack(
2087 Arg, AssociatedDecl, TTP->getIndex(), Final);
2088 }
2089
2090 PackIndex = getPackIndex(Arg);
2091 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2092 }
2093
2094 TemplateName Template = Arg.getAsTemplate();
2095 assert(!Template.isNull() && "Null template template argument");
2096
2097 if (Final)
2098 return Template;
2099 return getSema().Context.getSubstTemplateTemplateParm(
2100 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2101 }
2102 }
2103
2105 = Name.getAsSubstTemplateTemplateParmPack()) {
2106 if (getSema().ArgumentPackSubstitutionIndex == -1)
2107 return Name;
2108
2109 TemplateArgument Pack = SubstPack->getArgumentPack();
2110 TemplateName Template =
2112 if (SubstPack->getFinal())
2113 return Template;
2114 return getSema().Context.getSubstTemplateTemplateParm(
2115 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2116 getPackIndex(Pack));
2117 }
2118
2119 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2120 FirstQualifierInScope,
2121 AllowInjectedClassName);
2122}
2123
2125TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2126 if (!E->isTypeDependent())
2127 return E;
2128
2129 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2130}
2131
2133TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2135 // If the corresponding template argument is NULL or non-existent, it's
2136 // because we are performing instantiation from explicitly-specified
2137 // template arguments in a function template, but there were some
2138 // arguments left unspecified.
2139 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2140 NTTP->getPosition())) {
2141 IsIncomplete = true;
2142 return BailOutOnIncomplete ? ExprError() : E;
2143 }
2144
2145 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2146
2147 if (TemplateArgs.isRewrite()) {
2148 // We're rewriting the template parameter as a reference to another
2149 // template parameter.
2150 if (Arg.getKind() == TemplateArgument::Pack) {
2151 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2152 "unexpected pack arguments in template rewrite");
2153 Arg = Arg.pack_begin()->getPackExpansionPattern();
2154 }
2155 assert(Arg.getKind() == TemplateArgument::Expression &&
2156 "unexpected nontype template argument kind in template rewrite");
2157 // FIXME: This can lead to the same subexpression appearing multiple times
2158 // in a complete expression.
2159 return Arg.getAsExpr();
2160 }
2161
2162 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2163 std::optional<unsigned> PackIndex;
2164 if (NTTP->isParameterPack()) {
2165 assert(Arg.getKind() == TemplateArgument::Pack &&
2166 "Missing argument pack");
2167
2168 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2169 // We have an argument pack, but we can't select a particular argument
2170 // out of it yet. Therefore, we'll build an expression to hold on to that
2171 // argument pack.
2172 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2173 E->getLocation(),
2174 NTTP->getDeclName());
2175 if (TargetType.isNull())
2176 return ExprError();
2177
2178 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2179 if (TargetType->isRecordType())
2180 ExprType.addConst();
2181 // FIXME: Pass in Final.
2183 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2184 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2185 }
2186 PackIndex = getPackIndex(Arg);
2187 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2188 }
2189 // FIXME: Don't put subst node on Final replacement.
2190 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2191 Arg, PackIndex);
2192}
2193
2194const AnnotateAttr *
2195TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2197 for (Expr *Arg : AA->args()) {
2198 ExprResult Res = getDerived().TransformExpr(Arg);
2199 if (Res.isUsable())
2200 Args.push_back(Res.get());
2201 }
2202 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2203 Args.data(), Args.size(), AA->getRange());
2204}
2205
2206const CXXAssumeAttr *
2207TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2208 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2209 if (!Res.isUsable())
2210 return AA;
2211
2212 Res = getSema().ActOnFinishFullExpr(Res.get(),
2213 /*DiscardedValue=*/false);
2214 if (!Res.isUsable())
2215 return AA;
2216
2217 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2218 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2219 AA->getRange());
2220 if (!Res.isUsable())
2221 return AA;
2222 }
2223
2224 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2225 AA->getRange());
2226}
2227
2228const LoopHintAttr *
2229TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2230 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2231
2232 if (TransformedExpr == LH->getValue())
2233 return LH;
2234
2235 // Generate error if there is a problem with the value.
2236 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2237 LH->getSemanticSpelling() ==
2238 LoopHintAttr::Pragma_unroll))
2239 return LH;
2240
2241 LoopHintAttr::OptionType Option = LH->getOption();
2242 LoopHintAttr::LoopHintState State = LH->getState();
2243
2244 llvm::APSInt ValueAPS =
2245 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2246 // The values of 0 and 1 block any unrolling of the loop.
2247 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2248 Option = LoopHintAttr::Unroll;
2249 State = LoopHintAttr::Disable;
2250 }
2251
2252 // Create new LoopHintValueAttr with integral expression in place of the
2253 // non-type template parameter.
2254 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2255 TransformedExpr, *LH);
2256}
2257const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2258 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2259 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2260 return nullptr;
2261
2262 return A;
2263}
2264const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2265 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2266 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2267 return nullptr;
2268
2269 return A;
2270}
2271
2272const CodeAlignAttr *
2273TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2274 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2275 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2276}
2277
2278ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2279 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2281 std::optional<unsigned> PackIndex) {
2282 ExprResult result;
2283
2284 // Determine the substituted parameter type. We can usually infer this from
2285 // the template argument, but not always.
2286 auto SubstParamType = [&] {
2287 QualType T;
2288 if (parm->isExpandedParameterPack())
2290 else
2291 T = parm->getType();
2292 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2293 T = cast<PackExpansionType>(T)->getPattern();
2294 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2295 };
2296
2297 bool refParam = false;
2298
2299 // The template argument itself might be an expression, in which case we just
2300 // return that expression. This happens when substituting into an alias
2301 // template.
2302 if (arg.getKind() == TemplateArgument::Expression) {
2303 Expr *argExpr = arg.getAsExpr();
2304 result = argExpr;
2305 if (argExpr->isLValue()) {
2306 if (argExpr->getType()->isRecordType()) {
2307 // Check whether the parameter was actually a reference.
2308 QualType paramType = SubstParamType();
2309 if (paramType.isNull())
2310 return ExprError();
2311 refParam = paramType->isReferenceType();
2312 } else {
2313 refParam = true;
2314 }
2315 }
2316 } else if (arg.getKind() == TemplateArgument::Declaration ||
2317 arg.getKind() == TemplateArgument::NullPtr) {
2318 if (arg.getKind() == TemplateArgument::Declaration) {
2319 ValueDecl *VD = arg.getAsDecl();
2320
2321 // Find the instantiation of the template argument. This is
2322 // required for nested templates.
2323 VD = cast_or_null<ValueDecl>(
2324 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2325 if (!VD)
2326 return ExprError();
2327 }
2328
2329 QualType paramType = arg.getNonTypeTemplateArgumentType();
2330 assert(!paramType.isNull() && "type substitution failed for param type");
2331 assert(!paramType->isDependentType() && "param type still dependent");
2332 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2333 refParam = paramType->isReferenceType();
2334 } else {
2335 QualType paramType = arg.getNonTypeTemplateArgumentType();
2337 refParam = paramType->isReferenceType();
2338 assert(result.isInvalid() ||
2340 paramType.getNonReferenceType()));
2341 }
2342
2343 if (result.isInvalid())
2344 return ExprError();
2345
2346 Expr *resultExpr = result.get();
2347 // FIXME: Don't put subst node on final replacement.
2349 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2350 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2351}
2352
2354TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2356 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2357 // We aren't expanding the parameter pack, so just return ourselves.
2358 return E;
2359 }
2360
2361 TemplateArgument Pack = E->getArgumentPack();
2363 // FIXME: Don't put subst node on final replacement.
2364 return transformNonTypeTemplateParmRef(
2365 E->getAssociatedDecl(), E->getParameterPack(),
2366 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2367}
2368
2370TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2372 ExprResult SubstReplacement = E->getReplacement();
2373 if (!isa<ConstantExpr>(SubstReplacement.get()))
2374 SubstReplacement = TransformExpr(E->getReplacement());
2375 if (SubstReplacement.isInvalid())
2376 return true;
2377 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2378 if (SubstType.isNull())
2379 return true;
2380 // The type may have been previously dependent and not now, which means we
2381 // might have to implicit cast the argument to the new type, for example:
2382 // template<auto T, decltype(T) U>
2383 // concept C = sizeof(U) == 4;
2384 // void foo() requires C<2, 'a'> { }
2385 // When normalizing foo(), we first form the normalized constraints of C:
2386 // AtomicExpr(sizeof(U) == 4,
2387 // U=SubstNonTypeTemplateParmExpr(Param=U,
2388 // Expr=DeclRef(U),
2389 // Type=decltype(T)))
2390 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2391 // produce:
2392 // AtomicExpr(sizeof(U) == 4,
2393 // U=SubstNonTypeTemplateParmExpr(Param=U,
2394 // Expr=ImpCast(
2395 // decltype(2),
2396 // SubstNTTPE(Param=U, Expr='a',
2397 // Type=char)),
2398 // Type=decltype(2)))
2399 // The call to CheckTemplateArgument here produces the ImpCast.
2400 TemplateArgument SugaredConverted, CanonicalConverted;
2401 if (SemaRef
2402 .CheckTemplateArgument(E->getParameter(), SubstType,
2403 SubstReplacement.get(), SugaredConverted,
2404 CanonicalConverted, Sema::CTAK_Specified)
2405 .isInvalid())
2406 return true;
2407 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2408 E->getParameter(), E->getExprLoc(),
2409 SugaredConverted, E->getPackIndex());
2410}
2411
2412ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2414 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2415 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2416}
2417
2419TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2420 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2421 // We can expand this parameter pack now.
2422 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2423 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2424 if (!VD)
2425 return ExprError();
2426 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2427 }
2428
2429 QualType T = TransformType(E->getType());
2430 if (T.isNull())
2431 return ExprError();
2432
2433 // Transform each of the parameter expansions into the corresponding
2434 // parameters in the instantiation of the function decl.
2436 Vars.reserve(E->getNumExpansions());
2437 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2438 I != End; ++I) {
2439 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2440 if (!D)
2441 return ExprError();
2442 Vars.push_back(D);
2443 }
2444
2445 auto *PackExpr =
2446 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2447 E->getParameterPackLocation(), Vars);
2448 getSema().MarkFunctionParmPackReferenced(PackExpr);
2449 return PackExpr;
2450}
2451
2453TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2454 VarDecl *PD) {
2455 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2456 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2457 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2458 assert(Found && "no instantiation for parameter pack");
2459
2460 Decl *TransformedDecl;
2461 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2462 // If this is a reference to a function parameter pack which we can
2463 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2464 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2465 QualType T = TransformType(E->getType());
2466 if (T.isNull())
2467 return ExprError();
2468 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2469 E->getExprLoc(), *Pack);
2470 getSema().MarkFunctionParmPackReferenced(PackExpr);
2471 return PackExpr;
2472 }
2473
2474 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2475 } else {
2476 TransformedDecl = cast<Decl *>(*Found);
2477 }
2478
2479 // We have either an unexpanded pack or a specific expansion.
2480 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2481}
2482
2484TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2485 NamedDecl *D = E->getDecl();
2486
2487 // Handle references to non-type template parameters and non-type template
2488 // parameter packs.
2489 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2490 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2491 return TransformTemplateParmRefExpr(E, NTTP);
2492
2493 // We have a non-type template parameter that isn't fully substituted;
2494 // FindInstantiatedDecl will find it in the local instantiation scope.
2495 }
2496
2497 // Handle references to function parameter packs.
2498 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2499 if (PD->isParameterPack())
2500 return TransformFunctionParmPackRefExpr(E, PD);
2501
2502 return inherited::TransformDeclRefExpr(E);
2503}
2504
2505ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2507 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2508 getDescribedFunctionTemplate() &&
2509 "Default arg expressions are never formed in dependent cases.");
2511 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2512 E->getParam());
2513}
2514
2515template<typename Fn>
2516QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2518 CXXRecordDecl *ThisContext,
2519 Qualifiers ThisTypeQuals,
2520 Fn TransformExceptionSpec) {
2521 // If this is a lambda or block, the transformation MUST be done in the
2522 // CurrentInstantiationScope since it introduces a mapping of
2523 // the original to the newly created transformed parameters.
2524 //
2525 // In that case, TemplateInstantiator::TransformLambdaExpr will
2526 // have already pushed a scope for this prototype, so don't create
2527 // a second one.
2528 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2529 std::optional<LocalInstantiationScope> Scope;
2530 if (!Current || !Current->isLambdaOrBlock())
2531 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2532
2533 return inherited::TransformFunctionProtoType(
2534 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2535}
2536
2537ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2538 ParmVarDecl *OldParm, int indexAdjustment,
2539 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2540 auto NewParm = SemaRef.SubstParmVarDecl(
2541 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2542 ExpectParameterPack, EvaluateConstraints);
2543 if (NewParm && SemaRef.getLangOpts().OpenCL)
2545 return NewParm;
2546}
2547
2548QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2549 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2550 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2551 TemplateArgument Arg, SourceLocation NameLoc) {
2552 QualType Replacement = Arg.getAsType();
2553
2554 // If the template parameter had ObjC lifetime qualifiers,
2555 // then any such qualifiers on the replacement type are ignored.
2556 if (SuppressObjCLifetime) {
2557 Qualifiers RQs;
2558 RQs = Replacement.getQualifiers();
2559 RQs.removeObjCLifetime();
2560 Replacement =
2561 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2562 }
2563
2564 if (Final) {
2565 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2566 return Replacement;
2567 }
2568 // TODO: only do this uniquing once, at the start of instantiation.
2569 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2570 Replacement, AssociatedDecl, Index, PackIndex);
2573 NewTL.setNameLoc(NameLoc);
2574 return Result;
2575}
2576
2578TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2580 bool SuppressObjCLifetime) {
2581 const TemplateTypeParmType *T = TL.getTypePtr();
2582 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2583 // Replace the template type parameter with its corresponding
2584 // template argument.
2585
2586 // If the corresponding template argument is NULL or doesn't exist, it's
2587 // because we are performing instantiation from explicitly-specified
2588 // template arguments in a function template class, but there were some
2589 // arguments left unspecified.
2590 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2591 IsIncomplete = true;
2592 if (BailOutOnIncomplete)
2593 return QualType();
2594
2597 NewTL.setNameLoc(TL.getNameLoc());
2598 return TL.getType();
2599 }
2600
2601 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2602
2603 if (TemplateArgs.isRewrite()) {
2604 // We're rewriting the template parameter as a reference to another
2605 // template parameter.
2606 if (Arg.getKind() == TemplateArgument::Pack) {
2607 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2608 "unexpected pack arguments in template rewrite");
2609 Arg = Arg.pack_begin()->getPackExpansionPattern();
2610 }
2611 assert(Arg.getKind() == TemplateArgument::Type &&
2612 "unexpected nontype template argument kind in template rewrite");
2613 QualType NewT = Arg.getAsType();
2614 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2615 return NewT;
2616 }
2617
2618 auto [AssociatedDecl, Final] =
2619 TemplateArgs.getAssociatedDecl(T->getDepth());
2620 std::optional<unsigned> PackIndex;
2621 if (T->isParameterPack()) {
2622 assert(Arg.getKind() == TemplateArgument::Pack &&
2623 "Missing argument pack");
2624
2625 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2626 // We have the template argument pack, but we're not expanding the
2627 // enclosing pack expansion yet. Just save the template argument
2628 // pack for later substitution.
2629 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2630 AssociatedDecl, T->getIndex(), Final, Arg);
2633 NewTL.setNameLoc(TL.getNameLoc());
2634 return Result;
2635 }
2636
2637 // PackIndex starts from last element.
2638 PackIndex = getPackIndex(Arg);
2639 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2640 }
2641
2642 assert(Arg.getKind() == TemplateArgument::Type &&
2643 "Template argument kind mismatch");
2644
2645 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2646 AssociatedDecl, T->getIndex(),
2647 PackIndex, Arg, TL.getNameLoc());
2648 }
2649
2650 // The template type parameter comes from an inner template (e.g.,
2651 // the template parameter list of a member template inside the
2652 // template we are instantiating). Create a new template type
2653 // parameter with the template "level" reduced by one.
2654 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2655 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2656 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2657 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2658 QualType Result = getSema().Context.getTemplateTypeParmType(
2659 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2660 T->isParameterPack(), NewTTPDecl);
2662 NewTL.setNameLoc(TL.getNameLoc());
2663 return Result;
2664}
2665
2666QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2668 bool SuppressObjCLifetime) {
2670
2671 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2672
2673 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2674 // We aren't expanding the parameter pack, so just return ourselves.
2675 QualType Result = TL.getType();
2676 if (NewReplaced != T->getAssociatedDecl())
2677 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2678 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2681 NewTL.setNameLoc(TL.getNameLoc());
2682 return Result;
2683 }
2684
2685 TemplateArgument Pack = T->getArgumentPack();
2687 return BuildSubstTemplateTypeParmType(
2688 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2689 getPackIndex(Pack), Arg, TL.getNameLoc());
2690}
2691
2694 Sema::EntityPrinter Printer) {
2695 SmallString<128> Message;
2696 SourceLocation ErrorLoc;
2697 if (Info.hasSFINAEDiagnostic()) {
2700 Info.takeSFINAEDiagnostic(PDA);
2701 PDA.second.EmitToString(S.getDiagnostics(), Message);
2702 ErrorLoc = PDA.first;
2703 } else {
2704 ErrorLoc = Info.getLocation();
2705 }
2706 SmallString<128> Entity;
2707 llvm::raw_svector_ostream OS(Entity);
2708 Printer(OS);
2709 const ASTContext &C = S.Context;
2711 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2712}
2713
2716 SmallString<128> Entity;
2717 llvm::raw_svector_ostream OS(Entity);
2718 Printer(OS);
2719 const ASTContext &C = Context;
2721 /*SubstitutedEntity=*/C.backupStr(Entity),
2722 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2723}
2724
2725ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2726 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2729 SmallVectorImpl<ParmVarDecl *> &TransParams,
2731
2732 TemplateDeductionInfo Info(KWLoc);
2733 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2734 RE, Info,
2735 SourceRange{KWLoc, RBraceLoc});
2737
2738 unsigned ErrorIdx;
2739 if (getDerived().TransformFunctionTypeParams(
2740 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2741 &TransParams, PInfos, &ErrorIdx) ||
2742 Trap.hasErrorOccurred()) {
2744 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2745 // Add a 'failed' Requirement to contain the error that caused the failure
2746 // here.
2747 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2748 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2749 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2750 TransParams, RE->getRParenLoc(),
2751 TransReqs, RBraceLoc);
2752 }
2753
2754 return ExprResult{};
2755}
2756
2758TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2759 if (!Req->isDependent() && !AlwaysRebuild())
2760 return Req;
2761 if (Req->isSubstitutionFailure()) {
2762 if (AlwaysRebuild())
2763 return RebuildTypeRequirement(
2765 return Req;
2766 }
2767
2771 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2772 Req->getType()->getTypeLoc().getSourceRange());
2773 if (TypeInst.isInvalid())
2774 return nullptr;
2775 TypeSourceInfo *TransType = TransformType(Req->getType());
2776 if (!TransType || Trap.hasErrorOccurred())
2777 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2778 [&] (llvm::raw_ostream& OS) {
2779 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2780 }));
2781 return RebuildTypeRequirement(TransType);
2782}
2783
2785TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2786 if (!Req->isDependent() && !AlwaysRebuild())
2787 return Req;
2788
2790
2791 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2792 TransExpr;
2793 if (Req->isExprSubstitutionFailure())
2794 TransExpr = Req->getExprSubstitutionDiagnostic();
2795 else {
2796 Expr *E = Req->getExpr();
2798 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2799 E->getSourceRange());
2800 if (ExprInst.isInvalid())
2801 return nullptr;
2802 ExprResult TransExprRes = TransformExpr(E);
2803 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2804 TransExprRes.get()->hasPlaceholderType())
2805 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2806 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2807 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2809 });
2810 else
2811 TransExpr = TransExprRes.get();
2812 }
2813
2814 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2815 const auto &RetReq = Req->getReturnTypeRequirement();
2816 if (RetReq.isEmpty())
2817 TransRetReq.emplace();
2818 else if (RetReq.isSubstitutionFailure())
2819 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2820 else if (RetReq.isTypeConstraint()) {
2821 TemplateParameterList *OrigTPL =
2822 RetReq.getTypeConstraintTemplateParameterList();
2823 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2825 Req, Info, OrigTPL->getSourceRange());
2826 if (TPLInst.isInvalid())
2827 return nullptr;
2828 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2829 if (!TPL || Trap.hasErrorOccurred())
2830 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2831 [&] (llvm::raw_ostream& OS) {
2832 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2833 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2834 }));
2835 else {
2836 TPLInst.Clear();
2837 TransRetReq.emplace(TPL);
2838 }
2839 }
2840 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2841 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2842 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2843 std::move(*TransRetReq));
2844 return RebuildExprRequirement(
2845 cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),
2846 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2847}
2848
2850TemplateInstantiator::TransformNestedRequirement(
2852 if (!Req->isDependent() && !AlwaysRebuild())
2853 return Req;
2854 if (Req->hasInvalidConstraint()) {
2855 if (AlwaysRebuild())
2856 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2858 return Req;
2859 }
2861 Req->getConstraintExpr()->getBeginLoc(), Req,
2864 if (!getEvaluateConstraints()) {
2865 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2866 if (TransConstraint.isInvalid() || !TransConstraint.get())
2867 return nullptr;
2868 if (TransConstraint.get()->isInstantiationDependent())
2869 return new (SemaRef.Context)
2870 concepts::NestedRequirement(TransConstraint.get());
2871 ConstraintSatisfaction Satisfaction;
2873 SemaRef.Context, TransConstraint.get(), Satisfaction);
2874 }
2875
2876 ExprResult TransConstraint;
2877 ConstraintSatisfaction Satisfaction;
2879 {
2884 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2886 if (ConstrInst.isInvalid())
2887 return nullptr;
2890 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2891 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2892 !Result.empty())
2893 TransConstraint = Result[0];
2894 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2895 "by CheckConstraintSatisfaction.");
2896 }
2898 if (TransConstraint.isUsable() &&
2899 TransConstraint.get()->isInstantiationDependent())
2900 return new (C) concepts::NestedRequirement(TransConstraint.get());
2901 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2902 Satisfaction.HasSubstitutionFailure()) {
2903 SmallString<128> Entity;
2904 llvm::raw_svector_ostream OS(Entity);
2905 Req->getConstraintExpr()->printPretty(OS, nullptr,
2907 return new (C) concepts::NestedRequirement(
2908 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2909 }
2910 return new (C)
2911 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2912}
2913
2917 DeclarationName Entity,
2918 bool AllowDeducedTST) {
2919 assert(!CodeSynthesisContexts.empty() &&
2920 "Cannot perform an instantiation without some context on the "
2921 "instantiation stack");
2922
2923 if (!T->getType()->isInstantiationDependentType() &&
2924 !T->getType()->isVariablyModifiedType())
2925 return T;
2926
2927 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2928 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2929 : Instantiator.TransformType(T);
2930}
2931
2935 DeclarationName Entity) {
2936 assert(!CodeSynthesisContexts.empty() &&
2937 "Cannot perform an instantiation without some context on the "
2938 "instantiation stack");
2939
2940 if (TL.getType().isNull())
2941 return nullptr;
2942
2945 // FIXME: Make a copy of the TypeLoc data here, so that we can
2946 // return a new TypeSourceInfo. Inefficient!
2947 TypeLocBuilder TLB;
2948 TLB.pushFullCopy(TL);
2949 return TLB.getTypeSourceInfo(Context, TL.getType());
2950 }
2951
2952 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2953 TypeLocBuilder TLB;
2954 TLB.reserve(TL.getFullDataSize());
2955 QualType Result = Instantiator.TransformType(TLB, TL);
2956 if (Result.isNull())
2957 return nullptr;
2958
2959 return TLB.getTypeSourceInfo(Context, Result);
2960}
2961
2962/// Deprecated form of the above.
2964 const MultiLevelTemplateArgumentList &TemplateArgs,
2966 bool *IsIncompleteSubstitution) {
2967 assert(!CodeSynthesisContexts.empty() &&
2968 "Cannot perform an instantiation without some context on the "
2969 "instantiation stack");
2970
2971 // If T is not a dependent type or a variably-modified type, there
2972 // is nothing to do.
2974 return T;
2975
2976 TemplateInstantiator Instantiator(
2977 *this, TemplateArgs, Loc, Entity,
2978 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2979 QualType QT = Instantiator.TransformType(T);
2980 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2981 *IsIncompleteSubstitution = true;
2982 return QT;
2983}
2984
2986 if (T->getType()->isInstantiationDependentType() ||
2987 T->getType()->isVariablyModifiedType())
2988 return true;
2989
2990 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2991 if (!TL.getAs<FunctionProtoTypeLoc>())
2992 return false;
2993
2995 for (ParmVarDecl *P : FP.getParams()) {
2996 // This must be synthesized from a typedef.
2997 if (!P) continue;
2998
2999 // If there are any parameters, a new TypeSourceInfo that refers to the
3000 // instantiated parameters must be built.
3001 return true;
3002 }
3003
3004 return false;
3005}
3006
3010 DeclarationName Entity,
3011 CXXRecordDecl *ThisContext,
3012 Qualifiers ThisTypeQuals,
3013 bool EvaluateConstraints) {
3014 assert(!CodeSynthesisContexts.empty() &&
3015 "Cannot perform an instantiation without some context on the "
3016 "instantiation stack");
3017
3019 return T;
3020
3021 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3022 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3023
3024 TypeLocBuilder TLB;
3025
3026 TypeLoc TL = T->getTypeLoc();
3027 TLB.reserve(TL.getFullDataSize());
3028
3030
3031 if (FunctionProtoTypeLoc Proto =
3033 // Instantiate the type, other than its exception specification. The
3034 // exception specification is instantiated in InitFunctionInstantiation
3035 // once we've built the FunctionDecl.
3036 // FIXME: Set the exception specification to EST_Uninstantiated here,
3037 // instead of rebuilding the function type again later.
3038 Result = Instantiator.TransformFunctionProtoType(
3039 TLB, Proto, ThisContext, ThisTypeQuals,
3041 bool &Changed) { return false; });
3042 } else {
3043 Result = Instantiator.TransformType(TLB, TL);
3044 }
3045 // When there are errors resolving types, clang may use IntTy as a fallback,
3046 // breaking our assumption that function declarations have function types.
3047 if (Result.isNull() || !Result->isFunctionType())
3048 return nullptr;
3049
3050 return TLB.getTypeSourceInfo(Context, Result);
3051}
3052
3055 SmallVectorImpl<QualType> &ExceptionStorage,
3056 const MultiLevelTemplateArgumentList &Args) {
3057 bool Changed = false;
3058 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3059 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3060 Changed);
3061}
3062
3064 const MultiLevelTemplateArgumentList &Args) {
3067
3068 SmallVector<QualType, 4> ExceptionStorage;
3070 ESI, ExceptionStorage, Args))
3071 // On error, recover by dropping the exception specification.
3072 ESI.Type = EST_None;
3073
3074 UpdateExceptionSpec(New, ESI);
3075}
3076
3077namespace {
3078
3079 struct GetContainedInventedTypeParmVisitor :
3080 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3081 TemplateTypeParmDecl *> {
3082 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3083 TemplateTypeParmDecl *>::Visit;
3084
3086 if (T.isNull())
3087 return nullptr;
3088 return Visit(T.getTypePtr());
3089 }
3090 // The deduced type itself.
3091 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3092 const TemplateTypeParmType *T) {
3093 if (!T->getDecl() || !T->getDecl()->isImplicit())
3094 return nullptr;
3095 return T->getDecl();
3096 }
3097
3098 // Only these types can contain 'auto' types, and subsequently be replaced
3099 // by references to invented parameters.
3100
3101 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3102 return Visit(T->getNamedType());
3103 }
3104
3105 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3106 return Visit(T->getPointeeType());
3107 }
3108
3109 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3110 return Visit(T->getPointeeType());
3111 }
3112
3113 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3114 return Visit(T->getPointeeTypeAsWritten());
3115 }
3116
3117 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3118 return Visit(T->getPointeeType());
3119 }
3120
3121 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3122 return Visit(T->getElementType());
3123 }
3124
3125 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3127 return Visit(T->getElementType());
3128 }
3129
3130 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3131 return Visit(T->getElementType());
3132 }
3133
3134 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3135 return VisitFunctionType(T);
3136 }
3137
3138 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3139 return Visit(T->getReturnType());
3140 }
3141
3142 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3143 return Visit(T->getInnerType());
3144 }
3145
3146 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3147 return Visit(T->getModifiedType());
3148 }
3149
3150 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3151 return Visit(T->getUnderlyingType());
3152 }
3153
3154 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3155 return Visit(T->getOriginalType());
3156 }
3157
3158 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3159 return Visit(T->getPattern());
3160 }
3161 };
3162
3163} // namespace
3164
3165namespace {
3166
3167struct ExpandPackedTypeConstraints
3168 : TreeTransform<ExpandPackedTypeConstraints> {
3169
3171
3172 const MultiLevelTemplateArgumentList &TemplateArgs;
3173
3174 ExpandPackedTypeConstraints(
3175 Sema &SemaRef, const MultiLevelTemplateArgumentList &TemplateArgs)
3176 : inherited(SemaRef), TemplateArgs(TemplateArgs) {}
3177
3178 using inherited::TransformTemplateTypeParmType;
3179
3180 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
3181 TemplateTypeParmTypeLoc TL, bool) {
3182 const TemplateTypeParmType *T = TL.getTypePtr();
3183 if (!T->isParameterPack()) {
3186 NewTL.setNameLoc(TL.getNameLoc());
3187 return TL.getType();
3188 }
3189
3190 assert(SemaRef.ArgumentPackSubstitutionIndex != -1);
3191
3192 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
3193
3194 std::optional<unsigned> PackIndex;
3195 if (Arg.getKind() == TemplateArgument::Pack)
3196 PackIndex = Arg.pack_size() - 1 - SemaRef.ArgumentPackSubstitutionIndex;
3197
3199 TL.getType(), T->getDecl(), T->getIndex(), PackIndex,
3200 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace);
3203 NewTL.setNameLoc(TL.getNameLoc());
3204 return Result;
3205 }
3206
3207 QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
3210 if (T->getPackIndex()) {
3213 TypeLoc.setNameLoc(TL.getNameLoc());
3214 return TypeLoc.getType();
3215 }
3216 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
3217 }
3218
3219 bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3221 return inherited::TransformTemplateArguments(Args.begin(), Args.end(), Out);
3222 }
3223};
3224
3225} // namespace
3226
3228 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3229 const MultiLevelTemplateArgumentList &TemplateArgs,
3230 bool EvaluateConstraints) {
3231 const ASTTemplateArgumentListInfo *TemplArgInfo =
3233
3234 if (!EvaluateConstraints) {
3235 bool ShouldExpandExplicitTemplateArgs =
3236 TemplArgInfo && ArgumentPackSubstitutionIndex != -1 &&
3237 llvm::any_of(TemplArgInfo->arguments(), [](auto &Arg) {
3238 return Arg.getArgument().containsUnexpandedParameterPack();
3239 });
3240
3241 // We want to transform the packs into Subst* nodes for type constraints
3242 // inside a pack expansion. For example,
3243 //
3244 // template <class... Ts> void foo() {
3245 // bar([](C<Ts> auto value) {}...);
3246 // }
3247 //
3248 // As we expand Ts in the process of instantiating foo(), and retain
3249 // the original template depths of Ts until the constraint evaluation, we
3250 // would otherwise have no chance to expand Ts by the time of evaluating
3251 // C<auto, Ts>.
3252 //
3253 // So we form a Subst* node for Ts along with a proper substitution index
3254 // here, and substitute the node with a complete MLTAL later in evaluation.
3255 if (ShouldExpandExplicitTemplateArgs) {
3256 TemplateArgumentListInfo InstArgs;
3257 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3258 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3259 if (ExpandPackedTypeConstraints(*this, TemplateArgs)
3260 .SubstTemplateArguments(TemplArgInfo->arguments(), InstArgs))
3261 return true;
3262
3263 // The type of the original parameter.
3264 auto *ConstraintExpr = TC->getImmediatelyDeclaredConstraint();
3265 QualType ConstrainedType;
3266
3267 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr)) {
3268 assert(FE->getLHS());
3269 ConstraintExpr = FE->getLHS();
3270 }
3271 auto *CSE = cast<ConceptSpecializationExpr>(ConstraintExpr);
3272 assert(!CSE->getTemplateArguments().empty() &&
3273 "Empty template arguments?");
3274 ConstrainedType = CSE->getTemplateArguments()[0].getAsType();
3275 assert(!ConstrainedType.isNull() &&
3276 "Failed to extract the original ConstrainedType?");
3277
3278 return AttachTypeConstraint(
3280 TC->getNamedConcept(),
3281 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs,
3282 Inst, ConstrainedType,
3283 Inst->isParameterPack()
3284 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3285 ->getEllipsisLoc()
3286 : SourceLocation());
3287 }
3290 return false;
3291 }
3292
3293 TemplateArgumentListInfo InstArgs;
3294
3295 if (TemplArgInfo) {
3296 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3297 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3298 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3299 InstArgs))
3300 return true;
3301 }
3302 return AttachTypeConstraint(
3304 TC->getNamedConcept(),
3305 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3307 Inst->isParameterPack()
3308 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3309 ->getEllipsisLoc()
3310 : SourceLocation());
3311}
3312
3314 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3315 int indexAdjustment, std::optional<unsigned> NumExpansions,
3316 bool ExpectParameterPack, bool EvaluateConstraint) {
3317 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3318 TypeSourceInfo *NewDI = nullptr;
3319
3320 TypeLoc OldTL = OldDI->getTypeLoc();
3321 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3322
3323 // We have a function parameter pack. Substitute into the pattern of the
3324 // expansion.
3325 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3326 OldParm->getLocation(), OldParm->getDeclName());
3327 if (!NewDI)
3328 return nullptr;
3329
3330 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3331 // We still have unexpanded parameter packs, which means that
3332 // our function parameter is still a function parameter pack.
3333 // Therefore, make its type a pack expansion type.
3334 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3335 NumExpansions);
3336 } else if (ExpectParameterPack) {
3337 // We expected to get a parameter pack but didn't (because the type
3338 // itself is not a pack expansion type), so complain. This can occur when
3339 // the substitution goes through an alias template that "loses" the
3340 // pack expansion.
3341 Diag(OldParm->getLocation(),
3342 diag::err_function_parameter_pack_without_parameter_packs)
3343 << NewDI->getType();
3344 return nullptr;
3345 }
3346 } else {
3347 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3348 OldParm->getDeclName());
3349 }
3350
3351 if (!NewDI)
3352 return nullptr;
3353
3354 if (NewDI->getType()->isVoidType()) {
3355 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3356 return nullptr;
3357 }
3358
3359 // In abbreviated templates, TemplateTypeParmDecls with possible
3360 // TypeConstraints are created when the parameter list is originally parsed.
3361 // The TypeConstraints can therefore reference other functions parameters in
3362 // the abbreviated function template, which is why we must instantiate them
3363 // here, when the instantiated versions of those referenced parameters are in
3364 // scope.
3365 if (TemplateTypeParmDecl *TTP =
3366 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3367 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3368 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3369 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3370 // We will first get here when instantiating the abbreviated function
3371 // template's described function, but we might also get here later.
3372 // Make sure we do not instantiate the TypeConstraint more than once.
3373 if (Inst && !Inst->getTypeConstraint()) {
3374 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3375 return nullptr;
3376 }
3377 }
3378 }
3379
3381 OldParm->getInnerLocStart(),
3382 OldParm->getLocation(),
3383 OldParm->getIdentifier(),
3384 NewDI->getType(), NewDI,
3385 OldParm->getStorageClass());
3386 if (!NewParm)
3387 return nullptr;
3388
3389 // Mark the (new) default argument as uninstantiated (if any).
3390 if (OldParm->hasUninstantiatedDefaultArg()) {
3391 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3392 NewParm->setUninstantiatedDefaultArg(Arg);
3393 } else if (OldParm->hasUnparsedDefaultArg()) {
3394 NewParm->setUnparsedDefaultArg();
3395 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3396 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3397 // Default arguments cannot be substituted until the declaration context
3398 // for the associated function or lambda capture class is available.
3399 // This is necessary for cases like the following where construction of
3400 // the lambda capture class for the outer lambda is dependent on the
3401 // parameter types but where the default argument is dependent on the
3402 // outer lambda's declaration context.
3403 // template <typename T>
3404 // auto f() {
3405 // return [](T = []{ return T{}; }()) { return 0; };
3406 // }
3407 NewParm->setUninstantiatedDefaultArg(Arg);
3408 }
3409
3413
3414 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3415 // Add the new parameter to the instantiated parameter pack.
3417 } else {
3418 // Introduce an Old -> New mapping
3420 }
3421
3422 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3423 // can be anything, is this right ?
3424 NewParm->setDeclContext(CurContext);
3425
3426 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3427 OldParm->getFunctionScopeIndex() + indexAdjustment);
3428
3429 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3430
3431 return NewParm;
3432}
3433
3436 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3437 const MultiLevelTemplateArgumentList &TemplateArgs,
3438 SmallVectorImpl<QualType> &ParamTypes,
3440 ExtParameterInfoBuilder &ParamInfos) {
3441 assert(!CodeSynthesisContexts.empty() &&
3442 "Cannot perform an instantiation without some context on the "
3443 "instantiation stack");
3444
3445 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3446 DeclarationName());
3447 return Instantiator.TransformFunctionTypeParams(
3448 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3449}
3450
3453 ParmVarDecl *Param,
3454 const MultiLevelTemplateArgumentList &TemplateArgs,
3455 bool ForCallExpr) {
3456 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3457 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3458
3461
3462 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3463 if (Inst.isInvalid())
3464 return true;
3465 if (Inst.isAlreadyInstantiating()) {
3466 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3467 Param->setInvalidDecl();
3468 return true;
3469 }
3470
3472 {
3473 // C++ [dcl.fct.default]p5:
3474 // The names in the [default argument] expression are bound, and
3475 // the semantic constraints are checked, at the point where the
3476 // default argument expression appears.
3477 ContextRAII SavedContext(*this, FD);
3478 std::unique_ptr<LocalInstantiationScope> LIS;
3479
3480 if (ForCallExpr) {
3481 // When instantiating a default argument due to use in a call expression,
3482 // an instantiation scope that includes the parameters of the callee is
3483 // required to satisfy references from the default argument. For example:
3484 // template<typename T> void f(T a, int = decltype(a)());
3485 // void g() { f(0); }
3486 LIS = std::make_unique<LocalInstantiationScope>(*this);
3488 /*ForDefinition*/ false);
3489 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3490 return true;
3491 }
3492
3494 Result = SubstInitializer(PatternExpr, TemplateArgs,
3495 /*DirectInit*/ false);
3496 });
3497 }
3498 if (Result.isInvalid())
3499 return true;
3500
3501 if (ForCallExpr) {
3502 // Check the expression as an initializer for the parameter.
3503 InitializedEntity Entity
3506 Param->getLocation(),
3507 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3508 Expr *ResultE = Result.getAs<Expr>();
3509
3510 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3511 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3512 if (Result.isInvalid())
3513 return true;
3514
3515 Result =
3517 /*DiscardedValue*/ false);
3518 } else {
3519 // FIXME: Obtain the source location for the '=' token.
3520 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3521 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3522 }
3523 if (Result.isInvalid())
3524 return true;
3525
3526 // Remember the instantiated default argument.
3527 Param->setDefaultArg(Result.getAs<Expr>());
3528
3529 return false;
3530}
3531
3532bool
3534 CXXRecordDecl *Pattern,
3535 const MultiLevelTemplateArgumentList &TemplateArgs) {
3536 bool Invalid = false;
3537 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3538 for (const auto &Base : Pattern->bases()) {
3539 if (!Base.getType()->isDependentType()) {
3540 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3541 if (RD->isInvalidDecl())
3542 Instantiation->setInvalidDecl();
3543 }
3544 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3545 continue;
3546 }
3547
3548 SourceLocation EllipsisLoc;
3549 TypeSourceInfo *BaseTypeLoc;
3550 if (Base.isPackExpansion()) {
3551 // This is a pack expansion. See whether we should expand it now, or
3552 // wait until later.
3554 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3555 Unexpanded);
3556 bool ShouldExpand = false;
3557 bool RetainExpansion = false;
3558 std::optional<unsigned> NumExpansions;
3559 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3560 Base.getSourceRange(),
3561 Unexpanded,
3562 TemplateArgs, ShouldExpand,
3563 RetainExpansion,
3564 NumExpansions)) {
3565 Invalid = true;
3566 continue;
3567 }
3568
3569 // If we should expand this pack expansion now, do so.
3570 if (ShouldExpand) {
3571 for (unsigned I = 0; I != *NumExpansions; ++I) {
3572 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3573
3574 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3575 TemplateArgs,
3576 Base.getSourceRange().getBegin(),
3577 DeclarationName());
3578 if (!BaseTypeLoc) {
3579 Invalid = true;
3580 continue;
3581 }
3582
3583 if (CXXBaseSpecifier *InstantiatedBase
3584 = CheckBaseSpecifier(Instantiation,
3585 Base.getSourceRange(),
3586 Base.isVirtual(),
3587 Base.getAccessSpecifierAsWritten(),
3588 BaseTypeLoc,
3589 SourceLocation()))
3590 InstantiatedBases.push_back(InstantiatedBase);
3591 else
3592 Invalid = true;
3593 }
3594
3595 continue;
3596 }
3597
3598 // The resulting base specifier will (still) be a pack expansion.
3599 EllipsisLoc = Base.getEllipsisLoc();
3600 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3601 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3602 TemplateArgs,
3603 Base.getSourceRange().getBegin(),
3604 DeclarationName());
3605 } else {
3606 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3607 TemplateArgs,
3608 Base.getSourceRange().getBegin(),
3609 DeclarationName());
3610 }
3611
3612 if (!BaseTypeLoc) {
3613 Invalid = true;
3614 continue;
3615 }
3616
3617 if (CXXBaseSpecifier *InstantiatedBase
3618 = CheckBaseSpecifier(Instantiation,
3619 Base.getSourceRange(),
3620 Base.isVirtual(),
3621 Base.getAccessSpecifierAsWritten(),
3622 BaseTypeLoc,
3623 EllipsisLoc))
3624 InstantiatedBases.push_back(InstantiatedBase);
3625 else
3626 Invalid = true;
3627 }
3628
3629 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3630 Invalid = true;
3631
3632 return Invalid;
3633}
3634
3635// Defined via #include from SemaTemplateInstantiateDecl.cpp
3636namespace clang {
3637 namespace sema {
3639 const MultiLevelTemplateArgumentList &TemplateArgs);
3641 const Attr *At, ASTContext &C, Sema &S,
3642 const MultiLevelTemplateArgumentList &TemplateArgs);
3643 }
3644}
3645
3646bool
3648 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3649 const MultiLevelTemplateArgumentList &TemplateArgs,
3651 bool Complain) {
3652 CXXRecordDecl *PatternDef
3653 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3654 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3655 Instantiation->getInstantiatedFromMemberClass(),
3656 Pattern, PatternDef, TSK, Complain))
3657 return true;
3658
3659 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3660 llvm::TimeTraceMetadata M;
3661 llvm::raw_string_ostream OS(M.Detail);
3662 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3663 /*Qualified=*/true);
3664 if (llvm::isTimeTraceVerbose()) {
3665 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3666 M.File = SourceMgr.getFilename(Loc);
3668 }
3669 return M;
3670 });
3671
3672 Pattern = PatternDef;
3673
3674 // Record the point of instantiation.
3675 if (MemberSpecializationInfo *MSInfo
3676 = Instantiation->getMemberSpecializationInfo()) {
3677 MSInfo->setTemplateSpecializationKind(TSK);
3678 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3679 } else if (ClassTemplateSpecializationDecl *Spec
3680 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3681 Spec->setTemplateSpecializationKind(TSK);
3682 Spec->setPointOfInstantiation(PointOfInstantiation);
3683 }
3684
3685 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3686 if (Inst.isInvalid())
3687 return true;
3688 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3689 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3690 "instantiating class definition");
3691
3692 // Enter the scope of this instantiation. We don't use
3693 // PushDeclContext because we don't have a scope.
3694 ContextRAII SavedContext(*this, Instantiation);
3697
3698 // If this is an instantiation of a local class, merge this local
3699 // instantiation scope with the enclosing scope. Otherwise, every
3700 // instantiation of a class has its own local instantiation scope.
3701 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3702 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3703
3704 // Some class state isn't processed immediately but delayed till class
3705 // instantiation completes. We may not be ready to handle any delayed state
3706 // already on the stack as it might correspond to a different class, so save
3707 // it now and put it back later.
3708 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3709
3710 // Pull attributes from the pattern onto the instantiation.
3711 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3712
3713 // Start the definition of this instantiation.
3714 Instantiation->startDefinition();
3715
3716 // The instantiation is visible here, even if it was first declared in an
3717 // unimported module.
3718 Instantiation->setVisibleDespiteOwningModule();
3719
3720 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3721 Instantiation->setTagKind(Pattern->getTagKind());
3722
3723 // Do substitution on the base class specifiers.
3724 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3725 Instantiation->setInvalidDecl();
3726
3727 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3728 Instantiator.setEvaluateConstraints(false);
3729 SmallVector<Decl*, 4> Fields;
3730 // Delay instantiation of late parsed attributes.
3731 LateInstantiatedAttrVec LateAttrs;
3732 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3733
3734 bool MightHaveConstexprVirtualFunctions = false;
3735 for (auto *Member : Pattern->decls()) {
3736 // Don't instantiate members not belonging in this semantic context.
3737 // e.g. for:
3738 // @code
3739 // template <int i> class A {
3740 // class B *g;
3741 // };
3742 // @endcode
3743 // 'class B' has the template as lexical context but semantically it is
3744 // introduced in namespace scope.
3745 if (Member->getDeclContext() != Pattern)
3746 continue;
3747
3748 // BlockDecls can appear in a default-member-initializer. They must be the
3749 // child of a BlockExpr, so we only know how to instantiate them from there.
3750 // Similarly, lambda closure types are recreated when instantiating the
3751 // corresponding LambdaExpr.
3752 if (isa<BlockDecl>(Member) ||
3753 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3754 continue;
3755
3756 if (Member->isInvalidDecl()) {
3757 Instantiation->setInvalidDecl();
3758 continue;
3759 }
3760
3761 Decl *NewMember = Instantiator.Visit(Member);
3762 if (NewMember) {
3763 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3764 Fields.push_back(Field);
3765 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3766 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3767 // specialization causes the implicit instantiation of the definitions
3768 // of unscoped member enumerations.
3769 // Record a point of instantiation for this implicit instantiation.
3770 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3771 Enum->isCompleteDefinition()) {
3772 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3773 assert(MSInfo && "no spec info for member enum specialization");
3775 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3776 }
3777 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3778 if (SA->isFailed()) {
3779 // A static_assert failed. Bail out; instantiating this
3780 // class is probably not meaningful.
3781 Instantiation->setInvalidDecl();
3782 break;
3783 }
3784 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3785 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3786 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3787 MightHaveConstexprVirtualFunctions = true;
3788 }
3789
3790 if (NewMember->isInvalidDecl())
3791 Instantiation->setInvalidDecl();
3792 } else {
3793 // FIXME: Eventually, a NULL return will mean that one of the
3794 // instantiations was a semantic disaster, and we'll want to mark the
3795 // declaration invalid.
3796 // For now, we expect to skip some members that we can't yet handle.
3797 }
3798 }
3799
3800 // Finish checking fields.
3801 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3803 CheckCompletedCXXClass(nullptr, Instantiation);
3804
3805 // Default arguments are parsed, if not instantiated. We can go instantiate
3806 // default arg exprs for default constructors if necessary now. Unless we're
3807 // parsing a class, in which case wait until that's finished.
3808 if (ParsingClassDepth == 0)
3810
3811 // Instantiate late parsed attributes, and attach them to their decls.
3812 // See Sema::InstantiateAttrs
3813 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3814 E = LateAttrs.end(); I != E; ++I) {
3815 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3816 CurrentInstantiationScope = I->Scope;
3817
3818 // Allow 'this' within late-parsed attributes.
3819 auto *ND = cast<NamedDecl>(I->NewDecl);
3820 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3821 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3822 ND->isCXXInstanceMember());
3823
3824 Attr *NewAttr =
3825 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3826 if (NewAttr)
3827 I->NewDecl->addAttr(NewAttr);
3829 Instantiator.getStartingScope());
3830 }
3831 Instantiator.disableLateAttributeInstantiation();
3832 LateAttrs.clear();
3833
3835
3836 // FIXME: We should do something similar for explicit instantiations so they
3837 // end up in the right module.
3838 if (TSK == TSK_ImplicitInstantiation) {
3839 Instantiation->setLocation(Pattern->getLocation());
3840 Instantiation->setLocStart(Pattern->getInnerLocStart());
3841 Instantiation->setBraceRange(Pattern->getBraceRange());
3842 }
3843
3844 if (!Instantiation->isInvalidDecl()) {
3845 // Perform any dependent diagnostics from the pattern.
3846 if (Pattern->isDependentContext())
3847 PerformDependentDiagnostics(Pattern, TemplateArgs);
3848
3849 // Instantiate any out-of-line class template partial
3850 // specializations now.
3852 P = Instantiator.delayed_partial_spec_begin(),
3853 PEnd = Instantiator.delayed_partial_spec_end();
3854 P != PEnd; ++P) {
3856 P->first, P->second)) {
3857 Instantiation->setInvalidDecl();
3858 break;
3859 }
3860 }
3861
3862 // Instantiate any out-of-line variable template partial
3863 // specializations now.
3865 P = Instantiator.delayed_var_partial_spec_begin(),
3866 PEnd = Instantiator.delayed_var_partial_spec_end();
3867 P != PEnd; ++P) {
3869 P->first, P->second)) {
3870 Instantiation->setInvalidDecl();
3871 break;
3872 }
3873 }
3874 }
3875
3876 // Exit the scope of this instantiation.
3877 SavedContext.pop();
3878
3879 if (!Instantiation->isInvalidDecl()) {
3880 // Always emit the vtable for an explicit instantiation definition
3881 // of a polymorphic class template specialization. Otherwise, eagerly
3882 // instantiate only constexpr virtual functions in preparation for their use
3883 // in constant evaluation.
3885 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3886 else if (MightHaveConstexprVirtualFunctions)
3887 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3888 /*ConstexprOnly*/ true);
3889 }
3890
3891 Consumer.HandleTagDeclDefinition(Instantiation);
3892
3893 return Instantiation->isInvalidDecl();
3894}
3895
3896bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3897 EnumDecl *Instantiation, EnumDecl *Pattern,
3898 const MultiLevelTemplateArgumentList &TemplateArgs,
3900 EnumDecl *PatternDef = Pattern->getDefinition();
3901 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3902 Instantiation->getInstantiatedFromMemberEnum(),
3903 Pattern, PatternDef, TSK,/*Complain*/true))
3904 return true;
3905 Pattern = PatternDef;
3906
3907 // Record the point of instantiation.
3908 if (MemberSpecializationInfo *MSInfo
3909 = Instantiation->getMemberSpecializationInfo()) {
3910 MSInfo->setTemplateSpecializationKind(TSK);
3911 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3912 }
3913
3914 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3915 if (Inst.isInvalid())
3916 return true;
3917 if (Inst.isAlreadyInstantiating())
3918 return false;
3919 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3920 "instantiating enum definition");
3921
3922 // The instantiation is visible here, even if it was first declared in an
3923 // unimported module.
3924 Instantiation->setVisibleDespiteOwningModule();
3925
3926 // Enter the scope of this instantiation. We don't use
3927 // PushDeclContext because we don't have a scope.
3928 ContextRAII SavedContext(*this, Instantiation);
3931
3932 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3933
3934 // Pull attributes from the pattern onto the instantiation.
3935 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3936
3937 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3938 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3939
3940 // Exit the scope of this instantiation.
3941 SavedContext.pop();
3942
3943 return Instantiation->isInvalidDecl();
3944}
3945
3947 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3948 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3949 // If there is no initializer, we don't need to do anything.
3950 if (!Pattern->hasInClassInitializer())
3951 return false;
3952
3953 assert(Instantiation->getInClassInitStyle() ==
3954 Pattern->getInClassInitStyle() &&
3955 "pattern and instantiation disagree about init style");
3956
3957 // Error out if we haven't parsed the initializer of the pattern yet because
3958 // we are waiting for the closing brace of the outer class.
3959 Expr *OldInit = Pattern->getInClassInitializer();
3960 if (!OldInit) {
3961 RecordDecl *PatternRD = Pattern->getParent();
3962 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3963 Diag(PointOfInstantiation,
3964 diag::err_default_member_initializer_not_yet_parsed)
3965 << OutermostClass << Pattern;
3966 Diag(Pattern->getEndLoc(),
3967 diag::note_default_member_initializer_not_yet_parsed);
3968 Instantiation->setInvalidDecl();
3969 return true;
3970 }
3971
3972 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3973 if (Inst.isInvalid())
3974 return true;
3975 if (Inst.isAlreadyInstantiating()) {
3976 // Error out if we hit an instantiation cycle for this initializer.
3977 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3978 << Instantiation;
3979 return true;
3980 }
3981 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3982 "instantiating default member init");
3983
3984 // Enter the scope of this instantiation. We don't use PushDeclContext because
3985 // we don't have a scope.
3986 ContextRAII SavedContext(*this, Instantiation->getParent());
3989 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3990 PointOfInstantiation, Instantiation, CurContext};
3991
3992 LocalInstantiationScope Scope(*this, true);
3993
3994 // Instantiate the initializer.
3996 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3997
3998 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3999 /*CXXDirectInit=*/false);
4000 Expr *Init = NewInit.get();
4001 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
4003 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
4004
4005 if (auto *L = getASTMutationListener())
4006 L->DefaultMemberInitializerInstantiated(Instantiation);
4007
4008 // Return true if the in-class initializer is still missing.
4009 return !Instantiation->getInClassInitializer();
4010}
4011
4012namespace {
4013 /// A partial specialization whose template arguments have matched
4014 /// a given template-id.
4015 struct PartialSpecMatchResult {
4018 };
4019}
4020
4023 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4025 return true;
4026
4028 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4029 CTD->getPartialSpecializations(PartialSpecs);
4030 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4031 // C++ [temp.spec.partial.member]p2:
4032 // If the primary member template is explicitly specialized for a given
4033 // (implicit) specialization of the enclosing class template, the partial
4034 // specializations of the member template are ignored for this
4035 // specialization of the enclosing class template. If a partial
4036 // specialization of the member template is explicitly specialized for a
4037 // given (implicit) specialization of the enclosing class template, the
4038 // primary member template and its other partial specializations are still
4039 // considered for this specialization of the enclosing class template.
4041 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
4042 continue;
4043
4045 if (DeduceTemplateArguments(CTPSD,
4046 ClassTemplateSpec->getTemplateArgs().asArray(),
4048 return true;
4049 }
4050
4051 return false;
4052}
4053
4054/// Get the instantiation pattern to use to instantiate the definition of a
4055/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4056/// template or of a partial specialization).
4058 Sema &S, SourceLocation PointOfInstantiation,
4059 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4061 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4062 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4063 if (Inst.isInvalid())
4064 return {/*Invalid=*/true};
4065 if (Inst.isAlreadyInstantiating())
4066 return {/*Invalid=*/false};
4067
4068 llvm::PointerUnion<ClassTemplateDecl *,
4070 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4071 if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4072 // Find best matching specialization.
4073 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4074
4075 // C++ [temp.class.spec.match]p1:
4076 // When a class template is used in a context that requires an
4077 // instantiation of the class, it is necessary to determine
4078 // whether the instantiation is to be generated using the primary
4079 // template or one of the partial specializations. This is done by
4080 // matching the template arguments of the class template
4081 // specialization with the template argument lists of the partial
4082 // specializations.
4083 typedef PartialSpecMatchResult MatchResult;
4084 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4086 Template->getPartialSpecializations(PartialSpecs);
4087 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4088 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4089 // C++ [temp.spec.partial.member]p2:
4090 // If the primary member template is explicitly specialized for a given
4091 // (implicit) specialization of the enclosing class template, the
4092 // partial specializations of the member template are ignored for this
4093 // specialization of the enclosing class template. If a partial
4094 // specialization of the member template is explicitly specialized for a
4095 // given (implicit) specialization of the enclosing class template, the
4096 // primary member template and its other partial specializations are
4097 // still considered for this specialization of the enclosing class
4098 // template.
4099 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4100 !Partial->getMostRecentDecl()->isMemberSpecialization())
4101 continue;
4102
4103 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4105 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4107 // Store the failed-deduction information for use in diagnostics, later.
4108 // TODO: Actually use the failed-deduction info?
4109 FailedCandidates.addCandidate().set(
4110 DeclAccessPair::make(Template, AS_public), Partial,
4112 (void)Result;
4113 } else {
4114 auto &List =
4115 Info.hasMatchedPackOnParmToNonPackOnArg() ? ExtraMatched : Matched;
4116 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4117 }
4118 }
4119 if (Matched.empty() && PrimaryHasMatchedPackOnParmToNonPackOnArg)
4120 Matched = std::move(ExtraMatched);
4121
4122 // If we're dealing with a member template where the template parameters
4123 // have been instantiated, this provides the original template parameters
4124 // from which the member template's parameters were instantiated.
4125
4126 if (Matched.size() >= 1) {
4127 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4128 if (Matched.size() == 1) {
4129 // -- If exactly one matching specialization is found, the
4130 // instantiation is generated from that specialization.
4131 // We don't need to do anything for this.
4132 } else {
4133 // -- If more than one matching specialization is found, the
4134 // partial order rules (14.5.4.2) are used to determine
4135 // whether one of the specializations is more specialized
4136 // than the others. If none of the specializations is more
4137 // specialized than all of the other matching
4138 // specializations, then the use of the class template is
4139 // ambiguous and the program is ill-formed.
4141 PEnd = Matched.end();
4142 P != PEnd; ++P) {
4144 P->Partial, Best->Partial, PointOfInstantiation) ==
4145 P->Partial)
4146 Best = P;
4147 }
4148
4149 // Determine if the best partial specialization is more specialized than
4150 // the others.
4151 bool Ambiguous = false;
4152 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4153 PEnd = Matched.end();
4154 P != PEnd; ++P) {
4156 P->Partial, Best->Partial,
4157 PointOfInstantiation) != Best->Partial) {
4158 Ambiguous = true;
4159 break;
4160 }
4161 }
4162
4163 if (Ambiguous) {
4164 // Partial ordering did not produce a clear winner. Complain.
4165 Inst.Clear();
4166 ClassTemplateSpec->setInvalidDecl();
4167 S.Diag(PointOfInstantiation,
4168 diag::err_partial_spec_ordering_ambiguous)
4169 << ClassTemplateSpec;
4170
4171 // Print the matching partial specializations.
4172 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4173 PEnd = Matched.end();
4174 P != PEnd; ++P)
4175 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4177 P->Partial->getTemplateParameters(), *P->Args);
4178
4179 return {/*Invalid=*/true};
4180 }
4181 }
4182
4183 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4184 } else {
4185 // -- If no matches are found, the instantiation is generated
4186 // from the primary template.
4187 }
4188 }
4189
4190 CXXRecordDecl *Pattern = nullptr;
4191 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4192 if (auto *PartialSpec =
4193 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4194 // Instantiate using the best class template partial specialization.
4195 while (PartialSpec->getInstantiatedFromMember()) {
4196 // If we've found an explicit specialization of this class template,
4197 // stop here and use that as the pattern.
4198 if (PartialSpec->isMemberSpecialization())
4199 break;
4200
4201 PartialSpec = PartialSpec->getInstantiatedFromMember();
4202 }
4203 Pattern = PartialSpec;
4204 } else {
4205 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4206 while (Template->getInstantiatedFromMemberTemplate()) {
4207 // If we've found an explicit specialization of this class template,
4208 // stop here and use that as the pattern.
4209 if (Template->isMemberSpecialization())
4210 break;
4211
4212 Template = Template->getInstantiatedFromMemberTemplate();
4213 }
4214 Pattern = Template->getTemplatedDecl();
4215 }
4216
4217 return Pattern;
4218}
4219
4221 SourceLocation PointOfInstantiation,
4222 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4223 TemplateSpecializationKind TSK, bool Complain,
4224 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4225 // Perform the actual instantiation on the canonical declaration.
4226 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4227 ClassTemplateSpec->getCanonicalDecl());
4228 if (ClassTemplateSpec->isInvalidDecl())
4229 return true;
4230
4233 *this, PointOfInstantiation, ClassTemplateSpec, TSK,
4234 PrimaryHasMatchedPackOnParmToNonPackOnArg);
4235 if (!Pattern.isUsable())
4236 return Pattern.isInvalid();
4237
4238 return InstantiateClass(
4239 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4240 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4241}
4242
4243void
4245 CXXRecordDecl *Instantiation,
4246 const MultiLevelTemplateArgumentList &TemplateArgs,
4248 // FIXME: We need to notify the ASTMutationListener that we did all of these
4249 // things, in case we have an explicit instantiation definition in a PCM, a
4250 // module, or preamble, and the declaration is in an imported AST.
4251 assert(
4254 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4255 "Unexpected template specialization kind!");
4256 for (auto *D : Instantiation->decls()) {
4257 bool SuppressNew = false;
4258 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4259 if (FunctionDecl *Pattern =
4260 Function->getInstantiatedFromMemberFunction()) {
4261
4262 if (Function->isIneligibleOrNotSelected())
4263 continue;
4264
4265 if (Function->getTrailingRequiresClause()) {
4266 ConstraintSatisfaction Satisfaction;
4267 if (CheckFunctionConstraints(Function, Satisfaction) ||
4268 !Satisfaction.IsSatisfied) {
4269 continue;
4270 }
4271 }
4272
4273 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4274 continue;
4275
4277 Function->getTemplateSpecializationKind();
4278 if (PrevTSK == TSK_ExplicitSpecialization)
4279 continue;
4280
4282 PointOfInstantiation, TSK, Function, PrevTSK,
4283 Function->getPointOfInstantiation(), SuppressNew) ||
4284 SuppressNew)
4285 continue;
4286
4287 // C++11 [temp.explicit]p8:
4288 // An explicit instantiation definition that names a class template
4289 // specialization explicitly instantiates the class template
4290 // specialization and is only an explicit instantiation definition
4291 // of members whose definition is visible at the point of
4292 // instantiation.
4293 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4294 continue;
4295
4296 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4297
4298 if (Function->isDefined()) {
4299 // Let the ASTConsumer know that this function has been explicitly
4300 // instantiated now, and its linkage might have changed.
4302 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4303 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4304 } else if (TSK == TSK_ImplicitInstantiation) {
4306 std::make_pair(Function, PointOfInstantiation));
4307 }
4308 }
4309 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4310 if (isa<VarTemplateSpecializationDecl>(Var))
4311 continue;
4312
4313 if (Var->isStaticDataMember()) {
4314 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4315 continue;
4316
4318 assert(MSInfo && "No member specialization information?");
4319 if (MSInfo->getTemplateSpecializationKind()
4321 continue;
4322
4323 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4324 Var,
4326 MSInfo->getPointOfInstantiation(),
4327 SuppressNew) ||
4328 SuppressNew)
4329 continue;
4330
4332 // C++0x [temp.explicit]p8:
4333 // An explicit instantiation definition that names a class template
4334 // specialization explicitly instantiates the class template
4335 // specialization and is only an explicit instantiation definition
4336 // of members whose definition is visible at the point of
4337 // instantiation.
4339 continue;
4340
4341 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4342 InstantiateVariableDefinition(PointOfInstantiation, Var);
4343 } else {
4344 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4345 }
4346 }
4347 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4348 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4349 continue;
4350
4351 // Always skip the injected-class-name, along with any
4352 // redeclarations of nested classes, since both would cause us
4353 // to try to instantiate the members of a class twice.
4354 // Skip closure types; they'll get instantiated when we instantiate
4355 // the corresponding lambda-expression.
4356 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4357 Record->isLambda())
4358 continue;
4359
4360 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4361 assert(MSInfo && "No member specialization information?");
4362
4363 if (MSInfo->getTemplateSpecializationKind()
4365 continue;
4366
4367 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4369 // On Windows, explicit instantiation decl of the outer class doesn't
4370 // affect the inner class. Typically extern template declarations are
4371 // used in combination with dll import/export annotations, but those
4372 // are not propagated from the outer class templates to inner classes.
4373 // Therefore, do not instantiate inner classes on this platform, so
4374 // that users don't end up with undefined symbols during linking.
4375 continue;
4376 }
4377
4378 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4379 Record,
4381 MSInfo->getPointOfInstantiation(),
4382 SuppressNew) ||
4383 SuppressNew)
4384 continue;
4385
4387 assert(Pattern && "Missing instantiated-from-template information");
4388
4389 if (!Record->getDefinition()) {
4390 if (!Pattern->getDefinition()) {
4391 // C++0x [temp.explicit]p8:
4392 // An explicit instantiation definition that names a class template
4393 // specialization explicitly instantiates the class template
4394 // specialization and is only an explicit instantiation definition
4395 // of members whose definition is visible at the point of
4396 // instantiation.
4398 MSInfo->setTemplateSpecializationKind(TSK);
4399 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4400 }
4401
4402 continue;
4403 }
4404
4405 InstantiateClass(PointOfInstantiation, Record, Pattern,
4406 TemplateArgs,
4407 TSK);
4408 } else {
4410 Record->getTemplateSpecializationKind() ==
4412 Record->setTemplateSpecializationKind(TSK);
4413 MarkVTableUsed(PointOfInstantiation, Record, true);
4414 }
4415 }
4416
4417 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4418 if (Pattern)
4419 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4420 TSK);
4421 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4422 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4423 assert(MSInfo && "No member specialization information?");
4424
4425 if (MSInfo->getTemplateSpecializationKind()
4427 continue;
4428
4430 PointOfInstantiation, TSK, Enum,
4432 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4433 SuppressNew)
4434 continue;
4435
4436 if (Enum->getDefinition())
4437 continue;
4438
4439 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4440 assert(Pattern && "Missing instantiated-from-template information");
4441
4443 if (!Pattern->getDefinition())
4444 continue;
4445
4446 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4447 } else {
4448 MSInfo->setTemplateSpecializationKind(TSK);
4449 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4450 }
4451 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4452 // No need to instantiate in-class initializers during explicit
4453 // instantiation.
4454 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4455 CXXRecordDecl *ClassPattern =
4456 Instantiation->getTemplateInstantiationPattern();
4458 ClassPattern->lookup(Field->getDeclName());
4459 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4460 assert(Pattern);
4461 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4462 TemplateArgs);
4463 }
4464 }
4465 }
4466}
4467
4468void
4470 SourceLocation PointOfInstantiation,
4471 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4473 // C++0x [temp.explicit]p7:
4474 // An explicit instantiation that names a class template
4475 // specialization is an explicit instantion of the same kind
4476 // (declaration or definition) of each of its members (not
4477 // including members inherited from base classes) that has not
4478 // been previously explicitly specialized in the translation unit
4479 // containing the explicit instantiation, except as described
4480 // below.
4481 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4482 getTemplateInstantiationArgs(ClassTemplateSpec),
4483 TSK);
4484}
4485
4488 if (!S)
4489 return S;
4490
4491 TemplateInstantiator Instantiator(*this, TemplateArgs,
4493 DeclarationName());
4494 return Instantiator.TransformStmt(S);
4495}
4496
4498 const TemplateArgumentLoc &Input,
4499 const MultiLevelTemplateArgumentList &TemplateArgs,
4501 const DeclarationName &Entity) {
4502 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4503 return Instantiator.TransformTemplateArgument(Input, Output);
4504}
4505
4508 const MultiLevelTemplateArgumentList &TemplateArgs,
4510 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4511 DeclarationName());
4512 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4513}
4514
4517 if (!E)
4518 return E;
4519
4520 TemplateInstantiator Instantiator(*this, TemplateArgs,
4522 DeclarationName());
4523 return Instantiator.TransformExpr(E);
4524}
4525
4528 const MultiLevelTemplateArgumentList &TemplateArgs) {
4529 // FIXME: should call SubstExpr directly if this function is equivalent or
4530 // should it be different?
4531 return SubstExpr(E, TemplateArgs);
4532}
4533
4535 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4536 if (!E)
4537 return E;
4538
4539 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4540 DeclarationName());
4541 Instantiator.setEvaluateConstraints(false);
4542 return Instantiator.TransformExpr(E);
4543}
4544
4546 const MultiLevelTemplateArgumentList &TemplateArgs,
4547 bool CXXDirectInit) {
4548 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4549 DeclarationName());
4550 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4551}
4552
4553bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4554 const MultiLevelTemplateArgumentList &TemplateArgs,
4555 SmallVectorImpl<Expr *> &Outputs) {
4556 if (Exprs.empty())
4557 return false;
4558
4559 TemplateInstantiator Instantiator(*this, TemplateArgs,
4561 DeclarationName());
4562 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4563 IsCall, Outputs);
4564}
4565
4568 const MultiLevelTemplateArgumentList &TemplateArgs) {
4569 if (!NNS)
4570 return NestedNameSpecifierLoc();
4571
4572 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4573 DeclarationName());
4574 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4575}
4576
4579 const MultiLevelTemplateArgumentList &TemplateArgs) {
4580 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4581 NameInfo.getName());
4582 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4583}
4584
4588 const MultiLevelTemplateArgumentList &TemplateArgs) {
4589 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4590 DeclarationName());
4591 CXXScopeSpec SS;
4592 SS.Adopt(QualifierLoc);
4593 return Instantiator.TransformTemplateName(SS, Name, Loc);
4594}
4595
4596static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4597 // When storing ParmVarDecls in the local instantiation scope, we always
4598 // want to use the ParmVarDecl from the canonical function declaration,
4599 // since the map is then valid for any redeclaration or definition of that
4600 // function.
4601 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4602 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4603 unsigned i = PV->getFunctionScopeIndex();
4604 // This parameter might be from a freestanding function type within the
4605 // function and isn't necessarily referring to one of FD's parameters.
4606 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4607 return FD->getCanonicalDecl()->getParamDecl(i);
4608 }
4609 }
4610 return D;
4611}
4612
4613
4614llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4617 for (LocalInstantiationScope *Current = this; Current;
4618 Current = Current->Outer) {
4619
4620 // Check if we found something within this scope.
4621 const Decl *CheckD = D;
4622 do {
4623 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4624 if (Found != Current->LocalDecls.end())
4625 return &Found->second;
4626
4627 // If this is a tag declaration, it's possible that we need to look for
4628 // a previous declaration.
4629 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4630 CheckD = Tag->getPreviousDecl();
4631 else
4632 CheckD = nullptr;
4633 } while (CheckD);
4634
4635 // If we aren't combined with our outer scope, we're done.
4636 if (!Current->CombineWithOuterScope)
4637 break;
4638 }
4639
4640 // If we're performing a partial substitution during template argument
4641 // deduction, we may not have values for template parameters yet.
4642 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4643 isa<TemplateTemplateParmDecl>(D))
4644 return nullptr;
4645
4646 // Local types referenced prior to definition may require instantiation.
4647 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4648 if (RD->isLocalClass())
4649 return nullptr;
4650
4651 // Enumeration types referenced prior to definition may appear as a result of
4652 // error recovery.
4653 if (isa<EnumDecl>(D))
4654 return nullptr;
4655
4656 // Materialized typedefs/type alias for implicit deduction guides may require
4657 // instantiation.
4658 if (isa<TypedefNameDecl>(D) &&
4659 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4660 return nullptr;
4661
4662 // If we didn't find the decl, then we either have a sema bug, or we have a
4663 // forward reference to a label declaration. Return null to indicate that
4664 // we have an uninstantiated label.
4665 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4666 return nullptr;
4667}
4668
4671 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4672 if (Stored.isNull()) {
4673#ifndef NDEBUG
4674 // It should not be present in any surrounding scope either.
4675 LocalInstantiationScope *Current = this;
4676 while (Current->CombineWithOuterScope && Current->Outer) {
4677 Current = Current->Outer;
4678 assert(!Current->LocalDecls.contains(D) &&
4679 "Instantiated local in inner and outer scopes");
4680 }
4681#endif
4682 Stored = Inst;
4683 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4684 Pack->push_back(cast<VarDecl>(Inst));
4685 } else {
4686 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4687 }
4688}
4689
4691 VarDecl *Inst) {
4693 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4694 Pack->push_back(Inst);
4695}
4696
4698#ifndef NDEBUG
4699 // This should be the first time we've been told about this decl.
4700 for (LocalInstantiationScope *Current = this;
4701 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4702 assert(!Current->LocalDecls.contains(D) &&
4703 "Creating local pack after instantiation of local");
4704#endif
4705
4707 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4709 Stored = Pack;
4710 ArgumentPacks.push_back(Pack);
4711}
4712
4714 for (DeclArgumentPack *Pack : ArgumentPacks)
4715 if (llvm::is_contained(*Pack, D))
4716 return true;
4717 return false;
4718}
4719
4721 const TemplateArgument *ExplicitArgs,
4722 unsigned NumExplicitArgs) {
4723 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4724 "Already have a partially-substituted pack");
4725 assert((!PartiallySubstitutedPack
4726 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4727 "Wrong number of arguments in partially-substituted pack");
4728 PartiallySubstitutedPack = Pack;
4729 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4730 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4731}
4732
4734 const TemplateArgument **ExplicitArgs,
4735 unsigned *NumExplicitArgs) const {
4736 if (ExplicitArgs)
4737 *ExplicitArgs = nullptr;
4738 if (NumExplicitArgs)
4739 *NumExplicitArgs = 0;
4740
4741 for (const LocalInstantiationScope *Current = this; Current;
4742 Current = Current->Outer) {
4743 if (Current->PartiallySubstitutedPack) {
4744 if (ExplicitArgs)
4745 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4746 if (NumExplicitArgs)
4747 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4748
4749 return Current->PartiallySubstitutedPack;
4750 }
4751
4752 if (!Current->CombineWithOuterScope)
4753 break;
4754 }
4755
4756 return nullptr;
4757}
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.
StringRef P
const Decl * D
Expr * E
Defines the C++ template declaration subclasses.
Defines Expressions and AST nodes for C++2a concepts.
static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx, QualType Ty)
Defines the clang::LangOptions interface.
llvm::MachO::Record Record
Definition: MachO.h:31
MatchFinder::MatchResult MatchResult
uint32_t Id
Definition: SemaARM.cpp:1134
SourceLocation Loc
Definition: SemaObjC.cpp:759
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool PrimaryHasMatchedPackOnParmToNonPackOnArg)
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)
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
#define bool
Definition: amdgpuintrin.h:20
virtual void HandleTagDeclDefinition(TagDecl *D)
HandleTagDeclDefinition - This callback is invoked each time a TagDecl (e.g.
Definition: ASTConsumer.h:73
virtual bool HandleTopLevelDecl(DeclGroupRef D)
HandleTopLevelDecl - Handle the specified top-level declaration.
Definition: ASTConsumer.cpp:18
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:188
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1141
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2739
QualType getSubstTemplateTypeParmType(QualType Replacement, Decl *AssociatedDecl, unsigned Index, std::optional< unsigned > PackIndex, SubstTemplateTypeParmTypeFlag Flag=SubstTemplateTypeParmTypeFlag::None) const
Retrieve a substitution-result type.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1703
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2296
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:733
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:799
PtrTy get() const
Definition: Ownership.h:170
bool isInvalid() const
Definition: Ownership.h:166
bool isUsable() const
Definition: Ownership.h:168
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:3357
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3577
Attr - This represents one attribute.
Definition: Attr.h:43
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6132
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3408
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2078
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:1791
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1563
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:1982
base_class_range bases()
Definition: DeclCXX.h:620
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1030
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:565
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:614
const CXXRecordDecl * getTemplateInstantiationPattern() const
Retrieve the record declaration from which this record could be instantiated.
Definition: DeclCXX.cpp:2036
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2011
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2003
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1989
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1700
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:524
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the kind of specialization or template instantiation this is.
Definition: DeclCXX.cpp:2022
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:129
Declaration of a class template.
ClassTemplateDecl * getMostRecentDecl()
CXXRecordDecl * getTemplatedDecl() const
Get the underlying class declarations of the template.
llvm::FoldingSetVector< ClassTemplatePartialSpecializationDecl > & getPartialSpecializations() const
Retrieve the set of partial specializations of this class template.
ClassTemplateDecl * getInstantiatedFromMemberTemplate() const
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:195
The result of a constraint satisfaction check, containing the necessary information to diagnose an un...
Definition: ASTConcept.h:35
static DeclAccessPair make(NamedDecl *D, AccessSpecifier AS)
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1372
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1439
bool isFileContext() const
Definition: DeclBase.h:2175
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1345
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1866
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2036
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2364
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
TemplateDecl * getDescribedTemplate() const
If this is a declaration that describes some template, this method returns that template declaration.
Definition: DeclBase.cpp:266
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1219
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:247
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:159
bool isFileContextDecl() const
Definition: DeclBase.cpp:435
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1047
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:301
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1226
bool isInvalidDecl() const
Definition: DeclBase.h:591
SourceLocation getLocation() const
Definition: DeclBase.h:442
void setLocation(SourceLocation L)
Definition: DeclBase.h:443
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:942
DeclContext * getDeclContext()
Definition: DeclBase.h:451
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:363
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:911
bool hasAttr() const
Definition: DeclBase.h:580
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:971
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:863
The name of a declaration.
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:792
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:777
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2039
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:786
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:764
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3960
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1493
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:873
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:654
Recursive AST visitor that supports extension via dynamic dispatch.
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6948
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3861
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4120
void setTemplateSpecializationKind(TemplateSpecializationKind TSK, SourceLocation PointOfInstantiation=SourceLocation())
For an enumeration member that was instantiated from a member enumeration of a templated class,...
Definition: Decl.cpp:4948
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4974
EnumDecl * getDefinition() const
Definition: Decl.h:3964
This represents one expression.
Definition: Expr.h:110
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition: Expr.h:437
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:192
llvm::APSInt EvaluateKnownConstInt(const ASTContext &Ctx, SmallVectorImpl< PartialDiagnosticAt > *Diag=nullptr) const
EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded integer.
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool isInstantiationDependent() const
Whether this expression is instantiation-dependent, meaning that it depends in some way on.
Definition: Expr.h:221
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:276
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
ExprDependence getDependence() const
Definition: Expr.h:162
Represents a member of a struct/union/class.
Definition: Decl.h:3033
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4591
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3208
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3202
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3264
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:138
Represents a function declaration or definition.
Definition: Decl.h:1935
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2649
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:4134
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4183
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2398
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2279
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4654
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4688
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1796
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5107
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5371
Declaration of a template function.
Definition: DeclTemplate.h:958
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1523
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4347
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4321
QualType getReturnType() const
Definition: Type.h:4648
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:515
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 the sequence of initializations required to initialize a given object or reference with a s...
Describes an entity that is being initialized.
static InitializedEntity InitializeParameter(ASTContext &Context, ParmVarDecl *Parm)
Create the initialization entity for a parameter.
Wrapper for source info for injected class names of class templates.
Definition: TypeLoc.h:706
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6798
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
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.
static void deleteScopes(LocalInstantiationScope *Scope, LocalInstantiationScope *Outermost)
deletes the given scope, and all outer scopes, down to the given outermost scope.
Definition: Template.h:505
void InstantiatedLocal(const Decl *D, Decl *Inst)
void InstantiatedLocalPackArg(const Decl *D, VarDecl *Inst)
llvm::PointerUnion< Decl *, DeclArgumentPack * > * findInstantiationOf(const Decl *D)
Find the instantiation of the declaration D within the current instantiation scope.
Sugar type that represents a type that was qualified by a qualifier written as a macro invocation.
Definition: Type.h:5770
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3519
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:619
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:650
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:641
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:659
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:664
Describes a module or submodule.
Definition: Module.h:115
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition: Template.h:76
bool hasTemplateArgument(unsigned Depth, unsigned Index) const
Determine whether there is a non-NULL template argument at the given depth and index.
Definition: Template.h:175
const ArgList & getInnermost() const
Retrieve the innermost template argument list.
Definition: Template.h:265
std::pair< Decl *, bool > getAssociatedDecl(unsigned Depth) const
A template-like entity which owns the whole pattern being substituted.
Definition: Template.h:164
unsigned getNumLevels() const
Determine the number of levels in this template argument list.
Definition: Template.h:123
unsigned getNumSubstitutedLevels() const
Determine the number of substituted levels in this template argument list.
Definition: Template.h:129
unsigned getNewDepth(unsigned OldDepth) const
Determine how many of the OldDepth outermost template parameter lists would be removed by substitutin...
Definition: Template.h:145
void setArgument(unsigned Depth, unsigned Index, TemplateArgument Arg)
Clear out a specific template argument.
Definition: Template.h:197
bool isRewrite() const
Determine whether we are rewriting template parameters rather than substituting for them.
Definition: Template.h:117
This represents a decl that may have a name.
Definition: Decl.h:253
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:274
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:280
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:319
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:1818
virtual void printName(raw_ostream &OS, const PrintingPolicy &Policy) const
Pretty-print the unqualified name of this declaration.
Definition: Decl.cpp:1660
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>::".
bool isInstantiationDependent() const
Whether this nested name specifier involves a template parameter.
NestedNameSpecifier * getPrefix() const
Return the prefix of this nested name specifier.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
NonTypeTemplateParmDecl - Declares a non-type template parameter, e.g., "Size" in.
QualType getExpansionType(unsigned I) const
Retrieve a particular expansion type within an expanded parameter pack.
unsigned getPosition() const
Get the position of the template parameter within its parameter list.
bool isExpandedParameterPack() const
Whether this parameter is a non-type template parameter pack that has a known list of different types...
bool isParameterPack() const
Whether this parameter is a non-type template parameter pack.
unsigned getIndex() const
Get the index of the template parameter within its parameter list.
unsigned getDepth() const
Get the nesting depth of the template parameter.
Represents a pack expansion of types.
Definition: Type.h:7146
Sugar for parentheses used when specifying types.
Definition: Type.h:3172
Represents a parameter to a function.
Definition: Decl.h:1725
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1785
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2987
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1821
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1866
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1854
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:3012
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1758
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1858
bool hasInheritedDefaultArg() const
Definition: Decl.h:1870
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1817
Expr * getDefaultArg()
Definition: Decl.cpp:2975
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3017
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1775
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1874
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3198
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PrettyDeclStackTraceEntry - If a crash occurs in the parser while parsing something related to a decl...
A (possibly-)qualified type.
Definition: Type.h:929
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3521
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1151
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:996
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:8139
The collection of all-type qualifiers we support.
Definition: Type.h:324
void removeObjCLifetime()
Definition: Type.h:544
Represents a struct/union/class.
Definition: Decl.h:4162
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6077
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:858
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3439
Represents the body of a requires-expression.
Definition: DeclCXX.h:2047
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:502
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:570
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:571
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:60
Sema & SemaRef
Definition: SemaBase.h:40
RAII object used to change the argument pack substitution index within a Sema object.
Definition: Sema.h:13218
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8048
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3010
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5891
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5923
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5920
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12623
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12093
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:464
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13168
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:13152
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12652
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.
bool CheckParameterPacksForExpansion(SourceLocation EllipsisLoc, SourceRange PatternRange, ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs, bool &ShouldExpand, bool &RetainExpansion, std::optional< unsigned > &NumExpansions)
Determine whether we could expand a pack expansion with the given set of parameter packs into separat...
TemplateName SubstTemplateName(NestedNameSpecifierLoc QualifierLoc, TemplateName Name, SourceLocation Loc, const MultiLevelTemplateArgumentList &TemplateArgs)
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK, bool PartialOrdering, bool *MatchedPackOnParmToNonPackOnArg)
Check that the given template argument corresponds to the given template parameter.
ParmVarDecl * SubstParmVarDecl(ParmVarDecl *D, const MultiLevelTemplateArgumentList &TemplateArgs, int indexAdjustment, std::optional< unsigned > NumExpansions, bool ExpectParameterPack, bool EvaluateConstraints=true)
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)
bool DiagnoseUninstantiableTemplate(SourceLocation PointOfInstantiation, NamedDecl *Instantiation, bool InstantiatedFromMember, const NamedDecl *Pattern, const NamedDecl *PatternDef, TemplateSpecializationKind TSK, bool Complain=true)
Determine whether we would be unable to instantiate this template (because it either has no definitio...
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 ...
llvm::DenseSet< std::pair< Decl *, unsigned > > InstantiatingSpecializations
Specializations whose definitions are currently being instantiated.
Definition: Sema.h:13155
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6867
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition: Sema.h:13513
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...
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11641
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:909
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:13179
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:529
TypeSourceInfo * CheckPackExpansion(TypeSourceInfo *Pattern, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions)
Construct a pack expansion type from the pattern of the pack expansion.
ExprResult BuildExpressionFromNonTypeTemplateArgument(const TemplateArgument &Arg, SourceLocation Loc)
ExprResult SubstConstraintExprWithoutSatisfaction(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
ASTContext & getASTContext() const
Definition: Sema.h:532
TypeSourceInfo * SubstType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, bool AllowDeducedTST=false)
Perform substitution on the type T with a given set of template arguments.
void InstantiateVariableDefinition(SourceLocation PointOfInstantiation, VarDecl *Var, bool Recursive=false, bool DefinitionRequired=false, bool AtEndOfTU=false)
Instantiate the definition of the given variable from its template.
void ActOnStartCXXInClassMemberInitializer()
Enter a new C++ default initializer scope.
PrintingPolicy getPrintingPolicy() const
Retrieve a suitable printing policy for diagnostics.
Definition: Sema.h:817
bool SubstTemplateArguments(ArrayRef< TemplateArgumentLoc > Args, const MultiLevelTemplateArgumentList &TemplateArgs, TemplateArgumentListInfo &Outputs)
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:16974
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:525
bool AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, QualType ConstrainedType, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
void collectUnexpandedParameterPacks(TemplateArgument Arg, SmallVectorImpl< UnexpandedParameterPack > &Unexpanded)
Collect the set of unexpanded parameter packs within the given template argument.
bool CheckConstraintSatisfaction(const NamedDecl *Template, ArrayRef< const Expr * > ConstraintExprs, const MultiLevelTemplateArgumentList &TemplateArgLists, SourceRange TemplateIDRange, ConstraintSatisfaction &Satisfaction)
Check whether the given list of constraint expressions are satisfied (as if in a 'conjunction') given...
Definition: Sema.h:14401
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:13204
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true, bool PrimaryHasMatchedPackOnParmToNonPackOnArg=false)
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3638
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:12664
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...
int ArgumentPackSubstitutionIndex
The current index into pack expansion arguments that will be used for substitution of parameter packs...
Definition: Sema.h:13212
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1044
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:13562
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15210
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...
ExprResult CheckPlaceholderExpr(Expr *E)
Check for operands with placeholder types and complain if found.
Definition: SemaExpr.cpp:20977
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:13188
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 CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5488
bool InstantiateInClassInitializer(SourceLocation PointOfInstantiation, FieldDecl *Instantiation, FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs)
Instantiate the definition of a field from the given pattern.
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:910
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1686
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
unsigned LastEmittedCodeSynthesisContextDepth
The depth of the context stack at the point when the most recent error or warning was produced.
Definition: Sema.h:13196
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)
Definition: SemaDecl.cpp:19016
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7767
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:7917
SourceManager & SourceMgr
Definition: Sema.h:912
DiagnosticsEngine & Diags
Definition: Sema.h:911
bool AttachBaseSpecifiers(CXXRecordDecl *Class, MutableArrayRef< CXXBaseSpecifier * > Bases)
Performs the actual work of attaching the given base class specifiers to a C++ class.
SmallVector< Module *, 16 > CodeSynthesisContextLookupModules
Extra modules inspected when performing a lookup during a template instantiation.
Definition: Sema.h:13163
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:564
ExprResult CreateRecoveryExpr(SourceLocation Begin, SourceLocation End, ArrayRef< Expr * > SubExprs, QualType T=QualType())
Attempts to produce a RecoveryExpr after some AST node cannot be created.
Definition: SemaExpr.cpp:21174
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)
std::string getTemplateArgumentBindingsText(const TemplateParameterList *Params, const TemplateArgumentList &Args)
Produces a formatted string that describes the binding of template parameters to template arguments.
ExprResult BuildExpressionFromDeclTemplateArgument(const TemplateArgument &Arg, QualType ParamType, SourceLocation Loc, NamedDecl *TemplateParam=nullptr)
Given a non-type template argument that refers to a declaration and the type of its corresponding non...
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)
ASTMutationListener * getASTMutationListener() const
Definition: Sema.cpp:590
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8268
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.
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4258
Encodes a location in the source.
unsigned getExpansionLineNumber(SourceLocation Loc, bool *Invalid=nullptr) const
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
SourceLocation getExpansionLoc(SourceLocation Loc) const
Given a SourceLocation object Loc, return the expansion location referenced by the ID.
A trivial tuple used to represent a source range.
void warnOnStackNearlyExhausted(SourceLocation Loc)
Check to see if we're low on stack space and produce a warning if we're low on stack space (Currently...
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4081
Stmt - This represents one statement.
Definition: Stmt.h:84
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 a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4490
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4575
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:149
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:865
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6469
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:858
Represents the result of substituting a type for a template type parameter.
Definition: Type.h:6388
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3578
void setTagKind(TagKind TK)
Definition: Decl.h:3777
SourceRange getBraceRange() const
Definition: Decl.h:3657
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3662
StringRef getKindName() const
Definition: Decl.h:3769
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4773
TagKind getTagKind() const
Definition: Decl.h:3773
void setBraceRange(SourceRange R)
Definition: Decl.h:3658
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1262
A convenient class for passing around template argument information.
Definition: TemplateBase.h:632
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:650
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:651
A template argument list.
Definition: DeclTemplate.h:250
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:280
Location wrapper for a TemplateArgument.
Definition: TemplateBase.h:524
const TemplateArgument & getArgument() const
Definition: TemplateBase.h:574
Represents a template argument.
Definition: TemplateBase.h:61
ArrayRef< TemplateArgument > getPackAsArray() const
Return the array of arguments in this template argument pack.
Definition: TemplateBase.h:444
Expr * getAsExpr() const
Retrieve the template argument as an expression.
Definition: TemplateBase.h:408
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.
Definition: TemplateBase.h:418
QualType getAsType() const
Retrieve the type for a type template argument.
Definition: TemplateBase.h:319
TemplateName getAsTemplate() const
Retrieve the template name for a template name argument.
Definition: TemplateBase.h:343
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.
Definition: TemplateBase.h:298
unsigned pack_size() const
The number of template arguments in the given template argument pack.
Definition: TemplateBase.h:438
@ Declaration
The template argument is a declaration that was provided for a pointer, reference,...
Definition: TemplateBase.h:74
@ Template
The template argument is a template name that was provided for a template template parameter.
Definition: TemplateBase.h:93
@ Pack
The template argument is actually a parameter pack.
Definition: TemplateBase.h:107
@ NullPtr
The template argument is a null pointer or null pointer to member that was provided for a non-type te...
Definition: TemplateBase.h:78
@ Type
The template argument is a type.
Definition: TemplateBase.h:70
@ Expression
The template argument is an expression, and we've not resolved it to one of the other forms yet,...
Definition: TemplateBase.h:103
ArgKind getKind() const
Return the kind of stored template argument.
Definition: TemplateBase.h:295
bool isPackExpansion() const
Determine whether this template argument is a pack expansion.
void enableLateAttributeInstantiation(Sema::LateInstantiatedAttrVec *LA)
Definition: Template.h:661
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:700
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition: Template.h:684
void setEvaluateConstraints(bool B)
Definition: Template.h:602
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:678
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:672
VarTemplatePartialSpecializationDecl * InstantiateVarTemplatePartialSpecialization(VarTemplateDecl *VarTemplate, VarTemplatePartialSpecializationDecl *PartialSpec)
Instantiate the declaration of a variable template partial specialization.
SmallVectorImpl< std::pair< ClassTemplateDecl *, ClassTemplatePartialSpecializationDecl * > >::iterator delayed_partial_spec_iterator
Definition: Template.h:675
void InstantiateEnumDefinition(EnumDecl *Enum, EnumDecl *Pattern)
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:696
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:688
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.).
Definition: DeclTemplate.h:398
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:417
Represents a C++ template name within the type system.
Definition: TemplateName.h:220
TemplateDecl * getAsTemplateDecl(bool IgnoreDeduced=false) const
Retrieve the underlying template declaration that this template name refers to, if known.
bool isNull() const
Determine whether this template name is NULL.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:147
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:209
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:205
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.
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:6666
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.
bool isParameterPack() const
Returns whether this is a parameter pack.
void setTypeConstraint(ConceptReference *CR, Expr *ImmediatelyDeclaredConstraint)
Wrapper for template type parameters.
Definition: TypeLoc.h:759
bool isParameterPack() const
Definition: Type.h:6349
unsigned getIndex() const
Definition: Type.h:6348
unsigned getDepth() const
Definition: Type.h:6347
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
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:260
ConceptDecl * getNamedConcept() const
Definition: ASTConcept.h:250
Expr * getImmediatelyDeclaredConstraint() const
Get the immediately-declared constraint expression introduced by this type-constraint,...
Definition: ASTConcept.h:242
const NestedNameSpecifierLoc & getNestedNameSpecifierLoc() const
Definition: ASTConcept.h:270
const DeclarationNameInfo & getConceptNameInfo() const
Definition: ASTConcept.h:274
ConceptReference * getConceptReference() const
Definition: ASTConcept.h:246
void setLocStart(SourceLocation L)
Definition: Decl.h:3413
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:1257
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:153
unsigned getFullDataSize() const
Returns the size of the type source info data block.
Definition: TypeLoc.h:164
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:235
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:192
A container of type source information.
Definition: Type.h:7907
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7918
SourceLocation getNameLoc() const
Definition: TypeLoc.h:536
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:540
An operation on a type.
Definition: TypeVisitor.h:64
static TagTypeKind getTagTypeKindForKeyword(ElaboratedTypeKeyword Keyword)
Converts an elaborated type keyword into a TagTypeKind.
Definition: Type.cpp:3213
The base class of the type hierarchy.
Definition: Type.h:1828
bool isVoidType() const
Definition: Type.h:8515
bool isReferenceType() const
Definition: Type.h:8209
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:738
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2714
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2706
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2361
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2724
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8736
bool isRecordType() const
Definition: Type.h:8291
QualType getUnderlyingType() const
Definition: Decl.h:3482
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:671
QualType getType() const
Definition: Decl.h:682
Represents a variable declaration or definition.
Definition: Decl.h:882
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1234
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2355
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2748
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:2883
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1119
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2662
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2874
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.
Represents a GCC generic vector type.
Definition: Type.h:4034
A requires-expression requirement which queries the validity and properties of an expression ('simple...
Definition: ExprConcepts.h:280
SubstitutionDiagnostic * getExprSubstitutionDiagnostic() const
Definition: ExprConcepts.h:408
const ReturnTypeRequirement & getReturnTypeRequirement() const
Definition: ExprConcepts.h:398
SourceLocation getNoexceptLoc() const
Definition: ExprConcepts.h:390
A requires-expression requirement which is satisfied when a general constraint expression is satisfie...
Definition: ExprConcepts.h:429
const ASTConstraintSatisfaction & getConstraintSatisfaction() const
Definition: ExprConcepts.h:484
A static requirement that can be used in a requires-expression to check properties of types and expre...
Definition: ExprConcepts.h:168
A requires-expression requirement which queries the existence of a type name or type template special...
Definition: ExprConcepts.h:225
SubstitutionDiagnostic * getSubstitutionDiagnostic() const
Definition: ExprConcepts.h:260
TypeSourceInfo * getType() const
Definition: ExprConcepts.h:267
RetTy Visit(PTR(Decl) D)
Definition: DeclVisitor.h:37
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.
Defines the clang::TargetInfo interface.
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)
void atTemplateBegin(TemplateInstantiationCallbackPtrs &Callbacks, const Sema &TheSema, const Sema::CodeSynthesisContext &Inst)
@ Specialization
We are substituting template parameters for template arguments in order to form a template specializa...
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition: ASTLambda.h:82
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
std::pair< unsigned, unsigned > getDepthAndIndex(const NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
TagTypeKind
The kind of a tag type.
Definition: Type.h:6876
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:264
llvm::PointerUnion< TemplateTypeParmDecl *, NonTypeTemplateParmDecl *, TemplateTemplateParmDecl * > TemplateParameter
Stores a template parameter of any kind.
Definition: DeclTemplate.h:65
@ 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
const FunctionProtoType * T
void printTemplateArgumentList(raw_ostream &OS, ArrayRef< TemplateArgument > Args, const PrintingPolicy &Policy, const TemplateParameterList *TPL=nullptr)
Print a template argument list, including the '<' and '>' enclosing the template arguments.
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
TemplateDeductionResult
Describes the result of template argument deduction.
Definition: Sema.h:365
@ Success
Template argument deduction was successful.
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
ElaboratedTypeKeyword
The elaboration keyword that precedes a qualified type name or introduces an elaborated-type-specifie...
Definition: Type.h:6851
@ None
No keyword precedes the qualified type name.
@ Enum
The "enum" keyword introduces the elaborated-type-specifier.
@ Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
@ EST_Uninstantiated
not instantiated yet
@ EST_None
no exception specification
@ AS_public
Definition: Specifiers.h:124
__DEVICE__ _Tp arg(const std::complex< _Tp > &__c)
Definition: complex_cmath.h:40
#define false
Definition: stdbool.h:26
Represents an explicit template argument list in C++, e.g., the "<int>" in "sort<int>".
Definition: TemplateBase.h:676
SourceLocation RAngleLoc
The source location of the right angle bracket ('>').
Definition: TemplateBase.h:691
SourceLocation LAngleLoc
The source location of the left angle bracket ('<').
Definition: TemplateBase.h:688
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:705
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: Type.h:5164
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5166
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5199
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12669
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:12833
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:12802
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:12828
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:12797
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12789
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12671
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12763
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:12681
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12690
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:12709
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12760
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:12717
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:12724
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12767
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:12735
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12773
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:12700
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:12779
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12776
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition: Sema.h:12782
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12697
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:12705
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12713
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:12674
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12727
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12731
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12686
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12757
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:12720
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12792
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:12857
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13017
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:13021
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.