clang 21.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 (Innermost) {
483 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
484 Final);
485 // Populate placeholder template arguments for TemplateTemplateParmDecls.
486 // This is essential for the case e.g.
487 //
488 // template <class> concept Concept = false;
489 // template <template <Concept C> class T> void foo(T<int>)
490 //
491 // where parameter C has a depth of 1 but the substituting argument `int`
492 // has a depth of 0.
493 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
494 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
495 CurDecl = DC ? Decl::castFromDeclContext(DC)
496 : Response::UseNextDecl(CurDecl).NextDecl;
497 } else if (!CurDecl)
498 CurDecl = Decl::castFromDeclContext(DC);
499
500 while (!CurDecl->isFileContextDecl()) {
501 Response R;
502 if (const auto *VarTemplSpec =
503 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
504 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
505 } else if (const auto *PartialClassTemplSpec =
506 dyn_cast<ClassTemplatePartialSpecializationDecl>(CurDecl)) {
507 R = HandlePartialClassTemplateSpec(PartialClassTemplSpec, Result,
508 SkipForSpecialization);
509 } else if (const auto *ClassTemplSpec =
510 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
511 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
512 SkipForSpecialization);
513 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
514 R = HandleFunction(*this, Function, Result, Pattern, RelativeToPrimary,
515 ForConstraintInstantiation,
516 ForDefaultArgumentSubstitution);
517 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
518 R = HandleRecordDecl(*this, Rec, Result, Context,
519 ForConstraintInstantiation);
520 } else if (const auto *CSD =
521 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
522 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
523 } else if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(CurDecl)) {
524 R = HandleFunctionTemplateDecl(*this, FTD, Result);
525 } else if (const auto *CTD = dyn_cast<ClassTemplateDecl>(CurDecl)) {
526 R = Response::ChangeDecl(CTD->getLexicalDeclContext());
527 } else if (!isa<DeclContext>(CurDecl)) {
528 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
529 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
530 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
531 }
532 } else {
533 R = HandleGenericDeclContext(CurDecl);
534 }
535
536 if (R.IsDone)
537 return Result;
538 if (R.ClearRelativeToPrimary)
539 RelativeToPrimary = false;
540 assert(R.NextDecl);
541 CurDecl = R.NextDecl;
542 }
543
544 return Result;
545}
546
548 switch (Kind) {
556 case ConstraintsCheck:
558 return true;
559
578 return false;
579
580 // This function should never be called when Kind's value is Memoization.
581 case Memoization:
582 break;
583 }
584
585 llvm_unreachable("Invalid SynthesisKind!");
586}
587
590 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
591 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
592 sema::TemplateDeductionInfo *DeductionInfo)
593 : SemaRef(SemaRef) {
594 // Don't allow further instantiation if a fatal error and an uncompilable
595 // error have occurred. Any diagnostics we might have raised will not be
596 // visible, and we do not need to construct a correct AST.
599 Invalid = true;
600 return;
601 }
602 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
603 if (!Invalid) {
605 Inst.Kind = Kind;
606 Inst.PointOfInstantiation = PointOfInstantiation;
607 Inst.Entity = Entity;
608 Inst.Template = Template;
609 Inst.TemplateArgs = TemplateArgs.data();
610 Inst.NumTemplateArgs = TemplateArgs.size();
611 Inst.DeductionInfo = DeductionInfo;
612 Inst.InstantiationRange = InstantiationRange;
614
615 AlreadyInstantiating = !Inst.Entity ? false :
617 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
618 .second;
620 }
621}
622
624 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
625 SourceRange InstantiationRange)
627 CodeSynthesisContext::TemplateInstantiation,
628 PointOfInstantiation, InstantiationRange, Entity) {}
629
631 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
632 ExceptionSpecification, SourceRange InstantiationRange)
634 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
635 PointOfInstantiation, InstantiationRange, Entity) {}
636
638 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
639 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
640 SourceRange InstantiationRange)
642 SemaRef,
643 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
644 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
645 Template, TemplateArgs) {}
646
648 Sema &SemaRef, SourceLocation PointOfInstantiation,
650 ArrayRef<TemplateArgument> TemplateArgs,
652 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
653 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
654 InstantiationRange, FunctionTemplate, nullptr,
655 TemplateArgs, &DeductionInfo) {
659}
660
662 Sema &SemaRef, SourceLocation PointOfInstantiation,
663 TemplateDecl *Template,
664 ArrayRef<TemplateArgument> TemplateArgs,
665 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
667 SemaRef,
668 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
669 PointOfInstantiation, InstantiationRange, Template, nullptr,
670 TemplateArgs, &DeductionInfo) {}
671
673 Sema &SemaRef, SourceLocation PointOfInstantiation,
675 ArrayRef<TemplateArgument> TemplateArgs,
676 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
678 SemaRef,
679 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
680 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
681 TemplateArgs, &DeductionInfo) {}
682
684 Sema &SemaRef, SourceLocation PointOfInstantiation,
686 ArrayRef<TemplateArgument> TemplateArgs,
687 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
689 SemaRef,
690 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
691 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
692 TemplateArgs, &DeductionInfo) {}
693
695 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
696 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
698 SemaRef,
699 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
700 PointOfInstantiation, InstantiationRange, Param, nullptr,
701 TemplateArgs) {}
702
704 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
706 SourceRange InstantiationRange)
708 SemaRef,
709 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
710 PointOfInstantiation, InstantiationRange, Param, Template,
711 TemplateArgs) {}
712
714 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
716 SourceRange InstantiationRange)
718 SemaRef,
719 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
720 PointOfInstantiation, InstantiationRange, Param, Template,
721 TemplateArgs) {}
722
724 Sema &SemaRef, SourceLocation PointOfInstantiation,
726 SourceRange InstantiationRange)
728 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
729 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
730 /*Template=*/nullptr, TemplateArgs) {}
731
733 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
734 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
735 SourceRange InstantiationRange)
737 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
738 PointOfInstantiation, InstantiationRange, Param, Template,
739 TemplateArgs) {}
740
742 Sema &SemaRef, SourceLocation PointOfInstantiation,
744 SourceRange InstantiationRange)
746 SemaRef, CodeSynthesisContext::RequirementInstantiation,
747 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
748 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
749
751 Sema &SemaRef, SourceLocation PointOfInstantiation,
753 SourceRange InstantiationRange)
755 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
756 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
757 /*Template=*/nullptr, /*TemplateArgs=*/{}) {}
758
760 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
761 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
763 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
764 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
765 /*Template=*/nullptr, /*TemplateArgs=*/{}, &DeductionInfo) {}
766
768 Sema &SemaRef, SourceLocation PointOfInstantiation,
769 ConstraintsCheck, NamedDecl *Template,
770 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
773 PointOfInstantiation, InstantiationRange, Template, nullptr,
774 TemplateArgs) {}
775
777 Sema &SemaRef, SourceLocation PointOfInstantiation,
779 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
782 PointOfInstantiation, InstantiationRange, Template, nullptr,
783 {}, &DeductionInfo) {}
784
786 Sema &SemaRef, SourceLocation PointOfInstantiation,
788 SourceRange InstantiationRange)
791 PointOfInstantiation, InstantiationRange, Template) {}
792
794 Sema &SemaRef, SourceLocation PointOfInstantiation,
796 SourceRange InstantiationRange)
799 PointOfInstantiation, InstantiationRange, Template) {}
800
802 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
803 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
805 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
806 PointOfInstantiation, InstantiationRange, Entity) {}
807
810 TemplateDecl *PArg, SourceRange InstantiationRange)
812 ArgLoc, InstantiationRange, PArg) {}
813
815 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
817
818 CodeSynthesisContexts.push_back(Ctx);
819
820 if (!Ctx.isInstantiationRecord())
822
823 // Check to see if we're low on stack space. We can't do anything about this
824 // from here, but we can at least warn the user.
825 StackHandler.warnOnStackNearlyExhausted(Ctx.PointOfInstantiation);
826}
827
829 auto &Active = CodeSynthesisContexts.back();
830 if (!Active.isInstantiationRecord()) {
831 assert(NonInstantiationEntries > 0);
833 }
834
835 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
836
837 // Name lookup no longer looks in this template's defining module.
838 assert(CodeSynthesisContexts.size() >=
840 "forgot to remove a lookup module for a template instantiation");
841 if (CodeSynthesisContexts.size() ==
844 LookupModulesCache.erase(M);
846 }
847
848 // If we've left the code synthesis context for the current context stack,
849 // stop remembering that we've emitted that stack.
850 if (CodeSynthesisContexts.size() ==
853
854 CodeSynthesisContexts.pop_back();
855}
856
858 if (!Invalid) {
859 if (!AlreadyInstantiating) {
860 auto &Active = SemaRef.CodeSynthesisContexts.back();
861 if (Active.Entity)
863 {Active.Entity->getCanonicalDecl(), Active.Kind});
864 }
865
868
870 Invalid = true;
871 }
872}
873
874static std::string convertCallArgsToString(Sema &S,
876 std::string Result;
877 llvm::raw_string_ostream OS(Result);
878 llvm::ListSeparator Comma;
879 for (const Expr *Arg : Args) {
880 OS << Comma;
881 Arg->IgnoreParens()->printPretty(OS, nullptr,
883 }
884 return Result;
885}
886
887bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
888 SourceLocation PointOfInstantiation,
889 SourceRange InstantiationRange) {
892 if ((SemaRef.CodeSynthesisContexts.size() -
894 <= SemaRef.getLangOpts().InstantiationDepth)
895 return false;
896
897 SemaRef.Diag(PointOfInstantiation,
898 diag::err_template_recursion_depth_exceeded)
899 << SemaRef.getLangOpts().InstantiationDepth
900 << InstantiationRange;
901 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
902 << SemaRef.getLangOpts().InstantiationDepth;
903 return true;
904}
905
907 // Determine which template instantiations to skip, if any.
908 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
909 unsigned Limit = Diags.getTemplateBacktraceLimit();
910 if (Limit && Limit < CodeSynthesisContexts.size()) {
911 SkipStart = Limit / 2 + Limit % 2;
912 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
913 }
914
915 // FIXME: In all of these cases, we need to show the template arguments
916 unsigned InstantiationIdx = 0;
918 Active = CodeSynthesisContexts.rbegin(),
919 ActiveEnd = CodeSynthesisContexts.rend();
920 Active != ActiveEnd;
921 ++Active, ++InstantiationIdx) {
922 // Skip this instantiation?
923 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
924 if (InstantiationIdx == SkipStart) {
925 // Note that we're skipping instantiations.
926 Diags.Report(Active->PointOfInstantiation,
927 diag::note_instantiation_contexts_suppressed)
928 << unsigned(CodeSynthesisContexts.size() - Limit);
929 }
930 continue;
931 }
932
933 switch (Active->Kind) {
935 Decl *D = Active->Entity;
936 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
937 unsigned DiagID = diag::note_template_member_class_here;
938 if (isa<ClassTemplateSpecializationDecl>(Record))
939 DiagID = diag::note_template_class_instantiation_here;
940 Diags.Report(Active->PointOfInstantiation, DiagID)
941 << Record << Active->InstantiationRange;
942 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
943 unsigned DiagID;
944 if (Function->getPrimaryTemplate())
945 DiagID = diag::note_function_template_spec_here;
946 else
947 DiagID = diag::note_template_member_function_here;
948 Diags.Report(Active->PointOfInstantiation, DiagID)
949 << Function
950 << Active->InstantiationRange;
951 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
952 Diags.Report(Active->PointOfInstantiation,
953 VD->isStaticDataMember()?
954 diag::note_template_static_data_member_def_here
955 : diag::note_template_variable_def_here)
956 << VD
957 << Active->InstantiationRange;
958 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
959 Diags.Report(Active->PointOfInstantiation,
960 diag::note_template_enum_def_here)
961 << ED
962 << Active->InstantiationRange;
963 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
964 Diags.Report(Active->PointOfInstantiation,
965 diag::note_template_nsdmi_here)
966 << FD << Active->InstantiationRange;
967 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
968 Diags.Report(Active->PointOfInstantiation,
969 diag::note_template_class_instantiation_here)
970 << CTD << Active->InstantiationRange;
971 }
972 break;
973 }
974
976 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
977 SmallString<128> TemplateArgsStr;
978 llvm::raw_svector_ostream OS(TemplateArgsStr);
979 Template->printName(OS, getPrintingPolicy());
980 printTemplateArgumentList(OS, Active->template_arguments(),
982 Diags.Report(Active->PointOfInstantiation,
983 diag::note_default_arg_instantiation_here)
984 << OS.str()
985 << Active->InstantiationRange;
986 break;
987 }
988
990 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
991 Diags.Report(Active->PointOfInstantiation,
992 diag::note_explicit_template_arg_substitution_here)
993 << FnTmpl
995 Active->TemplateArgs,
996 Active->NumTemplateArgs)
997 << Active->InstantiationRange;
998 break;
999 }
1000
1002 if (FunctionTemplateDecl *FnTmpl =
1003 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1004 Diags.Report(Active->PointOfInstantiation,
1005 diag::note_function_template_deduction_instantiation_here)
1006 << FnTmpl
1007 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1008 Active->TemplateArgs,
1009 Active->NumTemplateArgs)
1010 << Active->InstantiationRange;
1011 } else {
1012 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1013 isa<VarTemplateSpecializationDecl>(Active->Entity);
1014 bool IsTemplate = false;
1015 TemplateParameterList *Params;
1016 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1017 IsTemplate = true;
1018 Params = D->getTemplateParameters();
1019 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1020 Active->Entity)) {
1021 Params = D->getTemplateParameters();
1022 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1023 Active->Entity)) {
1024 Params = D->getTemplateParameters();
1025 } else {
1026 llvm_unreachable("unexpected template kind");
1027 }
1028
1029 Diags.Report(Active->PointOfInstantiation,
1030 diag::note_deduced_template_arg_substitution_here)
1031 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1032 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1033 Active->NumTemplateArgs)
1034 << Active->InstantiationRange;
1035 }
1036 break;
1037 }
1038
1040 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1041 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1042
1043 SmallString<128> TemplateArgsStr;
1044 llvm::raw_svector_ostream OS(TemplateArgsStr);
1046 printTemplateArgumentList(OS, Active->template_arguments(),
1048 Diags.Report(Active->PointOfInstantiation,
1049 diag::note_default_function_arg_instantiation_here)
1050 << OS.str()
1051 << Active->InstantiationRange;
1052 break;
1053 }
1054
1056 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1057 std::string Name;
1058 if (!Parm->getName().empty())
1059 Name = std::string(" '") + Parm->getName().str() + "'";
1060
1061 TemplateParameterList *TemplateParams = nullptr;
1062 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1063 TemplateParams = Template->getTemplateParameters();
1064 else
1065 TemplateParams =
1066 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1067 ->getTemplateParameters();
1068 Diags.Report(Active->PointOfInstantiation,
1069 diag::note_prior_template_arg_substitution)
1070 << isa<TemplateTemplateParmDecl>(Parm)
1071 << Name
1072 << getTemplateArgumentBindingsText(TemplateParams,
1073 Active->TemplateArgs,
1074 Active->NumTemplateArgs)
1075 << Active->InstantiationRange;
1076 break;
1077 }
1078
1080 TemplateParameterList *TemplateParams = nullptr;
1081 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1082 TemplateParams = Template->getTemplateParameters();
1083 else
1084 TemplateParams =
1085 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1086 ->getTemplateParameters();
1087
1088 Diags.Report(Active->PointOfInstantiation,
1089 diag::note_template_default_arg_checking)
1090 << getTemplateArgumentBindingsText(TemplateParams,
1091 Active->TemplateArgs,
1092 Active->NumTemplateArgs)
1093 << Active->InstantiationRange;
1094 break;
1095 }
1096
1098 Diags.Report(Active->PointOfInstantiation,
1099 diag::note_evaluating_exception_spec_here)
1100 << cast<FunctionDecl>(Active->Entity);
1101 break;
1102
1104 Diags.Report(Active->PointOfInstantiation,
1105 diag::note_template_exception_spec_instantiation_here)
1106 << cast<FunctionDecl>(Active->Entity)
1107 << Active->InstantiationRange;
1108 break;
1109
1111 Diags.Report(Active->PointOfInstantiation,
1112 diag::note_template_requirement_instantiation_here)
1113 << Active->InstantiationRange;
1114 break;
1116 Diags.Report(Active->PointOfInstantiation,
1117 diag::note_template_requirement_params_instantiation_here)
1118 << Active->InstantiationRange;
1119 break;
1120
1122 Diags.Report(Active->PointOfInstantiation,
1123 diag::note_nested_requirement_here)
1124 << Active->InstantiationRange;
1125 break;
1126
1128 Diags.Report(Active->PointOfInstantiation,
1129 diag::note_in_declaration_of_implicit_special_member)
1130 << cast<CXXRecordDecl>(Active->Entity)
1131 << llvm::to_underlying(Active->SpecialMember);
1132 break;
1133
1135 Diags.Report(Active->Entity->getLocation(),
1136 diag::note_in_declaration_of_implicit_equality_comparison);
1137 break;
1138
1140 // FIXME: For synthesized functions that are not defaulted,
1141 // produce a note.
1142 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1145 if (DFK.isSpecialMember()) {
1146 auto *MD = cast<CXXMethodDecl>(FD);
1147 Diags.Report(Active->PointOfInstantiation,
1148 diag::note_member_synthesized_at)
1149 << MD->isExplicitlyDefaulted()
1150 << llvm::to_underlying(DFK.asSpecialMember())
1151 << Context.getTagDeclType(MD->getParent());
1152 } else if (DFK.isComparison()) {
1153 QualType RecordType = FD->getParamDecl(0)
1154 ->getType()
1155 .getNonReferenceType()
1156 .getUnqualifiedType();
1157 Diags.Report(Active->PointOfInstantiation,
1158 diag::note_comparison_synthesized_at)
1159 << (int)DFK.asComparison() << RecordType;
1160 }
1161 break;
1162 }
1163
1165 Diags.Report(Active->Entity->getLocation(),
1166 diag::note_rewriting_operator_as_spaceship);
1167 break;
1168
1170 Diags.Report(Active->PointOfInstantiation,
1171 diag::note_in_binding_decl_init)
1172 << cast<BindingDecl>(Active->Entity);
1173 break;
1174
1176 Diags.Report(Active->PointOfInstantiation,
1177 diag::note_due_to_dllexported_class)
1178 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1179 break;
1180
1182 Diags.Report(Active->PointOfInstantiation,
1183 diag::note_building_builtin_dump_struct_call)
1185 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1186 break;
1187
1189 break;
1190
1192 Diags.Report(Active->PointOfInstantiation,
1193 diag::note_lambda_substitution_here);
1194 break;
1196 unsigned DiagID = 0;
1197 if (!Active->Entity) {
1198 Diags.Report(Active->PointOfInstantiation,
1199 diag::note_nested_requirement_here)
1200 << Active->InstantiationRange;
1201 break;
1202 }
1203 if (isa<ConceptDecl>(Active->Entity))
1204 DiagID = diag::note_concept_specialization_here;
1205 else if (isa<TemplateDecl>(Active->Entity))
1206 DiagID = diag::note_checking_constraints_for_template_id_here;
1207 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1208 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1209 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1210 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1211 else {
1212 assert(isa<FunctionDecl>(Active->Entity));
1213 DiagID = diag::note_checking_constraints_for_function_here;
1214 }
1215 SmallString<128> TemplateArgsStr;
1216 llvm::raw_svector_ostream OS(TemplateArgsStr);
1217 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1218 if (!isa<FunctionDecl>(Active->Entity)) {
1219 printTemplateArgumentList(OS, Active->template_arguments(),
1221 }
1222 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1223 << Active->InstantiationRange;
1224 break;
1225 }
1227 Diags.Report(Active->PointOfInstantiation,
1228 diag::note_constraint_substitution_here)
1229 << Active->InstantiationRange;
1230 break;
1232 Diags.Report(Active->PointOfInstantiation,
1233 diag::note_constraint_normalization_here)
1234 << cast<NamedDecl>(Active->Entity) << Active->InstantiationRange;
1235 break;
1237 Diags.Report(Active->PointOfInstantiation,
1238 diag::note_parameter_mapping_substitution_here)
1239 << Active->InstantiationRange;
1240 break;
1242 Diags.Report(Active->PointOfInstantiation,
1243 diag::note_building_deduction_guide_here);
1244 break;
1246 Diags.Report(Active->PointOfInstantiation,
1247 diag::note_template_type_alias_instantiation_here)
1248 << cast<TypeAliasTemplateDecl>(Active->Entity)
1249 << Active->InstantiationRange;
1250 break;
1252 Diags.Report(Active->PointOfInstantiation,
1253 diag::note_template_arg_template_params_mismatch);
1254 if (SourceLocation ParamLoc = Active->Entity->getLocation();
1255 ParamLoc.isValid())
1256 Diags.Report(ParamLoc, diag::note_template_prev_declaration)
1257 << /*isTemplateTemplateParam=*/true << Active->InstantiationRange;
1258 break;
1259 }
1260 }
1261}
1262
1263std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1265 return std::optional<TemplateDeductionInfo *>(nullptr);
1266
1268 Active = CodeSynthesisContexts.rbegin(),
1269 ActiveEnd = CodeSynthesisContexts.rend();
1270 Active != ActiveEnd;
1271 ++Active)
1272 {
1273 switch (Active->Kind) {
1275 // An instantiation of an alias template may or may not be a SFINAE
1276 // context, depending on what else is on the stack.
1277 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1278 break;
1279 [[fallthrough]];
1287 // This is a template instantiation, so there is no SFINAE.
1288 return std::nullopt;
1290 // [temp.deduct]p9
1291 // A lambda-expression appearing in a function type or a template
1292 // parameter is not considered part of the immediate context for the
1293 // purposes of template argument deduction.
1294 // CWG2672: A lambda-expression body is never in the immediate context.
1295 return std::nullopt;
1296
1302 // A default template argument instantiation and substitution into
1303 // template parameters with arguments for prior parameters may or may
1304 // not be a SFINAE context; look further up the stack.
1305 break;
1306
1309 // We're either substituting explicitly-specified template arguments,
1310 // deduced template arguments. SFINAE applies unless we are in a lambda
1311 // body, see [temp.deduct]p9.
1315 // SFINAE always applies in a constraint expression or a requirement
1316 // in a requires expression.
1317 assert(Active->DeductionInfo && "Missing deduction info pointer");
1318 return Active->DeductionInfo;
1319
1327 // This happens in a context unrelated to template instantiation, so
1328 // there is no SFINAE.
1329 return std::nullopt;
1330
1332 // FIXME: This should not be treated as a SFINAE context, because
1333 // we will cache an incorrect exception specification. However, clang
1334 // bootstrap relies this! See PR31692.
1335 break;
1336
1338 break;
1339 }
1340
1341 // The inner context was transparent for SFINAE. If it occurred within a
1342 // non-instantiation SFINAE context, then SFINAE applies.
1343 if (Active->SavedInNonInstantiationSFINAEContext)
1344 return std::optional<TemplateDeductionInfo *>(nullptr);
1345 }
1346
1347 return std::nullopt;
1348}
1349
1350//===----------------------------------------------------------------------===/
1351// Template Instantiation for Types
1352//===----------------------------------------------------------------------===/
1353namespace {
1354 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1355 const MultiLevelTemplateArgumentList &TemplateArgs;
1357 DeclarationName Entity;
1358 // Whether to evaluate the C++20 constraints or simply substitute into them.
1359 bool EvaluateConstraints = true;
1360 // Whether Substitution was Incomplete, that is, we tried to substitute in
1361 // any user provided template arguments which were null.
1362 bool IsIncomplete = false;
1363 // Whether an incomplete substituion should be treated as an error.
1364 bool BailOutOnIncomplete;
1365
1366 public:
1367 typedef TreeTransform<TemplateInstantiator> inherited;
1368
1369 TemplateInstantiator(Sema &SemaRef,
1370 const MultiLevelTemplateArgumentList &TemplateArgs,
1372 bool BailOutOnIncomplete = false)
1373 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1374 Entity(Entity), BailOutOnIncomplete(BailOutOnIncomplete) {}
1375
1376 void setEvaluateConstraints(bool B) {
1377 EvaluateConstraints = B;
1378 }
1379 bool getEvaluateConstraints() {
1380 return EvaluateConstraints;
1381 }
1382
1383 /// Determine whether the given type \p T has already been
1384 /// transformed.
1385 ///
1386 /// For the purposes of template instantiation, a type has already been
1387 /// transformed if it is NULL or if it is not dependent.
1388 bool AlreadyTransformed(QualType T);
1389
1390 /// Returns the location of the entity being instantiated, if known.
1391 SourceLocation getBaseLocation() { return Loc; }
1392
1393 /// Returns the name of the entity being instantiated, if any.
1394 DeclarationName getBaseEntity() { return Entity; }
1395
1396 /// Returns whether any substitution so far was incomplete.
1397 bool getIsIncomplete() const { return IsIncomplete; }
1398
1399 /// Sets the "base" location and entity when that
1400 /// information is known based on another transformation.
1401 void setBase(SourceLocation Loc, DeclarationName Entity) {
1402 this->Loc = Loc;
1403 this->Entity = Entity;
1404 }
1405
1406 unsigned TransformTemplateDepth(unsigned Depth) {
1407 return TemplateArgs.getNewDepth(Depth);
1408 }
1409
1410 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1411 int Index = getSema().ArgumentPackSubstitutionIndex;
1412 if (Index == -1)
1413 return std::nullopt;
1414 return Pack.pack_size() - 1 - Index;
1415 }
1416
1417 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1418 SourceRange PatternRange,
1420 bool &ShouldExpand, bool &RetainExpansion,
1421 std::optional<unsigned> &NumExpansions) {
1422 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1423 PatternRange, Unexpanded,
1424 TemplateArgs,
1425 ShouldExpand,
1426 RetainExpansion,
1427 NumExpansions);
1428 }
1429
1430 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1432 }
1433
1434 TemplateArgument ForgetPartiallySubstitutedPack() {
1435 TemplateArgument Result;
1436 if (NamedDecl *PartialPack
1438 MultiLevelTemplateArgumentList &TemplateArgs
1439 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1440 unsigned Depth, Index;
1441 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1442 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1443 Result = TemplateArgs(Depth, Index);
1444 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1445 } else {
1446 IsIncomplete = true;
1447 if (BailOutOnIncomplete)
1448 return TemplateArgument();
1449 }
1450 }
1451
1452 return Result;
1453 }
1454
1455 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1456 if (Arg.isNull())
1457 return;
1458
1459 if (NamedDecl *PartialPack
1461 MultiLevelTemplateArgumentList &TemplateArgs
1462 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1463 unsigned Depth, Index;
1464 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1465 TemplateArgs.setArgument(Depth, Index, Arg);
1466 }
1467 }
1468
1469 /// Transform the given declaration by instantiating a reference to
1470 /// this declaration.
1471 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1472
1473 void transformAttrs(Decl *Old, Decl *New) {
1474 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1475 }
1476
1477 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1478 if (Old->isParameterPack() &&
1479 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1481 for (auto *New : NewDecls)
1483 Old, cast<VarDecl>(New));
1484 return;
1485 }
1486
1487 assert(NewDecls.size() == 1 &&
1488 "should only have multiple expansions for a pack");
1489 Decl *New = NewDecls.front();
1490
1491 // If we've instantiated the call operator of a lambda or the call
1492 // operator template of a generic lambda, update the "instantiation of"
1493 // information.
1494 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1495 if (NewMD && isLambdaCallOperator(NewMD)) {
1496 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1497 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1498 NewTD->setInstantiatedFromMemberTemplate(
1499 OldMD->getDescribedFunctionTemplate());
1500 else
1501 NewMD->setInstantiationOfMemberFunction(OldMD,
1503 }
1504
1506
1507 // We recreated a local declaration, but not by instantiating it. There
1508 // may be pending dependent diagnostics to produce.
1509 if (auto *DC = dyn_cast<DeclContext>(Old);
1510 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1511 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1512 }
1513
1514 /// Transform the definition of the given declaration by
1515 /// instantiating it.
1516 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1517
1518 /// Transform the first qualifier within a scope by instantiating the
1519 /// declaration.
1520 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1521
1522 bool TransformExceptionSpec(SourceLocation Loc,
1524 SmallVectorImpl<QualType> &Exceptions,
1525 bool &Changed);
1526
1527 /// Rebuild the exception declaration and register the declaration
1528 /// as an instantiated local.
1529 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1531 SourceLocation StartLoc,
1532 SourceLocation NameLoc,
1533 IdentifierInfo *Name);
1534
1535 /// Rebuild the Objective-C exception declaration and register the
1536 /// declaration as an instantiated local.
1537 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1538 TypeSourceInfo *TSInfo, QualType T);
1539
1540 /// Check for tag mismatches when instantiating an
1541 /// elaborated type.
1542 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1543 ElaboratedTypeKeyword Keyword,
1544 NestedNameSpecifierLoc QualifierLoc,
1545 QualType T);
1546
1548 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1549 SourceLocation NameLoc,
1550 QualType ObjectType = QualType(),
1551 NamedDecl *FirstQualifierInScope = nullptr,
1552 bool AllowInjectedClassName = false);
1553
1554 const AnnotateAttr *TransformAnnotateAttr(const AnnotateAttr *AA);
1555 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1556 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1557 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1558 const Stmt *InstS,
1559 const NoInlineAttr *A);
1560 const AlwaysInlineAttr *
1561 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1562 const AlwaysInlineAttr *A);
1563 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1564 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1565 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1566 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1567
1568 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1570 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1572 ExprResult TransformSubstNonTypeTemplateParmExpr(
1574
1575 /// Rebuild a DeclRefExpr for a VarDecl reference.
1576 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1577
1578 /// Transform a reference to a function or init-capture parameter pack.
1579 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1580
1581 /// Transform a FunctionParmPackExpr which was built when we couldn't
1582 /// expand a function parameter pack reference which refers to an expanded
1583 /// pack.
1584 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1585
1586 // Transform a ResolvedUnexpandedPackExpr
1588 TransformResolvedUnexpandedPackExpr(ResolvedUnexpandedPackExpr *E);
1589
1590 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1592 // Call the base version; it will forward to our overridden version below.
1593 return inherited::TransformFunctionProtoType(TLB, TL);
1594 }
1595
1596 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1598 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1599 // Special case for transforming a deduction guide, we return a
1600 // transformed TemplateSpecializationType.
1601 if (Type.isNull() &&
1602 SemaRef.CodeSynthesisContexts.back().Kind ==
1604 // Return a TemplateSpecializationType for transforming a deduction
1605 // guide.
1606 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1607 auto Type =
1608 inherited::TransformType(ICT->getInjectedSpecializationType());
1609 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1610 return Type;
1611 }
1612 }
1613 return Type;
1614 }
1615 // Override the default version to handle a rewrite-template-arg-pack case
1616 // for building a deduction guide.
1617 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1618 TemplateArgumentLoc &Output,
1619 bool Uneval = false) {
1620 const TemplateArgument &Arg = Input.getArgument();
1621 std::vector<TemplateArgument> TArgs;
1622 switch (Arg.getKind()) {
1624 // Literally rewrite the template argument pack, instead of unpacking
1625 // it.
1626 for (auto &pack : Arg.getPackAsArray()) {
1628 pack, QualType(), SourceLocation{});
1629 TemplateArgumentLoc Output;
1630 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1631 return true; // fails
1632 TArgs.push_back(Output.getArgument());
1633 }
1634 Output = SemaRef.getTrivialTemplateArgumentLoc(
1635 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1637 return false;
1638 default:
1639 break;
1640 }
1641 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1642 }
1643
1644 template<typename Fn>
1645 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1647 CXXRecordDecl *ThisContext,
1648 Qualifiers ThisTypeQuals,
1649 Fn TransformExceptionSpec);
1650
1651 ParmVarDecl *
1652 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1653 std::optional<unsigned> NumExpansions,
1654 bool ExpectParameterPack);
1655
1656 using inherited::TransformTemplateTypeParmType;
1657 /// Transforms a template type parameter type by performing
1658 /// substitution of the corresponding template type argument.
1659 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1661 bool SuppressObjCLifetime);
1662
1663 QualType BuildSubstTemplateTypeParmType(
1664 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1665 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1666 TemplateArgument Arg, SourceLocation NameLoc);
1667
1668 /// Transforms an already-substituted template type parameter pack
1669 /// into either itself (if we aren't substituting into its pack expansion)
1670 /// or the appropriate substituted argument.
1671 using inherited::TransformSubstTemplateTypeParmPackType;
1672 QualType
1673 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1675 bool SuppressObjCLifetime);
1676
1677 QualType
1678 TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
1681 if (Type->getSubstitutionFlag() !=
1682 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace)
1683 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1684
1685 assert(Type->getPackIndex());
1686 TemplateArgument TA = TemplateArgs(
1687 Type->getReplacedParameter()->getDepth(), Type->getIndex());
1688 assert(*Type->getPackIndex() + 1 <= TA.pack_size());
1690 SemaRef, TA.pack_size() - 1 - *Type->getPackIndex());
1691
1692 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
1693 }
1694
1696 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1697 if (auto TypeAlias =
1698 TemplateInstArgsHelpers::getEnclosingTypeAliasTemplateDecl(
1699 getSema());
1700 TypeAlias && TemplateInstArgsHelpers::isLambdaEnclosedByTypeAliasDecl(
1701 LSI->CallOperator, TypeAlias.PrimaryTypeAliasDecl)) {
1702 unsigned TypeAliasDeclDepth = TypeAlias.Template->getTemplateDepth();
1703 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1704 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1705 for (const TemplateArgument &TA : TypeAlias.AssociatedTemplateArguments)
1706 if (TA.isDependent())
1707 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1708 }
1709 return inherited::ComputeLambdaDependency(LSI);
1710 }
1711
1712 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1713 // Do not rebuild lambdas to avoid creating a new type.
1714 // Lambdas have already been processed inside their eval contexts.
1716 return E;
1717 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1718 /*InstantiatingLambdaOrBlock=*/true);
1720
1721 return inherited::TransformLambdaExpr(E);
1722 }
1723
1724 ExprResult TransformBlockExpr(BlockExpr *E) {
1725 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true,
1726 /*InstantiatingLambdaOrBlock=*/true);
1727 return inherited::TransformBlockExpr(E);
1728 }
1729
1730 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1731 LambdaScopeInfo *LSI) {
1732 CXXMethodDecl *MD = LSI->CallOperator;
1733 for (ParmVarDecl *PVD : MD->parameters()) {
1734 assert(PVD && "null in a parameter list");
1735 if (!PVD->hasDefaultArg())
1736 continue;
1737 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1738 // FIXME: Obtain the source location for the '=' token.
1739 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1740 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1741 // If substitution fails, the default argument is set to a
1742 // RecoveryExpr that wraps the uninstantiated default argument so
1743 // that downstream diagnostics are omitted.
1744 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1745 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(), {UninstExpr},
1746 UninstExpr->getType());
1747 if (ErrorResult.isUsable())
1748 PVD->setDefaultArg(ErrorResult.get());
1749 }
1750 }
1751 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1752 }
1753
1754 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1755 // Currently, we instantiate the body when instantiating the lambda
1756 // expression. However, `EvaluateConstraints` is disabled during the
1757 // instantiation of the lambda expression, causing the instantiation
1758 // failure of the return type requirement in the body. If p0588r1 is fully
1759 // implemented, the body will be lazily instantiated, and this problem
1760 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1761 // `true` to temporarily fix this issue.
1762 // FIXME: This temporary fix can be removed after fully implementing
1763 // p0588r1.
1764 llvm::SaveAndRestore _(EvaluateConstraints, true);
1765 return inherited::TransformLambdaBody(E, Body);
1766 }
1767
1768 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1769 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1770 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1771 if (TransReq.isInvalid())
1772 return TransReq;
1773 assert(TransReq.get() != E &&
1774 "Do not change value of isSatisfied for the existing expression. "
1775 "Create a new expression instead.");
1776 if (E->getBody()->isDependentContext()) {
1777 Sema::SFINAETrap Trap(SemaRef);
1778 // We recreate the RequiresExpr body, but not by instantiating it.
1779 // Produce pending diagnostics for dependent access check.
1780 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1781 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1782 if (Trap.hasErrorOccurred())
1783 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1784 }
1785 return TransReq;
1786 }
1787
1788 bool TransformRequiresExprRequirements(
1791 bool SatisfactionDetermined = false;
1792 for (concepts::Requirement *Req : Reqs) {
1793 concepts::Requirement *TransReq = nullptr;
1794 if (!SatisfactionDetermined) {
1795 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1796 TransReq = TransformTypeRequirement(TypeReq);
1797 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1798 TransReq = TransformExprRequirement(ExprReq);
1799 else
1800 TransReq = TransformNestedRequirement(
1801 cast<concepts::NestedRequirement>(Req));
1802 if (!TransReq)
1803 return true;
1804 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1805 // [expr.prim.req]p6
1806 // [...] The substitution and semantic constraint checking
1807 // proceeds in lexical order and stops when a condition that
1808 // determines the result of the requires-expression is
1809 // encountered. [..]
1810 SatisfactionDetermined = true;
1811 } else
1812 TransReq = Req;
1813 Transformed.push_back(TransReq);
1814 }
1815 return false;
1816 }
1817
1818 TemplateParameterList *TransformTemplateParameterList(
1819 TemplateParameterList *OrigTPL) {
1820 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1821
1822 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1823 TemplateDeclInstantiator DeclInstantiator(getSema(),
1824 /* DeclContext *Owner */ Owner, TemplateArgs);
1825 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1826 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1827 }
1828
1830 TransformTypeRequirement(concepts::TypeRequirement *Req);
1832 TransformExprRequirement(concepts::ExprRequirement *Req);
1834 TransformNestedRequirement(concepts::NestedRequirement *Req);
1835 ExprResult TransformRequiresTypeParams(
1836 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1839 SmallVectorImpl<ParmVarDecl *> &TransParams,
1841
1842 private:
1844 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1845 const NonTypeTemplateParmDecl *parm,
1847 std::optional<unsigned> PackIndex);
1848 };
1849}
1850
1851bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1852 if (T.isNull())
1853 return true;
1854
1857 return false;
1858
1859 getSema().MarkDeclarationsReferencedInType(Loc, T);
1860 return true;
1861}
1862
1863static TemplateArgument
1865 assert(S.ArgumentPackSubstitutionIndex >= 0);
1866 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1868 if (Arg.isPackExpansion())
1869 Arg = Arg.getPackExpansionPattern();
1870 return Arg;
1871}
1872
1873Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1874 if (!D)
1875 return nullptr;
1876
1877 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1878 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1879 // If the corresponding template argument is NULL or non-existent, it's
1880 // because we are performing instantiation from explicitly-specified
1881 // template arguments in a function template, but there were some
1882 // arguments left unspecified.
1883 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1884 TTP->getPosition())) {
1885 IsIncomplete = true;
1886 return BailOutOnIncomplete ? nullptr : D;
1887 }
1888
1889 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1890
1891 if (TTP->isParameterPack()) {
1892 assert(Arg.getKind() == TemplateArgument::Pack &&
1893 "Missing argument pack");
1894 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1895 }
1896
1897 TemplateName Template = Arg.getAsTemplate();
1898 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1899 "Wrong kind of template template argument");
1900 return Template.getAsTemplateDecl();
1901 }
1902
1903 // Fall through to find the instantiated declaration for this template
1904 // template parameter.
1905 }
1906
1907 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1908}
1909
1910Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1911 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1912 if (!Inst)
1913 return nullptr;
1914
1915 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1916 return Inst;
1917}
1918
1919bool TemplateInstantiator::TransformExceptionSpec(
1921 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1922 if (ESI.Type == EST_Uninstantiated) {
1923 ESI.instantiate();
1924 Changed = true;
1925 }
1926 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1927}
1928
1929NamedDecl *
1930TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1932 // If the first part of the nested-name-specifier was a template type
1933 // parameter, instantiate that type parameter down to a tag type.
1934 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1935 const TemplateTypeParmType *TTP
1936 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1937
1938 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1939 // FIXME: This needs testing w/ member access expressions.
1940 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1941
1942 if (TTP->isParameterPack()) {
1943 assert(Arg.getKind() == TemplateArgument::Pack &&
1944 "Missing argument pack");
1945
1946 if (getSema().ArgumentPackSubstitutionIndex == -1)
1947 return nullptr;
1948
1949 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1950 }
1951
1952 QualType T = Arg.getAsType();
1953 if (T.isNull())
1954 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1955
1956 if (const TagType *Tag = T->getAs<TagType>())
1957 return Tag->getDecl();
1958
1959 // The resulting type is not a tag; complain.
1960 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1961 return nullptr;
1962 }
1963 }
1964
1965 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1966}
1967
1968VarDecl *
1969TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1971 SourceLocation StartLoc,
1972 SourceLocation NameLoc,
1973 IdentifierInfo *Name) {
1974 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1975 StartLoc, NameLoc, Name);
1976 if (Var)
1977 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1978 return Var;
1979}
1980
1981VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1982 TypeSourceInfo *TSInfo,
1983 QualType T) {
1984 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1985 if (Var)
1986 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1987 return Var;
1988}
1989
1991TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1992 ElaboratedTypeKeyword Keyword,
1993 NestedNameSpecifierLoc QualifierLoc,
1994 QualType T) {
1995 if (const TagType *TT = T->getAs<TagType>()) {
1996 TagDecl* TD = TT->getDecl();
1997
1998 SourceLocation TagLocation = KeywordLoc;
1999
2001
2002 // TODO: should we even warn on struct/class mismatches for this? Seems
2003 // like it's likely to produce a lot of spurious errors.
2004 if (Id && Keyword != ElaboratedTypeKeyword::None &&
2007 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
2008 TagLocation, Id)) {
2009 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
2010 << Id
2012 TD->getKindName());
2013 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
2014 }
2015 }
2016 }
2017
2018 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
2019}
2020
2021TemplateName TemplateInstantiator::TransformTemplateName(
2022 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
2023 QualType ObjectType, NamedDecl *FirstQualifierInScope,
2024 bool AllowInjectedClassName) {
2026 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
2027 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
2028 // If the corresponding template argument is NULL or non-existent, it's
2029 // because we are performing instantiation from explicitly-specified
2030 // template arguments in a function template, but there were some
2031 // arguments left unspecified.
2032 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
2033 TTP->getPosition())) {
2034 IsIncomplete = true;
2035 return BailOutOnIncomplete ? TemplateName() : Name;
2036 }
2037
2038 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
2039
2040 if (TemplateArgs.isRewrite()) {
2041 // We're rewriting the template parameter as a reference to another
2042 // template parameter.
2043 if (Arg.getKind() == TemplateArgument::Pack) {
2044 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2045 "unexpected pack arguments in template rewrite");
2046 Arg = Arg.pack_begin()->getPackExpansionPattern();
2047 }
2048 assert(Arg.getKind() == TemplateArgument::Template &&
2049 "unexpected nontype template argument kind in template rewrite");
2050 return Arg.getAsTemplate();
2051 }
2052
2053 auto [AssociatedDecl, Final] =
2054 TemplateArgs.getAssociatedDecl(TTP->getDepth());
2055 std::optional<unsigned> PackIndex;
2056 if (TTP->isParameterPack()) {
2057 assert(Arg.getKind() == TemplateArgument::Pack &&
2058 "Missing argument pack");
2059
2060 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2061 // We have the template argument pack to substitute, but we're not
2062 // actually expanding the enclosing pack expansion yet. So, just
2063 // keep the entire argument pack.
2064 return getSema().Context.getSubstTemplateTemplateParmPack(
2065 Arg, AssociatedDecl, TTP->getIndex(), Final);
2066 }
2067
2068 PackIndex = getPackIndex(Arg);
2069 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2070 }
2071
2072 TemplateName Template = Arg.getAsTemplate();
2073 assert(!Template.isNull() && "Null template template argument");
2074
2075 if (Final)
2076 return Template;
2077 return getSema().Context.getSubstTemplateTemplateParm(
2078 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2079 }
2080 }
2081
2083 = Name.getAsSubstTemplateTemplateParmPack()) {
2084 if (getSema().ArgumentPackSubstitutionIndex == -1)
2085 return Name;
2086
2087 TemplateArgument Pack = SubstPack->getArgumentPack();
2088 TemplateName Template =
2090 if (SubstPack->getFinal())
2091 return Template;
2092 return getSema().Context.getSubstTemplateTemplateParm(
2093 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2094 getPackIndex(Pack));
2095 }
2096
2097 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2098 FirstQualifierInScope,
2099 AllowInjectedClassName);
2100}
2101
2103TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2104 if (!E->isTypeDependent())
2105 return E;
2106
2107 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2108}
2109
2111TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2113 // If the corresponding template argument is NULL or non-existent, it's
2114 // because we are performing instantiation from explicitly-specified
2115 // template arguments in a function template, but there were some
2116 // arguments left unspecified.
2117 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2118 NTTP->getPosition())) {
2119 IsIncomplete = true;
2120 return BailOutOnIncomplete ? ExprError() : E;
2121 }
2122
2123 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2124
2125 if (TemplateArgs.isRewrite()) {
2126 // We're rewriting the template parameter as a reference to another
2127 // template parameter.
2128 if (Arg.getKind() == TemplateArgument::Pack) {
2129 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2130 "unexpected pack arguments in template rewrite");
2131 Arg = Arg.pack_begin()->getPackExpansionPattern();
2132 }
2133 assert(Arg.getKind() == TemplateArgument::Expression &&
2134 "unexpected nontype template argument kind in template rewrite");
2135 // FIXME: This can lead to the same subexpression appearing multiple times
2136 // in a complete expression.
2137 return Arg.getAsExpr();
2138 }
2139
2140 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2141 std::optional<unsigned> PackIndex;
2142 if (NTTP->isParameterPack()) {
2143 assert(Arg.getKind() == TemplateArgument::Pack &&
2144 "Missing argument pack");
2145
2146 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2147 // We have an argument pack, but we can't select a particular argument
2148 // out of it yet. Therefore, we'll build an expression to hold on to that
2149 // argument pack.
2150 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2151 E->getLocation(),
2152 NTTP->getDeclName());
2153 if (TargetType.isNull())
2154 return ExprError();
2155
2156 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2157 if (TargetType->isRecordType())
2158 ExprType.addConst();
2159 // FIXME: Pass in Final.
2161 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2162 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2163 }
2164 PackIndex = getPackIndex(Arg);
2165 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2166 }
2167 // FIXME: Don't put subst node on Final replacement.
2168 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2169 Arg, PackIndex);
2170}
2171
2172const AnnotateAttr *
2173TemplateInstantiator::TransformAnnotateAttr(const AnnotateAttr *AA) {
2175 for (Expr *Arg : AA->args()) {
2176 ExprResult Res = getDerived().TransformExpr(Arg);
2177 if (Res.isUsable())
2178 Args.push_back(Res.get());
2179 }
2180 return AnnotateAttr::CreateImplicit(getSema().Context, AA->getAnnotation(),
2181 Args.data(), Args.size(), AA->getRange());
2182}
2183
2184const CXXAssumeAttr *
2185TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2186 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2187 if (!Res.isUsable())
2188 return AA;
2189
2190 Res = getSema().ActOnFinishFullExpr(Res.get(),
2191 /*DiscardedValue=*/false);
2192 if (!Res.isUsable())
2193 return AA;
2194
2195 if (!(Res.get()->getDependence() & ExprDependence::TypeValueInstantiation)) {
2196 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2197 AA->getRange());
2198 if (!Res.isUsable())
2199 return AA;
2200 }
2201
2202 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2203 AA->getRange());
2204}
2205
2206const LoopHintAttr *
2207TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2208 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2209
2210 if (TransformedExpr == LH->getValue())
2211 return LH;
2212
2213 // Generate error if there is a problem with the value.
2214 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2215 LH->getSemanticSpelling() ==
2216 LoopHintAttr::Pragma_unroll))
2217 return LH;
2218
2219 LoopHintAttr::OptionType Option = LH->getOption();
2220 LoopHintAttr::LoopHintState State = LH->getState();
2221
2222 llvm::APSInt ValueAPS =
2223 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2224 // The values of 0 and 1 block any unrolling of the loop.
2225 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2226 Option = LoopHintAttr::Unroll;
2227 State = LoopHintAttr::Disable;
2228 }
2229
2230 // Create new LoopHintValueAttr with integral expression in place of the
2231 // non-type template parameter.
2232 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2233 TransformedExpr, *LH);
2234}
2235const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2236 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2237 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2238 return nullptr;
2239
2240 return A;
2241}
2242const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2243 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2244 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2245 return nullptr;
2246
2247 return A;
2248}
2249
2250const CodeAlignAttr *
2251TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2252 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2253 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2254}
2255
2256ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2257 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2259 std::optional<unsigned> PackIndex) {
2260 ExprResult result;
2261
2262 // Determine the substituted parameter type. We can usually infer this from
2263 // the template argument, but not always.
2264 auto SubstParamType = [&] {
2265 QualType T;
2266 if (parm->isExpandedParameterPack())
2268 else
2269 T = parm->getType();
2270 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2271 T = cast<PackExpansionType>(T)->getPattern();
2272 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2273 };
2274
2275 bool refParam = false;
2276
2277 // The template argument itself might be an expression, in which case we just
2278 // return that expression. This happens when substituting into an alias
2279 // template.
2280 if (arg.getKind() == TemplateArgument::Expression) {
2281 Expr *argExpr = arg.getAsExpr();
2282 result = argExpr;
2283 if (argExpr->isLValue()) {
2284 if (argExpr->getType()->isRecordType()) {
2285 // Check whether the parameter was actually a reference.
2286 QualType paramType = SubstParamType();
2287 if (paramType.isNull())
2288 return ExprError();
2289 refParam = paramType->isReferenceType();
2290 } else {
2291 refParam = true;
2292 }
2293 }
2294 } else if (arg.getKind() == TemplateArgument::Declaration ||
2295 arg.getKind() == TemplateArgument::NullPtr) {
2296 if (arg.getKind() == TemplateArgument::Declaration) {
2297 ValueDecl *VD = arg.getAsDecl();
2298
2299 // Find the instantiation of the template argument. This is
2300 // required for nested templates.
2301 VD = cast_or_null<ValueDecl>(
2302 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2303 if (!VD)
2304 return ExprError();
2305 }
2306
2307 QualType paramType = arg.getNonTypeTemplateArgumentType();
2308 assert(!paramType.isNull() && "type substitution failed for param type");
2309 assert(!paramType->isDependentType() && "param type still dependent");
2310 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2311 refParam = paramType->isReferenceType();
2312 } else {
2313 QualType paramType = arg.getNonTypeTemplateArgumentType();
2315 refParam = paramType->isReferenceType();
2316 assert(result.isInvalid() ||
2318 paramType.getNonReferenceType()));
2319 }
2320
2321 if (result.isInvalid())
2322 return ExprError();
2323
2324 Expr *resultExpr = result.get();
2325 // FIXME: Don't put subst node on final replacement.
2327 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2328 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2329}
2330
2332TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2334 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2335 // We aren't expanding the parameter pack, so just return ourselves.
2336 return E;
2337 }
2338
2339 TemplateArgument Pack = E->getArgumentPack();
2341 // FIXME: Don't put subst node on final replacement.
2342 return transformNonTypeTemplateParmRef(
2343 E->getAssociatedDecl(), E->getParameterPack(),
2344 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2345}
2346
2348TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2350 ExprResult SubstReplacement = E->getReplacement();
2351 if (!isa<ConstantExpr>(SubstReplacement.get()))
2352 SubstReplacement = TransformExpr(E->getReplacement());
2353 if (SubstReplacement.isInvalid())
2354 return true;
2355 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2356 if (SubstType.isNull())
2357 return true;
2358 // The type may have been previously dependent and not now, which means we
2359 // might have to implicit cast the argument to the new type, for example:
2360 // template<auto T, decltype(T) U>
2361 // concept C = sizeof(U) == 4;
2362 // void foo() requires C<2, 'a'> { }
2363 // When normalizing foo(), we first form the normalized constraints of C:
2364 // AtomicExpr(sizeof(U) == 4,
2365 // U=SubstNonTypeTemplateParmExpr(Param=U,
2366 // Expr=DeclRef(U),
2367 // Type=decltype(T)))
2368 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2369 // produce:
2370 // AtomicExpr(sizeof(U) == 4,
2371 // U=SubstNonTypeTemplateParmExpr(Param=U,
2372 // Expr=ImpCast(
2373 // decltype(2),
2374 // SubstNTTPE(Param=U, Expr='a',
2375 // Type=char)),
2376 // Type=decltype(2)))
2377 // The call to CheckTemplateArgument here produces the ImpCast.
2378 TemplateArgument SugaredConverted, CanonicalConverted;
2379 if (SemaRef
2381 E->getParameter(), SubstType, SubstReplacement.get(),
2382 SugaredConverted, CanonicalConverted,
2383 /*PartialOrderingTTP=*/false, Sema::CTAK_Specified)
2384 .isInvalid())
2385 return true;
2386 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2387 E->getParameter(), E->getExprLoc(),
2388 SugaredConverted, E->getPackIndex());
2389}
2390
2391ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2393 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2394 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2395}
2396
2398TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2399 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2400 // We can expand this parameter pack now.
2401 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2402 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2403 if (!VD)
2404 return ExprError();
2405 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2406 }
2407
2408 QualType T = TransformType(E->getType());
2409 if (T.isNull())
2410 return ExprError();
2411
2412 // Transform each of the parameter expansions into the corresponding
2413 // parameters in the instantiation of the function decl.
2415 Vars.reserve(E->getNumExpansions());
2416 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2417 I != End; ++I) {
2418 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2419 if (!D)
2420 return ExprError();
2421 Vars.push_back(D);
2422 }
2423
2424 auto *PackExpr =
2425 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2426 E->getParameterPackLocation(), Vars);
2427 getSema().MarkFunctionParmPackReferenced(PackExpr);
2428 return PackExpr;
2429}
2430
2432TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2433 VarDecl *PD) {
2434 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2435 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2436 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2437 assert(Found && "no instantiation for parameter pack");
2438
2439 Decl *TransformedDecl;
2440 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2441 // If this is a reference to a function parameter pack which we can
2442 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2443 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2444 QualType T = TransformType(E->getType());
2445 if (T.isNull())
2446 return ExprError();
2447 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2448 E->getExprLoc(), *Pack);
2449 getSema().MarkFunctionParmPackReferenced(PackExpr);
2450 return PackExpr;
2451 }
2452
2453 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2454 } else {
2455 TransformedDecl = cast<Decl *>(*Found);
2456 }
2457
2458 // We have either an unexpanded pack or a specific expansion.
2459 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2460}
2461
2463TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2464 NamedDecl *D = E->getDecl();
2465
2466 // Handle references to non-type template parameters and non-type template
2467 // parameter packs.
2468 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2469 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2470 return TransformTemplateParmRefExpr(E, NTTP);
2471
2472 // We have a non-type template parameter that isn't fully substituted;
2473 // FindInstantiatedDecl will find it in the local instantiation scope.
2474 }
2475
2476 // Handle references to function parameter packs.
2477 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2478 if (PD->isParameterPack())
2479 return TransformFunctionParmPackRefExpr(E, PD);
2480
2481 if (BindingDecl *BD = dyn_cast<BindingDecl>(D); BD && BD->isParameterPack()) {
2482 BD = cast_or_null<BindingDecl>(TransformDecl(BD->getLocation(), BD));
2483 if (!BD)
2484 return ExprError();
2485 if (auto *RP =
2486 dyn_cast_if_present<ResolvedUnexpandedPackExpr>(BD->getBinding()))
2487 return TransformResolvedUnexpandedPackExpr(RP);
2488 }
2489
2490 return inherited::TransformDeclRefExpr(E);
2491}
2492
2493ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2495 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2496 getDescribedFunctionTemplate() &&
2497 "Default arg expressions are never formed in dependent cases.");
2499 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2500 E->getParam());
2501}
2502
2503template<typename Fn>
2504QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2506 CXXRecordDecl *ThisContext,
2507 Qualifiers ThisTypeQuals,
2508 Fn TransformExceptionSpec) {
2509 // If this is a lambda or block, the transformation MUST be done in the
2510 // CurrentInstantiationScope since it introduces a mapping of
2511 // the original to the newly created transformed parameters.
2512 //
2513 // In that case, TemplateInstantiator::TransformLambdaExpr will
2514 // have already pushed a scope for this prototype, so don't create
2515 // a second one.
2516 LocalInstantiationScope *Current = getSema().CurrentInstantiationScope;
2517 std::optional<LocalInstantiationScope> Scope;
2518 if (!Current || !Current->isLambdaOrBlock())
2519 Scope.emplace(SemaRef, /*CombineWithOuterScope=*/true);
2520
2521 return inherited::TransformFunctionProtoType(
2522 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2523}
2524
2525ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2526 ParmVarDecl *OldParm, int indexAdjustment,
2527 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2528 auto NewParm = SemaRef.SubstParmVarDecl(
2529 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2530 ExpectParameterPack, EvaluateConstraints);
2531 if (NewParm && SemaRef.getLangOpts().OpenCL)
2533 return NewParm;
2534}
2535
2536QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2537 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2538 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2539 TemplateArgument Arg, SourceLocation NameLoc) {
2540 QualType Replacement = Arg.getAsType();
2541
2542 // If the template parameter had ObjC lifetime qualifiers,
2543 // then any such qualifiers on the replacement type are ignored.
2544 if (SuppressObjCLifetime) {
2545 Qualifiers RQs;
2546 RQs = Replacement.getQualifiers();
2547 RQs.removeObjCLifetime();
2548 Replacement =
2549 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2550 }
2551
2552 if (Final) {
2553 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2554 return Replacement;
2555 }
2556 // TODO: only do this uniquing once, at the start of instantiation.
2557 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2558 Replacement, AssociatedDecl, Index, PackIndex);
2561 NewTL.setNameLoc(NameLoc);
2562 return Result;
2563}
2564
2566TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2568 bool SuppressObjCLifetime) {
2569 const TemplateTypeParmType *T = TL.getTypePtr();
2570 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2571 // Replace the template type parameter with its corresponding
2572 // template argument.
2573
2574 // If the corresponding template argument is NULL or doesn't exist, it's
2575 // because we are performing instantiation from explicitly-specified
2576 // template arguments in a function template class, but there were some
2577 // arguments left unspecified.
2578 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2579 IsIncomplete = true;
2580 if (BailOutOnIncomplete)
2581 return QualType();
2582
2585 NewTL.setNameLoc(TL.getNameLoc());
2586 return TL.getType();
2587 }
2588
2589 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2590
2591 if (TemplateArgs.isRewrite()) {
2592 // We're rewriting the template parameter as a reference to another
2593 // template parameter.
2594 if (Arg.getKind() == TemplateArgument::Pack) {
2595 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2596 "unexpected pack arguments in template rewrite");
2597 Arg = Arg.pack_begin()->getPackExpansionPattern();
2598 }
2599 assert(Arg.getKind() == TemplateArgument::Type &&
2600 "unexpected nontype template argument kind in template rewrite");
2601 QualType NewT = Arg.getAsType();
2602 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2603 return NewT;
2604 }
2605
2606 auto [AssociatedDecl, Final] =
2607 TemplateArgs.getAssociatedDecl(T->getDepth());
2608 std::optional<unsigned> PackIndex;
2609 if (T->isParameterPack()) {
2610 assert(Arg.getKind() == TemplateArgument::Pack &&
2611 "Missing argument pack");
2612
2613 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2614 // We have the template argument pack, but we're not expanding the
2615 // enclosing pack expansion yet. Just save the template argument
2616 // pack for later substitution.
2617 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2618 AssociatedDecl, T->getIndex(), Final, Arg);
2621 NewTL.setNameLoc(TL.getNameLoc());
2622 return Result;
2623 }
2624
2625 // PackIndex starts from last element.
2626 PackIndex = getPackIndex(Arg);
2627 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2628 }
2629
2630 assert(Arg.getKind() == TemplateArgument::Type &&
2631 "Template argument kind mismatch");
2632
2633 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2634 AssociatedDecl, T->getIndex(),
2635 PackIndex, Arg, TL.getNameLoc());
2636 }
2637
2638 // The template type parameter comes from an inner template (e.g.,
2639 // the template parameter list of a member template inside the
2640 // template we are instantiating). Create a new template type
2641 // parameter with the template "level" reduced by one.
2642 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2643 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2644 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2645 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2646 QualType Result = getSema().Context.getTemplateTypeParmType(
2647 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2648 T->isParameterPack(), NewTTPDecl);
2650 NewTL.setNameLoc(TL.getNameLoc());
2651 return Result;
2652}
2653
2654ExprResult TemplateInstantiator::TransformResolvedUnexpandedPackExpr(
2656 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2657 assert(static_cast<unsigned>(getSema().ArgumentPackSubstitutionIndex) <
2658 E->getNumExprs() &&
2659 "ArgumentPackSubstitutionIndex is out of range");
2660 return TransformExpr(
2661 E->getExpansion(getSema().ArgumentPackSubstitutionIndex));
2662 }
2663
2664 return inherited::TransformResolvedUnexpandedPackExpr(E);
2665}
2666
2667QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2669 bool SuppressObjCLifetime) {
2671
2672 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2673
2674 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2675 // We aren't expanding the parameter pack, so just return ourselves.
2676 QualType Result = TL.getType();
2677 if (NewReplaced != T->getAssociatedDecl())
2678 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2679 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2682 NewTL.setNameLoc(TL.getNameLoc());
2683 return Result;
2684 }
2685
2686 TemplateArgument Pack = T->getArgumentPack();
2688 return BuildSubstTemplateTypeParmType(
2689 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2690 getPackIndex(Pack), Arg, TL.getNameLoc());
2691}
2692
2695 Sema::EntityPrinter Printer) {
2696 SmallString<128> Message;
2697 SourceLocation ErrorLoc;
2698 if (Info.hasSFINAEDiagnostic()) {
2701 Info.takeSFINAEDiagnostic(PDA);
2702 PDA.second.EmitToString(S.getDiagnostics(), Message);
2703 ErrorLoc = PDA.first;
2704 } else {
2705 ErrorLoc = Info.getLocation();
2706 }
2707 SmallString<128> Entity;
2708 llvm::raw_svector_ostream OS(Entity);
2709 Printer(OS);
2710 const ASTContext &C = S.Context;
2712 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2713}
2714
2717 SmallString<128> Entity;
2718 llvm::raw_svector_ostream OS(Entity);
2719 Printer(OS);
2720 const ASTContext &C = Context;
2722 /*SubstitutedEntity=*/C.backupStr(Entity),
2723 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2724}
2725
2726ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2727 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2730 SmallVectorImpl<ParmVarDecl *> &TransParams,
2732
2733 TemplateDeductionInfo Info(KWLoc);
2734 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2735 RE, Info,
2736 SourceRange{KWLoc, RBraceLoc});
2738
2739 unsigned ErrorIdx;
2740 if (getDerived().TransformFunctionTypeParams(
2741 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2742 &TransParams, PInfos, &ErrorIdx) ||
2743 Trap.hasErrorOccurred()) {
2745 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2746 // Add a 'failed' Requirement to contain the error that caused the failure
2747 // here.
2748 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2749 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2750 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2751 TransParams, RE->getRParenLoc(),
2752 TransReqs, RBraceLoc);
2753 }
2754
2755 return ExprResult{};
2756}
2757
2759TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2760 if (!Req->isDependent() && !AlwaysRebuild())
2761 return Req;
2762 if (Req->isSubstitutionFailure()) {
2763 if (AlwaysRebuild())
2764 return RebuildTypeRequirement(
2766 return Req;
2767 }
2768
2772 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2773 Req->getType()->getTypeLoc().getSourceRange());
2774 if (TypeInst.isInvalid())
2775 return nullptr;
2776 TypeSourceInfo *TransType = TransformType(Req->getType());
2777 if (!TransType || Trap.hasErrorOccurred())
2778 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2779 [&] (llvm::raw_ostream& OS) {
2780 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2781 }));
2782 return RebuildTypeRequirement(TransType);
2783}
2784
2786TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2787 if (!Req->isDependent() && !AlwaysRebuild())
2788 return Req;
2789
2791
2792 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2793 TransExpr;
2794 if (Req->isExprSubstitutionFailure())
2795 TransExpr = Req->getExprSubstitutionDiagnostic();
2796 else {
2797 Expr *E = Req->getExpr();
2799 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2800 E->getSourceRange());
2801 if (ExprInst.isInvalid())
2802 return nullptr;
2803 ExprResult TransExprRes = TransformExpr(E);
2804 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2805 TransExprRes.get()->hasPlaceholderType())
2806 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2807 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2808 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2810 });
2811 else
2812 TransExpr = TransExprRes.get();
2813 }
2814
2815 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2816 const auto &RetReq = Req->getReturnTypeRequirement();
2817 if (RetReq.isEmpty())
2818 TransRetReq.emplace();
2819 else if (RetReq.isSubstitutionFailure())
2820 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2821 else if (RetReq.isTypeConstraint()) {
2822 TemplateParameterList *OrigTPL =
2823 RetReq.getTypeConstraintTemplateParameterList();
2824 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2826 Req, Info, OrigTPL->getSourceRange());
2827 if (TPLInst.isInvalid())
2828 return nullptr;
2829 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2830 if (!TPL || Trap.hasErrorOccurred())
2831 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2832 [&] (llvm::raw_ostream& OS) {
2833 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2834 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2835 }));
2836 else {
2837 TPLInst.Clear();
2838 TransRetReq.emplace(TPL);
2839 }
2840 }
2841 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2842 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2843 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2844 std::move(*TransRetReq));
2845 return RebuildExprRequirement(
2846 cast<concepts::Requirement::SubstitutionDiagnostic *>(TransExpr),
2847 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2848}
2849
2851TemplateInstantiator::TransformNestedRequirement(
2853 if (!Req->isDependent() && !AlwaysRebuild())
2854 return Req;
2855 if (Req->hasInvalidConstraint()) {
2856 if (AlwaysRebuild())
2857 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2859 return Req;
2860 }
2862 Req->getConstraintExpr()->getBeginLoc(), Req,
2865 if (!getEvaluateConstraints()) {
2866 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2867 if (TransConstraint.isInvalid() || !TransConstraint.get())
2868 return nullptr;
2869 if (TransConstraint.get()->isInstantiationDependent())
2870 return new (SemaRef.Context)
2871 concepts::NestedRequirement(TransConstraint.get());
2872 ConstraintSatisfaction Satisfaction;
2874 SemaRef.Context, TransConstraint.get(), Satisfaction);
2875 }
2876
2877 ExprResult TransConstraint;
2878 ConstraintSatisfaction Satisfaction;
2880 {
2885 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2887 if (ConstrInst.isInvalid())
2888 return nullptr;
2891 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2892 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2893 !Result.empty())
2894 TransConstraint = Result[0];
2895 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2896 "by CheckConstraintSatisfaction.");
2897 }
2899 if (TransConstraint.isUsable() &&
2900 TransConstraint.get()->isInstantiationDependent())
2901 return new (C) concepts::NestedRequirement(TransConstraint.get());
2902 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2903 Satisfaction.HasSubstitutionFailure()) {
2904 SmallString<128> Entity;
2905 llvm::raw_svector_ostream OS(Entity);
2906 Req->getConstraintExpr()->printPretty(OS, nullptr,
2908 return new (C) concepts::NestedRequirement(
2909 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2910 }
2911 return new (C)
2912 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2913}
2914
2918 DeclarationName Entity,
2919 bool AllowDeducedTST) {
2920 assert(!CodeSynthesisContexts.empty() &&
2921 "Cannot perform an instantiation without some context on the "
2922 "instantiation stack");
2923
2924 if (!T->getType()->isInstantiationDependentType() &&
2925 !T->getType()->isVariablyModifiedType())
2926 return T;
2927
2928 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2929 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2930 : Instantiator.TransformType(T);
2931}
2932
2936 DeclarationName Entity) {
2937 assert(!CodeSynthesisContexts.empty() &&
2938 "Cannot perform an instantiation without some context on the "
2939 "instantiation stack");
2940
2941 if (TL.getType().isNull())
2942 return nullptr;
2943
2946 // FIXME: Make a copy of the TypeLoc data here, so that we can
2947 // return a new TypeSourceInfo. Inefficient!
2948 TypeLocBuilder TLB;
2949 TLB.pushFullCopy(TL);
2950 return TLB.getTypeSourceInfo(Context, TL.getType());
2951 }
2952
2953 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2954 TypeLocBuilder TLB;
2955 TLB.reserve(TL.getFullDataSize());
2956 QualType Result = Instantiator.TransformType(TLB, TL);
2957 if (Result.isNull())
2958 return nullptr;
2959
2960 return TLB.getTypeSourceInfo(Context, Result);
2961}
2962
2963/// Deprecated form of the above.
2965 const MultiLevelTemplateArgumentList &TemplateArgs,
2967 bool *IsIncompleteSubstitution) {
2968 assert(!CodeSynthesisContexts.empty() &&
2969 "Cannot perform an instantiation without some context on the "
2970 "instantiation stack");
2971
2972 // If T is not a dependent type or a variably-modified type, there
2973 // is nothing to do.
2975 return T;
2976
2977 TemplateInstantiator Instantiator(
2978 *this, TemplateArgs, Loc, Entity,
2979 /*BailOutOnIncomplete=*/IsIncompleteSubstitution != nullptr);
2980 QualType QT = Instantiator.TransformType(T);
2981 if (IsIncompleteSubstitution && Instantiator.getIsIncomplete())
2982 *IsIncompleteSubstitution = true;
2983 return QT;
2984}
2985
2987 if (T->getType()->isInstantiationDependentType() ||
2988 T->getType()->isVariablyModifiedType())
2989 return true;
2990
2991 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2992 if (!TL.getAs<FunctionProtoTypeLoc>())
2993 return false;
2994
2996 for (ParmVarDecl *P : FP.getParams()) {
2997 // This must be synthesized from a typedef.
2998 if (!P) continue;
2999
3000 // If there are any parameters, a new TypeSourceInfo that refers to the
3001 // instantiated parameters must be built.
3002 return true;
3003 }
3004
3005 return false;
3006}
3007
3011 DeclarationName Entity,
3012 CXXRecordDecl *ThisContext,
3013 Qualifiers ThisTypeQuals,
3014 bool EvaluateConstraints) {
3015 assert(!CodeSynthesisContexts.empty() &&
3016 "Cannot perform an instantiation without some context on the "
3017 "instantiation stack");
3018
3020 return T;
3021
3022 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
3023 Instantiator.setEvaluateConstraints(EvaluateConstraints);
3024
3025 TypeLocBuilder TLB;
3026
3027 TypeLoc TL = T->getTypeLoc();
3028 TLB.reserve(TL.getFullDataSize());
3029
3031
3032 if (FunctionProtoTypeLoc Proto =
3034 // Instantiate the type, other than its exception specification. The
3035 // exception specification is instantiated in InitFunctionInstantiation
3036 // once we've built the FunctionDecl.
3037 // FIXME: Set the exception specification to EST_Uninstantiated here,
3038 // instead of rebuilding the function type again later.
3039 Result = Instantiator.TransformFunctionProtoType(
3040 TLB, Proto, ThisContext, ThisTypeQuals,
3042 bool &Changed) { return false; });
3043 } else {
3044 Result = Instantiator.TransformType(TLB, TL);
3045 }
3046 // When there are errors resolving types, clang may use IntTy as a fallback,
3047 // breaking our assumption that function declarations have function types.
3048 if (Result.isNull() || !Result->isFunctionType())
3049 return nullptr;
3050
3051 return TLB.getTypeSourceInfo(Context, Result);
3052}
3053
3056 SmallVectorImpl<QualType> &ExceptionStorage,
3057 const MultiLevelTemplateArgumentList &Args) {
3058 bool Changed = false;
3059 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
3060 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
3061 Changed);
3062}
3063
3065 const MultiLevelTemplateArgumentList &Args) {
3068
3069 SmallVector<QualType, 4> ExceptionStorage;
3071 ESI, ExceptionStorage, Args))
3072 // On error, recover by dropping the exception specification.
3073 ESI.Type = EST_None;
3074
3075 UpdateExceptionSpec(New, ESI);
3076}
3077
3078namespace {
3079
3080 struct GetContainedInventedTypeParmVisitor :
3081 public TypeVisitor<GetContainedInventedTypeParmVisitor,
3082 TemplateTypeParmDecl *> {
3083 using TypeVisitor<GetContainedInventedTypeParmVisitor,
3084 TemplateTypeParmDecl *>::Visit;
3085
3087 if (T.isNull())
3088 return nullptr;
3089 return Visit(T.getTypePtr());
3090 }
3091 // The deduced type itself.
3092 TemplateTypeParmDecl *VisitTemplateTypeParmType(
3093 const TemplateTypeParmType *T) {
3094 if (!T->getDecl() || !T->getDecl()->isImplicit())
3095 return nullptr;
3096 return T->getDecl();
3097 }
3098
3099 // Only these types can contain 'auto' types, and subsequently be replaced
3100 // by references to invented parameters.
3101
3102 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
3103 return Visit(T->getNamedType());
3104 }
3105
3106 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
3107 return Visit(T->getPointeeType());
3108 }
3109
3110 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
3111 return Visit(T->getPointeeType());
3112 }
3113
3114 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
3115 return Visit(T->getPointeeTypeAsWritten());
3116 }
3117
3118 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
3119 return Visit(T->getPointeeType());
3120 }
3121
3122 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
3123 return Visit(T->getElementType());
3124 }
3125
3126 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
3128 return Visit(T->getElementType());
3129 }
3130
3131 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3132 return Visit(T->getElementType());
3133 }
3134
3135 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3136 return VisitFunctionType(T);
3137 }
3138
3139 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3140 return Visit(T->getReturnType());
3141 }
3142
3143 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3144 return Visit(T->getInnerType());
3145 }
3146
3147 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3148 return Visit(T->getModifiedType());
3149 }
3150
3151 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3152 return Visit(T->getUnderlyingType());
3153 }
3154
3155 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3156 return Visit(T->getOriginalType());
3157 }
3158
3159 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3160 return Visit(T->getPattern());
3161 }
3162 };
3163
3164} // namespace
3165
3166namespace {
3167
3168struct ExpandPackedTypeConstraints
3169 : TreeTransform<ExpandPackedTypeConstraints> {
3170
3172
3173 const MultiLevelTemplateArgumentList &TemplateArgs;
3174
3175 ExpandPackedTypeConstraints(
3176 Sema &SemaRef, const MultiLevelTemplateArgumentList &TemplateArgs)
3177 : inherited(SemaRef), TemplateArgs(TemplateArgs) {}
3178
3179 using inherited::TransformTemplateTypeParmType;
3180
3181 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
3182 TemplateTypeParmTypeLoc TL, bool) {
3183 const TemplateTypeParmType *T = TL.getTypePtr();
3184 if (!T->isParameterPack()) {
3187 NewTL.setNameLoc(TL.getNameLoc());
3188 return TL.getType();
3189 }
3190
3191 assert(SemaRef.ArgumentPackSubstitutionIndex != -1);
3192
3193 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
3194
3195 std::optional<unsigned> PackIndex;
3196 if (Arg.getKind() == TemplateArgument::Pack)
3197 PackIndex = Arg.pack_size() - 1 - SemaRef.ArgumentPackSubstitutionIndex;
3198
3200 TL.getType(), T->getDecl(), T->getIndex(), PackIndex,
3201 SubstTemplateTypeParmTypeFlag::ExpandPacksInPlace);
3204 NewTL.setNameLoc(TL.getNameLoc());
3205 return Result;
3206 }
3207
3208 QualType TransformSubstTemplateTypeParmType(TypeLocBuilder &TLB,
3211 if (T->getPackIndex()) {
3214 TypeLoc.setNameLoc(TL.getNameLoc());
3215 return TypeLoc.getType();
3216 }
3217 return inherited::TransformSubstTemplateTypeParmType(TLB, TL);
3218 }
3219
3220 bool SubstTemplateArguments(ArrayRef<TemplateArgumentLoc> Args,
3222 return inherited::TransformTemplateArguments(Args.begin(), Args.end(), Out);
3223 }
3224};
3225
3226} // namespace
3227
3229 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3230 const MultiLevelTemplateArgumentList &TemplateArgs,
3231 bool EvaluateConstraints) {
3232 const ASTTemplateArgumentListInfo *TemplArgInfo =
3234
3235 if (!EvaluateConstraints) {
3236 bool ShouldExpandExplicitTemplateArgs =
3237 TemplArgInfo && ArgumentPackSubstitutionIndex != -1 &&
3238 llvm::any_of(TemplArgInfo->arguments(), [](auto &Arg) {
3239 return Arg.getArgument().containsUnexpandedParameterPack();
3240 });
3241
3242 // We want to transform the packs into Subst* nodes for type constraints
3243 // inside a pack expansion. For example,
3244 //
3245 // template <class... Ts> void foo() {
3246 // bar([](C<Ts> auto value) {}...);
3247 // }
3248 //
3249 // As we expand Ts in the process of instantiating foo(), and retain
3250 // the original template depths of Ts until the constraint evaluation, we
3251 // would otherwise have no chance to expand Ts by the time of evaluating
3252 // C<auto, Ts>.
3253 //
3254 // So we form a Subst* node for Ts along with a proper substitution index
3255 // here, and substitute the node with a complete MLTAL later in evaluation.
3256 if (ShouldExpandExplicitTemplateArgs) {
3257 TemplateArgumentListInfo InstArgs;
3258 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3259 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3260 if (ExpandPackedTypeConstraints(*this, TemplateArgs)
3261 .SubstTemplateArguments(TemplArgInfo->arguments(), InstArgs))
3262 return true;
3263
3264 // The type of the original parameter.
3265 auto *ConstraintExpr = TC->getImmediatelyDeclaredConstraint();
3266 QualType ConstrainedType;
3267
3268 if (auto *FE = dyn_cast<CXXFoldExpr>(ConstraintExpr)) {
3269 assert(FE->getLHS());
3270 ConstraintExpr = FE->getLHS();
3271 }
3272 auto *CSE = cast<ConceptSpecializationExpr>(ConstraintExpr);
3273 assert(!CSE->getTemplateArguments().empty() &&
3274 "Empty template arguments?");
3275 ConstrainedType = CSE->getTemplateArguments()[0].getAsType();
3276 assert(!ConstrainedType.isNull() &&
3277 "Failed to extract the original ConstrainedType?");
3278
3279 return AttachTypeConstraint(
3281 TC->getNamedConcept(),
3282 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs,
3283 Inst, ConstrainedType,
3284 Inst->isParameterPack()
3285 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3286 ->getEllipsisLoc()
3287 : SourceLocation());
3288 }
3291 return false;
3292 }
3293
3294 TemplateArgumentListInfo InstArgs;
3295
3296 if (TemplArgInfo) {
3297 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3298 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3299 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3300 InstArgs))
3301 return true;
3302 }
3303 return AttachTypeConstraint(
3305 TC->getNamedConcept(),
3306 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3308 Inst->isParameterPack()
3309 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3310 ->getEllipsisLoc()
3311 : SourceLocation());
3312}
3313
3315 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3316 int indexAdjustment, std::optional<unsigned> NumExpansions,
3317 bool ExpectParameterPack, bool EvaluateConstraint) {
3318 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3319 TypeSourceInfo *NewDI = nullptr;
3320
3321 TypeLoc OldTL = OldDI->getTypeLoc();
3322 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3323
3324 // We have a function parameter pack. Substitute into the pattern of the
3325 // expansion.
3326 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3327 OldParm->getLocation(), OldParm->getDeclName());
3328 if (!NewDI)
3329 return nullptr;
3330
3331 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3332 // We still have unexpanded parameter packs, which means that
3333 // our function parameter is still a function parameter pack.
3334 // Therefore, make its type a pack expansion type.
3335 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3336 NumExpansions);
3337 } else if (ExpectParameterPack) {
3338 // We expected to get a parameter pack but didn't (because the type
3339 // itself is not a pack expansion type), so complain. This can occur when
3340 // the substitution goes through an alias template that "loses" the
3341 // pack expansion.
3342 Diag(OldParm->getLocation(),
3343 diag::err_function_parameter_pack_without_parameter_packs)
3344 << NewDI->getType();
3345 return nullptr;
3346 }
3347 } else {
3348 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3349 OldParm->getDeclName());
3350 }
3351
3352 if (!NewDI)
3353 return nullptr;
3354
3355 if (NewDI->getType()->isVoidType()) {
3356 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3357 return nullptr;
3358 }
3359
3360 // In abbreviated templates, TemplateTypeParmDecls with possible
3361 // TypeConstraints are created when the parameter list is originally parsed.
3362 // The TypeConstraints can therefore reference other functions parameters in
3363 // the abbreviated function template, which is why we must instantiate them
3364 // here, when the instantiated versions of those referenced parameters are in
3365 // scope.
3366 if (TemplateTypeParmDecl *TTP =
3367 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3368 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3369 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3370 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3371 // We will first get here when instantiating the abbreviated function
3372 // template's described function, but we might also get here later.
3373 // Make sure we do not instantiate the TypeConstraint more than once.
3374 if (Inst && !Inst->getTypeConstraint()) {
3375 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3376 return nullptr;
3377 }
3378 }
3379 }
3380
3382 OldParm->getInnerLocStart(),
3383 OldParm->getLocation(),
3384 OldParm->getIdentifier(),
3385 NewDI->getType(), NewDI,
3386 OldParm->getStorageClass());
3387 if (!NewParm)
3388 return nullptr;
3389
3390 // Mark the (new) default argument as uninstantiated (if any).
3391 if (OldParm->hasUninstantiatedDefaultArg()) {
3392 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3393 NewParm->setUninstantiatedDefaultArg(Arg);
3394 } else if (OldParm->hasUnparsedDefaultArg()) {
3395 NewParm->setUnparsedDefaultArg();
3396 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3397 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3398 // Default arguments cannot be substituted until the declaration context
3399 // for the associated function or lambda capture class is available.
3400 // This is necessary for cases like the following where construction of
3401 // the lambda capture class for the outer lambda is dependent on the
3402 // parameter types but where the default argument is dependent on the
3403 // outer lambda's declaration context.
3404 // template <typename T>
3405 // auto f() {
3406 // return [](T = []{ return T{}; }()) { return 0; };
3407 // }
3408 NewParm->setUninstantiatedDefaultArg(Arg);
3409 }
3410
3414
3415 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3416 // Add the new parameter to the instantiated parameter pack.
3418 } else {
3419 // Introduce an Old -> New mapping
3421 }
3422
3423 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3424 // can be anything, is this right ?
3425 NewParm->setDeclContext(CurContext);
3426
3427 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3428 OldParm->getFunctionScopeIndex() + indexAdjustment);
3429
3430 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3431
3432 return NewParm;
3433}
3434
3437 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3438 const MultiLevelTemplateArgumentList &TemplateArgs,
3439 SmallVectorImpl<QualType> &ParamTypes,
3441 ExtParameterInfoBuilder &ParamInfos) {
3442 assert(!CodeSynthesisContexts.empty() &&
3443 "Cannot perform an instantiation without some context on the "
3444 "instantiation stack");
3445
3446 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3447 DeclarationName());
3448 return Instantiator.TransformFunctionTypeParams(
3449 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3450}
3451
3454 ParmVarDecl *Param,
3455 const MultiLevelTemplateArgumentList &TemplateArgs,
3456 bool ForCallExpr) {
3457 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3458 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3459
3462
3463 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3464 if (Inst.isInvalid())
3465 return true;
3466 if (Inst.isAlreadyInstantiating()) {
3467 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3468 Param->setInvalidDecl();
3469 return true;
3470 }
3471
3473 {
3474 // C++ [dcl.fct.default]p5:
3475 // The names in the [default argument] expression are bound, and
3476 // the semantic constraints are checked, at the point where the
3477 // default argument expression appears.
3478 ContextRAII SavedContext(*this, FD);
3479 std::unique_ptr<LocalInstantiationScope> LIS;
3480
3481 if (ForCallExpr) {
3482 // When instantiating a default argument due to use in a call expression,
3483 // an instantiation scope that includes the parameters of the callee is
3484 // required to satisfy references from the default argument. For example:
3485 // template<typename T> void f(T a, int = decltype(a)());
3486 // void g() { f(0); }
3487 LIS = std::make_unique<LocalInstantiationScope>(*this);
3489 /*ForDefinition*/ false);
3490 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3491 return true;
3492 }
3493
3495 Result = SubstInitializer(PatternExpr, TemplateArgs,
3496 /*DirectInit*/ false);
3497 });
3498 }
3499 if (Result.isInvalid())
3500 return true;
3501
3502 if (ForCallExpr) {
3503 // Check the expression as an initializer for the parameter.
3504 InitializedEntity Entity
3507 Param->getLocation(),
3508 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3509 Expr *ResultE = Result.getAs<Expr>();
3510
3511 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3512 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3513 if (Result.isInvalid())
3514 return true;
3515
3516 Result =
3518 /*DiscardedValue*/ false);
3519 } else {
3520 // FIXME: Obtain the source location for the '=' token.
3521 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3522 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3523 }
3524 if (Result.isInvalid())
3525 return true;
3526
3527 // Remember the instantiated default argument.
3528 Param->setDefaultArg(Result.getAs<Expr>());
3529
3530 return false;
3531}
3532
3533bool
3535 CXXRecordDecl *Pattern,
3536 const MultiLevelTemplateArgumentList &TemplateArgs) {
3537 bool Invalid = false;
3538 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3539 for (const auto &Base : Pattern->bases()) {
3540 if (!Base.getType()->isDependentType()) {
3541 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3542 if (RD->isInvalidDecl())
3543 Instantiation->setInvalidDecl();
3544 }
3545 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3546 continue;
3547 }
3548
3549 SourceLocation EllipsisLoc;
3550 TypeSourceInfo *BaseTypeLoc;
3551 if (Base.isPackExpansion()) {
3552 // This is a pack expansion. See whether we should expand it now, or
3553 // wait until later.
3555 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3556 Unexpanded);
3557 bool ShouldExpand = false;
3558 bool RetainExpansion = false;
3559 std::optional<unsigned> NumExpansions;
3560 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3561 Base.getSourceRange(),
3562 Unexpanded,
3563 TemplateArgs, ShouldExpand,
3564 RetainExpansion,
3565 NumExpansions)) {
3566 Invalid = true;
3567 continue;
3568 }
3569
3570 // If we should expand this pack expansion now, do so.
3571 if (ShouldExpand) {
3572 for (unsigned I = 0; I != *NumExpansions; ++I) {
3573 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3574
3575 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3576 TemplateArgs,
3577 Base.getSourceRange().getBegin(),
3578 DeclarationName());
3579 if (!BaseTypeLoc) {
3580 Invalid = true;
3581 continue;
3582 }
3583
3584 if (CXXBaseSpecifier *InstantiatedBase
3585 = CheckBaseSpecifier(Instantiation,
3586 Base.getSourceRange(),
3587 Base.isVirtual(),
3588 Base.getAccessSpecifierAsWritten(),
3589 BaseTypeLoc,
3590 SourceLocation()))
3591 InstantiatedBases.push_back(InstantiatedBase);
3592 else
3593 Invalid = true;
3594 }
3595
3596 continue;
3597 }
3598
3599 // The resulting base specifier will (still) be a pack expansion.
3600 EllipsisLoc = Base.getEllipsisLoc();
3601 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3602 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3603 TemplateArgs,
3604 Base.getSourceRange().getBegin(),
3605 DeclarationName());
3606 } else {
3607 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3608 TemplateArgs,
3609 Base.getSourceRange().getBegin(),
3610 DeclarationName());
3611 }
3612
3613 if (!BaseTypeLoc) {
3614 Invalid = true;
3615 continue;
3616 }
3617
3618 if (CXXBaseSpecifier *InstantiatedBase
3619 = CheckBaseSpecifier(Instantiation,
3620 Base.getSourceRange(),
3621 Base.isVirtual(),
3622 Base.getAccessSpecifierAsWritten(),
3623 BaseTypeLoc,
3624 EllipsisLoc))
3625 InstantiatedBases.push_back(InstantiatedBase);
3626 else
3627 Invalid = true;
3628 }
3629
3630 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3631 Invalid = true;
3632
3633 return Invalid;
3634}
3635
3636// Defined via #include from SemaTemplateInstantiateDecl.cpp
3637namespace clang {
3638 namespace sema {
3640 const MultiLevelTemplateArgumentList &TemplateArgs);
3642 const Attr *At, ASTContext &C, Sema &S,
3643 const MultiLevelTemplateArgumentList &TemplateArgs);
3644 }
3645}
3646
3647bool
3649 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3650 const MultiLevelTemplateArgumentList &TemplateArgs,
3652 bool Complain) {
3653 CXXRecordDecl *PatternDef
3654 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3655 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3656 Instantiation->getInstantiatedFromMemberClass(),
3657 Pattern, PatternDef, TSK, Complain))
3658 return true;
3659
3660 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3661 llvm::TimeTraceMetadata M;
3662 llvm::raw_string_ostream OS(M.Detail);
3663 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3664 /*Qualified=*/true);
3665 if (llvm::isTimeTraceVerbose()) {
3666 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3667 M.File = SourceMgr.getFilename(Loc);
3669 }
3670 return M;
3671 });
3672
3673 Pattern = PatternDef;
3674
3675 // Record the point of instantiation.
3676 if (MemberSpecializationInfo *MSInfo
3677 = Instantiation->getMemberSpecializationInfo()) {
3678 MSInfo->setTemplateSpecializationKind(TSK);
3679 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3680 } else if (ClassTemplateSpecializationDecl *Spec
3681 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3682 Spec->setTemplateSpecializationKind(TSK);
3683 Spec->setPointOfInstantiation(PointOfInstantiation);
3684 }
3685
3686 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3687 if (Inst.isInvalid())
3688 return true;
3689 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3690 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3691 "instantiating class definition");
3692
3693 // Enter the scope of this instantiation. We don't use
3694 // PushDeclContext because we don't have a scope.
3695 ContextRAII SavedContext(*this, Instantiation);
3698
3699 // If this is an instantiation of a local class, merge this local
3700 // instantiation scope with the enclosing scope. Otherwise, every
3701 // instantiation of a class has its own local instantiation scope.
3702 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3703 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3704
3705 // Some class state isn't processed immediately but delayed till class
3706 // instantiation completes. We may not be ready to handle any delayed state
3707 // already on the stack as it might correspond to a different class, so save
3708 // it now and put it back later.
3709 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3710
3711 // Pull attributes from the pattern onto the instantiation.
3712 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3713
3714 // Start the definition of this instantiation.
3715 Instantiation->startDefinition();
3716
3717 // The instantiation is visible here, even if it was first declared in an
3718 // unimported module.
3719 Instantiation->setVisibleDespiteOwningModule();
3720
3721 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3722 Instantiation->setTagKind(Pattern->getTagKind());
3723
3724 // Do substitution on the base class specifiers.
3725 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3726 Instantiation->setInvalidDecl();
3727
3728 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3729 Instantiator.setEvaluateConstraints(false);
3730 SmallVector<Decl*, 4> Fields;
3731 // Delay instantiation of late parsed attributes.
3732 LateInstantiatedAttrVec LateAttrs;
3733 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3734
3735 bool MightHaveConstexprVirtualFunctions = false;
3736 for (auto *Member : Pattern->decls()) {
3737 // Don't instantiate members not belonging in this semantic context.
3738 // e.g. for:
3739 // @code
3740 // template <int i> class A {
3741 // class B *g;
3742 // };
3743 // @endcode
3744 // 'class B' has the template as lexical context but semantically it is
3745 // introduced in namespace scope.
3746 if (Member->getDeclContext() != Pattern)
3747 continue;
3748
3749 // BlockDecls can appear in a default-member-initializer. They must be the
3750 // child of a BlockExpr, so we only know how to instantiate them from there.
3751 // Similarly, lambda closure types are recreated when instantiating the
3752 // corresponding LambdaExpr.
3753 if (isa<BlockDecl>(Member) ||
3754 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3755 continue;
3756
3757 if (Member->isInvalidDecl()) {
3758 Instantiation->setInvalidDecl();
3759 continue;
3760 }
3761
3762 Decl *NewMember = Instantiator.Visit(Member);
3763 if (NewMember) {
3764 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3765 Fields.push_back(Field);
3766 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3767 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3768 // specialization causes the implicit instantiation of the definitions
3769 // of unscoped member enumerations.
3770 // Record a point of instantiation for this implicit instantiation.
3771 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3772 Enum->isCompleteDefinition()) {
3773 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3774 assert(MSInfo && "no spec info for member enum specialization");
3776 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3777 }
3778 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3779 if (SA->isFailed()) {
3780 // A static_assert failed. Bail out; instantiating this
3781 // class is probably not meaningful.
3782 Instantiation->setInvalidDecl();
3783 break;
3784 }
3785 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3786 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3787 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3788 MightHaveConstexprVirtualFunctions = true;
3789 }
3790
3791 if (NewMember->isInvalidDecl())
3792 Instantiation->setInvalidDecl();
3793 } else {
3794 // FIXME: Eventually, a NULL return will mean that one of the
3795 // instantiations was a semantic disaster, and we'll want to mark the
3796 // declaration invalid.
3797 // For now, we expect to skip some members that we can't yet handle.
3798 }
3799 }
3800
3801 // Finish checking fields.
3802 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3804 CheckCompletedCXXClass(nullptr, Instantiation);
3805
3806 // Default arguments are parsed, if not instantiated. We can go instantiate
3807 // default arg exprs for default constructors if necessary now. Unless we're
3808 // parsing a class, in which case wait until that's finished.
3809 if (ParsingClassDepth == 0)
3811
3812 // Instantiate late parsed attributes, and attach them to their decls.
3813 // See Sema::InstantiateAttrs
3814 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3815 E = LateAttrs.end(); I != E; ++I) {
3816 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3817 CurrentInstantiationScope = I->Scope;
3818
3819 // Allow 'this' within late-parsed attributes.
3820 auto *ND = cast<NamedDecl>(I->NewDecl);
3821 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3822 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3823 ND->isCXXInstanceMember());
3824
3825 Attr *NewAttr =
3826 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3827 if (NewAttr)
3828 I->NewDecl->addAttr(NewAttr);
3830 Instantiator.getStartingScope());
3831 }
3832 Instantiator.disableLateAttributeInstantiation();
3833 LateAttrs.clear();
3834
3836
3837 // FIXME: We should do something similar for explicit instantiations so they
3838 // end up in the right module.
3839 if (TSK == TSK_ImplicitInstantiation) {
3840 Instantiation->setLocation(Pattern->getLocation());
3841 Instantiation->setLocStart(Pattern->getInnerLocStart());
3842 Instantiation->setBraceRange(Pattern->getBraceRange());
3843 }
3844
3845 if (!Instantiation->isInvalidDecl()) {
3846 // Perform any dependent diagnostics from the pattern.
3847 if (Pattern->isDependentContext())
3848 PerformDependentDiagnostics(Pattern, TemplateArgs);
3849
3850 // Instantiate any out-of-line class template partial
3851 // specializations now.
3853 P = Instantiator.delayed_partial_spec_begin(),
3854 PEnd = Instantiator.delayed_partial_spec_end();
3855 P != PEnd; ++P) {
3857 P->first, P->second)) {
3858 Instantiation->setInvalidDecl();
3859 break;
3860 }
3861 }
3862
3863 // Instantiate any out-of-line variable template partial
3864 // specializations now.
3866 P = Instantiator.delayed_var_partial_spec_begin(),
3867 PEnd = Instantiator.delayed_var_partial_spec_end();
3868 P != PEnd; ++P) {
3870 P->first, P->second)) {
3871 Instantiation->setInvalidDecl();
3872 break;
3873 }
3874 }
3875 }
3876
3877 // Exit the scope of this instantiation.
3878 SavedContext.pop();
3879
3880 if (!Instantiation->isInvalidDecl()) {
3881 // Always emit the vtable for an explicit instantiation definition
3882 // of a polymorphic class template specialization. Otherwise, eagerly
3883 // instantiate only constexpr virtual functions in preparation for their use
3884 // in constant evaluation.
3886 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3887 else if (MightHaveConstexprVirtualFunctions)
3888 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3889 /*ConstexprOnly*/ true);
3890 }
3891
3892 Consumer.HandleTagDeclDefinition(Instantiation);
3893
3894 return Instantiation->isInvalidDecl();
3895}
3896
3897bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3898 EnumDecl *Instantiation, EnumDecl *Pattern,
3899 const MultiLevelTemplateArgumentList &TemplateArgs,
3901 EnumDecl *PatternDef = Pattern->getDefinition();
3902 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3903 Instantiation->getInstantiatedFromMemberEnum(),
3904 Pattern, PatternDef, TSK,/*Complain*/true))
3905 return true;
3906 Pattern = PatternDef;
3907
3908 // Record the point of instantiation.
3909 if (MemberSpecializationInfo *MSInfo
3910 = Instantiation->getMemberSpecializationInfo()) {
3911 MSInfo->setTemplateSpecializationKind(TSK);
3912 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3913 }
3914
3915 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3916 if (Inst.isInvalid())
3917 return true;
3918 if (Inst.isAlreadyInstantiating())
3919 return false;
3920 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3921 "instantiating enum definition");
3922
3923 // The instantiation is visible here, even if it was first declared in an
3924 // unimported module.
3925 Instantiation->setVisibleDespiteOwningModule();
3926
3927 // Enter the scope of this instantiation. We don't use
3928 // PushDeclContext because we don't have a scope.
3929 ContextRAII SavedContext(*this, Instantiation);
3932
3933 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3934
3935 // Pull attributes from the pattern onto the instantiation.
3936 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3937
3938 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3939 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3940
3941 // Exit the scope of this instantiation.
3942 SavedContext.pop();
3943
3944 return Instantiation->isInvalidDecl();
3945}
3946
3948 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3949 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3950 // If there is no initializer, we don't need to do anything.
3951 if (!Pattern->hasInClassInitializer())
3952 return false;
3953
3954 assert(Instantiation->getInClassInitStyle() ==
3955 Pattern->getInClassInitStyle() &&
3956 "pattern and instantiation disagree about init style");
3957
3958 // Error out if we haven't parsed the initializer of the pattern yet because
3959 // we are waiting for the closing brace of the outer class.
3960 Expr *OldInit = Pattern->getInClassInitializer();
3961 if (!OldInit) {
3962 RecordDecl *PatternRD = Pattern->getParent();
3963 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3964 Diag(PointOfInstantiation,
3965 diag::err_default_member_initializer_not_yet_parsed)
3966 << OutermostClass << Pattern;
3967 Diag(Pattern->getEndLoc(),
3968 diag::note_default_member_initializer_not_yet_parsed);
3969 Instantiation->setInvalidDecl();
3970 return true;
3971 }
3972
3973 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3974 if (Inst.isInvalid())
3975 return true;
3976 if (Inst.isAlreadyInstantiating()) {
3977 // Error out if we hit an instantiation cycle for this initializer.
3978 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3979 << Instantiation;
3980 return true;
3981 }
3982 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3983 "instantiating default member init");
3984
3985 // Enter the scope of this instantiation. We don't use PushDeclContext because
3986 // we don't have a scope.
3987 ContextRAII SavedContext(*this, Instantiation->getParent());
3990 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3991 PointOfInstantiation, Instantiation, CurContext};
3992
3993 LocalInstantiationScope Scope(*this, true);
3994
3995 // Instantiate the initializer.
3997 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3998
3999 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
4000 /*CXXDirectInit=*/false);
4001 Expr *Init = NewInit.get();
4002 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
4004 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
4005
4006 if (auto *L = getASTMutationListener())
4007 L->DefaultMemberInitializerInstantiated(Instantiation);
4008
4009 // Return true if the in-class initializer is still missing.
4010 return !Instantiation->getInClassInitializer();
4011}
4012
4013namespace {
4014 /// A partial specialization whose template arguments have matched
4015 /// a given template-id.
4016 struct PartialSpecMatchResult {
4019 };
4020}
4021
4024 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
4026 return true;
4027
4029 ClassTemplateDecl *CTD = ClassTemplateSpec->getSpecializedTemplate();
4030 CTD->getPartialSpecializations(PartialSpecs);
4031 for (ClassTemplatePartialSpecializationDecl *CTPSD : PartialSpecs) {
4032 // C++ [temp.spec.partial.member]p2:
4033 // If the primary member template is explicitly specialized for a given
4034 // (implicit) specialization of the enclosing class template, the partial
4035 // specializations of the member template are ignored for this
4036 // specialization of the enclosing class template. If a partial
4037 // specialization of the member template is explicitly specialized for a
4038 // given (implicit) specialization of the enclosing class template, the
4039 // primary member template and its other partial specializations are still
4040 // considered for this specialization of the enclosing class template.
4042 !CTPSD->getMostRecentDecl()->isMemberSpecialization())
4043 continue;
4044
4046 if (DeduceTemplateArguments(CTPSD,
4047 ClassTemplateSpec->getTemplateArgs().asArray(),
4049 return true;
4050 }
4051
4052 return false;
4053}
4054
4055/// Get the instantiation pattern to use to instantiate the definition of a
4056/// given ClassTemplateSpecializationDecl (either the pattern of the primary
4057/// template or of a partial specialization).
4059 Sema &S, SourceLocation PointOfInstantiation,
4060 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4062 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4063 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
4064 if (Inst.isInvalid())
4065 return {/*Invalid=*/true};
4066 if (Inst.isAlreadyInstantiating())
4067 return {/*Invalid=*/false};
4068
4069 llvm::PointerUnion<ClassTemplateDecl *,
4071 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4072 if (!isa<ClassTemplatePartialSpecializationDecl *>(Specialized)) {
4073 // Find best matching specialization.
4074 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4075
4076 // C++ [temp.class.spec.match]p1:
4077 // When a class template is used in a context that requires an
4078 // instantiation of the class, it is necessary to determine
4079 // whether the instantiation is to be generated using the primary
4080 // template or one of the partial specializations. This is done by
4081 // matching the template arguments of the class template
4082 // specialization with the template argument lists of the partial
4083 // specializations.
4084 typedef PartialSpecMatchResult MatchResult;
4085 SmallVector<MatchResult, 4> Matched, ExtraMatched;
4087 Template->getPartialSpecializations(PartialSpecs);
4088 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
4089 for (ClassTemplatePartialSpecializationDecl *Partial : PartialSpecs) {
4090 // C++ [temp.spec.partial.member]p2:
4091 // If the primary member template is explicitly specialized for a given
4092 // (implicit) specialization of the enclosing class template, the
4093 // partial specializations of the member template are ignored for this
4094 // specialization of the enclosing class template. If a partial
4095 // specialization of the member template is explicitly specialized for a
4096 // given (implicit) specialization of the enclosing class template, the
4097 // primary member template and its other partial specializations are
4098 // still considered for this specialization of the enclosing class
4099 // template.
4100 if (Template->getMostRecentDecl()->isMemberSpecialization() &&
4101 !Partial->getMostRecentDecl()->isMemberSpecialization())
4102 continue;
4103
4104 TemplateDeductionInfo Info(FailedCandidates.getLocation());
4106 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
4108 // Store the failed-deduction information for use in diagnostics, later.
4109 // TODO: Actually use the failed-deduction info?
4110 FailedCandidates.addCandidate().set(
4111 DeclAccessPair::make(Template, AS_public), Partial,
4113 (void)Result;
4114 } else {
4115 auto &List =
4116 Info.hasMatchedPackOnParmToNonPackOnArg() ? ExtraMatched : Matched;
4117 List.push_back(MatchResult{Partial, Info.takeCanonical()});
4118 }
4119 }
4120 if (Matched.empty() && PrimaryHasMatchedPackOnParmToNonPackOnArg)
4121 Matched = std::move(ExtraMatched);
4122
4123 // If we're dealing with a member template where the template parameters
4124 // have been instantiated, this provides the original template parameters
4125 // from which the member template's parameters were instantiated.
4126
4127 if (Matched.size() >= 1) {
4128 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
4129 if (Matched.size() == 1) {
4130 // -- If exactly one matching specialization is found, the
4131 // instantiation is generated from that specialization.
4132 // We don't need to do anything for this.
4133 } else {
4134 // -- If more than one matching specialization is found, the
4135 // partial order rules (14.5.4.2) are used to determine
4136 // whether one of the specializations is more specialized
4137 // than the others. If none of the specializations is more
4138 // specialized than all of the other matching
4139 // specializations, then the use of the class template is
4140 // ambiguous and the program is ill-formed.
4142 PEnd = Matched.end();
4143 P != PEnd; ++P) {
4145 P->Partial, Best->Partial, PointOfInstantiation) ==
4146 P->Partial)
4147 Best = P;
4148 }
4149
4150 // Determine if the best partial specialization is more specialized than
4151 // the others.
4152 bool Ambiguous = false;
4153 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4154 PEnd = Matched.end();
4155 P != PEnd; ++P) {
4157 P->Partial, Best->Partial,
4158 PointOfInstantiation) != Best->Partial) {
4159 Ambiguous = true;
4160 break;
4161 }
4162 }
4163
4164 if (Ambiguous) {
4165 // Partial ordering did not produce a clear winner. Complain.
4166 Inst.Clear();
4167 ClassTemplateSpec->setInvalidDecl();
4168 S.Diag(PointOfInstantiation,
4169 diag::err_partial_spec_ordering_ambiguous)
4170 << ClassTemplateSpec;
4171
4172 // Print the matching partial specializations.
4173 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
4174 PEnd = Matched.end();
4175 P != PEnd; ++P)
4176 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
4178 P->Partial->getTemplateParameters(), *P->Args);
4179
4180 return {/*Invalid=*/true};
4181 }
4182 }
4183
4184 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
4185 } else {
4186 // -- If no matches are found, the instantiation is generated
4187 // from the primary template.
4188 }
4189 }
4190
4191 CXXRecordDecl *Pattern = nullptr;
4192 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
4193 if (auto *PartialSpec =
4194 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
4195 // Instantiate using the best class template partial specialization.
4196 while (PartialSpec->getInstantiatedFromMember()) {
4197 // If we've found an explicit specialization of this class template,
4198 // stop here and use that as the pattern.
4199 if (PartialSpec->isMemberSpecialization())
4200 break;
4201
4202 PartialSpec = PartialSpec->getInstantiatedFromMember();
4203 }
4204 Pattern = PartialSpec;
4205 } else {
4206 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
4207 while (Template->getInstantiatedFromMemberTemplate()) {
4208 // If we've found an explicit specialization of this class template,
4209 // stop here and use that as the pattern.
4210 if (Template->isMemberSpecialization())
4211 break;
4212
4213 Template = Template->getInstantiatedFromMemberTemplate();
4214 }
4215 Pattern = Template->getTemplatedDecl();
4216 }
4217
4218 return Pattern;
4219}
4220
4222 SourceLocation PointOfInstantiation,
4223 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4224 TemplateSpecializationKind TSK, bool Complain,
4225 bool PrimaryHasMatchedPackOnParmToNonPackOnArg) {
4226 // Perform the actual instantiation on the canonical declaration.
4227 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
4228 ClassTemplateSpec->getCanonicalDecl());
4229 if (ClassTemplateSpec->isInvalidDecl())
4230 return true;
4231
4234 *this, PointOfInstantiation, ClassTemplateSpec, TSK,
4235 PrimaryHasMatchedPackOnParmToNonPackOnArg);
4236 if (!Pattern.isUsable())
4237 return Pattern.isInvalid();
4238
4239 return InstantiateClass(
4240 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
4241 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
4242}
4243
4244void
4246 CXXRecordDecl *Instantiation,
4247 const MultiLevelTemplateArgumentList &TemplateArgs,
4249 // FIXME: We need to notify the ASTMutationListener that we did all of these
4250 // things, in case we have an explicit instantiation definition in a PCM, a
4251 // module, or preamble, and the declaration is in an imported AST.
4252 assert(
4255 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
4256 "Unexpected template specialization kind!");
4257 for (auto *D : Instantiation->decls()) {
4258 bool SuppressNew = false;
4259 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
4260 if (FunctionDecl *Pattern =
4261 Function->getInstantiatedFromMemberFunction()) {
4262
4263 if (Function->isIneligibleOrNotSelected())
4264 continue;
4265
4266 if (Function->getTrailingRequiresClause()) {
4267 ConstraintSatisfaction Satisfaction;
4268 if (CheckFunctionConstraints(Function, Satisfaction) ||
4269 !Satisfaction.IsSatisfied) {
4270 continue;
4271 }
4272 }
4273
4274 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4275 continue;
4276
4278 Function->getTemplateSpecializationKind();
4279 if (PrevTSK == TSK_ExplicitSpecialization)
4280 continue;
4281
4283 PointOfInstantiation, TSK, Function, PrevTSK,
4284 Function->getPointOfInstantiation(), SuppressNew) ||
4285 SuppressNew)
4286 continue;
4287
4288 // C++11 [temp.explicit]p8:
4289 // An explicit instantiation definition that names a class template
4290 // specialization explicitly instantiates the class template
4291 // specialization and is only an explicit instantiation definition
4292 // of members whose definition is visible at the point of
4293 // instantiation.
4294 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4295 continue;
4296
4297 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4298
4299 if (Function->isDefined()) {
4300 // Let the ASTConsumer know that this function has been explicitly
4301 // instantiated now, and its linkage might have changed.
4303 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4304 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4305 } else if (TSK == TSK_ImplicitInstantiation) {
4307 std::make_pair(Function, PointOfInstantiation));
4308 }
4309 }
4310 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4311 if (isa<VarTemplateSpecializationDecl>(Var))
4312 continue;
4313
4314 if (Var->isStaticDataMember()) {
4315 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4316 continue;
4317
4319 assert(MSInfo && "No member specialization information?");
4320 if (MSInfo->getTemplateSpecializationKind()
4322 continue;
4323
4324 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4325 Var,
4327 MSInfo->getPointOfInstantiation(),
4328 SuppressNew) ||
4329 SuppressNew)
4330 continue;
4331
4333 // C++0x [temp.explicit]p8:
4334 // An explicit instantiation definition that names a class template
4335 // specialization explicitly instantiates the class template
4336 // specialization and is only an explicit instantiation definition
4337 // of members whose definition is visible at the point of
4338 // instantiation.
4340 continue;
4341
4342 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4343 InstantiateVariableDefinition(PointOfInstantiation, Var);
4344 } else {
4345 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4346 }
4347 }
4348 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4349 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4350 continue;
4351
4352 // Always skip the injected-class-name, along with any
4353 // redeclarations of nested classes, since both would cause us
4354 // to try to instantiate the members of a class twice.
4355 // Skip closure types; they'll get instantiated when we instantiate
4356 // the corresponding lambda-expression.
4357 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4358 Record->isLambda())
4359 continue;
4360
4361 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4362 assert(MSInfo && "No member specialization information?");
4363
4364 if (MSInfo->getTemplateSpecializationKind()
4366 continue;
4367
4368 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4370 // On Windows, explicit instantiation decl of the outer class doesn't
4371 // affect the inner class. Typically extern template declarations are
4372 // used in combination with dll import/export annotations, but those
4373 // are not propagated from the outer class templates to inner classes.
4374 // Therefore, do not instantiate inner classes on this platform, so
4375 // that users don't end up with undefined symbols during linking.
4376 continue;
4377 }
4378
4379 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4380 Record,
4382 MSInfo->getPointOfInstantiation(),
4383 SuppressNew) ||
4384 SuppressNew)
4385 continue;
4386
4388 assert(Pattern && "Missing instantiated-from-template information");
4389
4390 if (!Record->getDefinition()) {
4391 if (!Pattern->getDefinition()) {
4392 // C++0x [temp.explicit]p8:
4393 // An explicit instantiation definition that names a class template
4394 // specialization explicitly instantiates the class template
4395 // specialization and is only an explicit instantiation definition
4396 // of members whose definition is visible at the point of
4397 // instantiation.
4399 MSInfo->setTemplateSpecializationKind(TSK);
4400 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4401 }
4402
4403 continue;
4404 }
4405
4406 InstantiateClass(PointOfInstantiation, Record, Pattern,
4407 TemplateArgs,
4408 TSK);
4409 } else {
4411 Record->getTemplateSpecializationKind() ==
4413 Record->setTemplateSpecializationKind(TSK);
4414 MarkVTableUsed(PointOfInstantiation, Record, true);
4415 }
4416 }
4417
4418 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4419 if (Pattern)
4420 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4421 TSK);
4422 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4423 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4424 assert(MSInfo && "No member specialization information?");
4425
4426 if (MSInfo->getTemplateSpecializationKind()
4428 continue;
4429
4431 PointOfInstantiation, TSK, Enum,
4433 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4434 SuppressNew)
4435 continue;
4436
4437 if (Enum->getDefinition())
4438 continue;
4439
4440 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4441 assert(Pattern && "Missing instantiated-from-template information");
4442
4444 if (!Pattern->getDefinition())
4445 continue;
4446
4447 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4448 } else {
4449 MSInfo->setTemplateSpecializationKind(TSK);
4450 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4451 }
4452 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4453 // No need to instantiate in-class initializers during explicit
4454 // instantiation.
4455 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4456 CXXRecordDecl *ClassPattern =
4457 Instantiation->getTemplateInstantiationPattern();
4459 ClassPattern->lookup(Field->getDeclName());
4460 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4461 assert(Pattern);
4462 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4463 TemplateArgs);
4464 }
4465 }
4466 }
4467}
4468
4469void
4471 SourceLocation PointOfInstantiation,
4472 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4474 // C++0x [temp.explicit]p7:
4475 // An explicit instantiation that names a class template
4476 // specialization is an explicit instantion of the same kind
4477 // (declaration or definition) of each of its members (not
4478 // including members inherited from base classes) that has not
4479 // been previously explicitly specialized in the translation unit
4480 // containing the explicit instantiation, except as described
4481 // below.
4482 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4483 getTemplateInstantiationArgs(ClassTemplateSpec),
4484 TSK);
4485}
4486
4489 if (!S)
4490 return S;
4491
4492 TemplateInstantiator Instantiator(*this, TemplateArgs,
4494 DeclarationName());
4495 return Instantiator.TransformStmt(S);
4496}
4497
4499 const TemplateArgumentLoc &Input,
4500 const MultiLevelTemplateArgumentList &TemplateArgs,
4502 const DeclarationName &Entity) {
4503 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4504 return Instantiator.TransformTemplateArgument(Input, Output);
4505}
4506
4509 const MultiLevelTemplateArgumentList &TemplateArgs,
4511 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4512 DeclarationName());
4513 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4514}
4515
4518 if (!E)
4519 return E;
4520
4521 TemplateInstantiator Instantiator(*this, TemplateArgs,
4523 DeclarationName());
4524 return Instantiator.TransformExpr(E);
4525}
4526
4529 const MultiLevelTemplateArgumentList &TemplateArgs) {
4530 // FIXME: should call SubstExpr directly if this function is equivalent or
4531 // should it be different?
4532 return SubstExpr(E, TemplateArgs);
4533}
4534
4536 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4537 if (!E)
4538 return E;
4539
4540 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4541 DeclarationName());
4542 Instantiator.setEvaluateConstraints(false);
4543 return Instantiator.TransformExpr(E);
4544}
4545
4547 const MultiLevelTemplateArgumentList &TemplateArgs,
4548 bool CXXDirectInit) {
4549 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4550 DeclarationName());
4551 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4552}
4553
4554bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4555 const MultiLevelTemplateArgumentList &TemplateArgs,
4556 SmallVectorImpl<Expr *> &Outputs) {
4557 if (Exprs.empty())
4558 return false;
4559
4560 TemplateInstantiator Instantiator(*this, TemplateArgs,
4562 DeclarationName());
4563 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4564 IsCall, Outputs);
4565}
4566
4569 const MultiLevelTemplateArgumentList &TemplateArgs) {
4570 if (!NNS)
4571 return NestedNameSpecifierLoc();
4572
4573 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4574 DeclarationName());
4575 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4576}
4577
4580 const MultiLevelTemplateArgumentList &TemplateArgs) {
4581 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4582 NameInfo.getName());
4583 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4584}
4585
4589 const MultiLevelTemplateArgumentList &TemplateArgs) {
4590 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4591 DeclarationName());
4592 CXXScopeSpec SS;
4593 SS.Adopt(QualifierLoc);
4594 return Instantiator.TransformTemplateName(SS, Name, Loc);
4595}
4596
4597static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4598 // When storing ParmVarDecls in the local instantiation scope, we always
4599 // want to use the ParmVarDecl from the canonical function declaration,
4600 // since the map is then valid for any redeclaration or definition of that
4601 // function.
4602 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4603 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4604 unsigned i = PV->getFunctionScopeIndex();
4605 // This parameter might be from a freestanding function type within the
4606 // function and isn't necessarily referring to one of FD's parameters.
4607 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4608 return FD->getCanonicalDecl()->getParamDecl(i);
4609 }
4610 }
4611 return D;
4612}
4613
4614
4615llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4618 for (LocalInstantiationScope *Current = this; Current;
4619 Current = Current->Outer) {
4620
4621 // Check if we found something within this scope.
4622 const Decl *CheckD = D;
4623 do {
4624 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4625 if (Found != Current->LocalDecls.end())
4626 return &Found->second;
4627
4628 // If this is a tag declaration, it's possible that we need to look for
4629 // a previous declaration.
4630 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4631 CheckD = Tag->getPreviousDecl();
4632 else
4633 CheckD = nullptr;
4634 } while (CheckD);
4635
4636 // If we aren't combined with our outer scope, we're done.
4637 if (!Current->CombineWithOuterScope)
4638 break;
4639 }
4640
4641 // If we're performing a partial substitution during template argument
4642 // deduction, we may not have values for template parameters yet.
4643 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4644 isa<TemplateTemplateParmDecl>(D))
4645 return nullptr;
4646
4647 // Local types referenced prior to definition may require instantiation.
4648 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4649 if (RD->isLocalClass())
4650 return nullptr;
4651
4652 // Enumeration types referenced prior to definition may appear as a result of
4653 // error recovery.
4654 if (isa<EnumDecl>(D))
4655 return nullptr;
4656
4657 // Materialized typedefs/type alias for implicit deduction guides may require
4658 // instantiation.
4659 if (isa<TypedefNameDecl>(D) &&
4660 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4661 return nullptr;
4662
4663 // If we didn't find the decl, then we either have a sema bug, or we have a
4664 // forward reference to a label declaration. Return null to indicate that
4665 // we have an uninstantiated label.
4666 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4667 return nullptr;
4668}
4669
4672 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4673 if (Stored.isNull()) {
4674#ifndef NDEBUG
4675 // It should not be present in any surrounding scope either.
4676 LocalInstantiationScope *Current = this;
4677 while (Current->CombineWithOuterScope && Current->Outer) {
4678 Current = Current->Outer;
4679 assert(!Current->LocalDecls.contains(D) &&
4680 "Instantiated local in inner and outer scopes");
4681 }
4682#endif
4683 Stored = Inst;
4684 } else if (DeclArgumentPack *Pack = dyn_cast<DeclArgumentPack *>(Stored)) {
4685 Pack->push_back(cast<VarDecl>(Inst));
4686 } else {
4687 assert(cast<Decl *>(Stored) == Inst && "Already instantiated this local");
4688 }
4689}
4690
4692 VarDecl *Inst) {
4694 DeclArgumentPack *Pack = cast<DeclArgumentPack *>(LocalDecls[D]);
4695 Pack->push_back(Inst);
4696}
4697
4699#ifndef NDEBUG
4700 // This should be the first time we've been told about this decl.
4701 for (LocalInstantiationScope *Current = this;
4702 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4703 assert(!Current->LocalDecls.contains(D) &&
4704 "Creating local pack after instantiation of local");
4705#endif
4706
4708 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4710 Stored = Pack;
4711 ArgumentPacks.push_back(Pack);
4712}
4713
4715 for (DeclArgumentPack *Pack : ArgumentPacks)
4716 if (llvm::is_contained(*Pack, D))
4717 return true;
4718 return false;
4719}
4720
4722 const TemplateArgument *ExplicitArgs,
4723 unsigned NumExplicitArgs) {
4724 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4725 "Already have a partially-substituted pack");
4726 assert((!PartiallySubstitutedPack
4727 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4728 "Wrong number of arguments in partially-substituted pack");
4729 PartiallySubstitutedPack = Pack;
4730 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4731 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4732}
4733
4735 const TemplateArgument **ExplicitArgs,
4736 unsigned *NumExplicitArgs) const {
4737 if (ExplicitArgs)
4738 *ExplicitArgs = nullptr;
4739 if (NumExplicitArgs)
4740 *NumExplicitArgs = 0;
4741
4742 for (const LocalInstantiationScope *Current = this; Current;
4743 Current = Current->Outer) {
4744 if (Current->PartiallySubstitutedPack) {
4745 if (ExplicitArgs)
4746 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4747 if (NumExplicitArgs)
4748 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4749
4750 return Current->PartiallySubstitutedPack;
4751 }
4752
4753 if (!Current->CombineWithOuterScope)
4754 break;
4755 }
4756
4757 return nullptr;
4758}
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:1122
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:3358
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3578
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:6133
A binding in a decomposition declaration.
Definition: DeclCXX.h:4169
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6414
Pointer to a block type.
Definition: Type.h:3409
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:2117
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:2037
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:2012
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:2004
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:2023
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:2177
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:2366
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:796
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:781
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:790
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:768
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1904
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3961
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1497
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:875
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:656
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:6949
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3868
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4127
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:4953
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4979
EnumDecl * getDefinition() const
Definition: Decl.h:3971
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:3040
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4596
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3215
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3209
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3271
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:2656
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:4135
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4184
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2405
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:4652
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4686
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:5108
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5372
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:4348
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4322
QualType getReturnType() const
Definition: Type.h:4649
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:6799
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:5771
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3520
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:7147
Sugar for parentheses used when specifying types.
Definition: Type.h:3173
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:2983
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:3008
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:2971
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:3013
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:3199
[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:3519
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:8140
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:4169
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:6078
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:3440
Represents the body of a requires-expression.
Definition: DeclCXX.h:2086
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:13243
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8062
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3013
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5894
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5926
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5923
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12646
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12116
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:466
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13193
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:13177
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12675
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)
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:13180
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:13538
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:11656
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:911
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:13204
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:531
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:534
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:819
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:16979
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, CheckTemplateArgumentInfo &CTAI, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:527
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:14426
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:13229
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:3651
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:12687
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:13237
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1046
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:13587
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15213
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:20995
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:13213
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:5501
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:912
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:13221
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:19023
bool RebuildingImmediateInvocation
Whether the AST is currently being rebuilt to correct immediate invocations.
Definition: Sema.h:7781
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:7931
SourceManager & SourceMgr
Definition: Sema.h:914
DiagnosticsEngine & Diags
Definition: Sema.h:913
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:13188
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:21192
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:8282
TypeSourceInfo * SubstFunctionDeclType(TypeSourceInfo *T, const MultiLevelTemplateArgumentList &TemplateArgs, SourceLocation Loc, DeclarationName Entity, CXXRecordDecl *ThisContext, Qualifiers ThisTypeQuals, bool EvaluateConstraints=true)
A form of SubstType intended specifically for instantiating the type of a FunctionDecl.
Encodes a location in the source.
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:4120
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:4488
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4573
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:6470
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:6389
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3585
void setTagKind(TagKind TK)
Definition: Decl.h:3784
SourceRange getBraceRange() const
Definition: Decl.h:3664
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3669
StringRef getKindName() const
Definition: Decl.h:3776
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4778
TagKind getTagKind() const
Definition: Decl.h:3780
void setBraceRange(SourceRange R)
Definition: Decl.h:3665
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:6667
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:6350
unsigned getIndex() const
Definition: Type.h:6349
unsigned getDepth() const
Definition: Type.h:6348
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:3420
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:7908
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:7919
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:3211
The base class of the type hierarchy.
Definition: Type.h:1828
bool isVoidType() const
Definition: Type.h:8516
bool isReferenceType() const
Definition: Type.h:8210
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:2715
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2707
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:2725
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8741
bool isRecordType() const
Definition: Type.h:8292
QualType getUnderlyingType() const
Definition: Decl.h:3489
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
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition: Decl.cpp:5420
Represents a variable declaration or definition.
Definition: Decl.h:886
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1238
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:2744
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:2879
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1123
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2870
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:4035
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:89
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:28
@ 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:6877
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:367
@ 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:6852
@ 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:5165
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5167
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5200
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12692
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:12856
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:12825
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:12851
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:12820
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12812
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12694
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12786
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:12704
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12713
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:12732
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12783
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:12740
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:12747
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12790
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:12758
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12796
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:12723
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:12802
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12799
@ PartialOrderingTTP
We are performing partial ordering for template template parameters.
Definition: Sema.h:12805
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12720
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:12728
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12736
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:12697
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12750
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12754
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12709
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12780
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:12743
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12815
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:12880
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13040
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:13044
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)
Contains all information for a given match.