clang 20.0.0git
SemaTemplateInstantiate.cpp
Go to the documentation of this file.
1//===------- SemaTemplateInstantiate.cpp - C++ Template Instantiation ------===/
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//===----------------------------------------------------------------------===/
7//
8// This file implements C++ template instantiation.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
16#include "clang/AST/ASTLambda.h"
18#include "clang/AST/DeclBase.h"
20#include "clang/AST/Expr.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/Stack.h"
29#include "clang/Sema/DeclSpec.h"
32#include "clang/Sema/Lookup.h"
33#include "clang/Sema/Sema.h"
36#include "clang/Sema/Template.h"
39#include "llvm/ADT/STLForwardCompat.h"
40#include "llvm/ADT/StringExtras.h"
41#include "llvm/Support/ErrorHandling.h"
42#include "llvm/Support/SaveAndRestore.h"
43#include "llvm/Support/TimeProfiler.h"
44#include <optional>
45
46using namespace clang;
47using namespace sema;
48
49//===----------------------------------------------------------------------===/
50// Template Instantiation Support
51//===----------------------------------------------------------------------===/
52
53namespace {
55struct Response {
56 const Decl *NextDecl = nullptr;
57 bool IsDone = false;
58 bool ClearRelativeToPrimary = true;
59 static Response Done() {
60 Response R;
61 R.IsDone = true;
62 return R;
63 }
64 static Response ChangeDecl(const Decl *ND) {
65 Response R;
66 R.NextDecl = ND;
67 return R;
68 }
69 static Response ChangeDecl(const DeclContext *Ctx) {
70 Response R;
71 R.NextDecl = Decl::castFromDeclContext(Ctx);
72 return R;
73 }
74
75 static Response UseNextDecl(const Decl *CurDecl) {
76 return ChangeDecl(CurDecl->getDeclContext());
77 }
78
79 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
80 Response R = Response::UseNextDecl(CurDecl);
81 R.ClearRelativeToPrimary = false;
82 return R;
83 }
84};
85
86// Retrieve the primary template for a lambda call operator. It's
87// unfortunate that we only have the mappings of call operators rather
88// than lambda classes.
89const FunctionDecl *
90getPrimaryTemplateOfGenericLambda(const FunctionDecl *LambdaCallOperator) {
91 while (true) {
92 if (auto *FTD = dyn_cast_if_present<FunctionTemplateDecl>(
93 LambdaCallOperator->getDescribedTemplate());
94 FTD && FTD->getInstantiatedFromMemberTemplate()) {
95 LambdaCallOperator =
96 FTD->getInstantiatedFromMemberTemplate()->getTemplatedDecl();
97 } else if (auto *Prev = cast<CXXMethodDecl>(LambdaCallOperator)
98 ->getInstantiatedFromMemberFunction())
99 LambdaCallOperator = Prev;
100 else
101 break;
102 }
103 return LambdaCallOperator;
104}
105
106struct EnclosingTypeAliasTemplateDetails {
107 TypeAliasTemplateDecl *Template = nullptr;
108 TypeAliasTemplateDecl *PrimaryTypeAliasDecl = nullptr;
109 ArrayRef<TemplateArgument> AssociatedTemplateArguments;
110
111 explicit operator bool() noexcept { return Template; }
112};
113
114// Find the enclosing type alias template Decl from CodeSynthesisContexts, as
115// well as its primary template and instantiating template arguments.
116EnclosingTypeAliasTemplateDetails
117getEnclosingTypeAliasTemplateDecl(Sema &SemaRef) {
118 for (auto &CSC : llvm::reverse(SemaRef.CodeSynthesisContexts)) {
120 TypeAliasTemplateInstantiation)
121 continue;
122 EnclosingTypeAliasTemplateDetails Result;
123 auto *TATD = cast<TypeAliasTemplateDecl>(CSC.Entity),
124 *Next = TATD->getInstantiatedFromMemberTemplate();
125 Result = {
126 /*Template=*/TATD,
127 /*PrimaryTypeAliasDecl=*/TATD,
128 /*AssociatedTemplateArguments=*/CSC.template_arguments(),
129 };
130 while (Next) {
131 Result.PrimaryTypeAliasDecl = Next;
132 Next = Next->getInstantiatedFromMemberTemplate();
133 }
134 return Result;
135 }
136 return {};
137}
138
139// Check if we are currently inside of a lambda expression that is
140// surrounded by a using alias declaration. e.g.
141// template <class> using type = decltype([](auto) { ^ }());
142// By checking if:
143// 1. The lambda expression and the using alias declaration share the
144// same declaration context.
145// 2. They have the same template depth.
146// We have to do so since a TypeAliasTemplateDecl (or a TypeAliasDecl) is never
147// a DeclContext, nor does it have an associated specialization Decl from which
148// we could collect these template arguments.
149bool isLambdaEnclosedByTypeAliasDecl(
150 const FunctionDecl *PrimaryLambdaCallOperator,
151 const TypeAliasTemplateDecl *PrimaryTypeAliasDecl) {
152 return cast<CXXRecordDecl>(PrimaryLambdaCallOperator->getDeclContext())
153 ->getTemplateDepth() ==
154 PrimaryTypeAliasDecl->getTemplateDepth() &&
156 const_cast<FunctionDecl *>(PrimaryLambdaCallOperator)) ==
157 PrimaryTypeAliasDecl->getDeclContext();
158}
159
160// Add template arguments from a variable template instantiation.
161Response
162HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
164 bool SkipForSpecialization) {
165 // For a class-scope explicit specialization, there are no template arguments
166 // at this level, but there may be enclosing template arguments.
167 if (VarTemplSpec->isClassScopeExplicitSpecialization())
168 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
169
170 // We're done when we hit an explicit specialization.
171 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
172 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
173 return Response::Done();
174
175 // If this variable template specialization was instantiated from a
176 // specialized member that is a variable template, we're done.
177 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?");
178 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
179 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
181 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
182 if (!SkipForSpecialization)
183 Result.addOuterTemplateArguments(
184 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
185 /*Final=*/false);
186 if (Partial->isMemberSpecialization())
187 return Response::Done();
188 } else {
189 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
190 if (!SkipForSpecialization)
191 Result.addOuterTemplateArguments(
192 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
193 /*Final=*/false);
194 if (Tmpl->isMemberSpecialization())
195 return Response::Done();
196 }
197 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
198}
199
200// If we have a template template parameter with translation unit context,
201// then we're performing substitution into a default template argument of
202// this template template parameter before we've constructed the template
203// that will own this template template parameter. In this case, we
204// use empty template parameter lists for all of the outer templates
205// to avoid performing any substitutions.
206Response
207HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
209 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
210 Result.addOuterTemplateArguments(std::nullopt);
211 return Response::Done();
212}
213
214Response HandlePartialClassTemplateSpec(
215 const ClassTemplatePartialSpecializationDecl *PartialClassTemplSpec,
216 MultiLevelTemplateArgumentList &Result, bool SkipForSpecialization) {
217 if (!SkipForSpecialization)
218 Result.addOuterRetainedLevels(PartialClassTemplSpec->getTemplateDepth());
219 return Response::Done();
220}
221
222// Add template arguments from a class template instantiation.
223Response
224HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
226 bool SkipForSpecialization) {
227 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
228 // We're done when we hit an explicit specialization.
229 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
230 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
231 return Response::Done();
232
233 if (!SkipForSpecialization)
234 Result.addOuterTemplateArguments(
235 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
236 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
237 /*Final=*/false);
238
239 // If this class template specialization was instantiated from a
240 // specialized member that is a class template, we're done.
241 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?");
242 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
243 return Response::Done();
244
245 // If this was instantiated from a partial template specialization, we need
246 // to get the next level of declaration context from the partial
247 // specialization, as the ClassTemplateSpecializationDecl's
248 // DeclContext/LexicalDeclContext will be for the primary template.
249 if (auto *InstFromPartialTempl = ClassTemplSpec->getSpecializedTemplateOrPartial()
251 return Response::ChangeDecl(InstFromPartialTempl->getLexicalDeclContext());
252 }
253 return Response::UseNextDecl(ClassTemplSpec);
254}
255
256Response HandleFunction(Sema &SemaRef, const FunctionDecl *Function,
258 const FunctionDecl *Pattern, bool RelativeToPrimary,
259 bool ForConstraintInstantiation,
260 bool ForDefaultArgumentSubstitution) {
261 // Add template arguments from a function template specialization.
262 if (!RelativeToPrimary &&
263 Function->getTemplateSpecializationKindForInstantiation() ==
265 return Response::Done();
266
267 if (!RelativeToPrimary &&
268 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
269 // This is an implicit instantiation of an explicit specialization. We
270 // don't get any template arguments from this function but might get
271 // some from an enclosing template.
272 return Response::UseNextDecl(Function);
273 } else if (const TemplateArgumentList *TemplateArgs =
274 Function->getTemplateSpecializationArgs()) {
275 // Add the template arguments for this specialization.
276 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
277 TemplateArgs->asArray(),
278 /*Final=*/false);
279
280 if (RelativeToPrimary &&
281 (Function->getTemplateSpecializationKind() ==
283 (Function->getFriendObjectKind() &&
284 !Function->getPrimaryTemplate()->getFriendObjectKind())))
285 return Response::UseNextDecl(Function);
286
287 // If this function was instantiated from a specialized member that is
288 // a function template, we're done.
289 assert(Function->getPrimaryTemplate() && "No function template?");
290 if (!ForDefaultArgumentSubstitution &&
291 Function->getPrimaryTemplate()->isMemberSpecialization())
292 return Response::Done();
293
294 // If this function is a generic lambda specialization, we are done.
295 if (!ForConstraintInstantiation &&
297 // TypeAliasTemplateDecls should be taken into account, e.g.
298 // when we're deducing the return type of a lambda.
299 //
300 // template <class> int Value = 0;
301 // template <class T>
302 // using T = decltype([]<int U = 0>() { return Value<T>; }());
303 //
304 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
305 if (isLambdaEnclosedByTypeAliasDecl(
306 /*PrimaryLambdaCallOperator=*/getPrimaryTemplateOfGenericLambda(
307 Function),
308 /*PrimaryTypeAliasDecl=*/TypeAlias.PrimaryTypeAliasDecl))
309 return Response::UseNextDecl(Function);
310 }
311 return Response::Done();
312 }
313
314 } else if (Function->getDescribedFunctionTemplate()) {
315 assert(
316 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
317 "Outer template not instantiated?");
318 }
319 // If this is a friend or local declaration and it declares an entity at
320 // namespace scope, take arguments from its lexical parent
321 // instead of its semantic parent, unless of course the pattern we're
322 // instantiating actually comes from the file's context!
323 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
324 Function->getNonTransparentDeclContext()->isFileContext() &&
325 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
326 return Response::ChangeDecl(Function->getLexicalDeclContext());
327 }
328
329 if (ForConstraintInstantiation && Function->getFriendObjectKind())
330 return Response::ChangeDecl(Function->getLexicalDeclContext());
331 return Response::UseNextDecl(Function);
332}
333
334Response HandleFunctionTemplateDecl(const FunctionTemplateDecl *FTD,
336 if (!isa<ClassTemplateSpecializationDecl>(FTD->getDeclContext())) {
337 Result.addOuterTemplateArguments(
338 const_cast<FunctionTemplateDecl *>(FTD),
339 const_cast<FunctionTemplateDecl *>(FTD)->getInjectedTemplateArgs(),
340 /*Final=*/false);
341
343
344 while (const Type *Ty = NNS ? NNS->getAsType() : nullptr) {
345 if (NNS->isInstantiationDependent()) {
346 if (const auto *TSTy = Ty->getAs<TemplateSpecializationType>()) {
347 ArrayRef<TemplateArgument> Arguments = TSTy->template_arguments();
348 // Prefer template arguments from the injected-class-type if possible.
349 // For example,
350 // ```cpp
351 // template <class... Pack> struct S {
352 // template <class T> void foo();
353 // };
354 // template <class... Pack> template <class T>
355 // ^^^^^^^^^^^^^ InjectedTemplateArgs
356 // They're of kind TemplateArgument::Pack, not of
357 // TemplateArgument::Type.
358 // void S<Pack...>::foo() {}
359 // ^^^^^^^
360 // TSTy->template_arguments() (which are of PackExpansionType)
361 // ```
362 // This meets the contract in
363 // TreeTransform::TryExpandParameterPacks that the template arguments
364 // for unexpanded parameters should be of a Pack kind.
365 if (TSTy->isCurrentInstantiation()) {
366 auto *RD = TSTy->getCanonicalTypeInternal()->getAsCXXRecordDecl();
367 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
368 Arguments = CTD->getInjectedTemplateArgs();
369 else if (auto *Specialization =
370 dyn_cast<ClassTemplateSpecializationDecl>(RD))
371 Arguments =
372 Specialization->getTemplateInstantiationArgs().asArray();
373 }
374 Result.addOuterTemplateArguments(
375 const_cast<FunctionTemplateDecl *>(FTD), Arguments,
376 /*Final=*/false);
377 }
378 }
379
380 NNS = NNS->getPrefix();
381 }
382 }
383
384 return Response::ChangeDecl(FTD->getLexicalDeclContext());
385}
386
387Response HandleRecordDecl(Sema &SemaRef, const CXXRecordDecl *Rec,
389 ASTContext &Context,
390 bool ForConstraintInstantiation) {
391 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
392 assert(
393 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&
394 "Outer template not instantiated?");
395 if (ClassTemplate->isMemberSpecialization())
396 return Response::Done();
397 if (ForConstraintInstantiation)
398 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
399 ClassTemplate->getInjectedTemplateArgs(),
400 /*Final=*/false);
401 }
402
403 if (const MemberSpecializationInfo *MSInfo =
405 if (MSInfo->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
406 return Response::Done();
407
408 bool IsFriend = Rec->getFriendObjectKind() ||
411 if (ForConstraintInstantiation && IsFriend &&
413 return Response::ChangeDecl(Rec->getLexicalDeclContext());
414 }
415
416 // This is to make sure we pick up the VarTemplateSpecializationDecl or the
417 // TypeAliasTemplateDecl that this lambda is defined inside of.
418 if (Rec->isLambda()) {
419 if (const Decl *LCD = Rec->getLambdaContextDecl())
420 return Response::ChangeDecl(LCD);
421 // Retrieve the template arguments for a using alias declaration.
422 // This is necessary for constraint checking, since we always keep
423 // constraints relative to the primary template.
424 if (auto TypeAlias = getEnclosingTypeAliasTemplateDecl(SemaRef)) {
425 const FunctionDecl *PrimaryLambdaCallOperator =
426 getPrimaryTemplateOfGenericLambda(Rec->getLambdaCallOperator());
427 if (isLambdaEnclosedByTypeAliasDecl(PrimaryLambdaCallOperator,
428 TypeAlias.PrimaryTypeAliasDecl)) {
429 Result.addOuterTemplateArguments(TypeAlias.Template,
430 TypeAlias.AssociatedTemplateArguments,
431 /*Final=*/false);
432 // Visit the parent of the current type alias declaration rather than
433 // the lambda thereof.
434 // E.g., in the following example:
435 // struct S {
436 // template <class> using T = decltype([]<Concept> {} ());
437 // };
438 // void foo() {
439 // S::T var;
440 // }
441 // The instantiated lambda expression (which we're visiting at 'var')
442 // has a function DeclContext 'foo' rather than the Record DeclContext
443 // S. This seems to be an oversight to me that we may want to set a
444 // Sema Context from the CXXScopeSpec before substituting into T.
445 return Response::ChangeDecl(TypeAlias.Template->getDeclContext());
446 }
447 }
448 }
449
450 return Response::UseNextDecl(Rec);
451}
452
453Response HandleImplicitConceptSpecializationDecl(
456 Result.addOuterTemplateArguments(
457 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
459 /*Final=*/false);
460 return Response::UseNextDecl(CSD);
461}
462
463Response HandleGenericDeclContext(const Decl *CurDecl) {
464 return Response::UseNextDecl(CurDecl);
465}
466} // namespace TemplateInstArgsHelpers
467} // namespace
468
470 const NamedDecl *ND, const DeclContext *DC, bool Final,
471 std::optional<ArrayRef<TemplateArgument>> Innermost, bool RelativeToPrimary,
472 const FunctionDecl *Pattern, bool ForConstraintInstantiation,
473 bool SkipForSpecialization, bool ForDefaultArgumentSubstitution) {
474 assert((ND || DC) && "Can't find arguments for a decl if one isn't provided");
475 // Accumulate the set of template argument lists in this structure.
477
478 using namespace TemplateInstArgsHelpers;
479 const Decl *CurDecl = ND;
480
481 if (!CurDecl)
482 CurDecl = Decl::castFromDeclContext(DC);
483
484 if (Innermost) {
485 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND), *Innermost,
486 Final);
487 // Populate placeholder template arguments for TemplateTemplateParmDecls.
488 // This is essential for the case e.g.
489 //
490 // template <class> concept Concept = false;
491 // template <template <Concept C> class T> void foo(T<int>)
492 //
493 // where parameter C has a depth of 1 but the substituting argument `int`
494 // has a depth of 0.
495 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl))
496 HandleDefaultTempArgIntoTempTempParam(TTP, Result);
497 CurDecl = Response::UseNextDecl(CurDecl).NextDecl;
498 }
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(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
577 return false;
578
579 // This function should never be called when Kind's value is Memoization.
580 case Memoization:
581 break;
582 }
583
584 llvm_unreachable("Invalid SynthesisKind!");
585}
586
589 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
590 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
591 sema::TemplateDeductionInfo *DeductionInfo)
592 : SemaRef(SemaRef) {
593 // Don't allow further instantiation if a fatal error and an uncompilable
594 // error have occurred. Any diagnostics we might have raised will not be
595 // visible, and we do not need to construct a correct AST.
598 Invalid = true;
599 return;
600 }
601 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
602 if (!Invalid) {
604 Inst.Kind = Kind;
605 Inst.PointOfInstantiation = PointOfInstantiation;
606 Inst.Entity = Entity;
607 Inst.Template = Template;
608 Inst.TemplateArgs = TemplateArgs.data();
609 Inst.NumTemplateArgs = TemplateArgs.size();
610 Inst.DeductionInfo = DeductionInfo;
611 Inst.InstantiationRange = InstantiationRange;
613
614 AlreadyInstantiating = !Inst.Entity ? false :
616 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
617 .second;
619 }
620}
621
623 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
624 SourceRange InstantiationRange)
626 CodeSynthesisContext::TemplateInstantiation,
627 PointOfInstantiation, InstantiationRange, Entity) {}
628
630 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
631 ExceptionSpecification, SourceRange InstantiationRange)
633 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
634 PointOfInstantiation, InstantiationRange, Entity) {}
635
637 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
638 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
639 SourceRange InstantiationRange)
641 SemaRef,
642 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
643 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
644 Template, TemplateArgs) {}
645
647 Sema &SemaRef, SourceLocation PointOfInstantiation,
649 ArrayRef<TemplateArgument> TemplateArgs,
651 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
652 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
653 InstantiationRange, FunctionTemplate, nullptr,
654 TemplateArgs, &DeductionInfo) {
658}
659
661 Sema &SemaRef, SourceLocation PointOfInstantiation,
662 TemplateDecl *Template,
663 ArrayRef<TemplateArgument> TemplateArgs,
664 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
666 SemaRef,
667 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
668 PointOfInstantiation, InstantiationRange, Template, nullptr,
669 TemplateArgs, &DeductionInfo) {}
670
672 Sema &SemaRef, SourceLocation PointOfInstantiation,
674 ArrayRef<TemplateArgument> TemplateArgs,
675 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
677 SemaRef,
678 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
679 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
680 TemplateArgs, &DeductionInfo) {}
681
683 Sema &SemaRef, SourceLocation PointOfInstantiation,
685 ArrayRef<TemplateArgument> TemplateArgs,
686 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
688 SemaRef,
689 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
690 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
691 TemplateArgs, &DeductionInfo) {}
692
694 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
695 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
697 SemaRef,
698 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
699 PointOfInstantiation, InstantiationRange, Param, nullptr,
700 TemplateArgs) {}
701
703 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
705 SourceRange InstantiationRange)
707 SemaRef,
708 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
709 PointOfInstantiation, InstantiationRange, Param, Template,
710 TemplateArgs) {}
711
713 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
715 SourceRange InstantiationRange)
717 SemaRef,
718 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
719 PointOfInstantiation, InstantiationRange, Param, Template,
720 TemplateArgs) {}
721
723 Sema &SemaRef, SourceLocation PointOfInstantiation,
725 SourceRange InstantiationRange)
727 SemaRef, CodeSynthesisContext::TypeAliasTemplateInstantiation,
728 PointOfInstantiation, InstantiationRange, /*Entity=*/Entity,
729 /*Template=*/nullptr, TemplateArgs) {}
730
732 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
733 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
734 SourceRange InstantiationRange)
736 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
737 PointOfInstantiation, InstantiationRange, Param, Template,
738 TemplateArgs) {}
739
741 Sema &SemaRef, SourceLocation PointOfInstantiation,
743 SourceRange InstantiationRange)
745 SemaRef, CodeSynthesisContext::RequirementInstantiation,
746 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
747 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
748}
749
751 Sema &SemaRef, SourceLocation PointOfInstantiation,
753 SourceRange InstantiationRange)
755 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
756 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
757 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
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=*/std::nullopt, &DeductionInfo) {
766}
767
769 Sema &SemaRef, SourceLocation PointOfInstantiation,
770 ConstraintsCheck, NamedDecl *Template,
771 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
774 PointOfInstantiation, InstantiationRange, Template, nullptr,
775 TemplateArgs) {}
776
778 Sema &SemaRef, SourceLocation PointOfInstantiation,
780 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
783 PointOfInstantiation, InstantiationRange, Template, nullptr,
784 {}, &DeductionInfo) {}
785
787 Sema &SemaRef, SourceLocation PointOfInstantiation,
789 SourceRange InstantiationRange)
792 PointOfInstantiation, InstantiationRange, Template) {}
793
795 Sema &SemaRef, SourceLocation PointOfInstantiation,
797 SourceRange InstantiationRange)
800 PointOfInstantiation, InstantiationRange, Template) {}
801
803 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Entity,
804 BuildingDeductionGuidesTag, SourceRange InstantiationRange)
806 SemaRef, CodeSynthesisContext::BuildingDeductionGuides,
807 PointOfInstantiation, InstantiationRange, Entity) {}
808
809
813
814 CodeSynthesisContexts.push_back(Ctx);
815
816 if (!Ctx.isInstantiationRecord())
818
819 // Check to see if we're low on stack space. We can't do anything about this
820 // from here, but we can at least warn the user.
823}
824
826 auto &Active = CodeSynthesisContexts.back();
827 if (!Active.isInstantiationRecord()) {
828 assert(NonInstantiationEntries > 0);
830 }
831
832 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
833
834 // Name lookup no longer looks in this template's defining module.
835 assert(CodeSynthesisContexts.size() >=
837 "forgot to remove a lookup module for a template instantiation");
838 if (CodeSynthesisContexts.size() ==
841 LookupModulesCache.erase(M);
843 }
844
845 // If we've left the code synthesis context for the current context stack,
846 // stop remembering that we've emitted that stack.
847 if (CodeSynthesisContexts.size() ==
850
851 CodeSynthesisContexts.pop_back();
852}
853
855 if (!Invalid) {
856 if (!AlreadyInstantiating) {
857 auto &Active = SemaRef.CodeSynthesisContexts.back();
858 if (Active.Entity)
860 {Active.Entity->getCanonicalDecl(), Active.Kind});
861 }
862
865
867 Invalid = true;
868 }
869}
870
871static std::string convertCallArgsToString(Sema &S,
873 std::string Result;
874 llvm::raw_string_ostream OS(Result);
875 llvm::ListSeparator Comma;
876 for (const Expr *Arg : Args) {
877 OS << Comma;
878 Arg->IgnoreParens()->printPretty(OS, nullptr,
880 }
881 return Result;
882}
883
884bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
885 SourceLocation PointOfInstantiation,
886 SourceRange InstantiationRange) {
889 if ((SemaRef.CodeSynthesisContexts.size() -
891 <= SemaRef.getLangOpts().InstantiationDepth)
892 return false;
893
894 SemaRef.Diag(PointOfInstantiation,
895 diag::err_template_recursion_depth_exceeded)
896 << SemaRef.getLangOpts().InstantiationDepth
897 << InstantiationRange;
898 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
899 << SemaRef.getLangOpts().InstantiationDepth;
900 return true;
901}
902
904 // Determine which template instantiations to skip, if any.
905 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
906 unsigned Limit = Diags.getTemplateBacktraceLimit();
907 if (Limit && Limit < CodeSynthesisContexts.size()) {
908 SkipStart = Limit / 2 + Limit % 2;
909 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
910 }
911
912 // FIXME: In all of these cases, we need to show the template arguments
913 unsigned InstantiationIdx = 0;
915 Active = CodeSynthesisContexts.rbegin(),
916 ActiveEnd = CodeSynthesisContexts.rend();
917 Active != ActiveEnd;
918 ++Active, ++InstantiationIdx) {
919 // Skip this instantiation?
920 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
921 if (InstantiationIdx == SkipStart) {
922 // Note that we're skipping instantiations.
923 Diags.Report(Active->PointOfInstantiation,
924 diag::note_instantiation_contexts_suppressed)
925 << unsigned(CodeSynthesisContexts.size() - Limit);
926 }
927 continue;
928 }
929
930 switch (Active->Kind) {
932 Decl *D = Active->Entity;
933 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
934 unsigned DiagID = diag::note_template_member_class_here;
935 if (isa<ClassTemplateSpecializationDecl>(Record))
936 DiagID = diag::note_template_class_instantiation_here;
937 Diags.Report(Active->PointOfInstantiation, DiagID)
938 << Record << Active->InstantiationRange;
939 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
940 unsigned DiagID;
941 if (Function->getPrimaryTemplate())
942 DiagID = diag::note_function_template_spec_here;
943 else
944 DiagID = diag::note_template_member_function_here;
945 Diags.Report(Active->PointOfInstantiation, DiagID)
946 << Function
947 << Active->InstantiationRange;
948 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
949 Diags.Report(Active->PointOfInstantiation,
950 VD->isStaticDataMember()?
951 diag::note_template_static_data_member_def_here
952 : diag::note_template_variable_def_here)
953 << VD
954 << Active->InstantiationRange;
955 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
956 Diags.Report(Active->PointOfInstantiation,
957 diag::note_template_enum_def_here)
958 << ED
959 << Active->InstantiationRange;
960 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
961 Diags.Report(Active->PointOfInstantiation,
962 diag::note_template_nsdmi_here)
963 << FD << Active->InstantiationRange;
964 } else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(D)) {
965 Diags.Report(Active->PointOfInstantiation,
966 diag::note_template_class_instantiation_here)
967 << CTD << Active->InstantiationRange;
968 }
969 break;
970 }
971
973 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
974 SmallString<128> TemplateArgsStr;
975 llvm::raw_svector_ostream OS(TemplateArgsStr);
976 Template->printName(OS, getPrintingPolicy());
977 printTemplateArgumentList(OS, Active->template_arguments(),
979 Diags.Report(Active->PointOfInstantiation,
980 diag::note_default_arg_instantiation_here)
981 << OS.str()
982 << Active->InstantiationRange;
983 break;
984 }
985
987 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
988 Diags.Report(Active->PointOfInstantiation,
989 diag::note_explicit_template_arg_substitution_here)
990 << FnTmpl
992 Active->TemplateArgs,
993 Active->NumTemplateArgs)
994 << Active->InstantiationRange;
995 break;
996 }
997
999 if (FunctionTemplateDecl *FnTmpl =
1000 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
1001 Diags.Report(Active->PointOfInstantiation,
1002 diag::note_function_template_deduction_instantiation_here)
1003 << FnTmpl
1004 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
1005 Active->TemplateArgs,
1006 Active->NumTemplateArgs)
1007 << Active->InstantiationRange;
1008 } else {
1009 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
1010 isa<VarTemplateSpecializationDecl>(Active->Entity);
1011 bool IsTemplate = false;
1012 TemplateParameterList *Params;
1013 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
1014 IsTemplate = true;
1015 Params = D->getTemplateParameters();
1016 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
1017 Active->Entity)) {
1018 Params = D->getTemplateParameters();
1019 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
1020 Active->Entity)) {
1021 Params = D->getTemplateParameters();
1022 } else {
1023 llvm_unreachable("unexpected template kind");
1024 }
1025
1026 Diags.Report(Active->PointOfInstantiation,
1027 diag::note_deduced_template_arg_substitution_here)
1028 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
1029 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
1030 Active->NumTemplateArgs)
1031 << Active->InstantiationRange;
1032 }
1033 break;
1034 }
1035
1037 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
1038 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
1039
1040 SmallString<128> TemplateArgsStr;
1041 llvm::raw_svector_ostream OS(TemplateArgsStr);
1043 printTemplateArgumentList(OS, Active->template_arguments(),
1045 Diags.Report(Active->PointOfInstantiation,
1046 diag::note_default_function_arg_instantiation_here)
1047 << OS.str()
1048 << Active->InstantiationRange;
1049 break;
1050 }
1051
1053 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
1054 std::string Name;
1055 if (!Parm->getName().empty())
1056 Name = std::string(" '") + Parm->getName().str() + "'";
1057
1058 TemplateParameterList *TemplateParams = nullptr;
1059 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1060 TemplateParams = Template->getTemplateParameters();
1061 else
1062 TemplateParams =
1063 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1064 ->getTemplateParameters();
1065 Diags.Report(Active->PointOfInstantiation,
1066 diag::note_prior_template_arg_substitution)
1067 << isa<TemplateTemplateParmDecl>(Parm)
1068 << Name
1069 << getTemplateArgumentBindingsText(TemplateParams,
1070 Active->TemplateArgs,
1071 Active->NumTemplateArgs)
1072 << Active->InstantiationRange;
1073 break;
1074 }
1075
1077 TemplateParameterList *TemplateParams = nullptr;
1078 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
1079 TemplateParams = Template->getTemplateParameters();
1080 else
1081 TemplateParams =
1082 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
1083 ->getTemplateParameters();
1084
1085 Diags.Report(Active->PointOfInstantiation,
1086 diag::note_template_default_arg_checking)
1087 << getTemplateArgumentBindingsText(TemplateParams,
1088 Active->TemplateArgs,
1089 Active->NumTemplateArgs)
1090 << Active->InstantiationRange;
1091 break;
1092 }
1093
1095 Diags.Report(Active->PointOfInstantiation,
1096 diag::note_evaluating_exception_spec_here)
1097 << cast<FunctionDecl>(Active->Entity);
1098 break;
1099
1101 Diags.Report(Active->PointOfInstantiation,
1102 diag::note_template_exception_spec_instantiation_here)
1103 << cast<FunctionDecl>(Active->Entity)
1104 << Active->InstantiationRange;
1105 break;
1106
1108 Diags.Report(Active->PointOfInstantiation,
1109 diag::note_template_requirement_instantiation_here)
1110 << Active->InstantiationRange;
1111 break;
1113 Diags.Report(Active->PointOfInstantiation,
1114 diag::note_template_requirement_params_instantiation_here)
1115 << Active->InstantiationRange;
1116 break;
1117
1119 Diags.Report(Active->PointOfInstantiation,
1120 diag::note_nested_requirement_here)
1121 << Active->InstantiationRange;
1122 break;
1123
1125 Diags.Report(Active->PointOfInstantiation,
1126 diag::note_in_declaration_of_implicit_special_member)
1127 << cast<CXXRecordDecl>(Active->Entity)
1128 << llvm::to_underlying(Active->SpecialMember);
1129 break;
1130
1132 Diags.Report(Active->Entity->getLocation(),
1133 diag::note_in_declaration_of_implicit_equality_comparison);
1134 break;
1135
1137 // FIXME: For synthesized functions that are not defaulted,
1138 // produce a note.
1139 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
1142 if (DFK.isSpecialMember()) {
1143 auto *MD = cast<CXXMethodDecl>(FD);
1144 Diags.Report(Active->PointOfInstantiation,
1145 diag::note_member_synthesized_at)
1146 << MD->isExplicitlyDefaulted()
1147 << llvm::to_underlying(DFK.asSpecialMember())
1148 << Context.getTagDeclType(MD->getParent());
1149 } else if (DFK.isComparison()) {
1150 QualType RecordType = FD->getParamDecl(0)
1151 ->getType()
1152 .getNonReferenceType()
1153 .getUnqualifiedType();
1154 Diags.Report(Active->PointOfInstantiation,
1155 diag::note_comparison_synthesized_at)
1156 << (int)DFK.asComparison() << RecordType;
1157 }
1158 break;
1159 }
1160
1162 Diags.Report(Active->Entity->getLocation(),
1163 diag::note_rewriting_operator_as_spaceship);
1164 break;
1165
1167 Diags.Report(Active->PointOfInstantiation,
1168 diag::note_in_binding_decl_init)
1169 << cast<BindingDecl>(Active->Entity);
1170 break;
1171
1173 Diags.Report(Active->PointOfInstantiation,
1174 diag::note_due_to_dllexported_class)
1175 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
1176 break;
1177
1179 Diags.Report(Active->PointOfInstantiation,
1180 diag::note_building_builtin_dump_struct_call)
1182 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
1183 break;
1184
1186 break;
1187
1189 Diags.Report(Active->PointOfInstantiation,
1190 diag::note_lambda_substitution_here);
1191 break;
1193 unsigned DiagID = 0;
1194 if (!Active->Entity) {
1195 Diags.Report(Active->PointOfInstantiation,
1196 diag::note_nested_requirement_here)
1197 << Active->InstantiationRange;
1198 break;
1199 }
1200 if (isa<ConceptDecl>(Active->Entity))
1201 DiagID = diag::note_concept_specialization_here;
1202 else if (isa<TemplateDecl>(Active->Entity))
1203 DiagID = diag::note_checking_constraints_for_template_id_here;
1204 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
1205 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
1206 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
1207 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
1208 else {
1209 assert(isa<FunctionDecl>(Active->Entity));
1210 DiagID = diag::note_checking_constraints_for_function_here;
1211 }
1212 SmallString<128> TemplateArgsStr;
1213 llvm::raw_svector_ostream OS(TemplateArgsStr);
1214 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
1215 if (!isa<FunctionDecl>(Active->Entity)) {
1216 printTemplateArgumentList(OS, Active->template_arguments(),
1218 }
1219 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
1220 << Active->InstantiationRange;
1221 break;
1222 }
1224 Diags.Report(Active->PointOfInstantiation,
1225 diag::note_constraint_substitution_here)
1226 << Active->InstantiationRange;
1227 break;
1229 Diags.Report(Active->PointOfInstantiation,
1230 diag::note_constraint_normalization_here)
1231 << cast<NamedDecl>(Active->Entity)->getName()
1232 << Active->InstantiationRange;
1233 break;
1235 Diags.Report(Active->PointOfInstantiation,
1236 diag::note_parameter_mapping_substitution_here)
1237 << Active->InstantiationRange;
1238 break;
1240 Diags.Report(Active->PointOfInstantiation,
1241 diag::note_building_deduction_guide_here);
1242 break;
1244 Diags.Report(Active->PointOfInstantiation,
1245 diag::note_template_type_alias_instantiation_here)
1246 << cast<TypeAliasTemplateDecl>(Active->Entity)
1247 << Active->InstantiationRange;
1248 break;
1249 }
1250 }
1251}
1252
1253std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1255 return std::optional<TemplateDeductionInfo *>(nullptr);
1256
1258 Active = CodeSynthesisContexts.rbegin(),
1259 ActiveEnd = CodeSynthesisContexts.rend();
1260 Active != ActiveEnd;
1261 ++Active)
1262 {
1263 switch (Active->Kind) {
1265 // An instantiation of an alias template may or may not be a SFINAE
1266 // context, depending on what else is on the stack.
1267 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1268 break;
1269 [[fallthrough]];
1277 // This is a template instantiation, so there is no SFINAE.
1278 return std::nullopt;
1280 // [temp.deduct]p9
1281 // A lambda-expression appearing in a function type or a template
1282 // parameter is not considered part of the immediate context for the
1283 // purposes of template argument deduction.
1284 // CWG2672: A lambda-expression body is never in the immediate context.
1285 return std::nullopt;
1286
1291 // A default template argument instantiation and substitution into
1292 // template parameters with arguments for prior parameters may or may
1293 // not be a SFINAE context; look further up the stack.
1294 break;
1295
1298 // We're either substituting explicitly-specified template arguments,
1299 // deduced template arguments. SFINAE applies unless we are in a lambda
1300 // body, see [temp.deduct]p9.
1304 // SFINAE always applies in a constraint expression or a requirement
1305 // in a requires expression.
1306 assert(Active->DeductionInfo && "Missing deduction info pointer");
1307 return Active->DeductionInfo;
1308
1316 // This happens in a context unrelated to template instantiation, so
1317 // there is no SFINAE.
1318 return std::nullopt;
1319
1321 // FIXME: This should not be treated as a SFINAE context, because
1322 // we will cache an incorrect exception specification. However, clang
1323 // bootstrap relies this! See PR31692.
1324 break;
1325
1327 break;
1328 }
1329
1330 // The inner context was transparent for SFINAE. If it occurred within a
1331 // non-instantiation SFINAE context, then SFINAE applies.
1332 if (Active->SavedInNonInstantiationSFINAEContext)
1333 return std::optional<TemplateDeductionInfo *>(nullptr);
1334 }
1335
1336 return std::nullopt;
1337}
1338
1339//===----------------------------------------------------------------------===/
1340// Template Instantiation for Types
1341//===----------------------------------------------------------------------===/
1342namespace {
1343 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1344 const MultiLevelTemplateArgumentList &TemplateArgs;
1346 DeclarationName Entity;
1347 // Whether to evaluate the C++20 constraints or simply substitute into them.
1348 bool EvaluateConstraints = true;
1349
1350 public:
1351 typedef TreeTransform<TemplateInstantiator> inherited;
1352
1353 TemplateInstantiator(Sema &SemaRef,
1354 const MultiLevelTemplateArgumentList &TemplateArgs,
1356 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1357 Entity(Entity) {}
1358
1359 void setEvaluateConstraints(bool B) {
1360 EvaluateConstraints = B;
1361 }
1362 bool getEvaluateConstraints() {
1363 return EvaluateConstraints;
1364 }
1365
1366 /// Determine whether the given type \p T has already been
1367 /// transformed.
1368 ///
1369 /// For the purposes of template instantiation, a type has already been
1370 /// transformed if it is NULL or if it is not dependent.
1371 bool AlreadyTransformed(QualType T);
1372
1373 /// Returns the location of the entity being instantiated, if known.
1374 SourceLocation getBaseLocation() { return Loc; }
1375
1376 /// Returns the name of the entity being instantiated, if any.
1377 DeclarationName getBaseEntity() { return Entity; }
1378
1379 /// Sets the "base" location and entity when that
1380 /// information is known based on another transformation.
1381 void setBase(SourceLocation Loc, DeclarationName Entity) {
1382 this->Loc = Loc;
1383 this->Entity = Entity;
1384 }
1385
1386 unsigned TransformTemplateDepth(unsigned Depth) {
1387 return TemplateArgs.getNewDepth(Depth);
1388 }
1389
1390 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1391 int Index = getSema().ArgumentPackSubstitutionIndex;
1392 if (Index == -1)
1393 return std::nullopt;
1394 return Pack.pack_size() - 1 - Index;
1395 }
1396
1397 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1398 SourceRange PatternRange,
1400 bool &ShouldExpand, bool &RetainExpansion,
1401 std::optional<unsigned> &NumExpansions) {
1402 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1403 PatternRange, Unexpanded,
1404 TemplateArgs,
1405 ShouldExpand,
1406 RetainExpansion,
1407 NumExpansions);
1408 }
1409
1410 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1412 }
1413
1414 TemplateArgument ForgetPartiallySubstitutedPack() {
1415 TemplateArgument Result;
1416 if (NamedDecl *PartialPack
1418 MultiLevelTemplateArgumentList &TemplateArgs
1419 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1420 unsigned Depth, Index;
1421 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1422 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1423 Result = TemplateArgs(Depth, Index);
1424 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1425 }
1426 }
1427
1428 return Result;
1429 }
1430
1431 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1432 if (Arg.isNull())
1433 return;
1434
1435 if (NamedDecl *PartialPack
1437 MultiLevelTemplateArgumentList &TemplateArgs
1438 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1439 unsigned Depth, Index;
1440 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1441 TemplateArgs.setArgument(Depth, Index, Arg);
1442 }
1443 }
1444
1445 /// Transform the given declaration by instantiating a reference to
1446 /// this declaration.
1447 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1448
1449 void transformAttrs(Decl *Old, Decl *New) {
1450 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1451 }
1452
1453 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1454 if (Old->isParameterPack() &&
1455 (NewDecls.size() != 1 || !NewDecls.front()->isParameterPack())) {
1457 for (auto *New : NewDecls)
1459 Old, cast<VarDecl>(New));
1460 return;
1461 }
1462
1463 assert(NewDecls.size() == 1 &&
1464 "should only have multiple expansions for a pack");
1465 Decl *New = NewDecls.front();
1466
1467 // If we've instantiated the call operator of a lambda or the call
1468 // operator template of a generic lambda, update the "instantiation of"
1469 // information.
1470 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
1471 if (NewMD && isLambdaCallOperator(NewMD)) {
1472 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
1473 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
1474 NewTD->setInstantiatedFromMemberTemplate(
1475 OldMD->getDescribedFunctionTemplate());
1476 else
1477 NewMD->setInstantiationOfMemberFunction(OldMD,
1479 }
1480
1482
1483 // We recreated a local declaration, but not by instantiating it. There
1484 // may be pending dependent diagnostics to produce.
1485 if (auto *DC = dyn_cast<DeclContext>(Old);
1486 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1487 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1488 }
1489
1490 /// Transform the definition of the given declaration by
1491 /// instantiating it.
1492 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1493
1494 /// Transform the first qualifier within a scope by instantiating the
1495 /// declaration.
1496 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1497
1498 bool TransformExceptionSpec(SourceLocation Loc,
1500 SmallVectorImpl<QualType> &Exceptions,
1501 bool &Changed);
1502
1503 /// Rebuild the exception declaration and register the declaration
1504 /// as an instantiated local.
1505 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1507 SourceLocation StartLoc,
1508 SourceLocation NameLoc,
1509 IdentifierInfo *Name);
1510
1511 /// Rebuild the Objective-C exception declaration and register the
1512 /// declaration as an instantiated local.
1513 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1514 TypeSourceInfo *TSInfo, QualType T);
1515
1516 /// Check for tag mismatches when instantiating an
1517 /// elaborated type.
1518 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1519 ElaboratedTypeKeyword Keyword,
1520 NestedNameSpecifierLoc QualifierLoc,
1521 QualType T);
1522
1524 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1525 SourceLocation NameLoc,
1526 QualType ObjectType = QualType(),
1527 NamedDecl *FirstQualifierInScope = nullptr,
1528 bool AllowInjectedClassName = false);
1529
1530 const CXXAssumeAttr *TransformCXXAssumeAttr(const CXXAssumeAttr *AA);
1531 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1532 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1533 const Stmt *InstS,
1534 const NoInlineAttr *A);
1535 const AlwaysInlineAttr *
1536 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1537 const AlwaysInlineAttr *A);
1538 const CodeAlignAttr *TransformCodeAlignAttr(const CodeAlignAttr *CA);
1539 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1540 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1541 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1542
1543 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1545 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1547 ExprResult TransformSubstNonTypeTemplateParmExpr(
1549
1550 /// Rebuild a DeclRefExpr for a VarDecl reference.
1551 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1552
1553 /// Transform a reference to a function or init-capture parameter pack.
1554 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1555
1556 /// Transform a FunctionParmPackExpr which was built when we couldn't
1557 /// expand a function parameter pack reference which refers to an expanded
1558 /// pack.
1559 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1560
1561 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1563 // Call the base version; it will forward to our overridden version below.
1564 return inherited::TransformFunctionProtoType(TLB, TL);
1565 }
1566
1567 QualType TransformInjectedClassNameType(TypeLocBuilder &TLB,
1569 auto Type = inherited::TransformInjectedClassNameType(TLB, TL);
1570 // Special case for transforming a deduction guide, we return a
1571 // transformed TemplateSpecializationType.
1572 if (Type.isNull() &&
1573 SemaRef.CodeSynthesisContexts.back().Kind ==
1575 // Return a TemplateSpecializationType for transforming a deduction
1576 // guide.
1577 if (auto *ICT = TL.getType()->getAs<InjectedClassNameType>()) {
1578 auto Type =
1579 inherited::TransformType(ICT->getInjectedSpecializationType());
1580 TLB.pushTrivial(SemaRef.Context, Type, TL.getNameLoc());
1581 return Type;
1582 }
1583 }
1584 return Type;
1585 }
1586 // Override the default version to handle a rewrite-template-arg-pack case
1587 // for building a deduction guide.
1588 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
1589 TemplateArgumentLoc &Output,
1590 bool Uneval = false) {
1591 const TemplateArgument &Arg = Input.getArgument();
1592 std::vector<TemplateArgument> TArgs;
1593 switch (Arg.getKind()) {
1595 // Literally rewrite the template argument pack, instead of unpacking
1596 // it.
1597 for (auto &pack : Arg.getPackAsArray()) {
1599 pack, QualType(), SourceLocation{});
1600 TemplateArgumentLoc Output;
1601 if (SemaRef.SubstTemplateArgument(Input, TemplateArgs, Output))
1602 return true; // fails
1603 TArgs.push_back(Output.getArgument());
1604 }
1605 Output = SemaRef.getTrivialTemplateArgumentLoc(
1606 TemplateArgument(llvm::ArrayRef(TArgs).copy(SemaRef.Context)),
1608 return false;
1609 default:
1610 break;
1611 }
1612 return inherited::TransformTemplateArgument(Input, Output, Uneval);
1613 }
1614
1615 template<typename Fn>
1616 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1618 CXXRecordDecl *ThisContext,
1619 Qualifiers ThisTypeQuals,
1620 Fn TransformExceptionSpec);
1621
1622 ParmVarDecl *
1623 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1624 std::optional<unsigned> NumExpansions,
1625 bool ExpectParameterPack);
1626
1627 using inherited::TransformTemplateTypeParmType;
1628 /// Transforms a template type parameter type by performing
1629 /// substitution of the corresponding template type argument.
1630 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1632 bool SuppressObjCLifetime);
1633
1634 QualType BuildSubstTemplateTypeParmType(
1635 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1636 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1637 TemplateArgument Arg, SourceLocation NameLoc);
1638
1639 /// Transforms an already-substituted template type parameter pack
1640 /// into either itself (if we aren't substituting into its pack expansion)
1641 /// or the appropriate substituted argument.
1642 using inherited::TransformSubstTemplateTypeParmPackType;
1643 QualType
1644 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1646 bool SuppressObjCLifetime);
1647
1649 ComputeLambdaDependency(LambdaScopeInfo *LSI) {
1650 auto &CCS = SemaRef.CodeSynthesisContexts.back();
1651 if (CCS.Kind ==
1653 unsigned TypeAliasDeclDepth = CCS.Entity->getTemplateDepth();
1654 if (TypeAliasDeclDepth >= TemplateArgs.getNumSubstitutedLevels())
1655 return CXXRecordDecl::LambdaDependencyKind::LDK_AlwaysDependent;
1656 }
1657 return inherited::ComputeLambdaDependency(LSI);
1658 }
1659
1660 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1661 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1663
1664 return inherited::TransformLambdaExpr(E);
1665 }
1666
1667 ExprResult RebuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1668 LambdaScopeInfo *LSI) {
1669 CXXMethodDecl *MD = LSI->CallOperator;
1670 for (ParmVarDecl *PVD : MD->parameters()) {
1671 assert(PVD && "null in a parameter list");
1672 if (!PVD->hasDefaultArg())
1673 continue;
1674 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1675 // FIXME: Obtain the source location for the '=' token.
1676 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1677 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1678 // If substitution fails, the default argument is set to a
1679 // RecoveryExpr that wraps the uninstantiated default argument so
1680 // that downstream diagnostics are omitted.
1681 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1682 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1683 { UninstExpr }, UninstExpr->getType());
1684 if (ErrorResult.isUsable())
1685 PVD->setDefaultArg(ErrorResult.get());
1686 }
1687 }
1688 return inherited::RebuildLambdaExpr(StartLoc, EndLoc, LSI);
1689 }
1690
1691 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body) {
1692 // Currently, we instantiate the body when instantiating the lambda
1693 // expression. However, `EvaluateConstraints` is disabled during the
1694 // instantiation of the lambda expression, causing the instantiation
1695 // failure of the return type requirement in the body. If p0588r1 is fully
1696 // implemented, the body will be lazily instantiated, and this problem
1697 // will not occur. Here, `EvaluateConstraints` is temporarily set to
1698 // `true` to temporarily fix this issue.
1699 // FIXME: This temporary fix can be removed after fully implementing
1700 // p0588r1.
1701 llvm::SaveAndRestore _(EvaluateConstraints, true);
1702 return inherited::TransformLambdaBody(E, Body);
1703 }
1704
1705 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1706 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1707 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1708 if (TransReq.isInvalid())
1709 return TransReq;
1710 assert(TransReq.get() != E &&
1711 "Do not change value of isSatisfied for the existing expression. "
1712 "Create a new expression instead.");
1713 if (E->getBody()->isDependentContext()) {
1714 Sema::SFINAETrap Trap(SemaRef);
1715 // We recreate the RequiresExpr body, but not by instantiating it.
1716 // Produce pending diagnostics for dependent access check.
1717 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1718 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1719 if (Trap.hasErrorOccurred())
1720 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1721 }
1722 return TransReq;
1723 }
1724
1725 bool TransformRequiresExprRequirements(
1728 bool SatisfactionDetermined = false;
1729 for (concepts::Requirement *Req : Reqs) {
1730 concepts::Requirement *TransReq = nullptr;
1731 if (!SatisfactionDetermined) {
1732 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1733 TransReq = TransformTypeRequirement(TypeReq);
1734 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1735 TransReq = TransformExprRequirement(ExprReq);
1736 else
1737 TransReq = TransformNestedRequirement(
1738 cast<concepts::NestedRequirement>(Req));
1739 if (!TransReq)
1740 return true;
1741 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1742 // [expr.prim.req]p6
1743 // [...] The substitution and semantic constraint checking
1744 // proceeds in lexical order and stops when a condition that
1745 // determines the result of the requires-expression is
1746 // encountered. [..]
1747 SatisfactionDetermined = true;
1748 } else
1749 TransReq = Req;
1750 Transformed.push_back(TransReq);
1751 }
1752 return false;
1753 }
1754
1755 TemplateParameterList *TransformTemplateParameterList(
1756 TemplateParameterList *OrigTPL) {
1757 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1758
1759 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1760 TemplateDeclInstantiator DeclInstantiator(getSema(),
1761 /* DeclContext *Owner */ Owner, TemplateArgs);
1762 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1763 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1764 }
1765
1767 TransformTypeRequirement(concepts::TypeRequirement *Req);
1769 TransformExprRequirement(concepts::ExprRequirement *Req);
1771 TransformNestedRequirement(concepts::NestedRequirement *Req);
1772 ExprResult TransformRequiresTypeParams(
1773 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1776 SmallVectorImpl<ParmVarDecl *> &TransParams,
1778
1779 private:
1781 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1782 const NonTypeTemplateParmDecl *parm,
1784 std::optional<unsigned> PackIndex);
1785 };
1786}
1787
1788bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1789 if (T.isNull())
1790 return true;
1791
1793 return false;
1794
1795 getSema().MarkDeclarationsReferencedInType(Loc, T);
1796 return true;
1797}
1798
1799static TemplateArgument
1801 assert(S.ArgumentPackSubstitutionIndex >= 0);
1802 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size());
1804 if (Arg.isPackExpansion())
1805 Arg = Arg.getPackExpansionPattern();
1806 return Arg;
1807}
1808
1809Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1810 if (!D)
1811 return nullptr;
1812
1813 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1814 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1815 // If the corresponding template argument is NULL or non-existent, it's
1816 // because we are performing instantiation from explicitly-specified
1817 // template arguments in a function template, but there were some
1818 // arguments left unspecified.
1819 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1820 TTP->getPosition()))
1821 return D;
1822
1823 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1824
1825 if (TTP->isParameterPack()) {
1826 assert(Arg.getKind() == TemplateArgument::Pack &&
1827 "Missing argument pack");
1828 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1829 }
1830
1831 TemplateName Template = Arg.getAsTemplate();
1832 assert(!Template.isNull() && Template.getAsTemplateDecl() &&
1833 "Wrong kind of template template argument");
1834 return Template.getAsTemplateDecl();
1835 }
1836
1837 // Fall through to find the instantiated declaration for this template
1838 // template parameter.
1839 }
1840
1841 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1842}
1843
1844Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1845 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1846 if (!Inst)
1847 return nullptr;
1848
1849 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1850 return Inst;
1851}
1852
1853bool TemplateInstantiator::TransformExceptionSpec(
1855 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
1856 if (ESI.Type == EST_Uninstantiated) {
1857 ESI.instantiate();
1858 Changed = true;
1859 }
1860 return inherited::TransformExceptionSpec(Loc, ESI, Exceptions, Changed);
1861}
1862
1863NamedDecl *
1864TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1866 // If the first part of the nested-name-specifier was a template type
1867 // parameter, instantiate that type parameter down to a tag type.
1868 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1869 const TemplateTypeParmType *TTP
1870 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1871
1872 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1873 // FIXME: This needs testing w/ member access expressions.
1874 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1875
1876 if (TTP->isParameterPack()) {
1877 assert(Arg.getKind() == TemplateArgument::Pack &&
1878 "Missing argument pack");
1879
1880 if (getSema().ArgumentPackSubstitutionIndex == -1)
1881 return nullptr;
1882
1883 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1884 }
1885
1886 QualType T = Arg.getAsType();
1887 if (T.isNull())
1888 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1889
1890 if (const TagType *Tag = T->getAs<TagType>())
1891 return Tag->getDecl();
1892
1893 // The resulting type is not a tag; complain.
1894 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1895 return nullptr;
1896 }
1897 }
1898
1899 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1900}
1901
1902VarDecl *
1903TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1905 SourceLocation StartLoc,
1906 SourceLocation NameLoc,
1907 IdentifierInfo *Name) {
1908 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1909 StartLoc, NameLoc, Name);
1910 if (Var)
1911 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1912 return Var;
1913}
1914
1915VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1916 TypeSourceInfo *TSInfo,
1917 QualType T) {
1918 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1919 if (Var)
1920 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1921 return Var;
1922}
1923
1925TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1926 ElaboratedTypeKeyword Keyword,
1927 NestedNameSpecifierLoc QualifierLoc,
1928 QualType T) {
1929 if (const TagType *TT = T->getAs<TagType>()) {
1930 TagDecl* TD = TT->getDecl();
1931
1932 SourceLocation TagLocation = KeywordLoc;
1933
1935
1936 // TODO: should we even warn on struct/class mismatches for this? Seems
1937 // like it's likely to produce a lot of spurious errors.
1938 if (Id && Keyword != ElaboratedTypeKeyword::None &&
1941 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1942 TagLocation, Id)) {
1943 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1944 << Id
1946 TD->getKindName());
1947 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1948 }
1949 }
1950 }
1951
1952 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1953}
1954
1955TemplateName TemplateInstantiator::TransformTemplateName(
1956 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1957 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1958 bool AllowInjectedClassName) {
1960 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1961 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1962 // If the corresponding template argument is NULL or non-existent, it's
1963 // because we are performing instantiation from explicitly-specified
1964 // template arguments in a function template, but there were some
1965 // arguments left unspecified.
1966 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1967 TTP->getPosition()))
1968 return Name;
1969
1970 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1971
1972 if (TemplateArgs.isRewrite()) {
1973 // We're rewriting the template parameter as a reference to another
1974 // template parameter.
1975 if (Arg.getKind() == TemplateArgument::Pack) {
1976 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
1977 "unexpected pack arguments in template rewrite");
1978 Arg = Arg.pack_begin()->getPackExpansionPattern();
1979 }
1980 assert(Arg.getKind() == TemplateArgument::Template &&
1981 "unexpected nontype template argument kind in template rewrite");
1982 return Arg.getAsTemplate();
1983 }
1984
1985 auto [AssociatedDecl, Final] =
1986 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1987 std::optional<unsigned> PackIndex;
1988 if (TTP->isParameterPack()) {
1989 assert(Arg.getKind() == TemplateArgument::Pack &&
1990 "Missing argument pack");
1991
1992 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1993 // We have the template argument pack to substitute, but we're not
1994 // actually expanding the enclosing pack expansion yet. So, just
1995 // keep the entire argument pack.
1996 return getSema().Context.getSubstTemplateTemplateParmPack(
1997 Arg, AssociatedDecl, TTP->getIndex(), Final);
1998 }
1999
2000 PackIndex = getPackIndex(Arg);
2001 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2002 }
2003
2004 TemplateName Template = Arg.getAsTemplate();
2005 assert(!Template.isNull() && "Null template template argument");
2006
2007 if (Final)
2008 return Template;
2009 return getSema().Context.getSubstTemplateTemplateParm(
2010 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
2011 }
2012 }
2013
2015 = Name.getAsSubstTemplateTemplateParmPack()) {
2016 if (getSema().ArgumentPackSubstitutionIndex == -1)
2017 return Name;
2018
2019 TemplateArgument Pack = SubstPack->getArgumentPack();
2020 TemplateName Template =
2022 if (SubstPack->getFinal())
2023 return Template;
2024 return getSema().Context.getSubstTemplateTemplateParm(
2025 Template, SubstPack->getAssociatedDecl(), SubstPack->getIndex(),
2026 getPackIndex(Pack));
2027 }
2028
2029 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
2030 FirstQualifierInScope,
2031 AllowInjectedClassName);
2032}
2033
2035TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
2036 if (!E->isTypeDependent())
2037 return E;
2038
2039 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
2040}
2041
2043TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
2045 // If the corresponding template argument is NULL or non-existent, it's
2046 // because we are performing instantiation from explicitly-specified
2047 // template arguments in a function template, but there were some
2048 // arguments left unspecified.
2049 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
2050 NTTP->getPosition()))
2051 return E;
2052
2053 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
2054
2055 if (TemplateArgs.isRewrite()) {
2056 // We're rewriting the template parameter as a reference to another
2057 // template parameter.
2058 if (Arg.getKind() == TemplateArgument::Pack) {
2059 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2060 "unexpected pack arguments in template rewrite");
2061 Arg = Arg.pack_begin()->getPackExpansionPattern();
2062 }
2063 assert(Arg.getKind() == TemplateArgument::Expression &&
2064 "unexpected nontype template argument kind in template rewrite");
2065 // FIXME: This can lead to the same subexpression appearing multiple times
2066 // in a complete expression.
2067 return Arg.getAsExpr();
2068 }
2069
2070 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
2071 std::optional<unsigned> PackIndex;
2072 if (NTTP->isParameterPack()) {
2073 assert(Arg.getKind() == TemplateArgument::Pack &&
2074 "Missing argument pack");
2075
2076 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2077 // We have an argument pack, but we can't select a particular argument
2078 // out of it yet. Therefore, we'll build an expression to hold on to that
2079 // argument pack.
2080 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
2081 E->getLocation(),
2082 NTTP->getDeclName());
2083 if (TargetType.isNull())
2084 return ExprError();
2085
2086 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
2087 if (TargetType->isRecordType())
2088 ExprType.addConst();
2089 // FIXME: Pass in Final.
2091 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
2092 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
2093 }
2094 PackIndex = getPackIndex(Arg);
2095 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2096 }
2097 // FIXME: Don't put subst node on Final replacement.
2098 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
2099 Arg, PackIndex);
2100}
2101
2102const CXXAssumeAttr *
2103TemplateInstantiator::TransformCXXAssumeAttr(const CXXAssumeAttr *AA) {
2104 ExprResult Res = getDerived().TransformExpr(AA->getAssumption());
2105 if (!Res.isUsable())
2106 return AA;
2107
2108 Res = getSema().BuildCXXAssumeExpr(Res.get(), AA->getAttrName(),
2109 AA->getRange());
2110 if (!Res.isUsable())
2111 return AA;
2112
2113 return CXXAssumeAttr::CreateImplicit(getSema().Context, Res.get(),
2114 AA->getRange());
2115}
2116
2117const LoopHintAttr *
2118TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
2119 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
2120
2121 if (TransformedExpr == LH->getValue())
2122 return LH;
2123
2124 // Generate error if there is a problem with the value.
2125 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation(),
2126 LH->getSemanticSpelling() ==
2127 LoopHintAttr::Pragma_unroll))
2128 return LH;
2129
2130 LoopHintAttr::OptionType Option = LH->getOption();
2131 LoopHintAttr::LoopHintState State = LH->getState();
2132
2133 llvm::APSInt ValueAPS =
2134 TransformedExpr->EvaluateKnownConstInt(getSema().getASTContext());
2135 // The values of 0 and 1 block any unrolling of the loop.
2136 if (ValueAPS.isZero() || ValueAPS.isOne()) {
2137 Option = LoopHintAttr::Unroll;
2138 State = LoopHintAttr::Disable;
2139 }
2140
2141 // Create new LoopHintValueAttr with integral expression in place of the
2142 // non-type template parameter.
2143 return LoopHintAttr::CreateImplicit(getSema().Context, Option, State,
2144 TransformedExpr, *LH);
2145}
2146const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
2147 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
2148 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
2149 return nullptr;
2150
2151 return A;
2152}
2153const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
2154 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
2155 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
2156 return nullptr;
2157
2158 return A;
2159}
2160
2161const CodeAlignAttr *
2162TemplateInstantiator::TransformCodeAlignAttr(const CodeAlignAttr *CA) {
2163 Expr *TransformedExpr = getDerived().TransformExpr(CA->getAlignment()).get();
2164 return getSema().BuildCodeAlignAttr(*CA, TransformedExpr);
2165}
2166
2167ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
2168 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
2170 std::optional<unsigned> PackIndex) {
2171 ExprResult result;
2172
2173 // Determine the substituted parameter type. We can usually infer this from
2174 // the template argument, but not always.
2175 auto SubstParamType = [&] {
2176 QualType T;
2177 if (parm->isExpandedParameterPack())
2179 else
2180 T = parm->getType();
2181 if (parm->isParameterPack() && isa<PackExpansionType>(T))
2182 T = cast<PackExpansionType>(T)->getPattern();
2183 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
2184 };
2185
2186 bool refParam = false;
2187
2188 // The template argument itself might be an expression, in which case we just
2189 // return that expression. This happens when substituting into an alias
2190 // template.
2191 if (arg.getKind() == TemplateArgument::Expression) {
2192 Expr *argExpr = arg.getAsExpr();
2193 result = argExpr;
2194 if (argExpr->isLValue()) {
2195 if (argExpr->getType()->isRecordType()) {
2196 // Check whether the parameter was actually a reference.
2197 QualType paramType = SubstParamType();
2198 if (paramType.isNull())
2199 return ExprError();
2200 refParam = paramType->isReferenceType();
2201 } else {
2202 refParam = true;
2203 }
2204 }
2205 } else if (arg.getKind() == TemplateArgument::Declaration ||
2206 arg.getKind() == TemplateArgument::NullPtr) {
2207 if (arg.getKind() == TemplateArgument::Declaration) {
2208 ValueDecl *VD = arg.getAsDecl();
2209
2210 // Find the instantiation of the template argument. This is
2211 // required for nested templates.
2212 VD = cast_or_null<ValueDecl>(
2213 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
2214 if (!VD)
2215 return ExprError();
2216 }
2217
2218 QualType paramType = arg.getNonTypeTemplateArgumentType();
2219 assert(!paramType.isNull() && "type substitution failed for param type");
2220 assert(!paramType->isDependentType() && "param type still dependent");
2221 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
2222 refParam = paramType->isReferenceType();
2223 } else {
2224 QualType paramType = arg.getNonTypeTemplateArgumentType();
2226 refParam = paramType->isReferenceType();
2227 assert(result.isInvalid() ||
2229 paramType.getNonReferenceType()));
2230 }
2231
2232 if (result.isInvalid())
2233 return ExprError();
2234
2235 Expr *resultExpr = result.get();
2236 // FIXME: Don't put subst node on final replacement.
2238 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
2239 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
2240}
2241
2243TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
2245 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2246 // We aren't expanding the parameter pack, so just return ourselves.
2247 return E;
2248 }
2249
2250 TemplateArgument Pack = E->getArgumentPack();
2252 // FIXME: Don't put subst node on final replacement.
2253 return transformNonTypeTemplateParmRef(
2254 E->getAssociatedDecl(), E->getParameterPack(),
2255 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
2256}
2257
2259TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
2261 ExprResult SubstReplacement = E->getReplacement();
2262 if (!isa<ConstantExpr>(SubstReplacement.get()))
2263 SubstReplacement = TransformExpr(E->getReplacement());
2264 if (SubstReplacement.isInvalid())
2265 return true;
2266 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
2267 if (SubstType.isNull())
2268 return true;
2269 // The type may have been previously dependent and not now, which means we
2270 // might have to implicit cast the argument to the new type, for example:
2271 // template<auto T, decltype(T) U>
2272 // concept C = sizeof(U) == 4;
2273 // void foo() requires C<2, 'a'> { }
2274 // When normalizing foo(), we first form the normalized constraints of C:
2275 // AtomicExpr(sizeof(U) == 4,
2276 // U=SubstNonTypeTemplateParmExpr(Param=U,
2277 // Expr=DeclRef(U),
2278 // Type=decltype(T)))
2279 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
2280 // produce:
2281 // AtomicExpr(sizeof(U) == 4,
2282 // U=SubstNonTypeTemplateParmExpr(Param=U,
2283 // Expr=ImpCast(
2284 // decltype(2),
2285 // SubstNTTPE(Param=U, Expr='a',
2286 // Type=char)),
2287 // Type=decltype(2)))
2288 // The call to CheckTemplateArgument here produces the ImpCast.
2289 TemplateArgument SugaredConverted, CanonicalConverted;
2290 if (SemaRef
2291 .CheckTemplateArgument(E->getParameter(), SubstType,
2292 SubstReplacement.get(), SugaredConverted,
2293 CanonicalConverted, Sema::CTAK_Specified)
2294 .isInvalid())
2295 return true;
2296 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
2297 E->getParameter(), E->getExprLoc(),
2298 SugaredConverted, E->getPackIndex());
2299}
2300
2301ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
2303 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
2304 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
2305}
2306
2308TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
2309 if (getSema().ArgumentPackSubstitutionIndex != -1) {
2310 // We can expand this parameter pack now.
2311 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
2312 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
2313 if (!VD)
2314 return ExprError();
2315 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
2316 }
2317
2318 QualType T = TransformType(E->getType());
2319 if (T.isNull())
2320 return ExprError();
2321
2322 // Transform each of the parameter expansions into the corresponding
2323 // parameters in the instantiation of the function decl.
2325 Vars.reserve(E->getNumExpansions());
2326 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
2327 I != End; ++I) {
2328 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
2329 if (!D)
2330 return ExprError();
2331 Vars.push_back(D);
2332 }
2333
2334 auto *PackExpr =
2335 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
2336 E->getParameterPackLocation(), Vars);
2337 getSema().MarkFunctionParmPackReferenced(PackExpr);
2338 return PackExpr;
2339}
2340
2342TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
2343 VarDecl *PD) {
2344 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
2345 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
2346 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
2347 assert(Found && "no instantiation for parameter pack");
2348
2349 Decl *TransformedDecl;
2350 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
2351 // If this is a reference to a function parameter pack which we can
2352 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
2353 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2354 QualType T = TransformType(E->getType());
2355 if (T.isNull())
2356 return ExprError();
2357 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
2358 E->getExprLoc(), *Pack);
2359 getSema().MarkFunctionParmPackReferenced(PackExpr);
2360 return PackExpr;
2361 }
2362
2363 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
2364 } else {
2365 TransformedDecl = Found->get<Decl*>();
2366 }
2367
2368 // We have either an unexpanded pack or a specific expansion.
2369 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
2370}
2371
2373TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2374 NamedDecl *D = E->getDecl();
2375
2376 // Handle references to non-type template parameters and non-type template
2377 // parameter packs.
2378 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2379 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2380 return TransformTemplateParmRefExpr(E, NTTP);
2381
2382 // We have a non-type template parameter that isn't fully substituted;
2383 // FindInstantiatedDecl will find it in the local instantiation scope.
2384 }
2385
2386 // Handle references to function parameter packs.
2387 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2388 if (PD->isParameterPack())
2389 return TransformFunctionParmPackRefExpr(E, PD);
2390
2391 return inherited::TransformDeclRefExpr(E);
2392}
2393
2394ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2396 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->
2397 getDescribedFunctionTemplate() &&
2398 "Default arg expressions are never formed in dependent cases.");
2400 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2401 E->getParam());
2402}
2403
2404template<typename Fn>
2405QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2407 CXXRecordDecl *ThisContext,
2408 Qualifiers ThisTypeQuals,
2409 Fn TransformExceptionSpec) {
2410 // We need a local instantiation scope for this function prototype.
2411 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2412 return inherited::TransformFunctionProtoType(
2413 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2414}
2415
2416ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2417 ParmVarDecl *OldParm, int indexAdjustment,
2418 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2419 auto NewParm = SemaRef.SubstParmVarDecl(
2420 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2421 ExpectParameterPack, EvaluateConstraints);
2422 if (NewParm && SemaRef.getLangOpts().OpenCL)
2424 return NewParm;
2425}
2426
2427QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2428 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2429 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2430 TemplateArgument Arg, SourceLocation NameLoc) {
2431 QualType Replacement = Arg.getAsType();
2432
2433 // If the template parameter had ObjC lifetime qualifiers,
2434 // then any such qualifiers on the replacement type are ignored.
2435 if (SuppressObjCLifetime) {
2436 Qualifiers RQs;
2437 RQs = Replacement.getQualifiers();
2438 RQs.removeObjCLifetime();
2439 Replacement =
2440 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2441 }
2442
2443 if (Final) {
2444 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2445 return Replacement;
2446 }
2447 // TODO: only do this uniquing once, at the start of instantiation.
2448 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2449 Replacement, AssociatedDecl, Index, PackIndex);
2452 NewTL.setNameLoc(NameLoc);
2453 return Result;
2454}
2455
2457TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2459 bool SuppressObjCLifetime) {
2460 const TemplateTypeParmType *T = TL.getTypePtr();
2461 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2462 // Replace the template type parameter with its corresponding
2463 // template argument.
2464
2465 // If the corresponding template argument is NULL or doesn't exist, it's
2466 // because we are performing instantiation from explicitly-specified
2467 // template arguments in a function template class, but there were some
2468 // arguments left unspecified.
2469 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2472 NewTL.setNameLoc(TL.getNameLoc());
2473 return TL.getType();
2474 }
2475
2476 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2477
2478 if (TemplateArgs.isRewrite()) {
2479 // We're rewriting the template parameter as a reference to another
2480 // template parameter.
2481 if (Arg.getKind() == TemplateArgument::Pack) {
2482 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&
2483 "unexpected pack arguments in template rewrite");
2484 Arg = Arg.pack_begin()->getPackExpansionPattern();
2485 }
2486 assert(Arg.getKind() == TemplateArgument::Type &&
2487 "unexpected nontype template argument kind in template rewrite");
2488 QualType NewT = Arg.getAsType();
2489 TLB.pushTrivial(SemaRef.Context, NewT, TL.getNameLoc());
2490 return NewT;
2491 }
2492
2493 auto [AssociatedDecl, Final] =
2494 TemplateArgs.getAssociatedDecl(T->getDepth());
2495 std::optional<unsigned> PackIndex;
2496 if (T->isParameterPack()) {
2497 assert(Arg.getKind() == TemplateArgument::Pack &&
2498 "Missing argument pack");
2499
2500 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2501 // We have the template argument pack, but we're not expanding the
2502 // enclosing pack expansion yet. Just save the template argument
2503 // pack for later substitution.
2504 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2505 AssociatedDecl, T->getIndex(), Final, Arg);
2508 NewTL.setNameLoc(TL.getNameLoc());
2509 return Result;
2510 }
2511
2512 // PackIndex starts from last element.
2513 PackIndex = getPackIndex(Arg);
2514 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2515 }
2516
2517 assert(Arg.getKind() == TemplateArgument::Type &&
2518 "Template argument kind mismatch");
2519
2520 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2521 AssociatedDecl, T->getIndex(),
2522 PackIndex, Arg, TL.getNameLoc());
2523 }
2524
2525 // The template type parameter comes from an inner template (e.g.,
2526 // the template parameter list of a member template inside the
2527 // template we are instantiating). Create a new template type
2528 // parameter with the template "level" reduced by one.
2529 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2530 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2531 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2532 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2533 QualType Result = getSema().Context.getTemplateTypeParmType(
2534 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2535 T->isParameterPack(), NewTTPDecl);
2537 NewTL.setNameLoc(TL.getNameLoc());
2538 return Result;
2539}
2540
2541QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2543 bool SuppressObjCLifetime) {
2545
2546 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2547
2548 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2549 // We aren't expanding the parameter pack, so just return ourselves.
2550 QualType Result = TL.getType();
2551 if (NewReplaced != T->getAssociatedDecl())
2552 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2553 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2556 NewTL.setNameLoc(TL.getNameLoc());
2557 return Result;
2558 }
2559
2560 TemplateArgument Pack = T->getArgumentPack();
2562 return BuildSubstTemplateTypeParmType(
2563 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2564 getPackIndex(Pack), Arg, TL.getNameLoc());
2565}
2566
2569 concepts::EntityPrinter Printer) {
2570 SmallString<128> Message;
2571 SourceLocation ErrorLoc;
2572 if (Info.hasSFINAEDiagnostic()) {
2575 Info.takeSFINAEDiagnostic(PDA);
2576 PDA.second.EmitToString(S.getDiagnostics(), Message);
2577 ErrorLoc = PDA.first;
2578 } else {
2579 ErrorLoc = Info.getLocation();
2580 }
2581 SmallString<128> Entity;
2582 llvm::raw_svector_ostream OS(Entity);
2583 Printer(OS);
2584 const ASTContext &C = S.Context;
2586 C.backupStr(Entity), ErrorLoc, C.backupStr(Message)};
2587}
2588
2591 EntityPrinter Printer) {
2592 SmallString<128> Entity;
2593 llvm::raw_svector_ostream OS(Entity);
2594 Printer(OS);
2595 const ASTContext &C = S.Context;
2597 /*SubstitutedEntity=*/C.backupStr(Entity),
2598 /*DiagLoc=*/Location, /*DiagMessage=*/StringRef()};
2599}
2600
2601ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2602 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2605 SmallVectorImpl<ParmVarDecl *> &TransParams,
2607
2608 TemplateDeductionInfo Info(KWLoc);
2609 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2610 RE, Info,
2611 SourceRange{KWLoc, RBraceLoc});
2613
2614 unsigned ErrorIdx;
2615 if (getDerived().TransformFunctionTypeParams(
2616 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2617 &TransParams, PInfos, &ErrorIdx) ||
2618 Trap.hasErrorOccurred()) {
2620 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2621 // Add a 'failed' Requirement to contain the error that caused the failure
2622 // here.
2623 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2624 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2625 return getDerived().RebuildRequiresExpr(KWLoc, Body, RE->getLParenLoc(),
2626 TransParams, RE->getRParenLoc(),
2627 TransReqs, RBraceLoc);
2628 }
2629
2630 return ExprResult{};
2631}
2632
2634TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2635 if (!Req->isDependent() && !AlwaysRebuild())
2636 return Req;
2637 if (Req->isSubstitutionFailure()) {
2638 if (AlwaysRebuild())
2639 return RebuildTypeRequirement(
2641 return Req;
2642 }
2643
2647 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2648 Req->getType()->getTypeLoc().getSourceRange());
2649 if (TypeInst.isInvalid())
2650 return nullptr;
2651 TypeSourceInfo *TransType = TransformType(Req->getType());
2652 if (!TransType || Trap.hasErrorOccurred())
2653 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2654 [&] (llvm::raw_ostream& OS) {
2655 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2656 }));
2657 return RebuildTypeRequirement(TransType);
2658}
2659
2661TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2662 if (!Req->isDependent() && !AlwaysRebuild())
2663 return Req;
2664
2666
2667 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2668 TransExpr;
2669 if (Req->isExprSubstitutionFailure())
2670 TransExpr = Req->getExprSubstitutionDiagnostic();
2671 else {
2672 Expr *E = Req->getExpr();
2674 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2675 E->getSourceRange());
2676 if (ExprInst.isInvalid())
2677 return nullptr;
2678 ExprResult TransExprRes = TransformExpr(E);
2679 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2680 TransExprRes.get()->hasPlaceholderType())
2681 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2682 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2683 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2685 });
2686 else
2687 TransExpr = TransExprRes.get();
2688 }
2689
2690 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2691 const auto &RetReq = Req->getReturnTypeRequirement();
2692 if (RetReq.isEmpty())
2693 TransRetReq.emplace();
2694 else if (RetReq.isSubstitutionFailure())
2695 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2696 else if (RetReq.isTypeConstraint()) {
2697 TemplateParameterList *OrigTPL =
2698 RetReq.getTypeConstraintTemplateParameterList();
2699 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2701 Req, Info, OrigTPL->getSourceRange());
2702 if (TPLInst.isInvalid())
2703 return nullptr;
2704 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2705 if (!TPL || Trap.hasErrorOccurred())
2706 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2707 [&] (llvm::raw_ostream& OS) {
2708 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2709 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2710 }));
2711 else {
2712 TPLInst.Clear();
2713 TransRetReq.emplace(TPL);
2714 }
2715 }
2716 assert(TransRetReq && "All code paths leading here must set TransRetReq");
2717 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2718 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2719 std::move(*TransRetReq));
2720 return RebuildExprRequirement(
2722 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2723}
2724
2726TemplateInstantiator::TransformNestedRequirement(
2728 if (!Req->isDependent() && !AlwaysRebuild())
2729 return Req;
2730 if (Req->hasInvalidConstraint()) {
2731 if (AlwaysRebuild())
2732 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2734 return Req;
2735 }
2737 Req->getConstraintExpr()->getBeginLoc(), Req,
2740 if (!getEvaluateConstraints()) {
2741 ExprResult TransConstraint = TransformExpr(Req->getConstraintExpr());
2742 if (TransConstraint.isInvalid() || !TransConstraint.get())
2743 return nullptr;
2744 if (TransConstraint.get()->isInstantiationDependent())
2745 return new (SemaRef.Context)
2746 concepts::NestedRequirement(TransConstraint.get());
2747 ConstraintSatisfaction Satisfaction;
2749 SemaRef.Context, TransConstraint.get(), Satisfaction);
2750 }
2751
2752 ExprResult TransConstraint;
2753 ConstraintSatisfaction Satisfaction;
2755 {
2760 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2762 if (ConstrInst.isInvalid())
2763 return nullptr;
2766 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2767 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2768 !Result.empty())
2769 TransConstraint = Result[0];
2770 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "
2771 "by CheckConstraintSatisfaction.");
2772 }
2774 if (TransConstraint.isUsable() &&
2775 TransConstraint.get()->isInstantiationDependent())
2776 return new (C) concepts::NestedRequirement(TransConstraint.get());
2777 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2778 Satisfaction.HasSubstitutionFailure()) {
2779 SmallString<128> Entity;
2780 llvm::raw_svector_ostream OS(Entity);
2781 Req->getConstraintExpr()->printPretty(OS, nullptr,
2783 return new (C) concepts::NestedRequirement(
2784 SemaRef.Context, C.backupStr(Entity), Satisfaction);
2785 }
2786 return new (C)
2787 concepts::NestedRequirement(C, TransConstraint.get(), Satisfaction);
2788}
2789
2793 DeclarationName Entity,
2794 bool AllowDeducedTST) {
2795 assert(!CodeSynthesisContexts.empty() &&
2796 "Cannot perform an instantiation without some context on the "
2797 "instantiation stack");
2798
2799 if (!T->getType()->isInstantiationDependentType() &&
2800 !T->getType()->isVariablyModifiedType())
2801 return T;
2802
2803 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2804 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2805 : Instantiator.TransformType(T);
2806}
2807
2811 DeclarationName Entity) {
2812 assert(!CodeSynthesisContexts.empty() &&
2813 "Cannot perform an instantiation without some context on the "
2814 "instantiation stack");
2815
2816 if (TL.getType().isNull())
2817 return nullptr;
2818
2821 // FIXME: Make a copy of the TypeLoc data here, so that we can
2822 // return a new TypeSourceInfo. Inefficient!
2823 TypeLocBuilder TLB;
2824 TLB.pushFullCopy(TL);
2825 return TLB.getTypeSourceInfo(Context, TL.getType());
2826 }
2827
2828 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2829 TypeLocBuilder TLB;
2830 TLB.reserve(TL.getFullDataSize());
2831 QualType Result = Instantiator.TransformType(TLB, TL);
2832 if (Result.isNull())
2833 return nullptr;
2834
2835 return TLB.getTypeSourceInfo(Context, Result);
2836}
2837
2838/// Deprecated form of the above.
2840 const MultiLevelTemplateArgumentList &TemplateArgs,
2842 assert(!CodeSynthesisContexts.empty() &&
2843 "Cannot perform an instantiation without some context on the "
2844 "instantiation stack");
2845
2846 // If T is not a dependent type or a variably-modified type, there
2847 // is nothing to do.
2849 return T;
2850
2851 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2852 return Instantiator.TransformType(T);
2853}
2854
2856 if (T->getType()->isInstantiationDependentType() ||
2857 T->getType()->isVariablyModifiedType())
2858 return true;
2859
2860 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2861 if (!TL.getAs<FunctionProtoTypeLoc>())
2862 return false;
2863
2865 for (ParmVarDecl *P : FP.getParams()) {
2866 // This must be synthesized from a typedef.
2867 if (!P) continue;
2868
2869 // If there are any parameters, a new TypeSourceInfo that refers to the
2870 // instantiated parameters must be built.
2871 return true;
2872 }
2873
2874 return false;
2875}
2876
2880 DeclarationName Entity,
2881 CXXRecordDecl *ThisContext,
2882 Qualifiers ThisTypeQuals,
2883 bool EvaluateConstraints) {
2884 assert(!CodeSynthesisContexts.empty() &&
2885 "Cannot perform an instantiation without some context on the "
2886 "instantiation stack");
2887
2889 return T;
2890
2891 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2892 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2893
2894 TypeLocBuilder TLB;
2895
2896 TypeLoc TL = T->getTypeLoc();
2897 TLB.reserve(TL.getFullDataSize());
2898
2900
2901 if (FunctionProtoTypeLoc Proto =
2903 // Instantiate the type, other than its exception specification. The
2904 // exception specification is instantiated in InitFunctionInstantiation
2905 // once we've built the FunctionDecl.
2906 // FIXME: Set the exception specification to EST_Uninstantiated here,
2907 // instead of rebuilding the function type again later.
2908 Result = Instantiator.TransformFunctionProtoType(
2909 TLB, Proto, ThisContext, ThisTypeQuals,
2911 bool &Changed) { return false; });
2912 } else {
2913 Result = Instantiator.TransformType(TLB, TL);
2914 }
2915 // When there are errors resolving types, clang may use IntTy as a fallback,
2916 // breaking our assumption that function declarations have function types.
2917 if (Result.isNull() || !Result->isFunctionType())
2918 return nullptr;
2919
2920 return TLB.getTypeSourceInfo(Context, Result);
2921}
2922
2925 SmallVectorImpl<QualType> &ExceptionStorage,
2926 const MultiLevelTemplateArgumentList &Args) {
2927 bool Changed = false;
2928 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2929 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2930 Changed);
2931}
2932
2934 const MultiLevelTemplateArgumentList &Args) {
2937
2938 SmallVector<QualType, 4> ExceptionStorage;
2940 ESI, ExceptionStorage, Args))
2941 // On error, recover by dropping the exception specification.
2942 ESI.Type = EST_None;
2943
2944 UpdateExceptionSpec(New, ESI);
2945}
2946
2947namespace {
2948
2949 struct GetContainedInventedTypeParmVisitor :
2950 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2951 TemplateTypeParmDecl *> {
2952 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2953 TemplateTypeParmDecl *>::Visit;
2954
2956 if (T.isNull())
2957 return nullptr;
2958 return Visit(T.getTypePtr());
2959 }
2960 // The deduced type itself.
2961 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2962 const TemplateTypeParmType *T) {
2963 if (!T->getDecl() || !T->getDecl()->isImplicit())
2964 return nullptr;
2965 return T->getDecl();
2966 }
2967
2968 // Only these types can contain 'auto' types, and subsequently be replaced
2969 // by references to invented parameters.
2970
2971 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2972 return Visit(T->getNamedType());
2973 }
2974
2975 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2976 return Visit(T->getPointeeType());
2977 }
2978
2979 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2980 return Visit(T->getPointeeType());
2981 }
2982
2983 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2984 return Visit(T->getPointeeTypeAsWritten());
2985 }
2986
2987 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2988 return Visit(T->getPointeeType());
2989 }
2990
2991 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2992 return Visit(T->getElementType());
2993 }
2994
2995 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2997 return Visit(T->getElementType());
2998 }
2999
3000 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
3001 return Visit(T->getElementType());
3002 }
3003
3004 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
3005 return VisitFunctionType(T);
3006 }
3007
3008 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
3009 return Visit(T->getReturnType());
3010 }
3011
3012 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
3013 return Visit(T->getInnerType());
3014 }
3015
3016 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
3017 return Visit(T->getModifiedType());
3018 }
3019
3020 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
3021 return Visit(T->getUnderlyingType());
3022 }
3023
3024 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
3025 return Visit(T->getOriginalType());
3026 }
3027
3028 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
3029 return Visit(T->getPattern());
3030 }
3031 };
3032
3033} // namespace
3034
3036 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
3037 const MultiLevelTemplateArgumentList &TemplateArgs,
3038 bool EvaluateConstraints) {
3039 const ASTTemplateArgumentListInfo *TemplArgInfo =
3041
3042 if (!EvaluateConstraints) {
3045 return false;
3046 }
3047
3048 TemplateArgumentListInfo InstArgs;
3049
3050 if (TemplArgInfo) {
3051 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
3052 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
3053 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
3054 InstArgs))
3055 return true;
3056 }
3057 return AttachTypeConstraint(
3059 TC->getNamedConcept(),
3060 /*FoundDecl=*/TC->getConceptReference()->getFoundDecl(), &InstArgs, Inst,
3061 Inst->isParameterPack()
3062 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
3063 ->getEllipsisLoc()
3064 : SourceLocation());
3065}
3066
3068 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
3069 int indexAdjustment, std::optional<unsigned> NumExpansions,
3070 bool ExpectParameterPack, bool EvaluateConstraint) {
3071 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
3072 TypeSourceInfo *NewDI = nullptr;
3073
3074 TypeLoc OldTL = OldDI->getTypeLoc();
3075 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
3076
3077 // We have a function parameter pack. Substitute into the pattern of the
3078 // expansion.
3079 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
3080 OldParm->getLocation(), OldParm->getDeclName());
3081 if (!NewDI)
3082 return nullptr;
3083
3084 if (NewDI->getType()->containsUnexpandedParameterPack()) {
3085 // We still have unexpanded parameter packs, which means that
3086 // our function parameter is still a function parameter pack.
3087 // Therefore, make its type a pack expansion type.
3088 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
3089 NumExpansions);
3090 } else if (ExpectParameterPack) {
3091 // We expected to get a parameter pack but didn't (because the type
3092 // itself is not a pack expansion type), so complain. This can occur when
3093 // the substitution goes through an alias template that "loses" the
3094 // pack expansion.
3095 Diag(OldParm->getLocation(),
3096 diag::err_function_parameter_pack_without_parameter_packs)
3097 << NewDI->getType();
3098 return nullptr;
3099 }
3100 } else {
3101 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
3102 OldParm->getDeclName());
3103 }
3104
3105 if (!NewDI)
3106 return nullptr;
3107
3108 if (NewDI->getType()->isVoidType()) {
3109 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
3110 return nullptr;
3111 }
3112
3113 // In abbreviated templates, TemplateTypeParmDecls with possible
3114 // TypeConstraints are created when the parameter list is originally parsed.
3115 // The TypeConstraints can therefore reference other functions parameters in
3116 // the abbreviated function template, which is why we must instantiate them
3117 // here, when the instantiated versions of those referenced parameters are in
3118 // scope.
3119 if (TemplateTypeParmDecl *TTP =
3120 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
3121 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
3122 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
3123 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
3124 // We will first get here when instantiating the abbreviated function
3125 // template's described function, but we might also get here later.
3126 // Make sure we do not instantiate the TypeConstraint more than once.
3127 if (Inst && !Inst->getTypeConstraint()) {
3128 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
3129 return nullptr;
3130 }
3131 }
3132 }
3133
3135 OldParm->getInnerLocStart(),
3136 OldParm->getLocation(),
3137 OldParm->getIdentifier(),
3138 NewDI->getType(), NewDI,
3139 OldParm->getStorageClass());
3140 if (!NewParm)
3141 return nullptr;
3142
3143 // Mark the (new) default argument as uninstantiated (if any).
3144 if (OldParm->hasUninstantiatedDefaultArg()) {
3145 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
3146 NewParm->setUninstantiatedDefaultArg(Arg);
3147 } else if (OldParm->hasUnparsedDefaultArg()) {
3148 NewParm->setUnparsedDefaultArg();
3149 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
3150 } else if (Expr *Arg = OldParm->getDefaultArg()) {
3151 // Default arguments cannot be substituted until the declaration context
3152 // for the associated function or lambda capture class is available.
3153 // This is necessary for cases like the following where construction of
3154 // the lambda capture class for the outer lambda is dependent on the
3155 // parameter types but where the default argument is dependent on the
3156 // outer lambda's declaration context.
3157 // template <typename T>
3158 // auto f() {
3159 // return [](T = []{ return T{}; }()) { return 0; };
3160 // }
3161 NewParm->setUninstantiatedDefaultArg(Arg);
3162 }
3163
3167
3168 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
3169 // Add the new parameter to the instantiated parameter pack.
3171 } else {
3172 // Introduce an Old -> New mapping
3174 }
3175
3176 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
3177 // can be anything, is this right ?
3178 NewParm->setDeclContext(CurContext);
3179
3180 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
3181 OldParm->getFunctionScopeIndex() + indexAdjustment);
3182
3183 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
3184
3185 return NewParm;
3186}
3187
3190 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
3191 const MultiLevelTemplateArgumentList &TemplateArgs,
3192 SmallVectorImpl<QualType> &ParamTypes,
3194 ExtParameterInfoBuilder &ParamInfos) {
3195 assert(!CodeSynthesisContexts.empty() &&
3196 "Cannot perform an instantiation without some context on the "
3197 "instantiation stack");
3198
3199 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
3200 DeclarationName());
3201 return Instantiator.TransformFunctionTypeParams(
3202 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
3203}
3204
3207 ParmVarDecl *Param,
3208 const MultiLevelTemplateArgumentList &TemplateArgs,
3209 bool ForCallExpr) {
3210 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
3211 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
3212
3215
3216 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
3217 if (Inst.isInvalid())
3218 return true;
3219 if (Inst.isAlreadyInstantiating()) {
3220 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
3221 Param->setInvalidDecl();
3222 return true;
3223 }
3224
3226 {
3227 // C++ [dcl.fct.default]p5:
3228 // The names in the [default argument] expression are bound, and
3229 // the semantic constraints are checked, at the point where the
3230 // default argument expression appears.
3231 ContextRAII SavedContext(*this, FD);
3232 std::unique_ptr<LocalInstantiationScope> LIS;
3233
3234 if (ForCallExpr) {
3235 // When instantiating a default argument due to use in a call expression,
3236 // an instantiation scope that includes the parameters of the callee is
3237 // required to satisfy references from the default argument. For example:
3238 // template<typename T> void f(T a, int = decltype(a)());
3239 // void g() { f(0); }
3240 LIS = std::make_unique<LocalInstantiationScope>(*this);
3242 /*ForDefinition*/ false);
3243 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
3244 return true;
3245 }
3246
3248 Result = SubstInitializer(PatternExpr, TemplateArgs,
3249 /*DirectInit*/ false);
3250 });
3251 }
3252 if (Result.isInvalid())
3253 return true;
3254
3255 if (ForCallExpr) {
3256 // Check the expression as an initializer for the parameter.
3257 InitializedEntity Entity
3260 Param->getLocation(),
3261 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
3262 Expr *ResultE = Result.getAs<Expr>();
3263
3264 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
3265 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
3266 if (Result.isInvalid())
3267 return true;
3268
3269 Result =
3271 /*DiscardedValue*/ false);
3272 } else {
3273 // FIXME: Obtain the source location for the '=' token.
3274 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
3275 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
3276 }
3277 if (Result.isInvalid())
3278 return true;
3279
3280 // Remember the instantiated default argument.
3281 Param->setDefaultArg(Result.getAs<Expr>());
3282
3283 return false;
3284}
3285
3286bool
3288 CXXRecordDecl *Pattern,
3289 const MultiLevelTemplateArgumentList &TemplateArgs) {
3290 bool Invalid = false;
3291 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
3292 for (const auto &Base : Pattern->bases()) {
3293 if (!Base.getType()->isDependentType()) {
3294 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
3295 if (RD->isInvalidDecl())
3296 Instantiation->setInvalidDecl();
3297 }
3298 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
3299 continue;
3300 }
3301
3302 SourceLocation EllipsisLoc;
3303 TypeSourceInfo *BaseTypeLoc;
3304 if (Base.isPackExpansion()) {
3305 // This is a pack expansion. See whether we should expand it now, or
3306 // wait until later.
3308 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
3309 Unexpanded);
3310 bool ShouldExpand = false;
3311 bool RetainExpansion = false;
3312 std::optional<unsigned> NumExpansions;
3313 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
3314 Base.getSourceRange(),
3315 Unexpanded,
3316 TemplateArgs, ShouldExpand,
3317 RetainExpansion,
3318 NumExpansions)) {
3319 Invalid = true;
3320 continue;
3321 }
3322
3323 // If we should expand this pack expansion now, do so.
3324 if (ShouldExpand) {
3325 for (unsigned I = 0; I != *NumExpansions; ++I) {
3326 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
3327
3328 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3329 TemplateArgs,
3330 Base.getSourceRange().getBegin(),
3331 DeclarationName());
3332 if (!BaseTypeLoc) {
3333 Invalid = true;
3334 continue;
3335 }
3336
3337 if (CXXBaseSpecifier *InstantiatedBase
3338 = CheckBaseSpecifier(Instantiation,
3339 Base.getSourceRange(),
3340 Base.isVirtual(),
3341 Base.getAccessSpecifierAsWritten(),
3342 BaseTypeLoc,
3343 SourceLocation()))
3344 InstantiatedBases.push_back(InstantiatedBase);
3345 else
3346 Invalid = true;
3347 }
3348
3349 continue;
3350 }
3351
3352 // The resulting base specifier will (still) be a pack expansion.
3353 EllipsisLoc = Base.getEllipsisLoc();
3354 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3355 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3356 TemplateArgs,
3357 Base.getSourceRange().getBegin(),
3358 DeclarationName());
3359 } else {
3360 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3361 TemplateArgs,
3362 Base.getSourceRange().getBegin(),
3363 DeclarationName());
3364 }
3365
3366 if (!BaseTypeLoc) {
3367 Invalid = true;
3368 continue;
3369 }
3370
3371 if (CXXBaseSpecifier *InstantiatedBase
3372 = CheckBaseSpecifier(Instantiation,
3373 Base.getSourceRange(),
3374 Base.isVirtual(),
3375 Base.getAccessSpecifierAsWritten(),
3376 BaseTypeLoc,
3377 EllipsisLoc))
3378 InstantiatedBases.push_back(InstantiatedBase);
3379 else
3380 Invalid = true;
3381 }
3382
3383 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3384 Invalid = true;
3385
3386 return Invalid;
3387}
3388
3389// Defined via #include from SemaTemplateInstantiateDecl.cpp
3390namespace clang {
3391 namespace sema {
3393 const MultiLevelTemplateArgumentList &TemplateArgs);
3395 const Attr *At, ASTContext &C, Sema &S,
3396 const MultiLevelTemplateArgumentList &TemplateArgs);
3397 }
3398}
3399
3400bool
3402 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3403 const MultiLevelTemplateArgumentList &TemplateArgs,
3405 bool Complain) {
3406 CXXRecordDecl *PatternDef
3407 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3408 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3409 Instantiation->getInstantiatedFromMemberClass(),
3410 Pattern, PatternDef, TSK, Complain))
3411 return true;
3412
3413 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3414 llvm::TimeTraceMetadata M;
3415 llvm::raw_string_ostream OS(M.Detail);
3416 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3417 /*Qualified=*/true);
3418 if (llvm::isTimeTraceVerbose()) {
3419 auto Loc = SourceMgr.getExpansionLoc(Instantiation->getLocation());
3420 M.File = SourceMgr.getFilename(Loc);
3422 }
3423 return M;
3424 });
3425
3426 Pattern = PatternDef;
3427
3428 // Record the point of instantiation.
3429 if (MemberSpecializationInfo *MSInfo
3430 = Instantiation->getMemberSpecializationInfo()) {
3431 MSInfo->setTemplateSpecializationKind(TSK);
3432 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3433 } else if (ClassTemplateSpecializationDecl *Spec
3434 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3435 Spec->setTemplateSpecializationKind(TSK);
3436 Spec->setPointOfInstantiation(PointOfInstantiation);
3437 }
3438
3439 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3440 if (Inst.isInvalid())
3441 return true;
3442 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller");
3443 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3444 "instantiating class definition");
3445
3446 // Enter the scope of this instantiation. We don't use
3447 // PushDeclContext because we don't have a scope.
3448 ContextRAII SavedContext(*this, Instantiation);
3451
3452 // If this is an instantiation of a local class, merge this local
3453 // instantiation scope with the enclosing scope. Otherwise, every
3454 // instantiation of a class has its own local instantiation scope.
3455 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3456 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3457
3458 // Some class state isn't processed immediately but delayed till class
3459 // instantiation completes. We may not be ready to handle any delayed state
3460 // already on the stack as it might correspond to a different class, so save
3461 // it now and put it back later.
3462 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3463
3464 // Pull attributes from the pattern onto the instantiation.
3465 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3466
3467 // Start the definition of this instantiation.
3468 Instantiation->startDefinition();
3469
3470 // The instantiation is visible here, even if it was first declared in an
3471 // unimported module.
3472 Instantiation->setVisibleDespiteOwningModule();
3473
3474 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3475 Instantiation->setTagKind(Pattern->getTagKind());
3476
3477 // Do substitution on the base class specifiers.
3478 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3479 Instantiation->setInvalidDecl();
3480
3481 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3482 Instantiator.setEvaluateConstraints(false);
3483 SmallVector<Decl*, 4> Fields;
3484 // Delay instantiation of late parsed attributes.
3485 LateInstantiatedAttrVec LateAttrs;
3486 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3487
3488 bool MightHaveConstexprVirtualFunctions = false;
3489 for (auto *Member : Pattern->decls()) {
3490 // Don't instantiate members not belonging in this semantic context.
3491 // e.g. for:
3492 // @code
3493 // template <int i> class A {
3494 // class B *g;
3495 // };
3496 // @endcode
3497 // 'class B' has the template as lexical context but semantically it is
3498 // introduced in namespace scope.
3499 if (Member->getDeclContext() != Pattern)
3500 continue;
3501
3502 // BlockDecls can appear in a default-member-initializer. They must be the
3503 // child of a BlockExpr, so we only know how to instantiate them from there.
3504 // Similarly, lambda closure types are recreated when instantiating the
3505 // corresponding LambdaExpr.
3506 if (isa<BlockDecl>(Member) ||
3507 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3508 continue;
3509
3510 if (Member->isInvalidDecl()) {
3511 Instantiation->setInvalidDecl();
3512 continue;
3513 }
3514
3515 Decl *NewMember = Instantiator.Visit(Member);
3516 if (NewMember) {
3517 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3518 Fields.push_back(Field);
3519 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3520 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3521 // specialization causes the implicit instantiation of the definitions
3522 // of unscoped member enumerations.
3523 // Record a point of instantiation for this implicit instantiation.
3524 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3525 Enum->isCompleteDefinition()) {
3526 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3527 assert(MSInfo && "no spec info for member enum specialization");
3529 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3530 }
3531 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3532 if (SA->isFailed()) {
3533 // A static_assert failed. Bail out; instantiating this
3534 // class is probably not meaningful.
3535 Instantiation->setInvalidDecl();
3536 break;
3537 }
3538 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3539 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3540 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3541 MightHaveConstexprVirtualFunctions = true;
3542 }
3543
3544 if (NewMember->isInvalidDecl())
3545 Instantiation->setInvalidDecl();
3546 } else {
3547 // FIXME: Eventually, a NULL return will mean that one of the
3548 // instantiations was a semantic disaster, and we'll want to mark the
3549 // declaration invalid.
3550 // For now, we expect to skip some members that we can't yet handle.
3551 }
3552 }
3553
3554 // Finish checking fields.
3555 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3557 CheckCompletedCXXClass(nullptr, Instantiation);
3558
3559 // Default arguments are parsed, if not instantiated. We can go instantiate
3560 // default arg exprs for default constructors if necessary now. Unless we're
3561 // parsing a class, in which case wait until that's finished.
3562 if (ParsingClassDepth == 0)
3564
3565 // Instantiate late parsed attributes, and attach them to their decls.
3566 // See Sema::InstantiateAttrs
3567 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3568 E = LateAttrs.end(); I != E; ++I) {
3569 assert(CurrentInstantiationScope == Instantiator.getStartingScope());
3570 CurrentInstantiationScope = I->Scope;
3571
3572 // Allow 'this' within late-parsed attributes.
3573 auto *ND = cast<NamedDecl>(I->NewDecl);
3574 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3575 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3576 ND->isCXXInstanceMember());
3577
3578 Attr *NewAttr =
3579 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3580 if (NewAttr)
3581 I->NewDecl->addAttr(NewAttr);
3583 Instantiator.getStartingScope());
3584 }
3585 Instantiator.disableLateAttributeInstantiation();
3586 LateAttrs.clear();
3587
3589
3590 // FIXME: We should do something similar for explicit instantiations so they
3591 // end up in the right module.
3592 if (TSK == TSK_ImplicitInstantiation) {
3593 Instantiation->setLocation(Pattern->getLocation());
3594 Instantiation->setLocStart(Pattern->getInnerLocStart());
3595 Instantiation->setBraceRange(Pattern->getBraceRange());
3596 }
3597
3598 if (!Instantiation->isInvalidDecl()) {
3599 // Perform any dependent diagnostics from the pattern.
3600 if (Pattern->isDependentContext())
3601 PerformDependentDiagnostics(Pattern, TemplateArgs);
3602
3603 // Instantiate any out-of-line class template partial
3604 // specializations now.
3606 P = Instantiator.delayed_partial_spec_begin(),
3607 PEnd = Instantiator.delayed_partial_spec_end();
3608 P != PEnd; ++P) {
3610 P->first, P->second)) {
3611 Instantiation->setInvalidDecl();
3612 break;
3613 }
3614 }
3615
3616 // Instantiate any out-of-line variable template partial
3617 // specializations now.
3619 P = Instantiator.delayed_var_partial_spec_begin(),
3620 PEnd = Instantiator.delayed_var_partial_spec_end();
3621 P != PEnd; ++P) {
3623 P->first, P->second)) {
3624 Instantiation->setInvalidDecl();
3625 break;
3626 }
3627 }
3628 }
3629
3630 // Exit the scope of this instantiation.
3631 SavedContext.pop();
3632
3633 if (!Instantiation->isInvalidDecl()) {
3634 // Always emit the vtable for an explicit instantiation definition
3635 // of a polymorphic class template specialization. Otherwise, eagerly
3636 // instantiate only constexpr virtual functions in preparation for their use
3637 // in constant evaluation.
3639 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3640 else if (MightHaveConstexprVirtualFunctions)
3641 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3642 /*ConstexprOnly*/ true);
3643 }
3644
3645 Consumer.HandleTagDeclDefinition(Instantiation);
3646
3647 return Instantiation->isInvalidDecl();
3648}
3649
3650bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3651 EnumDecl *Instantiation, EnumDecl *Pattern,
3652 const MultiLevelTemplateArgumentList &TemplateArgs,
3654 EnumDecl *PatternDef = Pattern->getDefinition();
3655 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3656 Instantiation->getInstantiatedFromMemberEnum(),
3657 Pattern, PatternDef, TSK,/*Complain*/true))
3658 return true;
3659 Pattern = PatternDef;
3660
3661 // Record the point of instantiation.
3662 if (MemberSpecializationInfo *MSInfo
3663 = Instantiation->getMemberSpecializationInfo()) {
3664 MSInfo->setTemplateSpecializationKind(TSK);
3665 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3666 }
3667
3668 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3669 if (Inst.isInvalid())
3670 return true;
3671 if (Inst.isAlreadyInstantiating())
3672 return false;
3673 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3674 "instantiating enum definition");
3675
3676 // The instantiation is visible here, even if it was first declared in an
3677 // unimported module.
3678 Instantiation->setVisibleDespiteOwningModule();
3679
3680 // Enter the scope of this instantiation. We don't use
3681 // PushDeclContext because we don't have a scope.
3682 ContextRAII SavedContext(*this, Instantiation);
3685
3686 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3687
3688 // Pull attributes from the pattern onto the instantiation.
3689 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3690
3691 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3692 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3693
3694 // Exit the scope of this instantiation.
3695 SavedContext.pop();
3696
3697 return Instantiation->isInvalidDecl();
3698}
3699
3701 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3702 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3703 // If there is no initializer, we don't need to do anything.
3704 if (!Pattern->hasInClassInitializer())
3705 return false;
3706
3707 assert(Instantiation->getInClassInitStyle() ==
3708 Pattern->getInClassInitStyle() &&
3709 "pattern and instantiation disagree about init style");
3710
3711 // Error out if we haven't parsed the initializer of the pattern yet because
3712 // we are waiting for the closing brace of the outer class.
3713 Expr *OldInit = Pattern->getInClassInitializer();
3714 if (!OldInit) {
3715 RecordDecl *PatternRD = Pattern->getParent();
3716 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3717 Diag(PointOfInstantiation,
3718 diag::err_default_member_initializer_not_yet_parsed)
3719 << OutermostClass << Pattern;
3720 Diag(Pattern->getEndLoc(),
3721 diag::note_default_member_initializer_not_yet_parsed);
3722 Instantiation->setInvalidDecl();
3723 return true;
3724 }
3725
3726 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3727 if (Inst.isInvalid())
3728 return true;
3729 if (Inst.isAlreadyInstantiating()) {
3730 // Error out if we hit an instantiation cycle for this initializer.
3731 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3732 << Instantiation;
3733 return true;
3734 }
3735 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3736 "instantiating default member init");
3737
3738 // Enter the scope of this instantiation. We don't use PushDeclContext because
3739 // we don't have a scope.
3740 ContextRAII SavedContext(*this, Instantiation->getParent());
3743 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3744 PointOfInstantiation, Instantiation, CurContext};
3745
3746 LocalInstantiationScope Scope(*this, true);
3747
3748 // Instantiate the initializer.
3750 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3751
3752 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3753 /*CXXDirectInit=*/false);
3754 Expr *Init = NewInit.get();
3755 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class");
3757 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3758
3759 if (auto *L = getASTMutationListener())
3760 L->DefaultMemberInitializerInstantiated(Instantiation);
3761
3762 // Return true if the in-class initializer is still missing.
3763 return !Instantiation->getInClassInitializer();
3764}
3765
3766namespace {
3767 /// A partial specialization whose template arguments have matched
3768 /// a given template-id.
3769 struct PartialSpecMatchResult {
3772 };
3773}
3774
3777 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3779 return true;
3780
3782 ClassTemplateSpec->getSpecializedTemplate()
3783 ->getPartialSpecializations(PartialSpecs);
3784 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3786 if (DeduceTemplateArguments(PartialSpecs[I],
3787 ClassTemplateSpec->getTemplateArgs().asArray(),
3789 return true;
3790 }
3791
3792 return false;
3793}
3794
3795/// Get the instantiation pattern to use to instantiate the definition of a
3796/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3797/// template or of a partial specialization).
3800 Sema &S, SourceLocation PointOfInstantiation,
3801 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3803 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3804 if (Inst.isInvalid())
3805 return {/*Invalid=*/true};
3806 if (Inst.isAlreadyInstantiating())
3807 return {/*Invalid=*/false};
3808
3809 llvm::PointerUnion<ClassTemplateDecl *,
3811 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3812 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3813 // Find best matching specialization.
3814 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3815
3816 // C++ [temp.class.spec.match]p1:
3817 // When a class template is used in a context that requires an
3818 // instantiation of the class, it is necessary to determine
3819 // whether the instantiation is to be generated using the primary
3820 // template or one of the partial specializations. This is done by
3821 // matching the template arguments of the class template
3822 // specialization with the template argument lists of the partial
3823 // specializations.
3824 typedef PartialSpecMatchResult MatchResult;
3827 Template->getPartialSpecializations(PartialSpecs);
3828 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3829 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3830 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3831 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3833 Partial, ClassTemplateSpec->getTemplateArgs().asArray(), Info);
3835 // Store the failed-deduction information for use in diagnostics, later.
3836 // TODO: Actually use the failed-deduction info?
3837 FailedCandidates.addCandidate().set(
3838 DeclAccessPair::make(Template, AS_public), Partial,
3840 (void)Result;
3841 } else {
3842 Matched.push_back(PartialSpecMatchResult());
3843 Matched.back().Partial = Partial;
3844 Matched.back().Args = Info.takeCanonical();
3845 }
3846 }
3847
3848 // If we're dealing with a member template where the template parameters
3849 // have been instantiated, this provides the original template parameters
3850 // from which the member template's parameters were instantiated.
3851
3852 if (Matched.size() >= 1) {
3853 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3854 if (Matched.size() == 1) {
3855 // -- If exactly one matching specialization is found, the
3856 // instantiation is generated from that specialization.
3857 // We don't need to do anything for this.
3858 } else {
3859 // -- If more than one matching specialization is found, the
3860 // partial order rules (14.5.4.2) are used to determine
3861 // whether one of the specializations is more specialized
3862 // than the others. If none of the specializations is more
3863 // specialized than all of the other matching
3864 // specializations, then the use of the class template is
3865 // ambiguous and the program is ill-formed.
3867 PEnd = Matched.end();
3868 P != PEnd; ++P) {
3870 P->Partial, Best->Partial, PointOfInstantiation) ==
3871 P->Partial)
3872 Best = P;
3873 }
3874
3875 // Determine if the best partial specialization is more specialized than
3876 // the others.
3877 bool Ambiguous = false;
3878 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3879 PEnd = Matched.end();
3880 P != PEnd; ++P) {
3882 P->Partial, Best->Partial,
3883 PointOfInstantiation) != Best->Partial) {
3884 Ambiguous = true;
3885 break;
3886 }
3887 }
3888
3889 if (Ambiguous) {
3890 // Partial ordering did not produce a clear winner. Complain.
3891 Inst.Clear();
3892 ClassTemplateSpec->setInvalidDecl();
3893 S.Diag(PointOfInstantiation,
3894 diag::err_partial_spec_ordering_ambiguous)
3895 << ClassTemplateSpec;
3896
3897 // Print the matching partial specializations.
3898 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3899 PEnd = Matched.end();
3900 P != PEnd; ++P)
3901 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3903 P->Partial->getTemplateParameters(), *P->Args);
3904
3905 return {/*Invalid=*/true};
3906 }
3907 }
3908
3909 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3910 } else {
3911 // -- If no matches are found, the instantiation is generated
3912 // from the primary template.
3913 }
3914 }
3915
3916 CXXRecordDecl *Pattern = nullptr;
3917 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3918 if (auto *PartialSpec =
3919 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3920 // Instantiate using the best class template partial specialization.
3921 while (PartialSpec->getInstantiatedFromMember()) {
3922 // If we've found an explicit specialization of this class template,
3923 // stop here and use that as the pattern.
3924 if (PartialSpec->isMemberSpecialization())
3925 break;
3926
3927 PartialSpec = PartialSpec->getInstantiatedFromMember();
3928 }
3929 Pattern = PartialSpec;
3930 } else {
3931 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3932 while (Template->getInstantiatedFromMemberTemplate()) {
3933 // If we've found an explicit specialization of this class template,
3934 // stop here and use that as the pattern.
3935 if (Template->isMemberSpecialization())
3936 break;
3937
3938 Template = Template->getInstantiatedFromMemberTemplate();
3939 }
3940 Pattern = Template->getTemplatedDecl();
3941 }
3942
3943 return Pattern;
3944}
3945
3947 SourceLocation PointOfInstantiation,
3948 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3949 TemplateSpecializationKind TSK, bool Complain) {
3950 // Perform the actual instantiation on the canonical declaration.
3951 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3952 ClassTemplateSpec->getCanonicalDecl());
3953 if (ClassTemplateSpec->isInvalidDecl())
3954 return true;
3955
3957 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3958 ClassTemplateSpec, TSK);
3959 if (!Pattern.isUsable())
3960 return Pattern.isInvalid();
3961
3962 return InstantiateClass(
3963 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3964 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3965}
3966
3967void
3969 CXXRecordDecl *Instantiation,
3970 const MultiLevelTemplateArgumentList &TemplateArgs,
3972 // FIXME: We need to notify the ASTMutationListener that we did all of these
3973 // things, in case we have an explicit instantiation definition in a PCM, a
3974 // module, or preamble, and the declaration is in an imported AST.
3975 assert(
3978 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&
3979 "Unexpected template specialization kind!");
3980 for (auto *D : Instantiation->decls()) {
3981 bool SuppressNew = false;
3982 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3983 if (FunctionDecl *Pattern =
3984 Function->getInstantiatedFromMemberFunction()) {
3985
3986 if (Function->isIneligibleOrNotSelected())
3987 continue;
3988
3989 if (Function->getTrailingRequiresClause()) {
3990 ConstraintSatisfaction Satisfaction;
3991 if (CheckFunctionConstraints(Function, Satisfaction) ||
3992 !Satisfaction.IsSatisfied) {
3993 continue;
3994 }
3995 }
3996
3997 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3998 continue;
3999
4000 MemberSpecializationInfo *MSInfo =
4001 Function->getMemberSpecializationInfo();
4002 assert(MSInfo && "No member specialization information?");
4003 if (MSInfo->getTemplateSpecializationKind()
4005 continue;
4006
4007 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4008 Function,
4010 MSInfo->getPointOfInstantiation(),
4011 SuppressNew) ||
4012 SuppressNew)
4013 continue;
4014
4015 // C++11 [temp.explicit]p8:
4016 // An explicit instantiation definition that names a class template
4017 // specialization explicitly instantiates the class template
4018 // specialization and is only an explicit instantiation definition
4019 // of members whose definition is visible at the point of
4020 // instantiation.
4021 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
4022 continue;
4023
4024 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4025
4026 if (Function->isDefined()) {
4027 // Let the ASTConsumer know that this function has been explicitly
4028 // instantiated now, and its linkage might have changed.
4030 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
4031 InstantiateFunctionDefinition(PointOfInstantiation, Function);
4032 } else if (TSK == TSK_ImplicitInstantiation) {
4034 std::make_pair(Function, PointOfInstantiation));
4035 }
4036 }
4037 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
4038 if (isa<VarTemplateSpecializationDecl>(Var))
4039 continue;
4040
4041 if (Var->isStaticDataMember()) {
4042 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4043 continue;
4044
4046 assert(MSInfo && "No member specialization information?");
4047 if (MSInfo->getTemplateSpecializationKind()
4049 continue;
4050
4051 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4052 Var,
4054 MSInfo->getPointOfInstantiation(),
4055 SuppressNew) ||
4056 SuppressNew)
4057 continue;
4058
4060 // C++0x [temp.explicit]p8:
4061 // An explicit instantiation definition that names a class template
4062 // specialization explicitly instantiates the class template
4063 // specialization and is only an explicit instantiation definition
4064 // of members whose definition is visible at the point of
4065 // instantiation.
4067 continue;
4068
4069 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4070 InstantiateVariableDefinition(PointOfInstantiation, Var);
4071 } else {
4072 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
4073 }
4074 }
4075 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
4076 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
4077 continue;
4078
4079 // Always skip the injected-class-name, along with any
4080 // redeclarations of nested classes, since both would cause us
4081 // to try to instantiate the members of a class twice.
4082 // Skip closure types; they'll get instantiated when we instantiate
4083 // the corresponding lambda-expression.
4084 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
4085 Record->isLambda())
4086 continue;
4087
4088 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
4089 assert(MSInfo && "No member specialization information?");
4090
4091 if (MSInfo->getTemplateSpecializationKind()
4093 continue;
4094
4095 if (Context.getTargetInfo().getTriple().isOSWindows() &&
4097 // On Windows, explicit instantiation decl of the outer class doesn't
4098 // affect the inner class. Typically extern template declarations are
4099 // used in combination with dll import/export annotations, but those
4100 // are not propagated from the outer class templates to inner classes.
4101 // Therefore, do not instantiate inner classes on this platform, so
4102 // that users don't end up with undefined symbols during linking.
4103 continue;
4104 }
4105
4106 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
4107 Record,
4109 MSInfo->getPointOfInstantiation(),
4110 SuppressNew) ||
4111 SuppressNew)
4112 continue;
4113
4115 assert(Pattern && "Missing instantiated-from-template information");
4116
4117 if (!Record->getDefinition()) {
4118 if (!Pattern->getDefinition()) {
4119 // C++0x [temp.explicit]p8:
4120 // An explicit instantiation definition that names a class template
4121 // specialization explicitly instantiates the class template
4122 // specialization and is only an explicit instantiation definition
4123 // of members whose definition is visible at the point of
4124 // instantiation.
4126 MSInfo->setTemplateSpecializationKind(TSK);
4127 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4128 }
4129
4130 continue;
4131 }
4132
4133 InstantiateClass(PointOfInstantiation, Record, Pattern,
4134 TemplateArgs,
4135 TSK);
4136 } else {
4138 Record->getTemplateSpecializationKind() ==
4140 Record->setTemplateSpecializationKind(TSK);
4141 MarkVTableUsed(PointOfInstantiation, Record, true);
4142 }
4143 }
4144
4145 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
4146 if (Pattern)
4147 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
4148 TSK);
4149 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
4150 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
4151 assert(MSInfo && "No member specialization information?");
4152
4153 if (MSInfo->getTemplateSpecializationKind()
4155 continue;
4156
4158 PointOfInstantiation, TSK, Enum,
4160 MSInfo->getPointOfInstantiation(), SuppressNew) ||
4161 SuppressNew)
4162 continue;
4163
4164 if (Enum->getDefinition())
4165 continue;
4166
4167 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
4168 assert(Pattern && "Missing instantiated-from-template information");
4169
4171 if (!Pattern->getDefinition())
4172 continue;
4173
4174 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
4175 } else {
4176 MSInfo->setTemplateSpecializationKind(TSK);
4177 MSInfo->setPointOfInstantiation(PointOfInstantiation);
4178 }
4179 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
4180 // No need to instantiate in-class initializers during explicit
4181 // instantiation.
4182 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
4183 CXXRecordDecl *ClassPattern =
4184 Instantiation->getTemplateInstantiationPattern();
4186 ClassPattern->lookup(Field->getDeclName());
4187 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
4188 assert(Pattern);
4189 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
4190 TemplateArgs);
4191 }
4192 }
4193 }
4194}
4195
4196void
4198 SourceLocation PointOfInstantiation,
4199 ClassTemplateSpecializationDecl *ClassTemplateSpec,
4201 // C++0x [temp.explicit]p7:
4202 // An explicit instantiation that names a class template
4203 // specialization is an explicit instantion of the same kind
4204 // (declaration or definition) of each of its members (not
4205 // including members inherited from base classes) that has not
4206 // been previously explicitly specialized in the translation unit
4207 // containing the explicit instantiation, except as described
4208 // below.
4209 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
4210 getTemplateInstantiationArgs(ClassTemplateSpec),
4211 TSK);
4212}
4213
4216 if (!S)
4217 return S;
4218
4219 TemplateInstantiator Instantiator(*this, TemplateArgs,
4221 DeclarationName());
4222 return Instantiator.TransformStmt(S);
4223}
4224
4226 const TemplateArgumentLoc &Input,
4227 const MultiLevelTemplateArgumentList &TemplateArgs,
4229 const DeclarationName &Entity) {
4230 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
4231 return Instantiator.TransformTemplateArgument(Input, Output);
4232}
4233
4236 const MultiLevelTemplateArgumentList &TemplateArgs,
4238 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4239 DeclarationName());
4240 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
4241}
4242
4245 if (!E)
4246 return E;
4247
4248 TemplateInstantiator Instantiator(*this, TemplateArgs,
4250 DeclarationName());
4251 return Instantiator.TransformExpr(E);
4252}
4253
4256 const MultiLevelTemplateArgumentList &TemplateArgs) {
4257 // FIXME: should call SubstExpr directly if this function is equivalent or
4258 // should it be different?
4259 return SubstExpr(E, TemplateArgs);
4260}
4261
4263 Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
4264 if (!E)
4265 return E;
4266
4267 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4268 DeclarationName());
4269 Instantiator.setEvaluateConstraints(false);
4270 return Instantiator.TransformExpr(E);
4271}
4272
4274 const MultiLevelTemplateArgumentList &TemplateArgs,
4275 bool CXXDirectInit) {
4276 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
4277 DeclarationName());
4278 return Instantiator.TransformInitializer(Init, CXXDirectInit);
4279}
4280
4281bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
4282 const MultiLevelTemplateArgumentList &TemplateArgs,
4283 SmallVectorImpl<Expr *> &Outputs) {
4284 if (Exprs.empty())
4285 return false;
4286
4287 TemplateInstantiator Instantiator(*this, TemplateArgs,
4289 DeclarationName());
4290 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
4291 IsCall, Outputs);
4292}
4293
4296 const MultiLevelTemplateArgumentList &TemplateArgs) {
4297 if (!NNS)
4298 return NestedNameSpecifierLoc();
4299
4300 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
4301 DeclarationName());
4302 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
4303}
4304
4307 const MultiLevelTemplateArgumentList &TemplateArgs) {
4308 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4309 NameInfo.getName());
4310 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4311}
4312
4316 const MultiLevelTemplateArgumentList &TemplateArgs) {
4317 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4318 DeclarationName());
4319 CXXScopeSpec SS;
4320 SS.Adopt(QualifierLoc);
4321 return Instantiator.TransformTemplateName(SS, Name, Loc);
4322}
4323
4324static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4325 // When storing ParmVarDecls in the local instantiation scope, we always
4326 // want to use the ParmVarDecl from the canonical function declaration,
4327 // since the map is then valid for any redeclaration or definition of that
4328 // function.
4329 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4330 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4331 unsigned i = PV->getFunctionScopeIndex();
4332 // This parameter might be from a freestanding function type within the
4333 // function and isn't necessarily referring to one of FD's parameters.
4334 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4335 return FD->getCanonicalDecl()->getParamDecl(i);
4336 }
4337 }
4338 return D;
4339}
4340
4341
4342llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4345 for (LocalInstantiationScope *Current = this; Current;
4346 Current = Current->Outer) {
4347
4348 // Check if we found something within this scope.
4349 const Decl *CheckD = D;
4350 do {
4351 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4352 if (Found != Current->LocalDecls.end())
4353 return &Found->second;
4354
4355 // If this is a tag declaration, it's possible that we need to look for
4356 // a previous declaration.
4357 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4358 CheckD = Tag->getPreviousDecl();
4359 else
4360 CheckD = nullptr;
4361 } while (CheckD);
4362
4363 // If we aren't combined with our outer scope, we're done.
4364 if (!Current->CombineWithOuterScope)
4365 break;
4366 }
4367
4368 // If we're performing a partial substitution during template argument
4369 // deduction, we may not have values for template parameters yet.
4370 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4371 isa<TemplateTemplateParmDecl>(D))
4372 return nullptr;
4373
4374 // Local types referenced prior to definition may require instantiation.
4375 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4376 if (RD->isLocalClass())
4377 return nullptr;
4378
4379 // Enumeration types referenced prior to definition may appear as a result of
4380 // error recovery.
4381 if (isa<EnumDecl>(D))
4382 return nullptr;
4383
4384 // Materialized typedefs/type alias for implicit deduction guides may require
4385 // instantiation.
4386 if (isa<TypedefNameDecl>(D) &&
4387 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4388 return nullptr;
4389
4390 // If we didn't find the decl, then we either have a sema bug, or we have a
4391 // forward reference to a label declaration. Return null to indicate that
4392 // we have an uninstantiated label.
4393 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope");
4394 return nullptr;
4395}
4396
4399 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4400 if (Stored.isNull()) {
4401#ifndef NDEBUG
4402 // It should not be present in any surrounding scope either.
4403 LocalInstantiationScope *Current = this;
4404 while (Current->CombineWithOuterScope && Current->Outer) {
4405 Current = Current->Outer;
4406 assert(!Current->LocalDecls.contains(D) &&
4407 "Instantiated local in inner and outer scopes");
4408 }
4409#endif
4410 Stored = Inst;
4411 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4412 Pack->push_back(cast<VarDecl>(Inst));
4413 } else {
4414 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local");
4415 }
4416}
4417
4419 VarDecl *Inst) {
4421 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4422 Pack->push_back(Inst);
4423}
4424
4426#ifndef NDEBUG
4427 // This should be the first time we've been told about this decl.
4428 for (LocalInstantiationScope *Current = this;
4429 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4430 assert(!Current->LocalDecls.contains(D) &&
4431 "Creating local pack after instantiation of local");
4432#endif
4433
4435 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4437 Stored = Pack;
4438 ArgumentPacks.push_back(Pack);
4439}
4440
4442 for (DeclArgumentPack *Pack : ArgumentPacks)
4443 if (llvm::is_contained(*Pack, D))
4444 return true;
4445 return false;
4446}
4447
4449 const TemplateArgument *ExplicitArgs,
4450 unsigned NumExplicitArgs) {
4451 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&
4452 "Already have a partially-substituted pack");
4453 assert((!PartiallySubstitutedPack
4454 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&
4455 "Wrong number of arguments in partially-substituted pack");
4456 PartiallySubstitutedPack = Pack;
4457 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4458 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4459}
4460
4462 const TemplateArgument **ExplicitArgs,
4463 unsigned *NumExplicitArgs) const {
4464 if (ExplicitArgs)
4465 *ExplicitArgs = nullptr;
4466 if (NumExplicitArgs)
4467 *NumExplicitArgs = 0;
4468
4469 for (const LocalInstantiationScope *Current = this; Current;
4470 Current = Current->Outer) {
4471 if (Current->PartiallySubstitutedPack) {
4472 if (ExplicitArgs)
4473 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4474 if (NumExplicitArgs)
4475 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4476
4477 return Current->PartiallySubstitutedPack;
4478 }
4479
4480 if (!Current->CombineWithOuterScope)
4481 break;
4482 }
4483
4484 return nullptr;
4485}
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:1144
SourceLocation Loc
Definition: SemaObjC.cpp:759
static const Decl * getCanonicalParmVarDecl(const Decl *D)
static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T)
static concepts::Requirement::SubstitutionDiagnostic * createSubstDiag(Sema &S, TemplateDeductionInfo &Info, concepts::EntityPrinter Printer)
static ActionResult< CXXRecordDecl * > getPatternForClassTemplateSpecialization(Sema &S, SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK)
Get the instantiation pattern to use to instantiate the definition of a given ClassTemplateSpecializa...
static std::string convertCallArgsToString(Sema &S, llvm::ArrayRef< const Expr * > Args)
static TemplateArgument getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg)
Defines utilities for dealing with stack allocation and stack space.
Defines the clang::TypeLoc interface and its subclasses.
C Language Family Type Representation.
__device__ int
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:187
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
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:2644
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:1637
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2210
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:713
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
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:3346
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
Attr - This represents one attribute.
Definition: Attr.h:42
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:6020
Pointer to a block type.
Definition: Type.h:3397
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:2064
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:1724
const FunctionDecl * isLocalClass() const
If the class is a local class [class.local], returns the enclosing function declaration.
Definition: DeclCXX.h:1552
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:1915
base_class_range bases()
Definition: DeclCXX.h:620
bool isLambda() const
Determine whether this class describes a lambda function object.
Definition: DeclCXX.h:1023
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:1969
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine whether this particular class is a specialization or instantiation of a class template or m...
Definition: DeclCXX.cpp:1944
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1936
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this class is an instantiation of a member class of a class template specialization,...
Definition: DeclCXX.cpp:1922
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1633
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:1955
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:132
Declaration of a class template.
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:1369
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
bool isFileContext() const
Definition: DeclBase.h:2161
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
RecordDecl * getOuterLexicalRecordContext()
Retrieve the outermost lexically enclosing record context.
Definition: DeclBase.cpp:2014
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2350
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:261
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1216
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
bool isFileContextDecl() const
Definition: DeclBase.cpp:430
static Decl * castFromDeclContext(const DeclContext *)
Definition: DeclBase.cpp:1041
unsigned getTemplateDepth() const
Determine the number of levels of template parameter surrounding this declaration.
Definition: DeclBase.cpp:296
DeclContext * getNonTransparentDeclContext()
Return the non transparent context.
Definition: DeclBase.cpp:1216
bool isInvalidDecl() const
Definition: DeclBase.h:595
SourceLocation getLocation() const
Definition: DeclBase.h:446
void setLocation(SourceLocation L)
Definition: DeclBase.h:447
bool isDefinedOutsideFunctionOrMethod() const
isDefinedOutsideFunctionOrMethod - This predicate returns true if this scoped decl is defined outside...
Definition: DeclBase.h:939
DeclContext * getDeclContext()
Definition: DeclBase.h:455
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:358
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
bool hasAttr() const
Definition: DeclBase.h:584
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:968
void setVisibleDespiteOwningModule()
Set that this declaration is globally visible, even if it came from a module that is not visible.
Definition: DeclBase.h:860
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:789
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:774
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:2032
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
Represents an extended vector type where either the type or size is dependent.
Definition: Type.h:3947
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1547
bool hasFatalErrorOccurred() const
Definition: Diagnostic.h:850
unsigned getTemplateBacktraceLimit() const
Retrieve the maximum number of template instantiation notes to emit along with a given diagnostic.
Definition: Diagnostic.h:631
Represents a type that was referred to using an elaborated type keyword, e.g., struct S,...
Definition: Type.h:6762
RAII object that enters a new expression evaluation context.
Represents an enum.
Definition: Decl.h:3844
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this enumeration is an instantiation of a member enumeration of a class template specialization,...
Definition: Decl.h:4103
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:4911
EnumDecl * getInstantiatedFromMemberEnum() const
Returns the enumeration (declared within the template) from which this enumeration type was instantia...
Definition: Decl.cpp:4937
EnumDecl * getDefinition() const
Definition: Decl.h:3947
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:277
QualType getType() const
Definition: Expr.h:142
bool hasPlaceholderType() const
Returns whether this expression has a placeholder type.
Definition: Expr.h:516
Represents a member of a struct/union/class.
Definition: Decl.h:3030
Expr * getInClassInitializer() const
Get the C++11 default member initializer for this member, or null if one has not been set.
Definition: Decl.cpp:4556
bool hasInClassInitializer() const
Determine whether this member has a C++11 default member initializer.
Definition: Decl.h:3191
InClassInitStyle getInClassInitStyle() const
Get the kind of (C++11) default member initializer that this field has.
Definition: Decl.h:3185
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3247
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:134
Represents a function declaration or definition.
Definition: Decl.h:1932
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
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:4099
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isVirtualAsWritten() const
Whether this function is marked as virtual explicitly.
Definition: Decl.h:2276
Represents a reference to a function parameter pack or init-capture pack that has been substituted bu...
Definition: ExprCXX.h:4648
VarDecl *const * iterator
Iterators over the parameters which the parameter pack expanded into.
Definition: ExprCXX.h:4682
static FunctionParmPackExpr * Create(const ASTContext &Context, QualType T, VarDecl *ParamPack, SourceLocation NameLoc, ArrayRef< VarDecl * > Params)
Definition: ExprCXX.cpp:1797
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
Declaration of a template function.
Definition: DeclTemplate.h:957
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
ArrayRef< ParmVarDecl * > getParams() const
Definition: TypeLoc.h:1491
Interesting information about a specific parameter that can't simply be reflected in parameter's type...
Definition: Type.h:4334
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4308
QualType getReturnType() const
Definition: Type.h:4630
One of these records is kept for each identifier that is lexed.
ArrayRef< TemplateArgument > getTemplateArguments() const
const TypeClass * getTypePtr() const
Definition: TypeLoc.h:514
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:705
The injected class name of a C++ class template or class template partial specialization.
Definition: Type.h:6612
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:498
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:5665
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
Provides information a specialization of a member of a class template, which may be a member function...
Definition: DeclTemplate.h:615
void setTemplateSpecializationKind(TemplateSpecializationKind TSK)
Set the template specialization kind.
Definition: DeclTemplate.h:646
TemplateSpecializationKind getTemplateSpecializationKind() const
Determine what kind of template specialization this is.
Definition: DeclTemplate.h:637
SourceLocation getPointOfInstantiation() const
Retrieve the first point of instantiation of this member.
Definition: DeclTemplate.h:655
void setPointOfInstantiation(SourceLocation POI)
Set the first point of instantiation.
Definition: DeclTemplate.h:660
Describes a module or submodule.
Definition: Module.h:105
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:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
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:1811
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:6960
Sugar for parentheses used when specifying types.
Definition: Type.h:3161
Represents a parameter to a function.
Definition: Decl.h:1722
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1782
void setDefaultArg(Expr *defarg)
Definition: Decl.cpp:2968
SourceLocation getExplicitObjectParamThisLoc() const
Definition: Decl.h:1818
void setUnparsedDefaultArg()
Specify that this parameter has an unparsed default argument.
Definition: Decl.h:1863
bool hasUnparsedDefaultArg() const
Determines whether this parameter has a default argument that has not yet been parsed.
Definition: Decl.h:1851
void setUninstantiatedDefaultArg(Expr *arg)
Definition: Decl.cpp:2993
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1755
bool hasUninstantiatedDefaultArg() const
Definition: Decl.h:1855
bool hasInheritedDefaultArg() const
Definition: Decl.h:1867
void setExplicitObjectParameterLoc(SourceLocation Loc)
Definition: Decl.h:1814
Expr * getDefaultArg()
Definition: Decl.cpp:2956
Expr * getUninstantiatedDefaultArg()
Definition: Decl.cpp:2998
unsigned getFunctionScopeDepth() const
Definition: Decl.h:1772
void setHasInheritedDefaultArg(bool I=true)
Definition: Decl.h:1871
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
[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:941
QualType getNonLValueExprType(const ASTContext &Context) const
Determine the type of a (typically non-lvalue) expression with the specified result type.
Definition: Type.cpp:3476
void addConst()
Add the const type qualifier to this QualType.
Definition: Type.h:1163
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
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:7951
The collection of all-type qualifiers we support.
Definition: Type.h:319
void removeObjCLifetime()
Definition: Type.h:538
Represents a struct/union/class.
Definition: Decl.h:4145
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
bool isMemberSpecialization() const
Determines whether this template was a specialization of a member template.
Definition: DeclTemplate.h:860
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
Represents the body of a requires-expression.
Definition: DeclCXX.h:2033
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
SourceLocation getLParenLoc() const
Definition: ExprConcepts.h:578
SourceLocation getRParenLoc() const
Definition: ExprConcepts.h:579
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:13212
RAII object used to temporarily allow the C++ 'this' expression to be used, with the given qualifiers...
Definition: Sema.h:8073
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3023
For a defaulted function, the kind of defaulted function that it is.
Definition: Sema.h:5901
DefaultedComparisonKind asComparison() const
Definition: Sema.h:5933
CXXSpecialMemberKind asSpecialMember() const
Definition: Sema.h:5930
A helper class for building up ExtParameterInfos.
Definition: Sema.h:12627
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:12099
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:493
llvm::DenseSet< Module * > LookupModulesCache
Cache of additional modules that should be used for name lookup within the current template instantia...
Definition: Sema.h:13162
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:13146
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:12656
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:13149
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6817
ExprResult SubstInitializer(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs, bool CXXDirectInit)
void SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto, const MultiLevelTemplateArgumentList &Args)
@ CTAK_Specified
The template argument was specified in the code or was instantiated with some deduced template argume...
Definition: Sema.h:11655
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:962
bool InNonInstantiationSFINAEContext
Whether we are in a SFINAE context that is not associated with template instantiation.
Definition: Sema.h:13173
ExprResult SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs)
DiagnosticsEngine & getDiagnostics() const
Definition: Sema.h:557
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:560
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:868
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:16826
bool InstantiateClassTemplateSpecialization(SourceLocation PointOfInstantiation, ClassTemplateSpecializationDecl *ClassTemplateSpec, TemplateSpecializationKind TSK, bool Complain=true)
void InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Pattern, Decl *Inst, LateInstantiatedAttrVec *LateAttrs=nullptr, LocalInstantiationScope *OuterMostScope=nullptr)
const LangOptions & getLangOpts() const
Definition: Sema.h:553
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:14375
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:13198
void PrintInstantiationStack()
Prints the current instantiation stack through a series of notes.
bool usesPartialOrExplicitSpecialization(SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec)
void pushCodeSynthesisContext(CodeSynthesisContext Ctx)
bool CheckLoopHintExpr(Expr *E, SourceLocation Loc, bool AllowZero)
Definition: SemaExpr.cpp:3629
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:12668
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:13206
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
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:13543
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, const IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15096
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:20717
unsigned NonInstantiationEntries
The number of CodeSynthesisContexts that are not template instantiations and, therefore,...
Definition: Sema.h:13182
bool CheckNoInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
bool CheckAlwaysInlineAttr(const Stmt *OrigSt, const Stmt *CurSt, const AttributeCommonInfo &A)
void ActOnFinishCXXInClassMemberInitializer(Decl *VarDecl, SourceLocation EqualLoc, Expr *Init)
This is invoked after parsing an in-class initializer for a non-static C++ class member,...
ExprResult BuildCXXDefaultArgExpr(SourceLocation CallLoc, FunctionDecl *FD, ParmVarDecl *Param, Expr *Init=nullptr)
BuildCXXDefaultArgExpr - Creates a CXXDefaultArgExpr, instantiating the default expr if needed.
Definition: SemaExpr.cpp:5453
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 AttachTypeConstraint(NestedNameSpecifierLoc NS, DeclarationNameInfo NameInfo, ConceptDecl *NamedConcept, NamedDecl *FoundDecl, const TemplateArgumentListInfo *TemplateArgs, TemplateTypeParmDecl *ConstrainedParameter, SourceLocation EllipsisLoc)
Attach a type-constraint to a template parameter.
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:963
bool hasUncompilableErrorOccurred() const
Whether uncompilable error has occurred.
Definition: Sema.cpp:1690
@ 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:13190
bool CheckTemplateArgument(NamedDecl *Param, TemplateArgumentLoc &Arg, NamedDecl *Template, SourceLocation TemplateLoc, SourceLocation RAngleLoc, unsigned ArgumentPackIndex, SmallVectorImpl< TemplateArgument > &SugaredConverted, SmallVectorImpl< TemplateArgument > &CanonicalConverted, CheckTemplateArgumentKind CTAK)
Check that the given template argument corresponds to the given template parameter.
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:18865
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:7946
SourceManager & SourceMgr
Definition: Sema.h:965
DiagnosticsEngine & Diags
Definition: Sema.h:964
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:13157
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:574
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:20914
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.
void warnStackExhausted(SourceLocation Loc)
Warn that the stack is nearly exhausted.
Definition: Sema.cpp:566
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:600
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8293
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.
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4062
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
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:326
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:338
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4484
Represents a reference to a non-type template parameter pack that has been substituted with a non-tem...
Definition: ExprCXX.h:4569
A structure for storing an already-substituted template template parameter pack.
Definition: TemplateName.h:141
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:864
Represents the result of substituting a set of types for a template type parameter pack.
Definition: Type.h:6283
Wrapper for substituted template type parameters.
Definition: TypeLoc.h:857
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3561
void setTagKind(TagKind TK)
Definition: Decl.h:3760
SourceRange getBraceRange() const
Definition: Decl.h:3640
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3645
StringRef getKindName() const
Definition: Decl.h:3752
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4736
TagKind getTagKind() const
Definition: Decl.h:3756
void setBraceRange(SourceRange R)
Definition: Decl.h:3641
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1256
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:244
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Definition: DeclTemplate.h:274
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
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:648
delayed_var_partial_spec_iterator delayed_var_partial_spec_end()
Definition: Template.h:687
delayed_partial_spec_iterator delayed_partial_spec_begin()
Return an iterator to the beginning of the set of "delayed" partial specializations,...
Definition: Template.h:671
void setEvaluateConstraints(bool B)
Definition: Template.h:592
SmallVectorImpl< std::pair< VarTemplateDecl *, VarTemplatePartialSpecializationDecl * > >::iterator delayed_var_partial_spec_iterator
Definition: Template.h:665
LocalInstantiationScope * getStartingScope() const
Definition: Template.h:659
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:662
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:683
delayed_var_partial_spec_iterator delayed_var_partial_spec_begin()
Definition: Template.h:675
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:394
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Represents a C++ template name within the type system.
Definition: TemplateName.h:203
bool isNull() const
Determine whether this template name is NULL.
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
NamedDecl * getParam(unsigned Idx)
Definition: DeclTemplate.h:144
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:203
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:199
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:6480
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:758
bool isParameterPack() const
Definition: Type.h:6174
unsigned getIndex() const
Definition: Type.h:6173
unsigned getDepth() const
Definition: Type.h:6172
A semantic tree transformation that allows one to transform one abstract syntax tree into another.
Declaration of an alias 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:3395
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:1225
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:7721
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:7732
SourceLocation getNameLoc() const
Definition: TypeLoc.h:535
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
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:3168
The base class of the type hierarchy.
Definition: Type.h:1829
bool isVoidType() const
Definition: Type.h:8319
bool isReferenceType() const
Definition: Type.h:8021
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2703
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2354
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2713
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isRecordType() const
Definition: Type.h:8103
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
Represents a variable declaration or definition.
Definition: Decl.h:879
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1231
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2348
VarDecl * getInstantiatedFromStaticDataMember() const
If this variable is an instantiated static data member of a class template specialization,...
Definition: Decl.cpp:2737
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:2864
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
MemberSpecializationInfo * getMemberSpecializationInfo() const
If this variable is an instantiation of a static data member of a class template specialization,...
Definition: Decl.cpp:2855
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:4021
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:868
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.
Requirement::SubstitutionDiagnostic * createSubstDiagAt(Sema &S, SourceLocation Location, EntityPrinter Printer)
create a Requirement::SubstitutionDiagnostic with only a SubstitutedEntity and DiagLoc using Sema's a...
llvm::function_ref< void(llvm::raw_ostream &)> EntityPrinter
Definition: ExprConcepts.h:493
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...
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
NamedDecl * getAsNamedDecl(TemplateParameter P)
bool isStackNearlyExhausted()
Determine whether the stack is nearly exhausted.
Definition: Stack.cpp:45
bool isGenericLambdaCallOperatorOrStaticInvokerSpecialization(const DeclContext *DC)
Definition: ASTLambda.h:82
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
TagTypeKind
The kind of a tag type.
Definition: Type.h:6690
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
std::pair< unsigned, unsigned > getDepthAndIndex(NamedDecl *ND)
Retrieve the depth and index of a template parameter.
Definition: SemaInternal.h:61
@ 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:345
@ 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:6665
@ 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
#define bool
Definition: stdbool.h:24
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:5059
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5061
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5094
A context in which code is being synthesized (where a source location alone is not sufficient to iden...
Definition: Sema.h:12673
SourceRange InstantiationRange
The source range that covers the construct that cause the instantiation, e.g., the template-id that c...
Definition: Sema.h:12834
enum clang::Sema::CodeSynthesisContext::SynthesisKind Kind
bool SavedInNonInstantiationSFINAEContext
Was the enclosing context a non-instantiation SFINAE context?
Definition: Sema.h:12787
const TemplateArgument * TemplateArgs
The list of template arguments we are substituting, if they are not part of the entity.
Definition: Sema.h:12803
sema::TemplateDeductionInfo * DeductionInfo
The template deduction info object associated with the substitution or checking of explicit or deduce...
Definition: Sema.h:12829
NamedDecl * Template
The template (or partial specialization) in which we are performing the instantiation,...
Definition: Sema.h:12798
SourceLocation PointOfInstantiation
The point of instantiation or synthesis within the source code.
Definition: Sema.h:12790
SynthesisKind
The kind of template instantiation we are performing.
Definition: Sema.h:12675
@ MarkingClassDllexported
We are marking a class as __dllexport.
Definition: Sema.h:12767
@ DefaultTemplateArgumentInstantiation
We are instantiating a default argument for a template parameter.
Definition: Sema.h:12685
@ ExplicitTemplateArgumentSubstitution
We are substituting explicit template arguments provided for a function template.
Definition: Sema.h:12694
@ DefaultTemplateArgumentChecking
We are checking the validity of a default template argument that has been used when naming a template...
Definition: Sema.h:12713
@ InitializingStructuredBinding
We are initializing a structured binding.
Definition: Sema.h:12764
@ ExceptionSpecInstantiation
We are instantiating the exception specification for a function template which was deferred until it ...
Definition: Sema.h:12721
@ NestedRequirementConstraintsCheck
We are checking the satisfaction of a nested requirement of a requires expression.
Definition: Sema.h:12728
@ BuildingBuiltinDumpStructCall
We are building an implied call from __builtin_dump_struct.
Definition: Sema.h:12771
@ DefiningSynthesizedFunction
We are defining a synthesized function (such as a defaulted special member).
Definition: Sema.h:12739
@ Memoization
Added for Template instantiation observation.
Definition: Sema.h:12777
@ LambdaExpressionSubstitution
We are substituting into a lambda expression.
Definition: Sema.h:12704
@ TypeAliasTemplateInstantiation
We are instantiating a type alias template declaration.
Definition: Sema.h:12783
@ BuildingDeductionGuides
We are building deduction guides for a class.
Definition: Sema.h:12780
@ DeducedTemplateArgumentSubstitution
We are substituting template argument determined as part of template argument deduction for either a ...
Definition: Sema.h:12701
@ PriorTemplateArgumentSubstitution
We are substituting prior template arguments into a new template parameter.
Definition: Sema.h:12709
@ ExceptionSpecEvaluation
We are computing the exception specification for a defaulted special member function.
Definition: Sema.h:12717
@ TemplateInstantiation
We are instantiating a template declaration.
Definition: Sema.h:12678
@ DeclaringSpecialMember
We are declaring an implicit special member function.
Definition: Sema.h:12731
@ DeclaringImplicitEqualityComparison
We are declaring an implicit 'operator==' for a defaulted 'operator<=>'.
Definition: Sema.h:12735
@ DefaultFunctionArgumentInstantiation
We are instantiating a default argument for a function.
Definition: Sema.h:12690
@ RewritingOperatorAsSpaceship
We are rewriting a comparison operator in terms of an operator<=>.
Definition: Sema.h:12761
@ RequirementInstantiation
We are instantiating a requirement of a requires expression.
Definition: Sema.h:12724
Decl * Entity
The entity that is being synthesized.
Definition: Sema.h:12793
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:12858
bool isInvalid() const
Determines whether we have exceeded the maximum recursive template instantiations.
Definition: Sema.h:13012
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:13016
void set(DeclAccessPair Found, Decl *Spec, DeductionFailureInfo Info)