Bug Summary

File:build/source/clang/lib/Sema/SemaTemplateInstantiate.cpp
Warning:line 1224, column 15
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -clear-ast-before-backend -disable-llvm-verifier -discard-value-names -main-file-name SemaTemplateInstantiate.cpp -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/source/build-llvm -resource-dir /usr/lib/llvm-17/lib/clang/17 -D _DEBUG -D _GLIBCXX_ASSERTIONS -D _GNU_SOURCE -D _LIBCPP_ENABLE_ASSERTIONS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Sema -I /build/source/clang/lib/Sema -I /build/source/clang/include -I tools/clang/include -I include -I /build/source/llvm/include -D _FORTIFY_SOURCE=2 -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-17/lib/clang/17/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -fmacro-prefix-map=/build/source/build-llvm=build-llvm -fmacro-prefix-map=/build/source/= -fcoverage-prefix-map=/build/source/build-llvm=build-llvm -fcoverage-prefix-map=/build/source/= -source-date-epoch 1679443490 -O3 -Wno-unused-command-line-argument -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -Wno-misleading-indentation -std=c++17 -fdeprecated-macro -fdebug-compilation-dir=/build/source/build-llvm -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -fdebug-prefix-map=/build/source/build-llvm=build-llvm -fdebug-prefix-map=/build/source/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2023-03-22-005342-16304-1 -x c++ /build/source/clang/lib/Sema/SemaTemplateInstantiate.cpp

/build/source/clang/lib/Sema/SemaTemplateInstantiate.cpp

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"
13#include "clang/AST/ASTConcept.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTLambda.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/Expr.h"
21#include "clang/AST/ExprConcepts.h"
22#include "clang/AST/PrettyDeclStackTrace.h"
23#include "clang/AST/Type.h"
24#include "clang/AST/TypeVisitor.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/Stack.h"
27#include "clang/Basic/TargetInfo.h"
28#include "clang/Sema/DeclSpec.h"
29#include "clang/Sema/Initialization.h"
30#include "clang/Sema/Lookup.h"
31#include "clang/Sema/Sema.h"
32#include "clang/Sema/SemaConcept.h"
33#include "clang/Sema/SemaInternal.h"
34#include "clang/Sema/Template.h"
35#include "clang/Sema/TemplateDeduction.h"
36#include "clang/Sema/TemplateInstCallback.h"
37#include "llvm/Support/ErrorHandling.h"
38#include "llvm/Support/TimeProfiler.h"
39#include <optional>
40
41using namespace clang;
42using namespace sema;
43
44//===----------------------------------------------------------------------===/
45// Template Instantiation Support
46//===----------------------------------------------------------------------===/
47
48namespace {
49namespace TemplateInstArgsHelpers {
50struct Response {
51 const Decl *NextDecl = nullptr;
52 bool IsDone = false;
53 bool ClearRelativeToPrimary = true;
54 static Response Done() {
55 Response R;
56 R.IsDone = true;
57 return R;
58 }
59 static Response ChangeDecl(const Decl *ND) {
60 Response R;
61 R.NextDecl = ND;
62 return R;
63 }
64 static Response ChangeDecl(const DeclContext *Ctx) {
65 Response R;
66 R.NextDecl = Decl::castFromDeclContext(Ctx);
67 return R;
68 }
69
70 static Response UseNextDecl(const Decl *CurDecl) {
71 return ChangeDecl(CurDecl->getDeclContext());
72 }
73
74 static Response DontClearRelativeToPrimaryNextDecl(const Decl *CurDecl) {
75 Response R = Response::UseNextDecl(CurDecl);
76 R.ClearRelativeToPrimary = false;
77 return R;
78 }
79};
80// Add template arguments from a variable template instantiation.
81Response
82HandleVarTemplateSpec(const VarTemplateSpecializationDecl *VarTemplSpec,
83 MultiLevelTemplateArgumentList &Result,
84 bool SkipForSpecialization) {
85 // For a class-scope explicit specialization, there are no template arguments
86 // at this level, but there may be enclosing template arguments.
87 if (VarTemplSpec->isClassScopeExplicitSpecialization())
88 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
89
90 // We're done when we hit an explicit specialization.
91 if (VarTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
92 !isa<VarTemplatePartialSpecializationDecl>(VarTemplSpec))
93 return Response::Done();
94
95 // If this variable template specialization was instantiated from a
96 // specialized member that is a variable template, we're done.
97 assert(VarTemplSpec->getSpecializedTemplate() && "No variable template?")(static_cast <bool> (VarTemplSpec->getSpecializedTemplate
() && "No variable template?") ? void (0) : __assert_fail
("VarTemplSpec->getSpecializedTemplate() && \"No variable template?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 97, __extension__
__PRETTY_FUNCTION__))
;
98 llvm::PointerUnion<VarTemplateDecl *, VarTemplatePartialSpecializationDecl *>
99 Specialized = VarTemplSpec->getSpecializedTemplateOrPartial();
100 if (VarTemplatePartialSpecializationDecl *Partial =
101 Specialized.dyn_cast<VarTemplatePartialSpecializationDecl *>()) {
102 if (!SkipForSpecialization)
103 Result.addOuterTemplateArguments(
104 Partial, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
105 /*Final=*/false);
106 if (Partial->isMemberSpecialization())
107 return Response::Done();
108 } else {
109 VarTemplateDecl *Tmpl = Specialized.get<VarTemplateDecl *>();
110 if (!SkipForSpecialization)
111 Result.addOuterTemplateArguments(
112 Tmpl, VarTemplSpec->getTemplateInstantiationArgs().asArray(),
113 /*Final=*/false);
114 if (Tmpl->isMemberSpecialization())
115 return Response::Done();
116 }
117 return Response::DontClearRelativeToPrimaryNextDecl(VarTemplSpec);
118}
119
120// If we have a template template parameter with translation unit context,
121// then we're performing substitution into a default template argument of
122// this template template parameter before we've constructed the template
123// that will own this template template parameter. In this case, we
124// use empty template parameter lists for all of the outer templates
125// to avoid performing any substitutions.
126Response
127HandleDefaultTempArgIntoTempTempParam(const TemplateTemplateParmDecl *TTP,
128 MultiLevelTemplateArgumentList &Result) {
129 for (unsigned I = 0, N = TTP->getDepth() + 1; I != N; ++I)
130 Result.addOuterTemplateArguments(std::nullopt);
131 return Response::Done();
132}
133
134// Add template arguments from a class template instantiation.
135Response
136HandleClassTemplateSpec(const ClassTemplateSpecializationDecl *ClassTemplSpec,
137 MultiLevelTemplateArgumentList &Result,
138 bool SkipForSpecialization) {
139 if (!ClassTemplSpec->isClassScopeExplicitSpecialization()) {
140 // We're done when we hit an explicit specialization.
141 if (ClassTemplSpec->getSpecializationKind() == TSK_ExplicitSpecialization &&
142 !isa<ClassTemplatePartialSpecializationDecl>(ClassTemplSpec))
143 return Response::Done();
144
145 if (!SkipForSpecialization)
146 Result.addOuterTemplateArguments(
147 const_cast<ClassTemplateSpecializationDecl *>(ClassTemplSpec),
148 ClassTemplSpec->getTemplateInstantiationArgs().asArray(),
149 /*Final=*/false);
150
151 // If this class template specialization was instantiated from a
152 // specialized member that is a class template, we're done.
153 assert(ClassTemplSpec->getSpecializedTemplate() && "No class template?")(static_cast <bool> (ClassTemplSpec->getSpecializedTemplate
() && "No class template?") ? void (0) : __assert_fail
("ClassTemplSpec->getSpecializedTemplate() && \"No class template?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 153, __extension__
__PRETTY_FUNCTION__))
;
154 if (ClassTemplSpec->getSpecializedTemplate()->isMemberSpecialization())
155 return Response::Done();
156 }
157 return Response::UseNextDecl(ClassTemplSpec);
158}
159
160Response HandleFunction(const FunctionDecl *Function,
161 MultiLevelTemplateArgumentList &Result,
162 const FunctionDecl *Pattern, bool RelativeToPrimary,
163 bool ForConstraintInstantiation) {
164 // Add template arguments from a function template specialization.
165 if (!RelativeToPrimary &&
166 Function->getTemplateSpecializationKindForInstantiation() ==
167 TSK_ExplicitSpecialization)
168 return Response::Done();
169
170 if (!RelativeToPrimary &&
171 Function->getTemplateSpecializationKind() == TSK_ExplicitSpecialization) {
172 // This is an implicit instantiation of an explicit specialization. We
173 // don't get any template arguments from this function but might get
174 // some from an enclosing template.
175 return Response::UseNextDecl(Function);
176 } else if (const TemplateArgumentList *TemplateArgs =
177 Function->getTemplateSpecializationArgs()) {
178 // Add the template arguments for this specialization.
179 Result.addOuterTemplateArguments(const_cast<FunctionDecl *>(Function),
180 TemplateArgs->asArray(),
181 /*Final=*/false);
182
183 // If this function was instantiated from a specialized member that is
184 // a function template, we're done.
185 assert(Function->getPrimaryTemplate() && "No function template?")(static_cast <bool> (Function->getPrimaryTemplate() &&
"No function template?") ? void (0) : __assert_fail ("Function->getPrimaryTemplate() && \"No function template?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 185, __extension__
__PRETTY_FUNCTION__))
;
186 if (Function->getPrimaryTemplate()->isMemberSpecialization())
187 return Response::Done();
188
189 // If this function is a generic lambda specialization, we are done.
190 if (!ForConstraintInstantiation &&
191 isGenericLambdaCallOperatorOrStaticInvokerSpecialization(Function))
192 return Response::Done();
193
194 } else if (Function->getDescribedFunctionTemplate()) {
195 assert((static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 197, __extension__
__PRETTY_FUNCTION__))
196 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 197, __extension__
__PRETTY_FUNCTION__))
197 "Outer template not instantiated?")(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 197, __extension__
__PRETTY_FUNCTION__))
;
198 }
199 // If this is a friend or local declaration and it declares an entity at
200 // namespace scope, take arguments from its lexical parent
201 // instead of its semantic parent, unless of course the pattern we're
202 // instantiating actually comes from the file's context!
203 if ((Function->getFriendObjectKind() || Function->isLocalExternDecl()) &&
204 Function->getNonTransparentDeclContext()->isFileContext() &&
205 (!Pattern || !Pattern->getLexicalDeclContext()->isFileContext())) {
206 return Response::ChangeDecl(Function->getLexicalDeclContext());
207 }
208 return Response::UseNextDecl(Function);
209}
210
211Response HandleRecordDecl(const CXXRecordDecl *Rec,
212 MultiLevelTemplateArgumentList &Result,
213 ASTContext &Context,
214 bool ForConstraintInstantiation) {
215 if (ClassTemplateDecl *ClassTemplate = Rec->getDescribedClassTemplate()) {
216 assert((static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 218, __extension__
__PRETTY_FUNCTION__))
217 (ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) &&(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 218, __extension__
__PRETTY_FUNCTION__))
218 "Outer template not instantiated?")(static_cast <bool> ((ForConstraintInstantiation || Result
.getNumSubstitutedLevels() == 0) && "Outer template not instantiated?"
) ? void (0) : __assert_fail ("(ForConstraintInstantiation || Result.getNumSubstitutedLevels() == 0) && \"Outer template not instantiated?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 218, __extension__
__PRETTY_FUNCTION__))
;
219 if (ClassTemplate->isMemberSpecialization())
220 return Response::Done();
221 if (ForConstraintInstantiation) {
222 QualType RecordType = Context.getTypeDeclType(Rec);
223 QualType Injected = cast<InjectedClassNameType>(RecordType)
224 ->getInjectedSpecializationType();
225 const auto *InjectedType = cast<TemplateSpecializationType>(Injected);
226 Result.addOuterTemplateArguments(const_cast<CXXRecordDecl *>(Rec),
227 InjectedType->template_arguments(),
228 /*Final=*/false);
229 }
230 }
231
232 bool IsFriend = Rec->getFriendObjectKind() ||
233 (Rec->getDescribedClassTemplate() &&
234 Rec->getDescribedClassTemplate()->getFriendObjectKind());
235 if (ForConstraintInstantiation && IsFriend &&
236 Rec->getNonTransparentDeclContext()->isFileContext()) {
237 return Response::ChangeDecl(Rec->getLexicalDeclContext());
238 }
239
240 // This is to make sure we pick up the VarTemplateSpecializationDecl that this
241 // lambda is defined inside of.
242 if (Rec->isLambda())
243 if (const Decl *LCD = Rec->getLambdaContextDecl())
244 return Response::ChangeDecl(LCD);
245
246 return Response::UseNextDecl(Rec);
247}
248
249Response HandleImplicitConceptSpecializationDecl(
250 const ImplicitConceptSpecializationDecl *CSD,
251 MultiLevelTemplateArgumentList &Result) {
252 Result.addOuterTemplateArguments(
253 const_cast<ImplicitConceptSpecializationDecl *>(CSD),
254 CSD->getTemplateArguments(),
255 /*Final=*/false);
256 return Response::UseNextDecl(CSD);
257}
258
259Response HandleGenericDeclContext(const Decl *CurDecl) {
260 return Response::UseNextDecl(CurDecl);
261}
262} // namespace TemplateInstArgsHelpers
263} // namespace
264
265/// Retrieve the template argument list(s) that should be used to
266/// instantiate the definition of the given declaration.
267///
268/// \param ND the declaration for which we are computing template instantiation
269/// arguments.
270///
271/// \param Innermost if non-NULL, specifies a template argument list for the
272/// template declaration passed as ND.
273///
274/// \param RelativeToPrimary true if we should get the template
275/// arguments relative to the primary template, even when we're
276/// dealing with a specialization. This is only relevant for function
277/// template specializations.
278///
279/// \param Pattern If non-NULL, indicates the pattern from which we will be
280/// instantiating the definition of the given declaration, \p ND. This is
281/// used to determine the proper set of template instantiation arguments for
282/// friend function template specializations.
283///
284/// \param ForConstraintInstantiation when collecting arguments,
285/// ForConstraintInstantiation indicates we should continue looking when
286/// encountering a lambda generic call operator, and continue looking for
287/// arguments on an enclosing class template.
288
289MultiLevelTemplateArgumentList Sema::getTemplateInstantiationArgs(
290 const NamedDecl *ND, bool Final, const TemplateArgumentList *Innermost,
291 bool RelativeToPrimary, const FunctionDecl *Pattern,
292 bool ForConstraintInstantiation, bool SkipForSpecialization) {
293 assert(ND && "Can't find arguments for a decl if one isn't provided")(static_cast <bool> (ND && "Can't find arguments for a decl if one isn't provided"
) ? void (0) : __assert_fail ("ND && \"Can't find arguments for a decl if one isn't provided\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 293, __extension__
__PRETTY_FUNCTION__))
;
294 // Accumulate the set of template argument lists in this structure.
295 MultiLevelTemplateArgumentList Result;
296
297 if (Innermost)
298 Result.addOuterTemplateArguments(const_cast<NamedDecl *>(ND),
299 Innermost->asArray(), Final);
300
301 const Decl *CurDecl = ND;
302
303 while (!CurDecl->isFileContextDecl()) {
304 using namespace TemplateInstArgsHelpers;
305 Response R;
306 if (const auto *VarTemplSpec =
307 dyn_cast<VarTemplateSpecializationDecl>(CurDecl)) {
308 R = HandleVarTemplateSpec(VarTemplSpec, Result, SkipForSpecialization);
309 } else if (const auto *ClassTemplSpec =
310 dyn_cast<ClassTemplateSpecializationDecl>(CurDecl)) {
311 R = HandleClassTemplateSpec(ClassTemplSpec, Result,
312 SkipForSpecialization);
313 } else if (const auto *Function = dyn_cast<FunctionDecl>(CurDecl)) {
314 R = HandleFunction(Function, Result, Pattern, RelativeToPrimary,
315 ForConstraintInstantiation);
316 } else if (const auto *Rec = dyn_cast<CXXRecordDecl>(CurDecl)) {
317 R = HandleRecordDecl(Rec, Result, Context, ForConstraintInstantiation);
318 } else if (const auto *CSD =
319 dyn_cast<ImplicitConceptSpecializationDecl>(CurDecl)) {
320 R = HandleImplicitConceptSpecializationDecl(CSD, Result);
321 } else if (!isa<DeclContext>(CurDecl)) {
322 R = Response::DontClearRelativeToPrimaryNextDecl(CurDecl);
323 if (CurDecl->getDeclContext()->isTranslationUnit()) {
324 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(CurDecl)) {
325 R = HandleDefaultTempArgIntoTempTempParam(TTP, Result);
326 }
327 }
328 } else {
329 R = HandleGenericDeclContext(CurDecl);
330 }
331
332 if (R.IsDone)
333 return Result;
334 if (R.ClearRelativeToPrimary)
335 RelativeToPrimary = false;
336 assert(R.NextDecl)(static_cast <bool> (R.NextDecl) ? void (0) : __assert_fail
("R.NextDecl", "clang/lib/Sema/SemaTemplateInstantiate.cpp",
336, __extension__ __PRETTY_FUNCTION__))
;
337 CurDecl = R.NextDecl;
338 }
339
340 return Result;
341}
342
343bool Sema::CodeSynthesisContext::isInstantiationRecord() const {
344 switch (Kind) {
345 case TemplateInstantiation:
346 case ExceptionSpecInstantiation:
347 case DefaultTemplateArgumentInstantiation:
348 case DefaultFunctionArgumentInstantiation:
349 case ExplicitTemplateArgumentSubstitution:
350 case DeducedTemplateArgumentSubstitution:
351 case PriorTemplateArgumentSubstitution:
352 case ConstraintsCheck:
353 case NestedRequirementConstraintsCheck:
354 return true;
355
356 case RequirementInstantiation:
357 case RequirementParameterInstantiation:
358 case DefaultTemplateArgumentChecking:
359 case DeclaringSpecialMember:
360 case DeclaringImplicitEqualityComparison:
361 case DefiningSynthesizedFunction:
362 case ExceptionSpecEvaluation:
363 case ConstraintSubstitution:
364 case ParameterMappingSubstitution:
365 case ConstraintNormalization:
366 case RewritingOperatorAsSpaceship:
367 case InitializingStructuredBinding:
368 case MarkingClassDllexported:
369 case BuildingBuiltinDumpStructCall:
370 return false;
371
372 // This function should never be called when Kind's value is Memoization.
373 case Memoization:
374 break;
375 }
376
377 llvm_unreachable("Invalid SynthesisKind!")::llvm::llvm_unreachable_internal("Invalid SynthesisKind!", "clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 377)
;
378}
379
380Sema::InstantiatingTemplate::InstantiatingTemplate(
381 Sema &SemaRef, CodeSynthesisContext::SynthesisKind Kind,
382 SourceLocation PointOfInstantiation, SourceRange InstantiationRange,
383 Decl *Entity, NamedDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
384 sema::TemplateDeductionInfo *DeductionInfo)
385 : SemaRef(SemaRef) {
386 // Don't allow further instantiation if a fatal error and an uncompilable
387 // error have occurred. Any diagnostics we might have raised will not be
388 // visible, and we do not need to construct a correct AST.
389 if (SemaRef.Diags.hasFatalErrorOccurred() &&
390 SemaRef.hasUncompilableErrorOccurred()) {
391 Invalid = true;
392 return;
393 }
394 Invalid = CheckInstantiationDepth(PointOfInstantiation, InstantiationRange);
395 if (!Invalid) {
396 CodeSynthesisContext Inst;
397 Inst.Kind = Kind;
398 Inst.PointOfInstantiation = PointOfInstantiation;
399 Inst.Entity = Entity;
400 Inst.Template = Template;
401 Inst.TemplateArgs = TemplateArgs.data();
402 Inst.NumTemplateArgs = TemplateArgs.size();
403 Inst.DeductionInfo = DeductionInfo;
404 Inst.InstantiationRange = InstantiationRange;
405 SemaRef.pushCodeSynthesisContext(Inst);
406
407 AlreadyInstantiating = !Inst.Entity ? false :
408 !SemaRef.InstantiatingSpecializations
409 .insert({Inst.Entity->getCanonicalDecl(), Inst.Kind})
410 .second;
411 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, Inst);
412 }
413}
414
415Sema::InstantiatingTemplate::InstantiatingTemplate(
416 Sema &SemaRef, SourceLocation PointOfInstantiation, Decl *Entity,
417 SourceRange InstantiationRange)
418 : InstantiatingTemplate(SemaRef,
419 CodeSynthesisContext::TemplateInstantiation,
420 PointOfInstantiation, InstantiationRange, Entity) {}
421
422Sema::InstantiatingTemplate::InstantiatingTemplate(
423 Sema &SemaRef, SourceLocation PointOfInstantiation, FunctionDecl *Entity,
424 ExceptionSpecification, SourceRange InstantiationRange)
425 : InstantiatingTemplate(
426 SemaRef, CodeSynthesisContext::ExceptionSpecInstantiation,
427 PointOfInstantiation, InstantiationRange, Entity) {}
428
429Sema::InstantiatingTemplate::InstantiatingTemplate(
430 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateParameter Param,
431 TemplateDecl *Template, ArrayRef<TemplateArgument> TemplateArgs,
432 SourceRange InstantiationRange)
433 : InstantiatingTemplate(
434 SemaRef,
435 CodeSynthesisContext::DefaultTemplateArgumentInstantiation,
436 PointOfInstantiation, InstantiationRange, getAsNamedDecl(Param),
437 Template, TemplateArgs) {}
438
439Sema::InstantiatingTemplate::InstantiatingTemplate(
440 Sema &SemaRef, SourceLocation PointOfInstantiation,
441 FunctionTemplateDecl *FunctionTemplate,
442 ArrayRef<TemplateArgument> TemplateArgs,
443 CodeSynthesisContext::SynthesisKind Kind,
444 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
445 : InstantiatingTemplate(SemaRef, Kind, PointOfInstantiation,
446 InstantiationRange, FunctionTemplate, nullptr,
447 TemplateArgs, &DeductionInfo) {
448 assert((static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 450, __extension__
__PRETTY_FUNCTION__))
449 Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution ||(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 450, __extension__
__PRETTY_FUNCTION__))
450 Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution)(static_cast <bool> (Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution
|| Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution
) ? void (0) : __assert_fail ("Kind == CodeSynthesisContext::ExplicitTemplateArgumentSubstitution || Kind == CodeSynthesisContext::DeducedTemplateArgumentSubstitution"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 450, __extension__
__PRETTY_FUNCTION__))
;
451}
452
453Sema::InstantiatingTemplate::InstantiatingTemplate(
454 Sema &SemaRef, SourceLocation PointOfInstantiation,
455 TemplateDecl *Template,
456 ArrayRef<TemplateArgument> TemplateArgs,
457 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
458 : InstantiatingTemplate(
459 SemaRef,
460 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
461 PointOfInstantiation, InstantiationRange, Template, nullptr,
462 TemplateArgs, &DeductionInfo) {}
463
464Sema::InstantiatingTemplate::InstantiatingTemplate(
465 Sema &SemaRef, SourceLocation PointOfInstantiation,
466 ClassTemplatePartialSpecializationDecl *PartialSpec,
467 ArrayRef<TemplateArgument> TemplateArgs,
468 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
469 : InstantiatingTemplate(
470 SemaRef,
471 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
472 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
473 TemplateArgs, &DeductionInfo) {}
474
475Sema::InstantiatingTemplate::InstantiatingTemplate(
476 Sema &SemaRef, SourceLocation PointOfInstantiation,
477 VarTemplatePartialSpecializationDecl *PartialSpec,
478 ArrayRef<TemplateArgument> TemplateArgs,
479 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
480 : InstantiatingTemplate(
481 SemaRef,
482 CodeSynthesisContext::DeducedTemplateArgumentSubstitution,
483 PointOfInstantiation, InstantiationRange, PartialSpec, nullptr,
484 TemplateArgs, &DeductionInfo) {}
485
486Sema::InstantiatingTemplate::InstantiatingTemplate(
487 Sema &SemaRef, SourceLocation PointOfInstantiation, ParmVarDecl *Param,
488 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
489 : InstantiatingTemplate(
490 SemaRef,
491 CodeSynthesisContext::DefaultFunctionArgumentInstantiation,
492 PointOfInstantiation, InstantiationRange, Param, nullptr,
493 TemplateArgs) {}
494
495Sema::InstantiatingTemplate::InstantiatingTemplate(
496 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
497 NonTypeTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
498 SourceRange InstantiationRange)
499 : InstantiatingTemplate(
500 SemaRef,
501 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
502 PointOfInstantiation, InstantiationRange, Param, Template,
503 TemplateArgs) {}
504
505Sema::InstantiatingTemplate::InstantiatingTemplate(
506 Sema &SemaRef, SourceLocation PointOfInstantiation, NamedDecl *Template,
507 TemplateTemplateParmDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
508 SourceRange InstantiationRange)
509 : InstantiatingTemplate(
510 SemaRef,
511 CodeSynthesisContext::PriorTemplateArgumentSubstitution,
512 PointOfInstantiation, InstantiationRange, Param, Template,
513 TemplateArgs) {}
514
515Sema::InstantiatingTemplate::InstantiatingTemplate(
516 Sema &SemaRef, SourceLocation PointOfInstantiation, TemplateDecl *Template,
517 NamedDecl *Param, ArrayRef<TemplateArgument> TemplateArgs,
518 SourceRange InstantiationRange)
519 : InstantiatingTemplate(
520 SemaRef, CodeSynthesisContext::DefaultTemplateArgumentChecking,
521 PointOfInstantiation, InstantiationRange, Param, Template,
522 TemplateArgs) {}
523
524Sema::InstantiatingTemplate::InstantiatingTemplate(
525 Sema &SemaRef, SourceLocation PointOfInstantiation,
526 concepts::Requirement *Req, sema::TemplateDeductionInfo &DeductionInfo,
527 SourceRange InstantiationRange)
528 : InstantiatingTemplate(
529 SemaRef, CodeSynthesisContext::RequirementInstantiation,
530 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
531 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
532}
533
534Sema::InstantiatingTemplate::InstantiatingTemplate(
535 Sema &SemaRef, SourceLocation PointOfInstantiation,
536 concepts::NestedRequirement *Req, ConstraintsCheck,
537 SourceRange InstantiationRange)
538 : InstantiatingTemplate(
539 SemaRef, CodeSynthesisContext::NestedRequirementConstraintsCheck,
540 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
541 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt) {}
542
543Sema::InstantiatingTemplate::InstantiatingTemplate(
544 Sema &SemaRef, SourceLocation PointOfInstantiation, const RequiresExpr *RE,
545 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
546 : InstantiatingTemplate(
547 SemaRef, CodeSynthesisContext::RequirementParameterInstantiation,
548 PointOfInstantiation, InstantiationRange, /*Entity=*/nullptr,
549 /*Template=*/nullptr, /*TemplateArgs=*/std::nullopt, &DeductionInfo) {
550}
551
552Sema::InstantiatingTemplate::InstantiatingTemplate(
553 Sema &SemaRef, SourceLocation PointOfInstantiation,
554 ConstraintsCheck, NamedDecl *Template,
555 ArrayRef<TemplateArgument> TemplateArgs, SourceRange InstantiationRange)
556 : InstantiatingTemplate(
557 SemaRef, CodeSynthesisContext::ConstraintsCheck,
558 PointOfInstantiation, InstantiationRange, Template, nullptr,
559 TemplateArgs) {}
560
561Sema::InstantiatingTemplate::InstantiatingTemplate(
562 Sema &SemaRef, SourceLocation PointOfInstantiation,
563 ConstraintSubstitution, NamedDecl *Template,
564 sema::TemplateDeductionInfo &DeductionInfo, SourceRange InstantiationRange)
565 : InstantiatingTemplate(
566 SemaRef, CodeSynthesisContext::ConstraintSubstitution,
567 PointOfInstantiation, InstantiationRange, Template, nullptr,
568 {}, &DeductionInfo) {}
569
570Sema::InstantiatingTemplate::InstantiatingTemplate(
571 Sema &SemaRef, SourceLocation PointOfInstantiation,
572 ConstraintNormalization, NamedDecl *Template,
573 SourceRange InstantiationRange)
574 : InstantiatingTemplate(
575 SemaRef, CodeSynthesisContext::ConstraintNormalization,
576 PointOfInstantiation, InstantiationRange, Template) {}
577
578Sema::InstantiatingTemplate::InstantiatingTemplate(
579 Sema &SemaRef, SourceLocation PointOfInstantiation,
580 ParameterMappingSubstitution, NamedDecl *Template,
581 SourceRange InstantiationRange)
582 : InstantiatingTemplate(
583 SemaRef, CodeSynthesisContext::ParameterMappingSubstitution,
584 PointOfInstantiation, InstantiationRange, Template) {}
585
586
587void Sema::pushCodeSynthesisContext(CodeSynthesisContext Ctx) {
588 Ctx.SavedInNonInstantiationSFINAEContext = InNonInstantiationSFINAEContext;
589 InNonInstantiationSFINAEContext = false;
590
591 CodeSynthesisContexts.push_back(Ctx);
592
593 if (!Ctx.isInstantiationRecord())
594 ++NonInstantiationEntries;
595
596 // Check to see if we're low on stack space. We can't do anything about this
597 // from here, but we can at least warn the user.
598 if (isStackNearlyExhausted())
599 warnStackExhausted(Ctx.PointOfInstantiation);
600}
601
602void Sema::popCodeSynthesisContext() {
603 auto &Active = CodeSynthesisContexts.back();
604 if (!Active.isInstantiationRecord()) {
605 assert(NonInstantiationEntries > 0)(static_cast <bool> (NonInstantiationEntries > 0) ? void
(0) : __assert_fail ("NonInstantiationEntries > 0", "clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 605, __extension__ __PRETTY_FUNCTION__))
;
606 --NonInstantiationEntries;
607 }
608
609 InNonInstantiationSFINAEContext = Active.SavedInNonInstantiationSFINAEContext;
610
611 // Name lookup no longer looks in this template's defining module.
612 assert(CodeSynthesisContexts.size() >=(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 614, __extension__
__PRETTY_FUNCTION__))
613 CodeSynthesisContextLookupModules.size() &&(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 614, __extension__
__PRETTY_FUNCTION__))
614 "forgot to remove a lookup module for a template instantiation")(static_cast <bool> (CodeSynthesisContexts.size() >=
CodeSynthesisContextLookupModules.size() && "forgot to remove a lookup module for a template instantiation"
) ? void (0) : __assert_fail ("CodeSynthesisContexts.size() >= CodeSynthesisContextLookupModules.size() && \"forgot to remove a lookup module for a template instantiation\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 614, __extension__
__PRETTY_FUNCTION__))
;
615 if (CodeSynthesisContexts.size() ==
616 CodeSynthesisContextLookupModules.size()) {
617 if (Module *M = CodeSynthesisContextLookupModules.back())
618 LookupModulesCache.erase(M);
619 CodeSynthesisContextLookupModules.pop_back();
620 }
621
622 // If we've left the code synthesis context for the current context stack,
623 // stop remembering that we've emitted that stack.
624 if (CodeSynthesisContexts.size() ==
625 LastEmittedCodeSynthesisContextDepth)
626 LastEmittedCodeSynthesisContextDepth = 0;
627
628 CodeSynthesisContexts.pop_back();
629}
630
631void Sema::InstantiatingTemplate::Clear() {
632 if (!Invalid) {
633 if (!AlreadyInstantiating) {
634 auto &Active = SemaRef.CodeSynthesisContexts.back();
635 if (Active.Entity)
636 SemaRef.InstantiatingSpecializations.erase(
637 {Active.Entity->getCanonicalDecl(), Active.Kind});
638 }
639
640 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef,
641 SemaRef.CodeSynthesisContexts.back());
642
643 SemaRef.popCodeSynthesisContext();
644 Invalid = true;
645 }
646}
647
648static std::string convertCallArgsToString(Sema &S,
649 llvm::ArrayRef<const Expr *> Args) {
650 std::string Result;
651 llvm::raw_string_ostream OS(Result);
652 llvm::ListSeparator Comma;
653 for (const Expr *Arg : Args) {
654 OS << Comma;
655 Arg->IgnoreParens()->printPretty(OS, nullptr,
656 S.Context.getPrintingPolicy());
657 }
658 return Result;
659}
660
661bool Sema::InstantiatingTemplate::CheckInstantiationDepth(
662 SourceLocation PointOfInstantiation,
663 SourceRange InstantiationRange) {
664 assert(SemaRef.NonInstantiationEntries <=(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 665, __extension__
__PRETTY_FUNCTION__))
665 SemaRef.CodeSynthesisContexts.size())(static_cast <bool> (SemaRef.NonInstantiationEntries <=
SemaRef.CodeSynthesisContexts.size()) ? void (0) : __assert_fail
("SemaRef.NonInstantiationEntries <= SemaRef.CodeSynthesisContexts.size()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 665, __extension__
__PRETTY_FUNCTION__))
;
666 if ((SemaRef.CodeSynthesisContexts.size() -
667 SemaRef.NonInstantiationEntries)
668 <= SemaRef.getLangOpts().InstantiationDepth)
669 return false;
670
671 SemaRef.Diag(PointOfInstantiation,
672 diag::err_template_recursion_depth_exceeded)
673 << SemaRef.getLangOpts().InstantiationDepth
674 << InstantiationRange;
675 SemaRef.Diag(PointOfInstantiation, diag::note_template_recursion_depth)
676 << SemaRef.getLangOpts().InstantiationDepth;
677 return true;
678}
679
680/// Prints the current instantiation stack through a series of
681/// notes.
682void Sema::PrintInstantiationStack() {
683 // Determine which template instantiations to skip, if any.
684 unsigned SkipStart = CodeSynthesisContexts.size(), SkipEnd = SkipStart;
685 unsigned Limit = Diags.getTemplateBacktraceLimit();
686 if (Limit && Limit < CodeSynthesisContexts.size()) {
687 SkipStart = Limit / 2 + Limit % 2;
688 SkipEnd = CodeSynthesisContexts.size() - Limit / 2;
689 }
690
691 // FIXME: In all of these cases, we need to show the template arguments
692 unsigned InstantiationIdx = 0;
693 for (SmallVectorImpl<CodeSynthesisContext>::reverse_iterator
694 Active = CodeSynthesisContexts.rbegin(),
695 ActiveEnd = CodeSynthesisContexts.rend();
696 Active != ActiveEnd;
697 ++Active, ++InstantiationIdx) {
698 // Skip this instantiation?
699 if (InstantiationIdx >= SkipStart && InstantiationIdx < SkipEnd) {
700 if (InstantiationIdx == SkipStart) {
701 // Note that we're skipping instantiations.
702 Diags.Report(Active->PointOfInstantiation,
703 diag::note_instantiation_contexts_suppressed)
704 << unsigned(CodeSynthesisContexts.size() - Limit);
705 }
706 continue;
707 }
708
709 switch (Active->Kind) {
710 case CodeSynthesisContext::TemplateInstantiation: {
711 Decl *D = Active->Entity;
712 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
713 unsigned DiagID = diag::note_template_member_class_here;
714 if (isa<ClassTemplateSpecializationDecl>(Record))
715 DiagID = diag::note_template_class_instantiation_here;
716 Diags.Report(Active->PointOfInstantiation, DiagID)
717 << Record << Active->InstantiationRange;
718 } else if (FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
719 unsigned DiagID;
720 if (Function->getPrimaryTemplate())
721 DiagID = diag::note_function_template_spec_here;
722 else
723 DiagID = diag::note_template_member_function_here;
724 Diags.Report(Active->PointOfInstantiation, DiagID)
725 << Function
726 << Active->InstantiationRange;
727 } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
728 Diags.Report(Active->PointOfInstantiation,
729 VD->isStaticDataMember()?
730 diag::note_template_static_data_member_def_here
731 : diag::note_template_variable_def_here)
732 << VD
733 << Active->InstantiationRange;
734 } else if (EnumDecl *ED = dyn_cast<EnumDecl>(D)) {
735 Diags.Report(Active->PointOfInstantiation,
736 diag::note_template_enum_def_here)
737 << ED
738 << Active->InstantiationRange;
739 } else if (FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
740 Diags.Report(Active->PointOfInstantiation,
741 diag::note_template_nsdmi_here)
742 << FD << Active->InstantiationRange;
743 } else {
744 Diags.Report(Active->PointOfInstantiation,
745 diag::note_template_type_alias_instantiation_here)
746 << cast<TypeAliasTemplateDecl>(D)
747 << Active->InstantiationRange;
748 }
749 break;
750 }
751
752 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation: {
753 TemplateDecl *Template = cast<TemplateDecl>(Active->Template);
754 SmallString<128> TemplateArgsStr;
755 llvm::raw_svector_ostream OS(TemplateArgsStr);
756 Template->printName(OS, getPrintingPolicy());
757 printTemplateArgumentList(OS, Active->template_arguments(),
758 getPrintingPolicy());
759 Diags.Report(Active->PointOfInstantiation,
760 diag::note_default_arg_instantiation_here)
761 << OS.str()
762 << Active->InstantiationRange;
763 break;
764 }
765
766 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution: {
767 FunctionTemplateDecl *FnTmpl = cast<FunctionTemplateDecl>(Active->Entity);
768 Diags.Report(Active->PointOfInstantiation,
769 diag::note_explicit_template_arg_substitution_here)
770 << FnTmpl
771 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
772 Active->TemplateArgs,
773 Active->NumTemplateArgs)
774 << Active->InstantiationRange;
775 break;
776 }
777
778 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution: {
779 if (FunctionTemplateDecl *FnTmpl =
780 dyn_cast<FunctionTemplateDecl>(Active->Entity)) {
781 Diags.Report(Active->PointOfInstantiation,
782 diag::note_function_template_deduction_instantiation_here)
783 << FnTmpl
784 << getTemplateArgumentBindingsText(FnTmpl->getTemplateParameters(),
785 Active->TemplateArgs,
786 Active->NumTemplateArgs)
787 << Active->InstantiationRange;
788 } else {
789 bool IsVar = isa<VarTemplateDecl>(Active->Entity) ||
790 isa<VarTemplateSpecializationDecl>(Active->Entity);
791 bool IsTemplate = false;
792 TemplateParameterList *Params;
793 if (auto *D = dyn_cast<TemplateDecl>(Active->Entity)) {
794 IsTemplate = true;
795 Params = D->getTemplateParameters();
796 } else if (auto *D = dyn_cast<ClassTemplatePartialSpecializationDecl>(
797 Active->Entity)) {
798 Params = D->getTemplateParameters();
799 } else if (auto *D = dyn_cast<VarTemplatePartialSpecializationDecl>(
800 Active->Entity)) {
801 Params = D->getTemplateParameters();
802 } else {
803 llvm_unreachable("unexpected template kind")::llvm::llvm_unreachable_internal("unexpected template kind",
"clang/lib/Sema/SemaTemplateInstantiate.cpp", 803)
;
804 }
805
806 Diags.Report(Active->PointOfInstantiation,
807 diag::note_deduced_template_arg_substitution_here)
808 << IsVar << IsTemplate << cast<NamedDecl>(Active->Entity)
809 << getTemplateArgumentBindingsText(Params, Active->TemplateArgs,
810 Active->NumTemplateArgs)
811 << Active->InstantiationRange;
812 }
813 break;
814 }
815
816 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation: {
817 ParmVarDecl *Param = cast<ParmVarDecl>(Active->Entity);
818 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
819
820 SmallString<128> TemplateArgsStr;
821 llvm::raw_svector_ostream OS(TemplateArgsStr);
822 FD->printName(OS, getPrintingPolicy());
823 printTemplateArgumentList(OS, Active->template_arguments(),
824 getPrintingPolicy());
825 Diags.Report(Active->PointOfInstantiation,
826 diag::note_default_function_arg_instantiation_here)
827 << OS.str()
828 << Active->InstantiationRange;
829 break;
830 }
831
832 case CodeSynthesisContext::PriorTemplateArgumentSubstitution: {
833 NamedDecl *Parm = cast<NamedDecl>(Active->Entity);
834 std::string Name;
835 if (!Parm->getName().empty())
836 Name = std::string(" '") + Parm->getName().str() + "'";
837
838 TemplateParameterList *TemplateParams = nullptr;
839 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
840 TemplateParams = Template->getTemplateParameters();
841 else
842 TemplateParams =
843 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
844 ->getTemplateParameters();
845 Diags.Report(Active->PointOfInstantiation,
846 diag::note_prior_template_arg_substitution)
847 << isa<TemplateTemplateParmDecl>(Parm)
848 << Name
849 << getTemplateArgumentBindingsText(TemplateParams,
850 Active->TemplateArgs,
851 Active->NumTemplateArgs)
852 << Active->InstantiationRange;
853 break;
854 }
855
856 case CodeSynthesisContext::DefaultTemplateArgumentChecking: {
857 TemplateParameterList *TemplateParams = nullptr;
858 if (TemplateDecl *Template = dyn_cast<TemplateDecl>(Active->Template))
859 TemplateParams = Template->getTemplateParameters();
860 else
861 TemplateParams =
862 cast<ClassTemplatePartialSpecializationDecl>(Active->Template)
863 ->getTemplateParameters();
864
865 Diags.Report(Active->PointOfInstantiation,
866 diag::note_template_default_arg_checking)
867 << getTemplateArgumentBindingsText(TemplateParams,
868 Active->TemplateArgs,
869 Active->NumTemplateArgs)
870 << Active->InstantiationRange;
871 break;
872 }
873
874 case CodeSynthesisContext::ExceptionSpecEvaluation:
875 Diags.Report(Active->PointOfInstantiation,
876 diag::note_evaluating_exception_spec_here)
877 << cast<FunctionDecl>(Active->Entity);
878 break;
879
880 case CodeSynthesisContext::ExceptionSpecInstantiation:
881 Diags.Report(Active->PointOfInstantiation,
882 diag::note_template_exception_spec_instantiation_here)
883 << cast<FunctionDecl>(Active->Entity)
884 << Active->InstantiationRange;
885 break;
886
887 case CodeSynthesisContext::RequirementInstantiation:
888 Diags.Report(Active->PointOfInstantiation,
889 diag::note_template_requirement_instantiation_here)
890 << Active->InstantiationRange;
891 break;
892 case CodeSynthesisContext::RequirementParameterInstantiation:
893 Diags.Report(Active->PointOfInstantiation,
894 diag::note_template_requirement_params_instantiation_here)
895 << Active->InstantiationRange;
896 break;
897
898 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
899 Diags.Report(Active->PointOfInstantiation,
900 diag::note_nested_requirement_here)
901 << Active->InstantiationRange;
902 break;
903
904 case CodeSynthesisContext::DeclaringSpecialMember:
905 Diags.Report(Active->PointOfInstantiation,
906 diag::note_in_declaration_of_implicit_special_member)
907 << cast<CXXRecordDecl>(Active->Entity) << Active->SpecialMember;
908 break;
909
910 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
911 Diags.Report(Active->Entity->getLocation(),
912 diag::note_in_declaration_of_implicit_equality_comparison);
913 break;
914
915 case CodeSynthesisContext::DefiningSynthesizedFunction: {
916 // FIXME: For synthesized functions that are not defaulted,
917 // produce a note.
918 auto *FD = dyn_cast<FunctionDecl>(Active->Entity);
919 DefaultedFunctionKind DFK =
920 FD ? getDefaultedFunctionKind(FD) : DefaultedFunctionKind();
921 if (DFK.isSpecialMember()) {
922 auto *MD = cast<CXXMethodDecl>(FD);
923 Diags.Report(Active->PointOfInstantiation,
924 diag::note_member_synthesized_at)
925 << MD->isExplicitlyDefaulted() << DFK.asSpecialMember()
926 << Context.getTagDeclType(MD->getParent());
927 } else if (DFK.isComparison()) {
928 Diags.Report(Active->PointOfInstantiation,
929 diag::note_comparison_synthesized_at)
930 << (int)DFK.asComparison()
931 << Context.getTagDeclType(
932 cast<CXXRecordDecl>(FD->getLexicalDeclContext()));
933 }
934 break;
935 }
936
937 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
938 Diags.Report(Active->Entity->getLocation(),
939 diag::note_rewriting_operator_as_spaceship);
940 break;
941
942 case CodeSynthesisContext::InitializingStructuredBinding:
943 Diags.Report(Active->PointOfInstantiation,
944 diag::note_in_binding_decl_init)
945 << cast<BindingDecl>(Active->Entity);
946 break;
947
948 case CodeSynthesisContext::MarkingClassDllexported:
949 Diags.Report(Active->PointOfInstantiation,
950 diag::note_due_to_dllexported_class)
951 << cast<CXXRecordDecl>(Active->Entity) << !getLangOpts().CPlusPlus11;
952 break;
953
954 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
955 Diags.Report(Active->PointOfInstantiation,
956 diag::note_building_builtin_dump_struct_call)
957 << convertCallArgsToString(
958 *this, llvm::ArrayRef(Active->CallArgs, Active->NumCallArgs));
959 break;
960
961 case CodeSynthesisContext::Memoization:
962 break;
963
964 case CodeSynthesisContext::ConstraintsCheck: {
965 unsigned DiagID = 0;
966 if (!Active->Entity) {
967 Diags.Report(Active->PointOfInstantiation,
968 diag::note_nested_requirement_here)
969 << Active->InstantiationRange;
970 break;
971 }
972 if (isa<ConceptDecl>(Active->Entity))
973 DiagID = diag::note_concept_specialization_here;
974 else if (isa<TemplateDecl>(Active->Entity))
975 DiagID = diag::note_checking_constraints_for_template_id_here;
976 else if (isa<VarTemplatePartialSpecializationDecl>(Active->Entity))
977 DiagID = diag::note_checking_constraints_for_var_spec_id_here;
978 else if (isa<ClassTemplatePartialSpecializationDecl>(Active->Entity))
979 DiagID = diag::note_checking_constraints_for_class_spec_id_here;
980 else {
981 assert(isa<FunctionDecl>(Active->Entity))(static_cast <bool> (isa<FunctionDecl>(Active->
Entity)) ? void (0) : __assert_fail ("isa<FunctionDecl>(Active->Entity)"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 981, __extension__
__PRETTY_FUNCTION__))
;
982 DiagID = diag::note_checking_constraints_for_function_here;
983 }
984 SmallString<128> TemplateArgsStr;
985 llvm::raw_svector_ostream OS(TemplateArgsStr);
986 cast<NamedDecl>(Active->Entity)->printName(OS, getPrintingPolicy());
987 if (!isa<FunctionDecl>(Active->Entity)) {
988 printTemplateArgumentList(OS, Active->template_arguments(),
989 getPrintingPolicy());
990 }
991 Diags.Report(Active->PointOfInstantiation, DiagID) << OS.str()
992 << Active->InstantiationRange;
993 break;
994 }
995 case CodeSynthesisContext::ConstraintSubstitution:
996 Diags.Report(Active->PointOfInstantiation,
997 diag::note_constraint_substitution_here)
998 << Active->InstantiationRange;
999 break;
1000 case CodeSynthesisContext::ConstraintNormalization:
1001 Diags.Report(Active->PointOfInstantiation,
1002 diag::note_constraint_normalization_here)
1003 << cast<NamedDecl>(Active->Entity)->getName()
1004 << Active->InstantiationRange;
1005 break;
1006 case CodeSynthesisContext::ParameterMappingSubstitution:
1007 Diags.Report(Active->PointOfInstantiation,
1008 diag::note_parameter_mapping_substitution_here)
1009 << Active->InstantiationRange;
1010 break;
1011 }
1012 }
1013}
1014
1015std::optional<TemplateDeductionInfo *> Sema::isSFINAEContext() const {
1016 if (InNonInstantiationSFINAEContext)
1017 return std::optional<TemplateDeductionInfo *>(nullptr);
1018
1019 for (SmallVectorImpl<CodeSynthesisContext>::const_reverse_iterator
1020 Active = CodeSynthesisContexts.rbegin(),
1021 ActiveEnd = CodeSynthesisContexts.rend();
1022 Active != ActiveEnd;
1023 ++Active)
1024 {
1025 switch (Active->Kind) {
1026 case CodeSynthesisContext::TemplateInstantiation:
1027 // An instantiation of an alias template may or may not be a SFINAE
1028 // context, depending on what else is on the stack.
1029 if (isa<TypeAliasTemplateDecl>(Active->Entity))
1030 break;
1031 [[fallthrough]];
1032 case CodeSynthesisContext::DefaultFunctionArgumentInstantiation:
1033 case CodeSynthesisContext::ExceptionSpecInstantiation:
1034 case CodeSynthesisContext::ConstraintsCheck:
1035 case CodeSynthesisContext::ParameterMappingSubstitution:
1036 case CodeSynthesisContext::ConstraintNormalization:
1037 case CodeSynthesisContext::NestedRequirementConstraintsCheck:
1038 // This is a template instantiation, so there is no SFINAE.
1039 return std::nullopt;
1040
1041 case CodeSynthesisContext::DefaultTemplateArgumentInstantiation:
1042 case CodeSynthesisContext::PriorTemplateArgumentSubstitution:
1043 case CodeSynthesisContext::DefaultTemplateArgumentChecking:
1044 case CodeSynthesisContext::RewritingOperatorAsSpaceship:
1045 // A default template argument instantiation and substitution into
1046 // template parameters with arguments for prior parameters may or may
1047 // not be a SFINAE context; look further up the stack.
1048 break;
1049
1050 case CodeSynthesisContext::ExplicitTemplateArgumentSubstitution:
1051 case CodeSynthesisContext::DeducedTemplateArgumentSubstitution:
1052 case CodeSynthesisContext::ConstraintSubstitution:
1053 case CodeSynthesisContext::RequirementInstantiation:
1054 case CodeSynthesisContext::RequirementParameterInstantiation:
1055 // We're either substituting explicitly-specified template arguments,
1056 // deduced template arguments, a constraint expression or a requirement
1057 // in a requires expression, so SFINAE applies.
1058 assert(Active->DeductionInfo && "Missing deduction info pointer")(static_cast <bool> (Active->DeductionInfo &&
"Missing deduction info pointer") ? void (0) : __assert_fail
("Active->DeductionInfo && \"Missing deduction info pointer\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1058, __extension__
__PRETTY_FUNCTION__))
;
1059 return Active->DeductionInfo;
1060
1061 case CodeSynthesisContext::DeclaringSpecialMember:
1062 case CodeSynthesisContext::DeclaringImplicitEqualityComparison:
1063 case CodeSynthesisContext::DefiningSynthesizedFunction:
1064 case CodeSynthesisContext::InitializingStructuredBinding:
1065 case CodeSynthesisContext::MarkingClassDllexported:
1066 case CodeSynthesisContext::BuildingBuiltinDumpStructCall:
1067 // This happens in a context unrelated to template instantiation, so
1068 // there is no SFINAE.
1069 return std::nullopt;
1070
1071 case CodeSynthesisContext::ExceptionSpecEvaluation:
1072 // FIXME: This should not be treated as a SFINAE context, because
1073 // we will cache an incorrect exception specification. However, clang
1074 // bootstrap relies this! See PR31692.
1075 break;
1076
1077 case CodeSynthesisContext::Memoization:
1078 break;
1079 }
1080
1081 // The inner context was transparent for SFINAE. If it occurred within a
1082 // non-instantiation SFINAE context, then SFINAE applies.
1083 if (Active->SavedInNonInstantiationSFINAEContext)
1084 return std::optional<TemplateDeductionInfo *>(nullptr);
1085 }
1086
1087 return std::nullopt;
1088}
1089
1090//===----------------------------------------------------------------------===/
1091// Template Instantiation for Types
1092//===----------------------------------------------------------------------===/
1093namespace {
1094 class TemplateInstantiator : public TreeTransform<TemplateInstantiator> {
1095 const MultiLevelTemplateArgumentList &TemplateArgs;
1096 SourceLocation Loc;
1097 DeclarationName Entity;
1098 bool EvaluateConstraints = true;
1099
1100 public:
1101 typedef TreeTransform<TemplateInstantiator> inherited;
1102
1103 TemplateInstantiator(Sema &SemaRef,
1104 const MultiLevelTemplateArgumentList &TemplateArgs,
1105 SourceLocation Loc, DeclarationName Entity)
1106 : inherited(SemaRef), TemplateArgs(TemplateArgs), Loc(Loc),
1107 Entity(Entity) {}
1108
1109 void setEvaluateConstraints(bool B) {
1110 EvaluateConstraints = B;
1111 }
1112 bool getEvaluateConstraints() {
1113 return EvaluateConstraints;
1114 }
1115
1116 /// Determine whether the given type \p T has already been
1117 /// transformed.
1118 ///
1119 /// For the purposes of template instantiation, a type has already been
1120 /// transformed if it is NULL or if it is not dependent.
1121 bool AlreadyTransformed(QualType T);
1122
1123 /// Returns the location of the entity being instantiated, if known.
1124 SourceLocation getBaseLocation() { return Loc; }
1125
1126 /// Returns the name of the entity being instantiated, if any.
1127 DeclarationName getBaseEntity() { return Entity; }
1128
1129 /// Sets the "base" location and entity when that
1130 /// information is known based on another transformation.
1131 void setBase(SourceLocation Loc, DeclarationName Entity) {
1132 this->Loc = Loc;
1133 this->Entity = Entity;
1134 }
1135
1136 unsigned TransformTemplateDepth(unsigned Depth) {
1137 return TemplateArgs.getNewDepth(Depth);
1138 }
1139
1140 std::optional<unsigned> getPackIndex(TemplateArgument Pack) {
1141 int Index = getSema().ArgumentPackSubstitutionIndex;
1142 if (Index == -1)
1143 return std::nullopt;
1144 return Pack.pack_size() - 1 - Index;
1145 }
1146
1147 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
1148 SourceRange PatternRange,
1149 ArrayRef<UnexpandedParameterPack> Unexpanded,
1150 bool &ShouldExpand, bool &RetainExpansion,
1151 std::optional<unsigned> &NumExpansions) {
1152 return getSema().CheckParameterPacksForExpansion(EllipsisLoc,
1153 PatternRange, Unexpanded,
1154 TemplateArgs,
1155 ShouldExpand,
1156 RetainExpansion,
1157 NumExpansions);
1158 }
1159
1160 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) {
1161 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Pack);
1162 }
1163
1164 TemplateArgument ForgetPartiallySubstitutedPack() {
1165 TemplateArgument Result;
1166 if (NamedDecl *PartialPack
1167 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1168 MultiLevelTemplateArgumentList &TemplateArgs
1169 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1170 unsigned Depth, Index;
1171 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1172 if (TemplateArgs.hasTemplateArgument(Depth, Index)) {
1173 Result = TemplateArgs(Depth, Index);
1174 TemplateArgs.setArgument(Depth, Index, TemplateArgument());
1175 }
1176 }
1177
1178 return Result;
1179 }
1180
1181 void RememberPartiallySubstitutedPack(TemplateArgument Arg) {
1182 if (Arg.isNull())
1183 return;
1184
1185 if (NamedDecl *PartialPack
1186 = SemaRef.CurrentInstantiationScope->getPartiallySubstitutedPack()){
1187 MultiLevelTemplateArgumentList &TemplateArgs
1188 = const_cast<MultiLevelTemplateArgumentList &>(this->TemplateArgs);
1189 unsigned Depth, Index;
1190 std::tie(Depth, Index) = getDepthAndIndex(PartialPack);
1191 TemplateArgs.setArgument(Depth, Index, Arg);
1192 }
1193 }
1194
1195 /// Transform the given declaration by instantiating a reference to
1196 /// this declaration.
1197 Decl *TransformDecl(SourceLocation Loc, Decl *D);
1198
1199 void transformAttrs(Decl *Old, Decl *New) {
1200 SemaRef.InstantiateAttrs(TemplateArgs, Old, New);
1201 }
1202
1203 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> NewDecls) {
1204 if (Old->isParameterPack()) {
17
Assuming the condition is false
1205 SemaRef.CurrentInstantiationScope->MakeInstantiatedLocalArgPack(Old);
1206 for (auto *New : NewDecls)
1207 SemaRef.CurrentInstantiationScope->InstantiatedLocalPackArg(
1208 Old, cast<VarDecl>(New));
1209 return;
1210 }
1211
1212 assert(NewDecls.size() == 1 &&(static_cast <bool> (NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? void (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1213, __extension__
__PRETTY_FUNCTION__))
18
Taking false branch
19
Assuming the condition is true
20
'?' condition is true
1213 "should only have multiple expansions for a pack")(static_cast <bool> (NewDecls.size() == 1 && "should only have multiple expansions for a pack"
) ? void (0) : __assert_fail ("NewDecls.size() == 1 && \"should only have multiple expansions for a pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1213, __extension__
__PRETTY_FUNCTION__))
;
1214 Decl *New = NewDecls.front();
1215
1216 // If we've instantiated the call operator of a lambda or the call
1217 // operator template of a generic lambda, update the "instantiation of"
1218 // information.
1219 auto *NewMD = dyn_cast<CXXMethodDecl>(New);
21
Assuming 'New' is a 'CastReturnType'
1220 if (NewMD
21.1
'NewMD' is non-null
21.1
'NewMD' is non-null
&& isLambdaCallOperator(NewMD)) {
22
Taking true branch
1221 auto *OldMD = dyn_cast<CXXMethodDecl>(Old);
23
Assuming 'Old' is not a 'CastReturnType'
24
'OldMD' initialized to a null pointer value
1222 if (auto *NewTD = NewMD->getDescribedFunctionTemplate())
25
Assuming 'NewTD' is non-null
26
Taking true branch
1223 NewTD->setInstantiatedFromMemberTemplate(
1224 OldMD->getDescribedFunctionTemplate());
27
Called C++ object pointer is null
1225 else
1226 NewMD->setInstantiationOfMemberFunction(OldMD,
1227 TSK_ImplicitInstantiation);
1228 }
1229
1230 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Old, New);
1231
1232 // We recreated a local declaration, but not by instantiating it. There
1233 // may be pending dependent diagnostics to produce.
1234 if (auto *DC = dyn_cast<DeclContext>(Old);
1235 DC && DC->isDependentContext() && DC->isFunctionOrMethod())
1236 SemaRef.PerformDependentDiagnostics(DC, TemplateArgs);
1237 }
1238
1239 /// Transform the definition of the given declaration by
1240 /// instantiating it.
1241 Decl *TransformDefinition(SourceLocation Loc, Decl *D);
1242
1243 /// Transform the first qualifier within a scope by instantiating the
1244 /// declaration.
1245 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc);
1246
1247 /// Rebuild the exception declaration and register the declaration
1248 /// as an instantiated local.
1249 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
1250 TypeSourceInfo *Declarator,
1251 SourceLocation StartLoc,
1252 SourceLocation NameLoc,
1253 IdentifierInfo *Name);
1254
1255 /// Rebuild the Objective-C exception declaration and register the
1256 /// declaration as an instantiated local.
1257 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1258 TypeSourceInfo *TSInfo, QualType T);
1259
1260 /// Check for tag mismatches when instantiating an
1261 /// elaborated type.
1262 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1263 ElaboratedTypeKeyword Keyword,
1264 NestedNameSpecifierLoc QualifierLoc,
1265 QualType T);
1266
1267 TemplateName
1268 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
1269 SourceLocation NameLoc,
1270 QualType ObjectType = QualType(),
1271 NamedDecl *FirstQualifierInScope = nullptr,
1272 bool AllowInjectedClassName = false);
1273
1274 const LoopHintAttr *TransformLoopHintAttr(const LoopHintAttr *LH);
1275 const NoInlineAttr *TransformStmtNoInlineAttr(const Stmt *OrigS,
1276 const Stmt *InstS,
1277 const NoInlineAttr *A);
1278 const AlwaysInlineAttr *
1279 TransformStmtAlwaysInlineAttr(const Stmt *OrigS, const Stmt *InstS,
1280 const AlwaysInlineAttr *A);
1281
1282 ExprResult TransformPredefinedExpr(PredefinedExpr *E);
1283 ExprResult TransformDeclRefExpr(DeclRefExpr *E);
1284 ExprResult TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E);
1285
1286 ExprResult TransformTemplateParmRefExpr(DeclRefExpr *E,
1287 NonTypeTemplateParmDecl *D);
1288 ExprResult TransformSubstNonTypeTemplateParmPackExpr(
1289 SubstNonTypeTemplateParmPackExpr *E);
1290 ExprResult TransformSubstNonTypeTemplateParmExpr(
1291 SubstNonTypeTemplateParmExpr *E);
1292
1293 /// Rebuild a DeclRefExpr for a VarDecl reference.
1294 ExprResult RebuildVarDeclRefExpr(VarDecl *PD, SourceLocation Loc);
1295
1296 /// Transform a reference to a function or init-capture parameter pack.
1297 ExprResult TransformFunctionParmPackRefExpr(DeclRefExpr *E, VarDecl *PD);
1298
1299 /// Transform a FunctionParmPackExpr which was built when we couldn't
1300 /// expand a function parameter pack reference which refers to an expanded
1301 /// pack.
1302 ExprResult TransformFunctionParmPackExpr(FunctionParmPackExpr *E);
1303
1304 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1305 FunctionProtoTypeLoc TL) {
1306 // Call the base version; it will forward to our overridden version below.
1307 return inherited::TransformFunctionProtoType(TLB, TL);
1308 }
1309
1310 template<typename Fn>
1311 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
1312 FunctionProtoTypeLoc TL,
1313 CXXRecordDecl *ThisContext,
1314 Qualifiers ThisTypeQuals,
1315 Fn TransformExceptionSpec);
1316
1317 ParmVarDecl *
1318 TransformFunctionTypeParam(ParmVarDecl *OldParm, int indexAdjustment,
1319 std::optional<unsigned> NumExpansions,
1320 bool ExpectParameterPack);
1321
1322 using inherited::TransformTemplateTypeParmType;
1323 /// Transforms a template type parameter type by performing
1324 /// substitution of the corresponding template type argument.
1325 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
1326 TemplateTypeParmTypeLoc TL,
1327 bool SuppressObjCLifetime);
1328
1329 QualType BuildSubstTemplateTypeParmType(
1330 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
1331 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
1332 TemplateArgument Arg, SourceLocation NameLoc);
1333
1334 /// Transforms an already-substituted template type parameter pack
1335 /// into either itself (if we aren't substituting into its pack expansion)
1336 /// or the appropriate substituted argument.
1337 using inherited::TransformSubstTemplateTypeParmPackType;
1338 QualType
1339 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
1340 SubstTemplateTypeParmPackTypeLoc TL,
1341 bool SuppressObjCLifetime);
1342
1343 ExprResult TransformLambdaExpr(LambdaExpr *E) {
1344 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1345 Sema::ConstraintEvalRAII<TemplateInstantiator> RAII(*this);
1346 ExprResult Result = inherited::TransformLambdaExpr(E);
1
Calling 'TreeTransform::TransformLambdaExpr'
1347 if (Result.isInvalid())
1348 return Result;
1349
1350 CXXMethodDecl *MD = Result.getAs<LambdaExpr>()->getCallOperator();
1351 for (ParmVarDecl *PVD : MD->parameters()) {
1352 if (!PVD || !PVD->hasDefaultArg())
1353 continue;
1354 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
1355 // FIXME: Obtain the source location for the '=' token.
1356 SourceLocation EqualLoc = UninstExpr->getBeginLoc();
1357 if (SemaRef.SubstDefaultArgument(EqualLoc, PVD, TemplateArgs)) {
1358 // If substitution fails, the default argument is set to a
1359 // RecoveryExpr that wraps the uninstantiated default argument so
1360 // that downstream diagnostics are omitted.
1361 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
1362 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
1363 { UninstExpr }, UninstExpr->getType());
1364 if (ErrorResult.isUsable())
1365 PVD->setDefaultArg(ErrorResult.get());
1366 }
1367 }
1368
1369 return Result;
1370 }
1371
1372 ExprResult TransformRequiresExpr(RequiresExpr *E) {
1373 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
1374 ExprResult TransReq = inherited::TransformRequiresExpr(E);
1375 if (TransReq.isInvalid())
1376 return TransReq;
1377 assert(TransReq.get() != E &&(static_cast <bool> (TransReq.get() != E && "Do not change value of isSatisfied for the existing expression. "
"Create a new expression instead.") ? void (0) : __assert_fail
("TransReq.get() != E && \"Do not change value of isSatisfied for the existing expression. \" \"Create a new expression instead.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1379, __extension__
__PRETTY_FUNCTION__))
1378 "Do not change value of isSatisfied for the existing expression. "(static_cast <bool> (TransReq.get() != E && "Do not change value of isSatisfied for the existing expression. "
"Create a new expression instead.") ? void (0) : __assert_fail
("TransReq.get() != E && \"Do not change value of isSatisfied for the existing expression. \" \"Create a new expression instead.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1379, __extension__
__PRETTY_FUNCTION__))
1379 "Create a new expression instead.")(static_cast <bool> (TransReq.get() != E && "Do not change value of isSatisfied for the existing expression. "
"Create a new expression instead.") ? void (0) : __assert_fail
("TransReq.get() != E && \"Do not change value of isSatisfied for the existing expression. \" \"Create a new expression instead.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1379, __extension__
__PRETTY_FUNCTION__))
;
1380 if (E->getBody()->isDependentContext()) {
1381 Sema::SFINAETrap Trap(SemaRef);
1382 // We recreate the RequiresExpr body, but not by instantiating it.
1383 // Produce pending diagnostics for dependent access check.
1384 SemaRef.PerformDependentDiagnostics(E->getBody(), TemplateArgs);
1385 // FIXME: Store SFINAE diagnostics in RequiresExpr for diagnosis.
1386 if (Trap.hasErrorOccurred())
1387 TransReq.getAs<RequiresExpr>()->setSatisfied(false);
1388 }
1389 return TransReq;
1390 }
1391
1392 bool TransformRequiresExprRequirements(
1393 ArrayRef<concepts::Requirement *> Reqs,
1394 SmallVectorImpl<concepts::Requirement *> &Transformed) {
1395 bool SatisfactionDetermined = false;
1396 for (concepts::Requirement *Req : Reqs) {
1397 concepts::Requirement *TransReq = nullptr;
1398 if (!SatisfactionDetermined) {
1399 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
1400 TransReq = TransformTypeRequirement(TypeReq);
1401 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
1402 TransReq = TransformExprRequirement(ExprReq);
1403 else
1404 TransReq = TransformNestedRequirement(
1405 cast<concepts::NestedRequirement>(Req));
1406 if (!TransReq)
1407 return true;
1408 if (!TransReq->isDependent() && !TransReq->isSatisfied())
1409 // [expr.prim.req]p6
1410 // [...] The substitution and semantic constraint checking
1411 // proceeds in lexical order and stops when a condition that
1412 // determines the result of the requires-expression is
1413 // encountered. [..]
1414 SatisfactionDetermined = true;
1415 } else
1416 TransReq = Req;
1417 Transformed.push_back(TransReq);
1418 }
1419 return false;
1420 }
1421
1422 TemplateParameterList *TransformTemplateParameterList(
1423 TemplateParameterList *OrigTPL) {
1424 if (!OrigTPL || !OrigTPL->size()) return OrigTPL;
1425
1426 DeclContext *Owner = OrigTPL->getParam(0)->getDeclContext();
1427 TemplateDeclInstantiator DeclInstantiator(getSema(),
1428 /* DeclContext *Owner */ Owner, TemplateArgs);
1429 DeclInstantiator.setEvaluateConstraints(EvaluateConstraints);
1430 return DeclInstantiator.SubstTemplateParams(OrigTPL);
1431 }
1432
1433 concepts::TypeRequirement *
1434 TransformTypeRequirement(concepts::TypeRequirement *Req);
1435 concepts::ExprRequirement *
1436 TransformExprRequirement(concepts::ExprRequirement *Req);
1437 concepts::NestedRequirement *
1438 TransformNestedRequirement(concepts::NestedRequirement *Req);
1439 ExprResult TransformRequiresTypeParams(
1440 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
1441 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
1442 SmallVectorImpl<QualType> &PTypes,
1443 SmallVectorImpl<ParmVarDecl *> &TransParams,
1444 Sema::ExtParameterInfoBuilder &PInfos);
1445
1446 private:
1447 ExprResult
1448 transformNonTypeTemplateParmRef(Decl *AssociatedDecl,
1449 const NonTypeTemplateParmDecl *parm,
1450 SourceLocation loc, TemplateArgument arg,
1451 std::optional<unsigned> PackIndex);
1452 };
1453}
1454
1455bool TemplateInstantiator::AlreadyTransformed(QualType T) {
1456 if (T.isNull())
1457 return true;
1458
1459 if (T->isInstantiationDependentType() || T->isVariablyModifiedType())
1460 return false;
1461
1462 getSema().MarkDeclarationsReferencedInType(Loc, T);
1463 return true;
1464}
1465
1466static TemplateArgument
1467getPackSubstitutedTemplateArgument(Sema &S, TemplateArgument Arg) {
1468 assert(S.ArgumentPackSubstitutionIndex >= 0)(static_cast <bool> (S.ArgumentPackSubstitutionIndex >=
0) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex >= 0"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1468, __extension__
__PRETTY_FUNCTION__))
;
1469 assert(S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size())(static_cast <bool> (S.ArgumentPackSubstitutionIndex <
(int)Arg.pack_size()) ? void (0) : __assert_fail ("S.ArgumentPackSubstitutionIndex < (int)Arg.pack_size()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1469, __extension__
__PRETTY_FUNCTION__))
;
1470 Arg = Arg.pack_begin()[S.ArgumentPackSubstitutionIndex];
1471 if (Arg.isPackExpansion())
1472 Arg = Arg.getPackExpansionPattern();
1473 return Arg;
1474}
1475
1476Decl *TemplateInstantiator::TransformDecl(SourceLocation Loc, Decl *D) {
1477 if (!D)
1478 return nullptr;
1479
1480 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(D)) {
1481 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1482 // If the corresponding template argument is NULL or non-existent, it's
1483 // because we are performing instantiation from explicitly-specified
1484 // template arguments in a function template, but there were some
1485 // arguments left unspecified.
1486 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1487 TTP->getPosition()))
1488 return D;
1489
1490 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1491
1492 if (TTP->isParameterPack()) {
1493 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1494, __extension__
__PRETTY_FUNCTION__))
1494 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1494, __extension__
__PRETTY_FUNCTION__))
;
1495 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1496 }
1497
1498 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1499 assert(!Template.isNull() && Template.getAsTemplateDecl() &&(static_cast <bool> (!Template.isNull() && Template
.getAsTemplateDecl() && "Wrong kind of template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1500, __extension__
__PRETTY_FUNCTION__))
1500 "Wrong kind of template template argument")(static_cast <bool> (!Template.isNull() && Template
.getAsTemplateDecl() && "Wrong kind of template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && Template.getAsTemplateDecl() && \"Wrong kind of template template argument\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1500, __extension__
__PRETTY_FUNCTION__))
;
1501 return Template.getAsTemplateDecl();
1502 }
1503
1504 // Fall through to find the instantiated declaration for this template
1505 // template parameter.
1506 }
1507
1508 return SemaRef.FindInstantiatedDecl(Loc, cast<NamedDecl>(D), TemplateArgs);
1509}
1510
1511Decl *TemplateInstantiator::TransformDefinition(SourceLocation Loc, Decl *D) {
1512 Decl *Inst = getSema().SubstDecl(D, getSema().CurContext, TemplateArgs);
1513 if (!Inst)
1514 return nullptr;
1515
1516 getSema().CurrentInstantiationScope->InstantiatedLocal(D, Inst);
1517 return Inst;
1518}
1519
1520NamedDecl *
1521TemplateInstantiator::TransformFirstQualifierInScope(NamedDecl *D,
1522 SourceLocation Loc) {
1523 // If the first part of the nested-name-specifier was a template type
1524 // parameter, instantiate that type parameter down to a tag type.
1525 if (TemplateTypeParmDecl *TTPD = dyn_cast_or_null<TemplateTypeParmDecl>(D)) {
1526 const TemplateTypeParmType *TTP
1527 = cast<TemplateTypeParmType>(getSema().Context.getTypeDeclType(TTPD));
1528
1529 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1530 // FIXME: This needs testing w/ member access expressions.
1531 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getIndex());
1532
1533 if (TTP->isParameterPack()) {
1534 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1535, __extension__
__PRETTY_FUNCTION__))
1535 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1535, __extension__
__PRETTY_FUNCTION__))
;
1536
1537 if (getSema().ArgumentPackSubstitutionIndex == -1)
1538 return nullptr;
1539
1540 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1541 }
1542
1543 QualType T = Arg.getAsType();
1544 if (T.isNull())
1545 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1546
1547 if (const TagType *Tag = T->getAs<TagType>())
1548 return Tag->getDecl();
1549
1550 // The resulting type is not a tag; complain.
1551 getSema().Diag(Loc, diag::err_nested_name_spec_non_tag) << T;
1552 return nullptr;
1553 }
1554 }
1555
1556 return cast_or_null<NamedDecl>(TransformDecl(Loc, D));
1557}
1558
1559VarDecl *
1560TemplateInstantiator::RebuildExceptionDecl(VarDecl *ExceptionDecl,
1561 TypeSourceInfo *Declarator,
1562 SourceLocation StartLoc,
1563 SourceLocation NameLoc,
1564 IdentifierInfo *Name) {
1565 VarDecl *Var = inherited::RebuildExceptionDecl(ExceptionDecl, Declarator,
1566 StartLoc, NameLoc, Name);
1567 if (Var)
1568 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1569 return Var;
1570}
1571
1572VarDecl *TemplateInstantiator::RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1573 TypeSourceInfo *TSInfo,
1574 QualType T) {
1575 VarDecl *Var = inherited::RebuildObjCExceptionDecl(ExceptionDecl, TSInfo, T);
1576 if (Var)
1577 getSema().CurrentInstantiationScope->InstantiatedLocal(ExceptionDecl, Var);
1578 return Var;
1579}
1580
1581QualType
1582TemplateInstantiator::RebuildElaboratedType(SourceLocation KeywordLoc,
1583 ElaboratedTypeKeyword Keyword,
1584 NestedNameSpecifierLoc QualifierLoc,
1585 QualType T) {
1586 if (const TagType *TT = T->getAs<TagType>()) {
1587 TagDecl* TD = TT->getDecl();
1588
1589 SourceLocation TagLocation = KeywordLoc;
1590
1591 IdentifierInfo *Id = TD->getIdentifier();
1592
1593 // TODO: should we even warn on struct/class mismatches for this? Seems
1594 // like it's likely to produce a lot of spurious errors.
1595 if (Id && Keyword != ETK_None && Keyword != ETK_Typename) {
1596 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1597 if (!SemaRef.isAcceptableTagRedeclaration(TD, Kind, /*isDefinition*/false,
1598 TagLocation, Id)) {
1599 SemaRef.Diag(TagLocation, diag::err_use_with_wrong_tag)
1600 << Id
1601 << FixItHint::CreateReplacement(SourceRange(TagLocation),
1602 TD->getKindName());
1603 SemaRef.Diag(TD->getLocation(), diag::note_previous_use);
1604 }
1605 }
1606 }
1607
1608 return inherited::RebuildElaboratedType(KeywordLoc, Keyword, QualifierLoc, T);
1609}
1610
1611TemplateName TemplateInstantiator::TransformTemplateName(
1612 CXXScopeSpec &SS, TemplateName Name, SourceLocation NameLoc,
1613 QualType ObjectType, NamedDecl *FirstQualifierInScope,
1614 bool AllowInjectedClassName) {
1615 if (TemplateTemplateParmDecl *TTP
1616 = dyn_cast_or_null<TemplateTemplateParmDecl>(Name.getAsTemplateDecl())) {
1617 if (TTP->getDepth() < TemplateArgs.getNumLevels()) {
1618 // If the corresponding template argument is NULL or non-existent, it's
1619 // because we are performing instantiation from explicitly-specified
1620 // template arguments in a function template, but there were some
1621 // arguments left unspecified.
1622 if (!TemplateArgs.hasTemplateArgument(TTP->getDepth(),
1623 TTP->getPosition()))
1624 return Name;
1625
1626 TemplateArgument Arg = TemplateArgs(TTP->getDepth(), TTP->getPosition());
1627
1628 if (TemplateArgs.isRewrite()) {
1629 // We're rewriting the template parameter as a reference to another
1630 // template parameter.
1631 if (Arg.getKind() == TemplateArgument::Pack) {
1632 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1633, __extension__
__PRETTY_FUNCTION__))
1633 "unexpected pack arguments in template rewrite")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1633, __extension__
__PRETTY_FUNCTION__))
;
1634 Arg = Arg.pack_begin()->getPackExpansionPattern();
1635 }
1636 assert(Arg.getKind() == TemplateArgument::Template &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Template && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Template && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1637, __extension__
__PRETTY_FUNCTION__))
1637 "unexpected nontype template argument kind in template rewrite")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Template && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Template && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1637, __extension__
__PRETTY_FUNCTION__))
;
1638 return Arg.getAsTemplate();
1639 }
1640
1641 auto [AssociatedDecl, Final] =
1642 TemplateArgs.getAssociatedDecl(TTP->getDepth());
1643 std::optional<unsigned> PackIndex;
1644 if (TTP->isParameterPack()) {
1645 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1646, __extension__
__PRETTY_FUNCTION__))
1646 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1646, __extension__
__PRETTY_FUNCTION__))
;
1647
1648 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1649 // We have the template argument pack to substitute, but we're not
1650 // actually expanding the enclosing pack expansion yet. So, just
1651 // keep the entire argument pack.
1652 return getSema().Context.getSubstTemplateTemplateParmPack(
1653 Arg, AssociatedDecl, TTP->getIndex(), Final);
1654 }
1655
1656 PackIndex = getPackIndex(Arg);
1657 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1658 }
1659
1660 TemplateName Template = Arg.getAsTemplate().getNameToSubstitute();
1661 assert(!Template.isNull() && "Null template template argument")(static_cast <bool> (!Template.isNull() && "Null template template argument"
) ? void (0) : __assert_fail ("!Template.isNull() && \"Null template template argument\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1661, __extension__
__PRETTY_FUNCTION__))
;
1662 assert(!Template.getAsQualifiedTemplateName() &&(static_cast <bool> (!Template.getAsQualifiedTemplateName
() && "template decl to substitute is qualified?") ? void
(0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1663, __extension__
__PRETTY_FUNCTION__))
1663 "template decl to substitute is qualified?")(static_cast <bool> (!Template.getAsQualifiedTemplateName
() && "template decl to substitute is qualified?") ? void
(0) : __assert_fail ("!Template.getAsQualifiedTemplateName() && \"template decl to substitute is qualified?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1663, __extension__
__PRETTY_FUNCTION__))
;
1664
1665 if (Final)
1666 return Template;
1667 return getSema().Context.getSubstTemplateTemplateParm(
1668 Template, AssociatedDecl, TTP->getIndex(), PackIndex);
1669 }
1670 }
1671
1672 if (SubstTemplateTemplateParmPackStorage *SubstPack
1673 = Name.getAsSubstTemplateTemplateParmPack()) {
1674 if (getSema().ArgumentPackSubstitutionIndex == -1)
1675 return Name;
1676
1677 TemplateArgument Pack = SubstPack->getArgumentPack();
1678 TemplateName Template =
1679 getPackSubstitutedTemplateArgument(getSema(), Pack).getAsTemplate();
1680 if (SubstPack->getFinal())
1681 return Template;
1682 return getSema().Context.getSubstTemplateTemplateParm(
1683 Template.getNameToSubstitute(), SubstPack->getAssociatedDecl(),
1684 SubstPack->getIndex(), getPackIndex(Pack));
1685 }
1686
1687 return inherited::TransformTemplateName(SS, Name, NameLoc, ObjectType,
1688 FirstQualifierInScope,
1689 AllowInjectedClassName);
1690}
1691
1692ExprResult
1693TemplateInstantiator::TransformPredefinedExpr(PredefinedExpr *E) {
1694 if (!E->isTypeDependent())
1695 return E;
1696
1697 return getSema().BuildPredefinedExpr(E->getLocation(), E->getIdentKind());
1698}
1699
1700ExprResult
1701TemplateInstantiator::TransformTemplateParmRefExpr(DeclRefExpr *E,
1702 NonTypeTemplateParmDecl *NTTP) {
1703 // If the corresponding template argument is NULL or non-existent, it's
1704 // because we are performing instantiation from explicitly-specified
1705 // template arguments in a function template, but there were some
1706 // arguments left unspecified.
1707 if (!TemplateArgs.hasTemplateArgument(NTTP->getDepth(),
1708 NTTP->getPosition()))
1709 return E;
1710
1711 TemplateArgument Arg = TemplateArgs(NTTP->getDepth(), NTTP->getPosition());
1712
1713 if (TemplateArgs.isRewrite()) {
1714 // We're rewriting the template parameter as a reference to another
1715 // template parameter.
1716 if (Arg.getKind() == TemplateArgument::Pack) {
1717 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1718, __extension__
__PRETTY_FUNCTION__))
1718 "unexpected pack arguments in template rewrite")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1718, __extension__
__PRETTY_FUNCTION__))
;
1719 Arg = Arg.pack_begin()->getPackExpansionPattern();
1720 }
1721 assert(Arg.getKind() == TemplateArgument::Expression &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1722, __extension__
__PRETTY_FUNCTION__))
1722 "unexpected nontype template argument kind in template rewrite")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Expression && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Expression && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1722, __extension__
__PRETTY_FUNCTION__))
;
1723 // FIXME: This can lead to the same subexpression appearing multiple times
1724 // in a complete expression.
1725 return Arg.getAsExpr();
1726 }
1727
1728 auto [AssociatedDecl, _] = TemplateArgs.getAssociatedDecl(NTTP->getDepth());
1729 std::optional<unsigned> PackIndex;
1730 if (NTTP->isParameterPack()) {
1731 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1732, __extension__
__PRETTY_FUNCTION__))
1732 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1732, __extension__
__PRETTY_FUNCTION__))
;
1733
1734 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1735 // We have an argument pack, but we can't select a particular argument
1736 // out of it yet. Therefore, we'll build an expression to hold on to that
1737 // argument pack.
1738 QualType TargetType = SemaRef.SubstType(NTTP->getType(), TemplateArgs,
1739 E->getLocation(),
1740 NTTP->getDeclName());
1741 if (TargetType.isNull())
1742 return ExprError();
1743
1744 QualType ExprType = TargetType.getNonLValueExprType(SemaRef.Context);
1745 if (TargetType->isRecordType())
1746 ExprType.addConst();
1747 // FIXME: Pass in Final.
1748 return new (SemaRef.Context) SubstNonTypeTemplateParmPackExpr(
1749 ExprType, TargetType->isReferenceType() ? VK_LValue : VK_PRValue,
1750 E->getLocation(), Arg, AssociatedDecl, NTTP->getPosition());
1751 }
1752 PackIndex = getPackIndex(Arg);
1753 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
1754 }
1755 // FIXME: Don't put subst node on Final replacement.
1756 return transformNonTypeTemplateParmRef(AssociatedDecl, NTTP, E->getLocation(),
1757 Arg, PackIndex);
1758}
1759
1760const LoopHintAttr *
1761TemplateInstantiator::TransformLoopHintAttr(const LoopHintAttr *LH) {
1762 Expr *TransformedExpr = getDerived().TransformExpr(LH->getValue()).get();
1763
1764 if (TransformedExpr == LH->getValue())
1765 return LH;
1766
1767 // Generate error if there is a problem with the value.
1768 if (getSema().CheckLoopHintExpr(TransformedExpr, LH->getLocation()))
1769 return LH;
1770
1771 // Create new LoopHintValueAttr with integral expression in place of the
1772 // non-type template parameter.
1773 return LoopHintAttr::CreateImplicit(getSema().Context, LH->getOption(),
1774 LH->getState(), TransformedExpr, *LH);
1775}
1776const NoInlineAttr *TemplateInstantiator::TransformStmtNoInlineAttr(
1777 const Stmt *OrigS, const Stmt *InstS, const NoInlineAttr *A) {
1778 if (!A || getSema().CheckNoInlineAttr(OrigS, InstS, *A))
1779 return nullptr;
1780
1781 return A;
1782}
1783const AlwaysInlineAttr *TemplateInstantiator::TransformStmtAlwaysInlineAttr(
1784 const Stmt *OrigS, const Stmt *InstS, const AlwaysInlineAttr *A) {
1785 if (!A || getSema().CheckAlwaysInlineAttr(OrigS, InstS, *A))
1786 return nullptr;
1787
1788 return A;
1789}
1790
1791ExprResult TemplateInstantiator::transformNonTypeTemplateParmRef(
1792 Decl *AssociatedDecl, const NonTypeTemplateParmDecl *parm,
1793 SourceLocation loc, TemplateArgument arg,
1794 std::optional<unsigned> PackIndex) {
1795 ExprResult result;
1796
1797 // Determine the substituted parameter type. We can usually infer this from
1798 // the template argument, but not always.
1799 auto SubstParamType = [&] {
1800 QualType T;
1801 if (parm->isExpandedParameterPack())
1802 T = parm->getExpansionType(SemaRef.ArgumentPackSubstitutionIndex);
1803 else
1804 T = parm->getType();
1805 if (parm->isParameterPack() && isa<PackExpansionType>(T))
1806 T = cast<PackExpansionType>(T)->getPattern();
1807 return SemaRef.SubstType(T, TemplateArgs, loc, parm->getDeclName());
1808 };
1809
1810 bool refParam = false;
1811
1812 // The template argument itself might be an expression, in which case we just
1813 // return that expression. This happens when substituting into an alias
1814 // template.
1815 if (arg.getKind() == TemplateArgument::Expression) {
1816 Expr *argExpr = arg.getAsExpr();
1817 result = argExpr;
1818 if (argExpr->isLValue()) {
1819 if (argExpr->getType()->isRecordType()) {
1820 // Check whether the parameter was actually a reference.
1821 QualType paramType = SubstParamType();
1822 if (paramType.isNull())
1823 return ExprError();
1824 refParam = paramType->isReferenceType();
1825 } else {
1826 refParam = true;
1827 }
1828 }
1829 } else if (arg.getKind() == TemplateArgument::Declaration ||
1830 arg.getKind() == TemplateArgument::NullPtr) {
1831 ValueDecl *VD;
1832 if (arg.getKind() == TemplateArgument::Declaration) {
1833 VD = arg.getAsDecl();
1834
1835 // Find the instantiation of the template argument. This is
1836 // required for nested templates.
1837 VD = cast_or_null<ValueDecl>(
1838 getSema().FindInstantiatedDecl(loc, VD, TemplateArgs));
1839 if (!VD)
1840 return ExprError();
1841 } else {
1842 // Propagate NULL template argument.
1843 VD = nullptr;
1844 }
1845
1846 QualType paramType = VD ? arg.getParamTypeForDecl() : arg.getNullPtrType();
1847 assert(!paramType.isNull() && "type substitution failed for param type")(static_cast <bool> (!paramType.isNull() && "type substitution failed for param type"
) ? void (0) : __assert_fail ("!paramType.isNull() && \"type substitution failed for param type\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1847, __extension__
__PRETTY_FUNCTION__))
;
1848 assert(!paramType->isDependentType() && "param type still dependent")(static_cast <bool> (!paramType->isDependentType() &&
"param type still dependent") ? void (0) : __assert_fail ("!paramType->isDependentType() && \"param type still dependent\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1848, __extension__
__PRETTY_FUNCTION__))
;
1849 result = SemaRef.BuildExpressionFromDeclTemplateArgument(arg, paramType, loc);
1850 refParam = paramType->isReferenceType();
1851 } else {
1852 result = SemaRef.BuildExpressionFromIntegralTemplateArgument(arg, loc);
1853 assert(result.isInvalid() ||(static_cast <bool> (result.isInvalid() || SemaRef.Context
.hasSameType(result.get()->getType(), arg.getIntegralType(
))) ? void (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1855, __extension__
__PRETTY_FUNCTION__))
1854 SemaRef.Context.hasSameType(result.get()->getType(),(static_cast <bool> (result.isInvalid() || SemaRef.Context
.hasSameType(result.get()->getType(), arg.getIntegralType(
))) ? void (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1855, __extension__
__PRETTY_FUNCTION__))
1855 arg.getIntegralType()))(static_cast <bool> (result.isInvalid() || SemaRef.Context
.hasSameType(result.get()->getType(), arg.getIntegralType(
))) ? void (0) : __assert_fail ("result.isInvalid() || SemaRef.Context.hasSameType(result.get()->getType(), arg.getIntegralType())"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1855, __extension__
__PRETTY_FUNCTION__))
;
1856 }
1857
1858 if (result.isInvalid())
1859 return ExprError();
1860
1861 Expr *resultExpr = result.get();
1862 // FIXME: Don't put subst node on final replacement.
1863 return new (SemaRef.Context) SubstNonTypeTemplateParmExpr(
1864 resultExpr->getType(), resultExpr->getValueKind(), loc, resultExpr,
1865 AssociatedDecl, parm->getIndex(), PackIndex, refParam);
1866}
1867
1868ExprResult
1869TemplateInstantiator::TransformSubstNonTypeTemplateParmPackExpr(
1870 SubstNonTypeTemplateParmPackExpr *E) {
1871 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1872 // We aren't expanding the parameter pack, so just return ourselves.
1873 return E;
1874 }
1875
1876 TemplateArgument Pack = E->getArgumentPack();
1877 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
1878 // FIXME: Don't put subst node on final replacement.
1879 return transformNonTypeTemplateParmRef(
1880 E->getAssociatedDecl(), E->getParameterPack(),
1881 E->getParameterPackLocation(), Arg, getPackIndex(Pack));
1882}
1883
1884ExprResult
1885TemplateInstantiator::TransformSubstNonTypeTemplateParmExpr(
1886 SubstNonTypeTemplateParmExpr *E) {
1887 ExprResult SubstReplacement = E->getReplacement();
1888 if (!isa<ConstantExpr>(SubstReplacement.get()))
1889 SubstReplacement = TransformExpr(E->getReplacement());
1890 if (SubstReplacement.isInvalid())
1891 return true;
1892 QualType SubstType = TransformType(E->getParameterType(getSema().Context));
1893 if (SubstType.isNull())
1894 return true;
1895 // The type may have been previously dependent and not now, which means we
1896 // might have to implicit cast the argument to the new type, for example:
1897 // template<auto T, decltype(T) U>
1898 // concept C = sizeof(U) == 4;
1899 // void foo() requires C<2, 'a'> { }
1900 // When normalizing foo(), we first form the normalized constraints of C:
1901 // AtomicExpr(sizeof(U) == 4,
1902 // U=SubstNonTypeTemplateParmExpr(Param=U,
1903 // Expr=DeclRef(U),
1904 // Type=decltype(T)))
1905 // Then we substitute T = 2, U = 'a' into the parameter mapping, and need to
1906 // produce:
1907 // AtomicExpr(sizeof(U) == 4,
1908 // U=SubstNonTypeTemplateParmExpr(Param=U,
1909 // Expr=ImpCast(
1910 // decltype(2),
1911 // SubstNTTPE(Param=U, Expr='a',
1912 // Type=char)),
1913 // Type=decltype(2)))
1914 // The call to CheckTemplateArgument here produces the ImpCast.
1915 TemplateArgument SugaredConverted, CanonicalConverted;
1916 if (SemaRef
1917 .CheckTemplateArgument(E->getParameter(), SubstType,
1918 SubstReplacement.get(), SugaredConverted,
1919 CanonicalConverted, Sema::CTAK_Specified)
1920 .isInvalid())
1921 return true;
1922 return transformNonTypeTemplateParmRef(E->getAssociatedDecl(),
1923 E->getParameter(), E->getExprLoc(),
1924 SugaredConverted, E->getPackIndex());
1925}
1926
1927ExprResult TemplateInstantiator::RebuildVarDeclRefExpr(VarDecl *PD,
1928 SourceLocation Loc) {
1929 DeclarationNameInfo NameInfo(PD->getDeclName(), Loc);
1930 return getSema().BuildDeclarationNameExpr(CXXScopeSpec(), NameInfo, PD);
1931}
1932
1933ExprResult
1934TemplateInstantiator::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
1935 if (getSema().ArgumentPackSubstitutionIndex != -1) {
1936 // We can expand this parameter pack now.
1937 VarDecl *D = E->getExpansion(getSema().ArgumentPackSubstitutionIndex);
1938 VarDecl *VD = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), D));
1939 if (!VD)
1940 return ExprError();
1941 return RebuildVarDeclRefExpr(VD, E->getExprLoc());
1942 }
1943
1944 QualType T = TransformType(E->getType());
1945 if (T.isNull())
1946 return ExprError();
1947
1948 // Transform each of the parameter expansions into the corresponding
1949 // parameters in the instantiation of the function decl.
1950 SmallVector<VarDecl *, 8> Vars;
1951 Vars.reserve(E->getNumExpansions());
1952 for (FunctionParmPackExpr::iterator I = E->begin(), End = E->end();
1953 I != End; ++I) {
1954 VarDecl *D = cast_or_null<VarDecl>(TransformDecl(E->getExprLoc(), *I));
1955 if (!D)
1956 return ExprError();
1957 Vars.push_back(D);
1958 }
1959
1960 auto *PackExpr =
1961 FunctionParmPackExpr::Create(getSema().Context, T, E->getParameterPack(),
1962 E->getParameterPackLocation(), Vars);
1963 getSema().MarkFunctionParmPackReferenced(PackExpr);
1964 return PackExpr;
1965}
1966
1967ExprResult
1968TemplateInstantiator::TransformFunctionParmPackRefExpr(DeclRefExpr *E,
1969 VarDecl *PD) {
1970 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
1971 llvm::PointerUnion<Decl *, DeclArgumentPack *> *Found
1972 = getSema().CurrentInstantiationScope->findInstantiationOf(PD);
1973 assert(Found && "no instantiation for parameter pack")(static_cast <bool> (Found && "no instantiation for parameter pack"
) ? void (0) : __assert_fail ("Found && \"no instantiation for parameter pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 1973, __extension__
__PRETTY_FUNCTION__))
;
1974
1975 Decl *TransformedDecl;
1976 if (DeclArgumentPack *Pack = Found->dyn_cast<DeclArgumentPack *>()) {
1977 // If this is a reference to a function parameter pack which we can
1978 // substitute but can't yet expand, build a FunctionParmPackExpr for it.
1979 if (getSema().ArgumentPackSubstitutionIndex == -1) {
1980 QualType T = TransformType(E->getType());
1981 if (T.isNull())
1982 return ExprError();
1983 auto *PackExpr = FunctionParmPackExpr::Create(getSema().Context, T, PD,
1984 E->getExprLoc(), *Pack);
1985 getSema().MarkFunctionParmPackReferenced(PackExpr);
1986 return PackExpr;
1987 }
1988
1989 TransformedDecl = (*Pack)[getSema().ArgumentPackSubstitutionIndex];
1990 } else {
1991 TransformedDecl = Found->get<Decl*>();
1992 }
1993
1994 // We have either an unexpanded pack or a specific expansion.
1995 return RebuildVarDeclRefExpr(cast<VarDecl>(TransformedDecl), E->getExprLoc());
1996}
1997
1998ExprResult
1999TemplateInstantiator::TransformDeclRefExpr(DeclRefExpr *E) {
2000 NamedDecl *D = E->getDecl();
2001
2002 // Handle references to non-type template parameters and non-type template
2003 // parameter packs.
2004 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(D)) {
2005 if (NTTP->getDepth() < TemplateArgs.getNumLevels())
2006 return TransformTemplateParmRefExpr(E, NTTP);
2007
2008 // We have a non-type template parameter that isn't fully substituted;
2009 // FindInstantiatedDecl will find it in the local instantiation scope.
2010 }
2011
2012 // Handle references to function parameter packs.
2013 if (VarDecl *PD = dyn_cast<VarDecl>(D))
2014 if (PD->isParameterPack())
2015 return TransformFunctionParmPackRefExpr(E, PD);
2016
2017 return inherited::TransformDeclRefExpr(E);
2018}
2019
2020ExprResult TemplateInstantiator::TransformCXXDefaultArgExpr(
2021 CXXDefaultArgExpr *E) {
2022 assert(!cast<FunctionDecl>(E->getParam()->getDeclContext())->(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2024, __extension__
__PRETTY_FUNCTION__))
2023 getDescribedFunctionTemplate() &&(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2024, __extension__
__PRETTY_FUNCTION__))
2024 "Default arg expressions are never formed in dependent cases.")(static_cast <bool> (!cast<FunctionDecl>(E->getParam
()->getDeclContext())-> getDescribedFunctionTemplate() &&
"Default arg expressions are never formed in dependent cases."
) ? void (0) : __assert_fail ("!cast<FunctionDecl>(E->getParam()->getDeclContext())-> getDescribedFunctionTemplate() && \"Default arg expressions are never formed in dependent cases.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2024, __extension__
__PRETTY_FUNCTION__))
;
2025 return SemaRef.BuildCXXDefaultArgExpr(
2026 E->getUsedLocation(), cast<FunctionDecl>(E->getParam()->getDeclContext()),
2027 E->getParam());
2028}
2029
2030template<typename Fn>
2031QualType TemplateInstantiator::TransformFunctionProtoType(TypeLocBuilder &TLB,
2032 FunctionProtoTypeLoc TL,
2033 CXXRecordDecl *ThisContext,
2034 Qualifiers ThisTypeQuals,
2035 Fn TransformExceptionSpec) {
2036 // We need a local instantiation scope for this function prototype.
2037 LocalInstantiationScope Scope(SemaRef, /*CombineWithOuterScope=*/true);
2038 return inherited::TransformFunctionProtoType(
2039 TLB, TL, ThisContext, ThisTypeQuals, TransformExceptionSpec);
2040}
2041
2042ParmVarDecl *TemplateInstantiator::TransformFunctionTypeParam(
2043 ParmVarDecl *OldParm, int indexAdjustment,
2044 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
2045 auto NewParm = SemaRef.SubstParmVarDecl(
2046 OldParm, TemplateArgs, indexAdjustment, NumExpansions,
2047 ExpectParameterPack, EvaluateConstraints);
2048 if (NewParm && SemaRef.getLangOpts().OpenCL)
2049 SemaRef.deduceOpenCLAddressSpace(NewParm);
2050 return NewParm;
2051}
2052
2053QualType TemplateInstantiator::BuildSubstTemplateTypeParmType(
2054 TypeLocBuilder &TLB, bool SuppressObjCLifetime, bool Final,
2055 Decl *AssociatedDecl, unsigned Index, std::optional<unsigned> PackIndex,
2056 TemplateArgument Arg, SourceLocation NameLoc) {
2057 QualType Replacement = Arg.getAsType();
2058
2059 // If the template parameter had ObjC lifetime qualifiers,
2060 // then any such qualifiers on the replacement type are ignored.
2061 if (SuppressObjCLifetime) {
2062 Qualifiers RQs;
2063 RQs = Replacement.getQualifiers();
2064 RQs.removeObjCLifetime();
2065 Replacement =
2066 SemaRef.Context.getQualifiedType(Replacement.getUnqualifiedType(), RQs);
2067 }
2068
2069 if (Final) {
2070 TLB.pushTrivial(SemaRef.Context, Replacement, NameLoc);
2071 return Replacement;
2072 }
2073 // TODO: only do this uniquing once, at the start of instantiation.
2074 QualType Result = getSema().Context.getSubstTemplateTypeParmType(
2075 Replacement, AssociatedDecl, Index, PackIndex);
2076 SubstTemplateTypeParmTypeLoc NewTL =
2077 TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
2078 NewTL.setNameLoc(NameLoc);
2079 return Result;
2080}
2081
2082QualType
2083TemplateInstantiator::TransformTemplateTypeParmType(TypeLocBuilder &TLB,
2084 TemplateTypeParmTypeLoc TL,
2085 bool SuppressObjCLifetime) {
2086 const TemplateTypeParmType *T = TL.getTypePtr();
2087 if (T->getDepth() < TemplateArgs.getNumLevels()) {
2088 // Replace the template type parameter with its corresponding
2089 // template argument.
2090
2091 // If the corresponding template argument is NULL or doesn't exist, it's
2092 // because we are performing instantiation from explicitly-specified
2093 // template arguments in a function template class, but there were some
2094 // arguments left unspecified.
2095 if (!TemplateArgs.hasTemplateArgument(T->getDepth(), T->getIndex())) {
2096 TemplateTypeParmTypeLoc NewTL
2097 = TLB.push<TemplateTypeParmTypeLoc>(TL.getType());
2098 NewTL.setNameLoc(TL.getNameLoc());
2099 return TL.getType();
2100 }
2101
2102 TemplateArgument Arg = TemplateArgs(T->getDepth(), T->getIndex());
2103
2104 if (TemplateArgs.isRewrite()) {
2105 // We're rewriting the template parameter as a reference to another
2106 // template parameter.
2107 if (Arg.getKind() == TemplateArgument::Pack) {
2108 assert(Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() &&(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2109, __extension__
__PRETTY_FUNCTION__))
2109 "unexpected pack arguments in template rewrite")(static_cast <bool> (Arg.pack_size() == 1 && Arg
.pack_begin()->isPackExpansion() && "unexpected pack arguments in template rewrite"
) ? void (0) : __assert_fail ("Arg.pack_size() == 1 && Arg.pack_begin()->isPackExpansion() && \"unexpected pack arguments in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2109, __extension__
__PRETTY_FUNCTION__))
;
2110 Arg = Arg.pack_begin()->getPackExpansionPattern();
2111 }
2112 assert(Arg.getKind() == TemplateArgument::Type &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2113, __extension__
__PRETTY_FUNCTION__))
2113 "unexpected nontype template argument kind in template rewrite")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "unexpected nontype template argument kind in template rewrite"
) ? void (0) : __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"unexpected nontype template argument kind in template rewrite\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2113, __extension__
__PRETTY_FUNCTION__))
;
2114 QualType NewT = Arg.getAsType();
2115 assert(isa<TemplateTypeParmType>(NewT) &&(static_cast <bool> (isa<TemplateTypeParmType>(NewT
) && "type parm not rewritten to type parm") ? void (
0) : __assert_fail ("isa<TemplateTypeParmType>(NewT) && \"type parm not rewritten to type parm\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2116, __extension__
__PRETTY_FUNCTION__))
2116 "type parm not rewritten to type parm")(static_cast <bool> (isa<TemplateTypeParmType>(NewT
) && "type parm not rewritten to type parm") ? void (
0) : __assert_fail ("isa<TemplateTypeParmType>(NewT) && \"type parm not rewritten to type parm\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2116, __extension__
__PRETTY_FUNCTION__))
;
2117 auto NewTL = TLB.push<TemplateTypeParmTypeLoc>(NewT);
2118 NewTL.setNameLoc(TL.getNameLoc());
2119 return NewT;
2120 }
2121
2122 auto [AssociatedDecl, Final] =
2123 TemplateArgs.getAssociatedDecl(T->getDepth());
2124 std::optional<unsigned> PackIndex;
2125 if (T->isParameterPack()) {
2126 assert(Arg.getKind() == TemplateArgument::Pack &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2127, __extension__
__PRETTY_FUNCTION__))
2127 "Missing argument pack")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Pack && "Missing argument pack") ? void (0) : __assert_fail
("Arg.getKind() == TemplateArgument::Pack && \"Missing argument pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2127, __extension__
__PRETTY_FUNCTION__))
;
2128
2129 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2130 // We have the template argument pack, but we're not expanding the
2131 // enclosing pack expansion yet. Just save the template argument
2132 // pack for later substitution.
2133 QualType Result = getSema().Context.getSubstTemplateTypeParmPackType(
2134 AssociatedDecl, T->getIndex(), Final, Arg);
2135 SubstTemplateTypeParmPackTypeLoc NewTL
2136 = TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2137 NewTL.setNameLoc(TL.getNameLoc());
2138 return Result;
2139 }
2140
2141 // PackIndex starts from last element.
2142 PackIndex = getPackIndex(Arg);
2143 Arg = getPackSubstitutedTemplateArgument(getSema(), Arg);
2144 }
2145
2146 assert(Arg.getKind() == TemplateArgument::Type &&(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "Template argument kind mismatch") ? void (0)
: __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2147, __extension__
__PRETTY_FUNCTION__))
2147 "Template argument kind mismatch")(static_cast <bool> (Arg.getKind() == TemplateArgument::
Type && "Template argument kind mismatch") ? void (0)
: __assert_fail ("Arg.getKind() == TemplateArgument::Type && \"Template argument kind mismatch\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2147, __extension__
__PRETTY_FUNCTION__))
;
2148
2149 return BuildSubstTemplateTypeParmType(TLB, SuppressObjCLifetime, Final,
2150 AssociatedDecl, T->getIndex(),
2151 PackIndex, Arg, TL.getNameLoc());
2152 }
2153
2154 // The template type parameter comes from an inner template (e.g.,
2155 // the template parameter list of a member template inside the
2156 // template we are instantiating). Create a new template type
2157 // parameter with the template "level" reduced by one.
2158 TemplateTypeParmDecl *NewTTPDecl = nullptr;
2159 if (TemplateTypeParmDecl *OldTTPDecl = T->getDecl())
2160 NewTTPDecl = cast_or_null<TemplateTypeParmDecl>(
2161 TransformDecl(TL.getNameLoc(), OldTTPDecl));
2162 QualType Result = getSema().Context.getTemplateTypeParmType(
2163 T->getDepth() - TemplateArgs.getNumSubstitutedLevels(), T->getIndex(),
2164 T->isParameterPack(), NewTTPDecl);
2165 TemplateTypeParmTypeLoc NewTL = TLB.push<TemplateTypeParmTypeLoc>(Result);
2166 NewTL.setNameLoc(TL.getNameLoc());
2167 return Result;
2168}
2169
2170QualType TemplateInstantiator::TransformSubstTemplateTypeParmPackType(
2171 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL,
2172 bool SuppressObjCLifetime) {
2173 const SubstTemplateTypeParmPackType *T = TL.getTypePtr();
2174
2175 Decl *NewReplaced = TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
2176
2177 if (getSema().ArgumentPackSubstitutionIndex == -1) {
2178 // We aren't expanding the parameter pack, so just return ourselves.
2179 QualType Result = TL.getType();
2180 if (NewReplaced != T->getAssociatedDecl())
2181 Result = getSema().Context.getSubstTemplateTypeParmPackType(
2182 NewReplaced, T->getIndex(), T->getFinal(), T->getArgumentPack());
2183 SubstTemplateTypeParmPackTypeLoc NewTL =
2184 TLB.push<SubstTemplateTypeParmPackTypeLoc>(Result);
2185 NewTL.setNameLoc(TL.getNameLoc());
2186 return Result;
2187 }
2188
2189 TemplateArgument Pack = T->getArgumentPack();
2190 TemplateArgument Arg = getPackSubstitutedTemplateArgument(getSema(), Pack);
2191 return BuildSubstTemplateTypeParmType(
2192 TLB, SuppressObjCLifetime, T->getFinal(), NewReplaced, T->getIndex(),
2193 getPackIndex(Pack), Arg, TL.getNameLoc());
2194}
2195
2196template<typename EntityPrinter>
2197static concepts::Requirement::SubstitutionDiagnostic *
2198createSubstDiag(Sema &S, TemplateDeductionInfo &Info, EntityPrinter Printer) {
2199 SmallString<128> Message;
2200 SourceLocation ErrorLoc;
2201 if (Info.hasSFINAEDiagnostic()) {
2202 PartialDiagnosticAt PDA(SourceLocation(),
2203 PartialDiagnostic::NullDiagnostic{});
2204 Info.takeSFINAEDiagnostic(PDA);
2205 PDA.second.EmitToString(S.getDiagnostics(), Message);
2206 ErrorLoc = PDA.first;
2207 } else {
2208 ErrorLoc = Info.getLocation();
2209 }
2210 char *MessageBuf = new (S.Context) char[Message.size()];
2211 std::copy(Message.begin(), Message.end(), MessageBuf);
2212 SmallString<128> Entity;
2213 llvm::raw_svector_ostream OS(Entity);
2214 Printer(OS);
2215 char *EntityBuf = new (S.Context) char[Entity.size()];
2216 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2217 return new (S.Context) concepts::Requirement::SubstitutionDiagnostic{
2218 StringRef(EntityBuf, Entity.size()), ErrorLoc,
2219 StringRef(MessageBuf, Message.size())};
2220}
2221
2222ExprResult TemplateInstantiator::TransformRequiresTypeParams(
2223 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
2224 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
2225 SmallVectorImpl<QualType> &PTypes,
2226 SmallVectorImpl<ParmVarDecl *> &TransParams,
2227 Sema::ExtParameterInfoBuilder &PInfos) {
2228
2229 TemplateDeductionInfo Info(KWLoc);
2230 Sema::InstantiatingTemplate TypeInst(SemaRef, KWLoc,
2231 RE, Info,
2232 SourceRange{KWLoc, RBraceLoc});
2233 Sema::SFINAETrap Trap(SemaRef);
2234
2235 unsigned ErrorIdx;
2236 if (getDerived().TransformFunctionTypeParams(
2237 KWLoc, Params, /*ParamTypes=*/nullptr, /*ParamInfos=*/nullptr, PTypes,
2238 &TransParams, PInfos, &ErrorIdx) ||
2239 Trap.hasErrorOccurred()) {
2240 SmallVector<concepts::Requirement *, 4> TransReqs;
2241 ParmVarDecl *FailedDecl = Params[ErrorIdx];
2242 // Add a 'failed' Requirement to contain the error that caused the failure
2243 // here.
2244 TransReqs.push_back(RebuildTypeRequirement(createSubstDiag(
2245 SemaRef, Info, [&](llvm::raw_ostream &OS) { OS << *FailedDecl; })));
2246 return getDerived().RebuildRequiresExpr(KWLoc, Body, TransParams, TransReqs,
2247 RBraceLoc);
2248 }
2249
2250 return ExprResult{};
2251}
2252
2253concepts::TypeRequirement *
2254TemplateInstantiator::TransformTypeRequirement(concepts::TypeRequirement *Req) {
2255 if (!Req->isDependent() && !AlwaysRebuild())
2256 return Req;
2257 if (Req->isSubstitutionFailure()) {
2258 if (AlwaysRebuild())
2259 return RebuildTypeRequirement(
2260 Req->getSubstitutionDiagnostic());
2261 return Req;
2262 }
2263
2264 Sema::SFINAETrap Trap(SemaRef);
2265 TemplateDeductionInfo Info(Req->getType()->getTypeLoc().getBeginLoc());
2266 Sema::InstantiatingTemplate TypeInst(SemaRef,
2267 Req->getType()->getTypeLoc().getBeginLoc(), Req, Info,
2268 Req->getType()->getTypeLoc().getSourceRange());
2269 if (TypeInst.isInvalid())
2270 return nullptr;
2271 TypeSourceInfo *TransType = TransformType(Req->getType());
2272 if (!TransType || Trap.hasErrorOccurred())
2273 return RebuildTypeRequirement(createSubstDiag(SemaRef, Info,
2274 [&] (llvm::raw_ostream& OS) {
2275 Req->getType()->getType().print(OS, SemaRef.getPrintingPolicy());
2276 }));
2277 return RebuildTypeRequirement(TransType);
2278}
2279
2280concepts::ExprRequirement *
2281TemplateInstantiator::TransformExprRequirement(concepts::ExprRequirement *Req) {
2282 if (!Req->isDependent() && !AlwaysRebuild())
2283 return Req;
2284
2285 Sema::SFINAETrap Trap(SemaRef);
2286
2287 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *>
2288 TransExpr;
2289 if (Req->isExprSubstitutionFailure())
2290 TransExpr = Req->getExprSubstitutionDiagnostic();
2291 else {
2292 Expr *E = Req->getExpr();
2293 TemplateDeductionInfo Info(E->getBeginLoc());
2294 Sema::InstantiatingTemplate ExprInst(SemaRef, E->getBeginLoc(), Req, Info,
2295 E->getSourceRange());
2296 if (ExprInst.isInvalid())
2297 return nullptr;
2298 ExprResult TransExprRes = TransformExpr(E);
2299 if (!TransExprRes.isInvalid() && !Trap.hasErrorOccurred() &&
2300 TransExprRes.get()->hasPlaceholderType())
2301 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
2302 if (TransExprRes.isInvalid() || Trap.hasErrorOccurred())
2303 TransExpr = createSubstDiag(SemaRef, Info, [&](llvm::raw_ostream &OS) {
2304 E->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2305 });
2306 else
2307 TransExpr = TransExprRes.get();
2308 }
2309
2310 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
2311 const auto &RetReq = Req->getReturnTypeRequirement();
2312 if (RetReq.isEmpty())
2313 TransRetReq.emplace();
2314 else if (RetReq.isSubstitutionFailure())
2315 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
2316 else if (RetReq.isTypeConstraint()) {
2317 TemplateParameterList *OrigTPL =
2318 RetReq.getTypeConstraintTemplateParameterList();
2319 TemplateDeductionInfo Info(OrigTPL->getTemplateLoc());
2320 Sema::InstantiatingTemplate TPLInst(SemaRef, OrigTPL->getTemplateLoc(),
2321 Req, Info, OrigTPL->getSourceRange());
2322 if (TPLInst.isInvalid())
2323 return nullptr;
2324 TemplateParameterList *TPL = TransformTemplateParameterList(OrigTPL);
2325 if (!TPL)
2326 TransRetReq.emplace(createSubstDiag(SemaRef, Info,
2327 [&] (llvm::raw_ostream& OS) {
2328 RetReq.getTypeConstraint()->getImmediatelyDeclaredConstraint()
2329 ->printPretty(OS, nullptr, SemaRef.getPrintingPolicy());
2330 }));
2331 else {
2332 TPLInst.Clear();
2333 TransRetReq.emplace(TPL);
2334 }
2335 }
2336 assert(TransRetReq && "All code paths leading here must set TransRetReq")(static_cast <bool> (TransRetReq && "All code paths leading here must set TransRetReq"
) ? void (0) : __assert_fail ("TransRetReq && \"All code paths leading here must set TransRetReq\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2336, __extension__
__PRETTY_FUNCTION__))
;
2337 if (Expr *E = TransExpr.dyn_cast<Expr *>())
2338 return RebuildExprRequirement(E, Req->isSimple(), Req->getNoexceptLoc(),
2339 std::move(*TransRetReq));
2340 return RebuildExprRequirement(
2341 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
2342 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
2343}
2344
2345concepts::NestedRequirement *
2346TemplateInstantiator::TransformNestedRequirement(
2347 concepts::NestedRequirement *Req) {
2348 if (!Req->isDependent() && !AlwaysRebuild())
2349 return Req;
2350 if (Req->hasInvalidConstraint()) {
2351 if (AlwaysRebuild())
2352 return RebuildNestedRequirement(Req->getInvalidConstraintEntity(),
2353 Req->getConstraintSatisfaction());
2354 return Req;
2355 }
2356 Sema::InstantiatingTemplate ReqInst(SemaRef,
2357 Req->getConstraintExpr()->getBeginLoc(), Req,
2358 Sema::InstantiatingTemplate::ConstraintsCheck{},
2359 Req->getConstraintExpr()->getSourceRange());
2360
2361 ExprResult TransConstraint;
2362 ConstraintSatisfaction Satisfaction;
2363 TemplateDeductionInfo Info(Req->getConstraintExpr()->getBeginLoc());
2364 {
2365 EnterExpressionEvaluationContext ContextRAII(
2366 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
2367 Sema::SFINAETrap Trap(SemaRef);
2368 Sema::InstantiatingTemplate ConstrInst(SemaRef,
2369 Req->getConstraintExpr()->getBeginLoc(), Req, Info,
2370 Req->getConstraintExpr()->getSourceRange());
2371 if (ConstrInst.isInvalid())
2372 return nullptr;
2373 llvm::SmallVector<Expr *> Result;
2374 if (!SemaRef.CheckConstraintSatisfaction(
2375 nullptr, {Req->getConstraintExpr()}, Result, TemplateArgs,
2376 Req->getConstraintExpr()->getSourceRange(), Satisfaction) &&
2377 !Result.empty())
2378 TransConstraint = Result[0];
2379 assert(!Trap.hasErrorOccurred() && "Substitution failures must be handled "(static_cast <bool> (!Trap.hasErrorOccurred() &&
"Substitution failures must be handled " "by CheckConstraintSatisfaction."
) ? void (0) : __assert_fail ("!Trap.hasErrorOccurred() && \"Substitution failures must be handled \" \"by CheckConstraintSatisfaction.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2380, __extension__
__PRETTY_FUNCTION__))
2380 "by CheckConstraintSatisfaction.")(static_cast <bool> (!Trap.hasErrorOccurred() &&
"Substitution failures must be handled " "by CheckConstraintSatisfaction."
) ? void (0) : __assert_fail ("!Trap.hasErrorOccurred() && \"Substitution failures must be handled \" \"by CheckConstraintSatisfaction.\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2380, __extension__
__PRETTY_FUNCTION__))
;
2381 }
2382 if (TransConstraint.isUsable() &&
2383 TransConstraint.get()->isInstantiationDependent())
2384 return new (SemaRef.Context)
2385 concepts::NestedRequirement(TransConstraint.get());
2386 if (TransConstraint.isInvalid() || !TransConstraint.get() ||
2387 Satisfaction.HasSubstitutionFailure()) {
2388 SmallString<128> Entity;
2389 llvm::raw_svector_ostream OS(Entity);
2390 Req->getConstraintExpr()->printPretty(OS, nullptr,
2391 SemaRef.getPrintingPolicy());
2392 char *EntityBuf = new (SemaRef.Context) char[Entity.size()];
2393 std::copy(Entity.begin(), Entity.end(), EntityBuf);
2394 return new (SemaRef.Context) concepts::NestedRequirement(
2395 SemaRef.Context, StringRef(EntityBuf, Entity.size()), Satisfaction);
2396 }
2397 return new (SemaRef.Context) concepts::NestedRequirement(
2398 SemaRef.Context, TransConstraint.get(), Satisfaction);
2399}
2400
2401
2402/// Perform substitution on the type T with a given set of template
2403/// arguments.
2404///
2405/// This routine substitutes the given template arguments into the
2406/// type T and produces the instantiated type.
2407///
2408/// \param T the type into which the template arguments will be
2409/// substituted. If this type is not dependent, it will be returned
2410/// immediately.
2411///
2412/// \param Args the template arguments that will be
2413/// substituted for the top-level template parameters within T.
2414///
2415/// \param Loc the location in the source code where this substitution
2416/// is being performed. It will typically be the location of the
2417/// declarator (if we're instantiating the type of some declaration)
2418/// or the location of the type in the source code (if, e.g., we're
2419/// instantiating the type of a cast expression).
2420///
2421/// \param Entity the name of the entity associated with a declaration
2422/// being instantiated (if any). May be empty to indicate that there
2423/// is no such entity (if, e.g., this is a type that occurs as part of
2424/// a cast expression) or that the entity has no name (e.g., an
2425/// unnamed function parameter).
2426///
2427/// \param AllowDeducedTST Whether a DeducedTemplateSpecializationType is
2428/// acceptable as the top level type of the result.
2429///
2430/// \returns If the instantiation succeeds, the instantiated
2431/// type. Otherwise, produces diagnostics and returns a NULL type.
2432TypeSourceInfo *Sema::SubstType(TypeSourceInfo *T,
2433 const MultiLevelTemplateArgumentList &Args,
2434 SourceLocation Loc,
2435 DeclarationName Entity,
2436 bool AllowDeducedTST) {
2437 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
2438 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
2439 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2439, __extension__
__PRETTY_FUNCTION__))
;
2440
2441 if (!T->getType()->isInstantiationDependentType() &&
2442 !T->getType()->isVariablyModifiedType())
2443 return T;
2444
2445 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2446 return AllowDeducedTST ? Instantiator.TransformTypeWithDeducedTST(T)
2447 : Instantiator.TransformType(T);
2448}
2449
2450TypeSourceInfo *Sema::SubstType(TypeLoc TL,
2451 const MultiLevelTemplateArgumentList &Args,
2452 SourceLocation Loc,
2453 DeclarationName Entity) {
2454 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2456, __extension__
__PRETTY_FUNCTION__))
2455 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2456, __extension__
__PRETTY_FUNCTION__))
2456 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2456, __extension__
__PRETTY_FUNCTION__))
;
2457
2458 if (TL.getType().isNull())
2459 return nullptr;
2460
2461 if (!TL.getType()->isInstantiationDependentType() &&
2462 !TL.getType()->isVariablyModifiedType()) {
2463 // FIXME: Make a copy of the TypeLoc data here, so that we can
2464 // return a new TypeSourceInfo. Inefficient!
2465 TypeLocBuilder TLB;
2466 TLB.pushFullCopy(TL);
2467 return TLB.getTypeSourceInfo(Context, TL.getType());
2468 }
2469
2470 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2471 TypeLocBuilder TLB;
2472 TLB.reserve(TL.getFullDataSize());
2473 QualType Result = Instantiator.TransformType(TLB, TL);
2474 if (Result.isNull())
2475 return nullptr;
2476
2477 return TLB.getTypeSourceInfo(Context, Result);
2478}
2479
2480/// Deprecated form of the above.
2481QualType Sema::SubstType(QualType T,
2482 const MultiLevelTemplateArgumentList &TemplateArgs,
2483 SourceLocation Loc, DeclarationName Entity) {
2484 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2486, __extension__
__PRETTY_FUNCTION__))
2485 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2486, __extension__
__PRETTY_FUNCTION__))
2486 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2486, __extension__
__PRETTY_FUNCTION__))
;
2487
2488 // If T is not a dependent type or a variably-modified type, there
2489 // is nothing to do.
2490 if (!T->isInstantiationDependentType() && !T->isVariablyModifiedType())
2491 return T;
2492
2493 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc, Entity);
2494 return Instantiator.TransformType(T);
2495}
2496
2497static bool NeedsInstantiationAsFunctionType(TypeSourceInfo *T) {
2498 if (T->getType()->isInstantiationDependentType() ||
2499 T->getType()->isVariablyModifiedType())
2500 return true;
2501
2502 TypeLoc TL = T->getTypeLoc().IgnoreParens();
2503 if (!TL.getAs<FunctionProtoTypeLoc>())
2504 return false;
2505
2506 FunctionProtoTypeLoc FP = TL.castAs<FunctionProtoTypeLoc>();
2507 for (ParmVarDecl *P : FP.getParams()) {
2508 // This must be synthesized from a typedef.
2509 if (!P) continue;
2510
2511 // If there are any parameters, a new TypeSourceInfo that refers to the
2512 // instantiated parameters must be built.
2513 return true;
2514 }
2515
2516 return false;
2517}
2518
2519/// A form of SubstType intended specifically for instantiating the
2520/// type of a FunctionDecl. Its purpose is solely to force the
2521/// instantiation of default-argument expressions and to avoid
2522/// instantiating an exception-specification.
2523TypeSourceInfo *Sema::SubstFunctionDeclType(TypeSourceInfo *T,
2524 const MultiLevelTemplateArgumentList &Args,
2525 SourceLocation Loc,
2526 DeclarationName Entity,
2527 CXXRecordDecl *ThisContext,
2528 Qualifiers ThisTypeQuals,
2529 bool EvaluateConstraints) {
2530 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2532, __extension__
__PRETTY_FUNCTION__))
2531 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2532, __extension__
__PRETTY_FUNCTION__))
2532 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2532, __extension__
__PRETTY_FUNCTION__))
;
2533
2534 if (!NeedsInstantiationAsFunctionType(T))
2535 return T;
2536
2537 TemplateInstantiator Instantiator(*this, Args, Loc, Entity);
2538 Instantiator.setEvaluateConstraints(EvaluateConstraints);
2539
2540 TypeLocBuilder TLB;
2541
2542 TypeLoc TL = T->getTypeLoc();
2543 TLB.reserve(TL.getFullDataSize());
2544
2545 QualType Result;
2546
2547 if (FunctionProtoTypeLoc Proto =
2548 TL.IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
2549 // Instantiate the type, other than its exception specification. The
2550 // exception specification is instantiated in InitFunctionInstantiation
2551 // once we've built the FunctionDecl.
2552 // FIXME: Set the exception specification to EST_Uninstantiated here,
2553 // instead of rebuilding the function type again later.
2554 Result = Instantiator.TransformFunctionProtoType(
2555 TLB, Proto, ThisContext, ThisTypeQuals,
2556 [](FunctionProtoType::ExceptionSpecInfo &ESI,
2557 bool &Changed) { return false; });
2558 } else {
2559 Result = Instantiator.TransformType(TLB, TL);
2560 }
2561 if (Result.isNull())
2562 return nullptr;
2563
2564 return TLB.getTypeSourceInfo(Context, Result);
2565}
2566
2567bool Sema::SubstExceptionSpec(SourceLocation Loc,
2568 FunctionProtoType::ExceptionSpecInfo &ESI,
2569 SmallVectorImpl<QualType> &ExceptionStorage,
2570 const MultiLevelTemplateArgumentList &Args) {
2571 assert(ESI.Type != EST_Uninstantiated)(static_cast <bool> (ESI.Type != EST_Uninstantiated) ? void
(0) : __assert_fail ("ESI.Type != EST_Uninstantiated", "clang/lib/Sema/SemaTemplateInstantiate.cpp"
, 2571, __extension__ __PRETTY_FUNCTION__))
;
2572
2573 bool Changed = false;
2574 TemplateInstantiator Instantiator(*this, Args, Loc, DeclarationName());
2575 return Instantiator.TransformExceptionSpec(Loc, ESI, ExceptionStorage,
2576 Changed);
2577}
2578
2579void Sema::SubstExceptionSpec(FunctionDecl *New, const FunctionProtoType *Proto,
2580 const MultiLevelTemplateArgumentList &Args) {
2581 FunctionProtoType::ExceptionSpecInfo ESI =
2582 Proto->getExtProtoInfo().ExceptionSpec;
2583
2584 SmallVector<QualType, 4> ExceptionStorage;
2585 if (SubstExceptionSpec(New->getTypeSourceInfo()->getTypeLoc().getEndLoc(),
2586 ESI, ExceptionStorage, Args))
2587 // On error, recover by dropping the exception specification.
2588 ESI.Type = EST_None;
2589
2590 UpdateExceptionSpec(New, ESI);
2591}
2592
2593namespace {
2594
2595 struct GetContainedInventedTypeParmVisitor :
2596 public TypeVisitor<GetContainedInventedTypeParmVisitor,
2597 TemplateTypeParmDecl *> {
2598 using TypeVisitor<GetContainedInventedTypeParmVisitor,
2599 TemplateTypeParmDecl *>::Visit;
2600
2601 TemplateTypeParmDecl *Visit(QualType T) {
2602 if (T.isNull())
2603 return nullptr;
2604 return Visit(T.getTypePtr());
2605 }
2606 // The deduced type itself.
2607 TemplateTypeParmDecl *VisitTemplateTypeParmType(
2608 const TemplateTypeParmType *T) {
2609 if (!T->getDecl() || !T->getDecl()->isImplicit())
2610 return nullptr;
2611 return T->getDecl();
2612 }
2613
2614 // Only these types can contain 'auto' types, and subsequently be replaced
2615 // by references to invented parameters.
2616
2617 TemplateTypeParmDecl *VisitElaboratedType(const ElaboratedType *T) {
2618 return Visit(T->getNamedType());
2619 }
2620
2621 TemplateTypeParmDecl *VisitPointerType(const PointerType *T) {
2622 return Visit(T->getPointeeType());
2623 }
2624
2625 TemplateTypeParmDecl *VisitBlockPointerType(const BlockPointerType *T) {
2626 return Visit(T->getPointeeType());
2627 }
2628
2629 TemplateTypeParmDecl *VisitReferenceType(const ReferenceType *T) {
2630 return Visit(T->getPointeeTypeAsWritten());
2631 }
2632
2633 TemplateTypeParmDecl *VisitMemberPointerType(const MemberPointerType *T) {
2634 return Visit(T->getPointeeType());
2635 }
2636
2637 TemplateTypeParmDecl *VisitArrayType(const ArrayType *T) {
2638 return Visit(T->getElementType());
2639 }
2640
2641 TemplateTypeParmDecl *VisitDependentSizedExtVectorType(
2642 const DependentSizedExtVectorType *T) {
2643 return Visit(T->getElementType());
2644 }
2645
2646 TemplateTypeParmDecl *VisitVectorType(const VectorType *T) {
2647 return Visit(T->getElementType());
2648 }
2649
2650 TemplateTypeParmDecl *VisitFunctionProtoType(const FunctionProtoType *T) {
2651 return VisitFunctionType(T);
2652 }
2653
2654 TemplateTypeParmDecl *VisitFunctionType(const FunctionType *T) {
2655 return Visit(T->getReturnType());
2656 }
2657
2658 TemplateTypeParmDecl *VisitParenType(const ParenType *T) {
2659 return Visit(T->getInnerType());
2660 }
2661
2662 TemplateTypeParmDecl *VisitAttributedType(const AttributedType *T) {
2663 return Visit(T->getModifiedType());
2664 }
2665
2666 TemplateTypeParmDecl *VisitMacroQualifiedType(const MacroQualifiedType *T) {
2667 return Visit(T->getUnderlyingType());
2668 }
2669
2670 TemplateTypeParmDecl *VisitAdjustedType(const AdjustedType *T) {
2671 return Visit(T->getOriginalType());
2672 }
2673
2674 TemplateTypeParmDecl *VisitPackExpansionType(const PackExpansionType *T) {
2675 return Visit(T->getPattern());
2676 }
2677 };
2678
2679} // namespace
2680
2681bool Sema::SubstTypeConstraint(
2682 TemplateTypeParmDecl *Inst, const TypeConstraint *TC,
2683 const MultiLevelTemplateArgumentList &TemplateArgs,
2684 bool EvaluateConstraints) {
2685 const ASTTemplateArgumentListInfo *TemplArgInfo =
2686 TC->getTemplateArgsAsWritten();
2687
2688 if (!EvaluateConstraints) {
2689 Inst->setTypeConstraint(TC->getNestedNameSpecifierLoc(),
2690 TC->getConceptNameInfo(), TC->getNamedConcept(),
2691 TC->getNamedConcept(), TemplArgInfo,
2692 TC->getImmediatelyDeclaredConstraint());
2693 return false;
2694 }
2695
2696 TemplateArgumentListInfo InstArgs;
2697
2698 if (TemplArgInfo) {
2699 InstArgs.setLAngleLoc(TemplArgInfo->LAngleLoc);
2700 InstArgs.setRAngleLoc(TemplArgInfo->RAngleLoc);
2701 if (SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
2702 InstArgs))
2703 return true;
2704 }
2705 return AttachTypeConstraint(
2706 TC->getNestedNameSpecifierLoc(), TC->getConceptNameInfo(),
2707 TC->getNamedConcept(), &InstArgs, Inst,
2708 Inst->isParameterPack()
2709 ? cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2710 ->getEllipsisLoc()
2711 : SourceLocation());
2712}
2713
2714ParmVarDecl *Sema::SubstParmVarDecl(
2715 ParmVarDecl *OldParm, const MultiLevelTemplateArgumentList &TemplateArgs,
2716 int indexAdjustment, std::optional<unsigned> NumExpansions,
2717 bool ExpectParameterPack, bool EvaluateConstraint) {
2718 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
2719 TypeSourceInfo *NewDI = nullptr;
2720
2721 TypeLoc OldTL = OldDI->getTypeLoc();
2722 if (PackExpansionTypeLoc ExpansionTL = OldTL.getAs<PackExpansionTypeLoc>()) {
2723
2724 // We have a function parameter pack. Substitute into the pattern of the
2725 // expansion.
2726 NewDI = SubstType(ExpansionTL.getPatternLoc(), TemplateArgs,
2727 OldParm->getLocation(), OldParm->getDeclName());
2728 if (!NewDI)
2729 return nullptr;
2730
2731 if (NewDI->getType()->containsUnexpandedParameterPack()) {
2732 // We still have unexpanded parameter packs, which means that
2733 // our function parameter is still a function parameter pack.
2734 // Therefore, make its type a pack expansion type.
2735 NewDI = CheckPackExpansion(NewDI, ExpansionTL.getEllipsisLoc(),
2736 NumExpansions);
2737 } else if (ExpectParameterPack) {
2738 // We expected to get a parameter pack but didn't (because the type
2739 // itself is not a pack expansion type), so complain. This can occur when
2740 // the substitution goes through an alias template that "loses" the
2741 // pack expansion.
2742 Diag(OldParm->getLocation(),
2743 diag::err_function_parameter_pack_without_parameter_packs)
2744 << NewDI->getType();
2745 return nullptr;
2746 }
2747 } else {
2748 NewDI = SubstType(OldDI, TemplateArgs, OldParm->getLocation(),
2749 OldParm->getDeclName());
2750 }
2751
2752 if (!NewDI)
2753 return nullptr;
2754
2755 if (NewDI->getType()->isVoidType()) {
2756 Diag(OldParm->getLocation(), diag::err_param_with_void_type);
2757 return nullptr;
2758 }
2759
2760 // In abbreviated templates, TemplateTypeParmDecls with possible
2761 // TypeConstraints are created when the parameter list is originally parsed.
2762 // The TypeConstraints can therefore reference other functions parameters in
2763 // the abbreviated function template, which is why we must instantiate them
2764 // here, when the instantiated versions of those referenced parameters are in
2765 // scope.
2766 if (TemplateTypeParmDecl *TTP =
2767 GetContainedInventedTypeParmVisitor().Visit(OldDI->getType())) {
2768 if (const TypeConstraint *TC = TTP->getTypeConstraint()) {
2769 auto *Inst = cast_or_null<TemplateTypeParmDecl>(
2770 FindInstantiatedDecl(TTP->getLocation(), TTP, TemplateArgs));
2771 // We will first get here when instantiating the abbreviated function
2772 // template's described function, but we might also get here later.
2773 // Make sure we do not instantiate the TypeConstraint more than once.
2774 if (Inst && !Inst->getTypeConstraint()) {
2775 if (SubstTypeConstraint(Inst, TC, TemplateArgs, EvaluateConstraint))
2776 return nullptr;
2777 }
2778 }
2779 }
2780
2781 ParmVarDecl *NewParm = CheckParameter(Context.getTranslationUnitDecl(),
2782 OldParm->getInnerLocStart(),
2783 OldParm->getLocation(),
2784 OldParm->getIdentifier(),
2785 NewDI->getType(), NewDI,
2786 OldParm->getStorageClass());
2787 if (!NewParm)
2788 return nullptr;
2789
2790 // Mark the (new) default argument as uninstantiated (if any).
2791 if (OldParm->hasUninstantiatedDefaultArg()) {
2792 Expr *Arg = OldParm->getUninstantiatedDefaultArg();
2793 NewParm->setUninstantiatedDefaultArg(Arg);
2794 } else if (OldParm->hasUnparsedDefaultArg()) {
2795 NewParm->setUnparsedDefaultArg();
2796 UnparsedDefaultArgInstantiations[OldParm].push_back(NewParm);
2797 } else if (Expr *Arg = OldParm->getDefaultArg()) {
2798 // Default arguments cannot be substituted until the declaration context
2799 // for the associated function or lambda capture class is available.
2800 // This is necessary for cases like the following where construction of
2801 // the lambda capture class for the outer lambda is dependent on the
2802 // parameter types but where the default argument is dependent on the
2803 // outer lambda's declaration context.
2804 // template <typename T>
2805 // auto f() {
2806 // return [](T = []{ return T{}; }()) { return 0; };
2807 // }
2808 NewParm->setUninstantiatedDefaultArg(Arg);
2809 }
2810
2811 NewParm->setHasInheritedDefaultArg(OldParm->hasInheritedDefaultArg());
2812
2813 if (OldParm->isParameterPack() && !NewParm->isParameterPack()) {
2814 // Add the new parameter to the instantiated parameter pack.
2815 CurrentInstantiationScope->InstantiatedLocalPackArg(OldParm, NewParm);
2816 } else {
2817 // Introduce an Old -> New mapping
2818 CurrentInstantiationScope->InstantiatedLocal(OldParm, NewParm);
2819 }
2820
2821 // FIXME: OldParm may come from a FunctionProtoType, in which case CurContext
2822 // can be anything, is this right ?
2823 NewParm->setDeclContext(CurContext);
2824
2825 NewParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
2826 OldParm->getFunctionScopeIndex() + indexAdjustment);
2827
2828 InstantiateAttrs(TemplateArgs, OldParm, NewParm);
2829
2830 return NewParm;
2831}
2832
2833/// Substitute the given template arguments into the given set of
2834/// parameters, producing the set of parameter types that would be generated
2835/// from such a substitution.
2836bool Sema::SubstParmTypes(
2837 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
2838 const FunctionProtoType::ExtParameterInfo *ExtParamInfos,
2839 const MultiLevelTemplateArgumentList &TemplateArgs,
2840 SmallVectorImpl<QualType> &ParamTypes,
2841 SmallVectorImpl<ParmVarDecl *> *OutParams,
2842 ExtParameterInfoBuilder &ParamInfos) {
2843 assert(!CodeSynthesisContexts.empty() &&(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2845, __extension__
__PRETTY_FUNCTION__))
2844 "Cannot perform an instantiation without some context on the "(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2845, __extension__
__PRETTY_FUNCTION__))
2845 "instantiation stack")(static_cast <bool> (!CodeSynthesisContexts.empty() &&
"Cannot perform an instantiation without some context on the "
"instantiation stack") ? void (0) : __assert_fail ("!CodeSynthesisContexts.empty() && \"Cannot perform an instantiation without some context on the \" \"instantiation stack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 2845, __extension__
__PRETTY_FUNCTION__))
;
2846
2847 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
2848 DeclarationName());
2849 return Instantiator.TransformFunctionTypeParams(
2850 Loc, Params, nullptr, ExtParamInfos, ParamTypes, OutParams, ParamInfos);
2851}
2852
2853/// Substitute the given template arguments into the default argument.
2854bool Sema::SubstDefaultArgument(
2855 SourceLocation Loc,
2856 ParmVarDecl *Param,
2857 const MultiLevelTemplateArgumentList &TemplateArgs,
2858 bool ForCallExpr) {
2859 FunctionDecl *FD = cast<FunctionDecl>(Param->getDeclContext());
2860 Expr *PatternExpr = Param->getUninstantiatedDefaultArg();
2861
2862 EnterExpressionEvaluationContext EvalContext(
2863 *this, ExpressionEvaluationContext::PotentiallyEvaluated, Param);
2864
2865 InstantiatingTemplate Inst(*this, Loc, Param, TemplateArgs.getInnermost());
2866 if (Inst.isInvalid())
2867 return true;
2868 if (Inst.isAlreadyInstantiating()) {
2869 Diag(Param->getBeginLoc(), diag::err_recursive_default_argument) << FD;
2870 Param->setInvalidDecl();
2871 return true;
2872 }
2873
2874 ExprResult Result;
2875 {
2876 // C++ [dcl.fct.default]p5:
2877 // The names in the [default argument] expression are bound, and
2878 // the semantic constraints are checked, at the point where the
2879 // default argument expression appears.
2880 ContextRAII SavedContext(*this, FD);
2881 std::unique_ptr<LocalInstantiationScope> LIS;
2882
2883 if (ForCallExpr) {
2884 // When instantiating a default argument due to use in a call expression,
2885 // an instantiation scope that includes the parameters of the callee is
2886 // required to satisfy references from the default argument. For example:
2887 // template<typename T> void f(T a, int = decltype(a)());
2888 // void g() { f(0); }
2889 LIS = std::make_unique<LocalInstantiationScope>(*this);
2890 FunctionDecl *PatternFD = FD->getTemplateInstantiationPattern(
2891 /*ForDefinition*/ false);
2892 if (addInstantiatedParametersToScope(FD, PatternFD, *LIS, TemplateArgs))
2893 return true;
2894 }
2895
2896 runWithSufficientStackSpace(Loc, [&] {
2897 Result = SubstInitializer(PatternExpr, TemplateArgs,
2898 /*DirectInit*/false);
2899 });
2900 }
2901 if (Result.isInvalid())
2902 return true;
2903
2904 if (ForCallExpr) {
2905 // Check the expression as an initializer for the parameter.
2906 InitializedEntity Entity
2907 = InitializedEntity::InitializeParameter(Context, Param);
2908 InitializationKind Kind = InitializationKind::CreateCopy(
2909 Param->getLocation(),
2910 /*FIXME:EqualLoc*/ PatternExpr->getBeginLoc());
2911 Expr *ResultE = Result.getAs<Expr>();
2912
2913 InitializationSequence InitSeq(*this, Entity, Kind, ResultE);
2914 Result = InitSeq.Perform(*this, Entity, Kind, ResultE);
2915 if (Result.isInvalid())
2916 return true;
2917
2918 Result =
2919 ActOnFinishFullExpr(Result.getAs<Expr>(), Param->getOuterLocStart(),
2920 /*DiscardedValue*/ false);
2921 } else {
2922 // FIXME: Obtain the source location for the '=' token.
2923 SourceLocation EqualLoc = PatternExpr->getBeginLoc();
2924 Result = ConvertParamDefaultArgument(Param, Result.getAs<Expr>(), EqualLoc);
2925 }
2926 if (Result.isInvalid())
2927 return true;
2928
2929 // Remember the instantiated default argument.
2930 Param->setDefaultArg(Result.getAs<Expr>());
2931
2932 return false;
2933}
2934
2935/// Perform substitution on the base class specifiers of the
2936/// given class template specialization.
2937///
2938/// Produces a diagnostic and returns true on error, returns false and
2939/// attaches the instantiated base classes to the class template
2940/// specialization if successful.
2941bool
2942Sema::SubstBaseSpecifiers(CXXRecordDecl *Instantiation,
2943 CXXRecordDecl *Pattern,
2944 const MultiLevelTemplateArgumentList &TemplateArgs) {
2945 bool Invalid = false;
2946 SmallVector<CXXBaseSpecifier*, 4> InstantiatedBases;
2947 for (const auto &Base : Pattern->bases()) {
2948 if (!Base.getType()->isDependentType()) {
2949 if (const CXXRecordDecl *RD = Base.getType()->getAsCXXRecordDecl()) {
2950 if (RD->isInvalidDecl())
2951 Instantiation->setInvalidDecl();
2952 }
2953 InstantiatedBases.push_back(new (Context) CXXBaseSpecifier(Base));
2954 continue;
2955 }
2956
2957 SourceLocation EllipsisLoc;
2958 TypeSourceInfo *BaseTypeLoc;
2959 if (Base.isPackExpansion()) {
2960 // This is a pack expansion. See whether we should expand it now, or
2961 // wait until later.
2962 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2963 collectUnexpandedParameterPacks(Base.getTypeSourceInfo()->getTypeLoc(),
2964 Unexpanded);
2965 bool ShouldExpand = false;
2966 bool RetainExpansion = false;
2967 std::optional<unsigned> NumExpansions;
2968 if (CheckParameterPacksForExpansion(Base.getEllipsisLoc(),
2969 Base.getSourceRange(),
2970 Unexpanded,
2971 TemplateArgs, ShouldExpand,
2972 RetainExpansion,
2973 NumExpansions)) {
2974 Invalid = true;
2975 continue;
2976 }
2977
2978 // If we should expand this pack expansion now, do so.
2979 if (ShouldExpand) {
2980 for (unsigned I = 0; I != *NumExpansions; ++I) {
2981 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
2982
2983 TypeSourceInfo *BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
2984 TemplateArgs,
2985 Base.getSourceRange().getBegin(),
2986 DeclarationName());
2987 if (!BaseTypeLoc) {
2988 Invalid = true;
2989 continue;
2990 }
2991
2992 if (CXXBaseSpecifier *InstantiatedBase
2993 = CheckBaseSpecifier(Instantiation,
2994 Base.getSourceRange(),
2995 Base.isVirtual(),
2996 Base.getAccessSpecifierAsWritten(),
2997 BaseTypeLoc,
2998 SourceLocation()))
2999 InstantiatedBases.push_back(InstantiatedBase);
3000 else
3001 Invalid = true;
3002 }
3003
3004 continue;
3005 }
3006
3007 // The resulting base specifier will (still) be a pack expansion.
3008 EllipsisLoc = Base.getEllipsisLoc();
3009 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, -1);
3010 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3011 TemplateArgs,
3012 Base.getSourceRange().getBegin(),
3013 DeclarationName());
3014 } else {
3015 BaseTypeLoc = SubstType(Base.getTypeSourceInfo(),
3016 TemplateArgs,
3017 Base.getSourceRange().getBegin(),
3018 DeclarationName());
3019 }
3020
3021 if (!BaseTypeLoc) {
3022 Invalid = true;
3023 continue;
3024 }
3025
3026 if (CXXBaseSpecifier *InstantiatedBase
3027 = CheckBaseSpecifier(Instantiation,
3028 Base.getSourceRange(),
3029 Base.isVirtual(),
3030 Base.getAccessSpecifierAsWritten(),
3031 BaseTypeLoc,
3032 EllipsisLoc))
3033 InstantiatedBases.push_back(InstantiatedBase);
3034 else
3035 Invalid = true;
3036 }
3037
3038 if (!Invalid && AttachBaseSpecifiers(Instantiation, InstantiatedBases))
3039 Invalid = true;
3040
3041 return Invalid;
3042}
3043
3044// Defined via #include from SemaTemplateInstantiateDecl.cpp
3045namespace clang {
3046 namespace sema {
3047 Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, Sema &S,
3048 const MultiLevelTemplateArgumentList &TemplateArgs);
3049 Attr *instantiateTemplateAttributeForDecl(
3050 const Attr *At, ASTContext &C, Sema &S,
3051 const MultiLevelTemplateArgumentList &TemplateArgs);
3052 }
3053}
3054
3055/// Instantiate the definition of a class from a given pattern.
3056///
3057/// \param PointOfInstantiation The point of instantiation within the
3058/// source code.
3059///
3060/// \param Instantiation is the declaration whose definition is being
3061/// instantiated. This will be either a class template specialization
3062/// or a member class of a class template specialization.
3063///
3064/// \param Pattern is the pattern from which the instantiation
3065/// occurs. This will be either the declaration of a class template or
3066/// the declaration of a member class of a class template.
3067///
3068/// \param TemplateArgs The template arguments to be substituted into
3069/// the pattern.
3070///
3071/// \param TSK the kind of implicit or explicit instantiation to perform.
3072///
3073/// \param Complain whether to complain if the class cannot be instantiated due
3074/// to the lack of a definition.
3075///
3076/// \returns true if an error occurred, false otherwise.
3077bool
3078Sema::InstantiateClass(SourceLocation PointOfInstantiation,
3079 CXXRecordDecl *Instantiation, CXXRecordDecl *Pattern,
3080 const MultiLevelTemplateArgumentList &TemplateArgs,
3081 TemplateSpecializationKind TSK,
3082 bool Complain) {
3083 CXXRecordDecl *PatternDef
3084 = cast_or_null<CXXRecordDecl>(Pattern->getDefinition());
3085 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3086 Instantiation->getInstantiatedFromMemberClass(),
3087 Pattern, PatternDef, TSK, Complain))
3088 return true;
3089
3090 llvm::TimeTraceScope TimeScope("InstantiateClass", [&]() {
3091 std::string Name;
3092 llvm::raw_string_ostream OS(Name);
3093 Instantiation->getNameForDiagnostic(OS, getPrintingPolicy(),
3094 /*Qualified=*/true);
3095 return Name;
3096 });
3097
3098 Pattern = PatternDef;
3099
3100 // Record the point of instantiation.
3101 if (MemberSpecializationInfo *MSInfo
3102 = Instantiation->getMemberSpecializationInfo()) {
3103 MSInfo->setTemplateSpecializationKind(TSK);
3104 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3105 } else if (ClassTemplateSpecializationDecl *Spec
3106 = dyn_cast<ClassTemplateSpecializationDecl>(Instantiation)) {
3107 Spec->setTemplateSpecializationKind(TSK);
3108 Spec->setPointOfInstantiation(PointOfInstantiation);
3109 }
3110
3111 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3112 if (Inst.isInvalid())
3113 return true;
3114 assert(!Inst.isAlreadyInstantiating() && "should have been caught by caller")(static_cast <bool> (!Inst.isAlreadyInstantiating() &&
"should have been caught by caller") ? void (0) : __assert_fail
("!Inst.isAlreadyInstantiating() && \"should have been caught by caller\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3114, __extension__
__PRETTY_FUNCTION__))
;
3115 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3116 "instantiating class definition");
3117
3118 // Enter the scope of this instantiation. We don't use
3119 // PushDeclContext because we don't have a scope.
3120 ContextRAII SavedContext(*this, Instantiation);
3121 EnterExpressionEvaluationContext EvalContext(
3122 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3123
3124 // If this is an instantiation of a local class, merge this local
3125 // instantiation scope with the enclosing scope. Otherwise, every
3126 // instantiation of a class has its own local instantiation scope.
3127 bool MergeWithParentScope = !Instantiation->isDefinedOutsideFunctionOrMethod();
3128 LocalInstantiationScope Scope(*this, MergeWithParentScope);
3129
3130 // Some class state isn't processed immediately but delayed till class
3131 // instantiation completes. We may not be ready to handle any delayed state
3132 // already on the stack as it might correspond to a different class, so save
3133 // it now and put it back later.
3134 SavePendingParsedClassStateRAII SavedPendingParsedClassState(*this);
3135
3136 // Pull attributes from the pattern onto the instantiation.
3137 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3138
3139 // Start the definition of this instantiation.
3140 Instantiation->startDefinition();
3141
3142 // The instantiation is visible here, even if it was first declared in an
3143 // unimported module.
3144 Instantiation->setVisibleDespiteOwningModule();
3145
3146 // FIXME: This loses the as-written tag kind for an explicit instantiation.
3147 Instantiation->setTagKind(Pattern->getTagKind());
3148
3149 // Do substitution on the base class specifiers.
3150 if (SubstBaseSpecifiers(Instantiation, Pattern, TemplateArgs))
3151 Instantiation->setInvalidDecl();
3152
3153 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3154 Instantiator.setEvaluateConstraints(false);
3155 SmallVector<Decl*, 4> Fields;
3156 // Delay instantiation of late parsed attributes.
3157 LateInstantiatedAttrVec LateAttrs;
3158 Instantiator.enableLateAttributeInstantiation(&LateAttrs);
3159
3160 bool MightHaveConstexprVirtualFunctions = false;
3161 for (auto *Member : Pattern->decls()) {
3162 // Don't instantiate members not belonging in this semantic context.
3163 // e.g. for:
3164 // @code
3165 // template <int i> class A {
3166 // class B *g;
3167 // };
3168 // @endcode
3169 // 'class B' has the template as lexical context but semantically it is
3170 // introduced in namespace scope.
3171 if (Member->getDeclContext() != Pattern)
3172 continue;
3173
3174 // BlockDecls can appear in a default-member-initializer. They must be the
3175 // child of a BlockExpr, so we only know how to instantiate them from there.
3176 // Similarly, lambda closure types are recreated when instantiating the
3177 // corresponding LambdaExpr.
3178 if (isa<BlockDecl>(Member) ||
3179 (isa<CXXRecordDecl>(Member) && cast<CXXRecordDecl>(Member)->isLambda()))
3180 continue;
3181
3182 if (Member->isInvalidDecl()) {
3183 Instantiation->setInvalidDecl();
3184 continue;
3185 }
3186
3187 Decl *NewMember = Instantiator.Visit(Member);
3188 if (NewMember) {
3189 if (FieldDecl *Field = dyn_cast<FieldDecl>(NewMember)) {
3190 Fields.push_back(Field);
3191 } else if (EnumDecl *Enum = dyn_cast<EnumDecl>(NewMember)) {
3192 // C++11 [temp.inst]p1: The implicit instantiation of a class template
3193 // specialization causes the implicit instantiation of the definitions
3194 // of unscoped member enumerations.
3195 // Record a point of instantiation for this implicit instantiation.
3196 if (TSK == TSK_ImplicitInstantiation && !Enum->isScoped() &&
3197 Enum->isCompleteDefinition()) {
3198 MemberSpecializationInfo *MSInfo =Enum->getMemberSpecializationInfo();
3199 assert(MSInfo && "no spec info for member enum specialization")(static_cast <bool> (MSInfo && "no spec info for member enum specialization"
) ? void (0) : __assert_fail ("MSInfo && \"no spec info for member enum specialization\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3199, __extension__
__PRETTY_FUNCTION__))
;
3200 MSInfo->setTemplateSpecializationKind(TSK_ImplicitInstantiation);
3201 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3202 }
3203 } else if (StaticAssertDecl *SA = dyn_cast<StaticAssertDecl>(NewMember)) {
3204 if (SA->isFailed()) {
3205 // A static_assert failed. Bail out; instantiating this
3206 // class is probably not meaningful.
3207 Instantiation->setInvalidDecl();
3208 break;
3209 }
3210 } else if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewMember)) {
3211 if (MD->isConstexpr() && !MD->getFriendObjectKind() &&
3212 (MD->isVirtualAsWritten() || Instantiation->getNumBases()))
3213 MightHaveConstexprVirtualFunctions = true;
3214 }
3215
3216 if (NewMember->isInvalidDecl())
3217 Instantiation->setInvalidDecl();
3218 } else {
3219 // FIXME: Eventually, a NULL return will mean that one of the
3220 // instantiations was a semantic disaster, and we'll want to mark the
3221 // declaration invalid.
3222 // For now, we expect to skip some members that we can't yet handle.
3223 }
3224 }
3225
3226 // Finish checking fields.
3227 ActOnFields(nullptr, Instantiation->getLocation(), Instantiation, Fields,
3228 SourceLocation(), SourceLocation(), ParsedAttributesView());
3229 CheckCompletedCXXClass(nullptr, Instantiation);
3230
3231 // Default arguments are parsed, if not instantiated. We can go instantiate
3232 // default arg exprs for default constructors if necessary now. Unless we're
3233 // parsing a class, in which case wait until that's finished.
3234 if (ParsingClassDepth == 0)
3235 ActOnFinishCXXNonNestedClass();
3236
3237 // Instantiate late parsed attributes, and attach them to their decls.
3238 // See Sema::InstantiateAttrs
3239 for (LateInstantiatedAttrVec::iterator I = LateAttrs.begin(),
3240 E = LateAttrs.end(); I != E; ++I) {
3241 assert(CurrentInstantiationScope == Instantiator.getStartingScope())(static_cast <bool> (CurrentInstantiationScope == Instantiator
.getStartingScope()) ? void (0) : __assert_fail ("CurrentInstantiationScope == Instantiator.getStartingScope()"
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3241, __extension__
__PRETTY_FUNCTION__))
;
3242 CurrentInstantiationScope = I->Scope;
3243
3244 // Allow 'this' within late-parsed attributes.
3245 auto *ND = cast<NamedDecl>(I->NewDecl);
3246 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
3247 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
3248 ND->isCXXInstanceMember());
3249
3250 Attr *NewAttr =
3251 instantiateTemplateAttribute(I->TmplAttr, Context, *this, TemplateArgs);
3252 if (NewAttr)
3253 I->NewDecl->addAttr(NewAttr);
3254 LocalInstantiationScope::deleteScopes(I->Scope,
3255 Instantiator.getStartingScope());
3256 }
3257 Instantiator.disableLateAttributeInstantiation();
3258 LateAttrs.clear();
3259
3260 ActOnFinishDelayedMemberInitializers(Instantiation);
3261
3262 // FIXME: We should do something similar for explicit instantiations so they
3263 // end up in the right module.
3264 if (TSK == TSK_ImplicitInstantiation) {
3265 Instantiation->setLocation(Pattern->getLocation());
3266 Instantiation->setLocStart(Pattern->getInnerLocStart());
3267 Instantiation->setBraceRange(Pattern->getBraceRange());
3268 }
3269
3270 if (!Instantiation->isInvalidDecl()) {
3271 // Perform any dependent diagnostics from the pattern.
3272 if (Pattern->isDependentContext())
3273 PerformDependentDiagnostics(Pattern, TemplateArgs);
3274
3275 // Instantiate any out-of-line class template partial
3276 // specializations now.
3277 for (TemplateDeclInstantiator::delayed_partial_spec_iterator
3278 P = Instantiator.delayed_partial_spec_begin(),
3279 PEnd = Instantiator.delayed_partial_spec_end();
3280 P != PEnd; ++P) {
3281 if (!Instantiator.InstantiateClassTemplatePartialSpecialization(
3282 P->first, P->second)) {
3283 Instantiation->setInvalidDecl();
3284 break;
3285 }
3286 }
3287
3288 // Instantiate any out-of-line variable template partial
3289 // specializations now.
3290 for (TemplateDeclInstantiator::delayed_var_partial_spec_iterator
3291 P = Instantiator.delayed_var_partial_spec_begin(),
3292 PEnd = Instantiator.delayed_var_partial_spec_end();
3293 P != PEnd; ++P) {
3294 if (!Instantiator.InstantiateVarTemplatePartialSpecialization(
3295 P->first, P->second)) {
3296 Instantiation->setInvalidDecl();
3297 break;
3298 }
3299 }
3300 }
3301
3302 // Exit the scope of this instantiation.
3303 SavedContext.pop();
3304
3305 if (!Instantiation->isInvalidDecl()) {
3306 // Always emit the vtable for an explicit instantiation definition
3307 // of a polymorphic class template specialization. Otherwise, eagerly
3308 // instantiate only constexpr virtual functions in preparation for their use
3309 // in constant evaluation.
3310 if (TSK == TSK_ExplicitInstantiationDefinition)
3311 MarkVTableUsed(PointOfInstantiation, Instantiation, true);
3312 else if (MightHaveConstexprVirtualFunctions)
3313 MarkVirtualMembersReferenced(PointOfInstantiation, Instantiation,
3314 /*ConstexprOnly*/ true);
3315 }
3316
3317 Consumer.HandleTagDeclDefinition(Instantiation);
3318
3319 return Instantiation->isInvalidDecl();
3320}
3321
3322/// Instantiate the definition of an enum from a given pattern.
3323///
3324/// \param PointOfInstantiation The point of instantiation within the
3325/// source code.
3326/// \param Instantiation is the declaration whose definition is being
3327/// instantiated. This will be a member enumeration of a class
3328/// temploid specialization, or a local enumeration within a
3329/// function temploid specialization.
3330/// \param Pattern The templated declaration from which the instantiation
3331/// occurs.
3332/// \param TemplateArgs The template arguments to be substituted into
3333/// the pattern.
3334/// \param TSK The kind of implicit or explicit instantiation to perform.
3335///
3336/// \return \c true if an error occurred, \c false otherwise.
3337bool Sema::InstantiateEnum(SourceLocation PointOfInstantiation,
3338 EnumDecl *Instantiation, EnumDecl *Pattern,
3339 const MultiLevelTemplateArgumentList &TemplateArgs,
3340 TemplateSpecializationKind TSK) {
3341 EnumDecl *PatternDef = Pattern->getDefinition();
3342 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Instantiation,
3343 Instantiation->getInstantiatedFromMemberEnum(),
3344 Pattern, PatternDef, TSK,/*Complain*/true))
3345 return true;
3346 Pattern = PatternDef;
3347
3348 // Record the point of instantiation.
3349 if (MemberSpecializationInfo *MSInfo
3350 = Instantiation->getMemberSpecializationInfo()) {
3351 MSInfo->setTemplateSpecializationKind(TSK);
3352 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3353 }
3354
3355 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3356 if (Inst.isInvalid())
3357 return true;
3358 if (Inst.isAlreadyInstantiating())
3359 return false;
3360 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3361 "instantiating enum definition");
3362
3363 // The instantiation is visible here, even if it was first declared in an
3364 // unimported module.
3365 Instantiation->setVisibleDespiteOwningModule();
3366
3367 // Enter the scope of this instantiation. We don't use
3368 // PushDeclContext because we don't have a scope.
3369 ContextRAII SavedContext(*this, Instantiation);
3370 EnterExpressionEvaluationContext EvalContext(
3371 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3372
3373 LocalInstantiationScope Scope(*this, /*MergeWithParentScope*/true);
3374
3375 // Pull attributes from the pattern onto the instantiation.
3376 InstantiateAttrs(TemplateArgs, Pattern, Instantiation);
3377
3378 TemplateDeclInstantiator Instantiator(*this, Instantiation, TemplateArgs);
3379 Instantiator.InstantiateEnumDefinition(Instantiation, Pattern);
3380
3381 // Exit the scope of this instantiation.
3382 SavedContext.pop();
3383
3384 return Instantiation->isInvalidDecl();
3385}
3386
3387
3388/// Instantiate the definition of a field from the given pattern.
3389///
3390/// \param PointOfInstantiation The point of instantiation within the
3391/// source code.
3392/// \param Instantiation is the declaration whose definition is being
3393/// instantiated. This will be a class of a class temploid
3394/// specialization, or a local enumeration within a function temploid
3395/// specialization.
3396/// \param Pattern The templated declaration from which the instantiation
3397/// occurs.
3398/// \param TemplateArgs The template arguments to be substituted into
3399/// the pattern.
3400///
3401/// \return \c true if an error occurred, \c false otherwise.
3402bool Sema::InstantiateInClassInitializer(
3403 SourceLocation PointOfInstantiation, FieldDecl *Instantiation,
3404 FieldDecl *Pattern, const MultiLevelTemplateArgumentList &TemplateArgs) {
3405 // If there is no initializer, we don't need to do anything.
3406 if (!Pattern->hasInClassInitializer())
3407 return false;
3408
3409 assert(Instantiation->getInClassInitStyle() ==(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3411, __extension__
__PRETTY_FUNCTION__))
3410 Pattern->getInClassInitStyle() &&(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3411, __extension__
__PRETTY_FUNCTION__))
3411 "pattern and instantiation disagree about init style")(static_cast <bool> (Instantiation->getInClassInitStyle
() == Pattern->getInClassInitStyle() && "pattern and instantiation disagree about init style"
) ? void (0) : __assert_fail ("Instantiation->getInClassInitStyle() == Pattern->getInClassInitStyle() && \"pattern and instantiation disagree about init style\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3411, __extension__
__PRETTY_FUNCTION__))
;
3412
3413 // Error out if we haven't parsed the initializer of the pattern yet because
3414 // we are waiting for the closing brace of the outer class.
3415 Expr *OldInit = Pattern->getInClassInitializer();
3416 if (!OldInit) {
3417 RecordDecl *PatternRD = Pattern->getParent();
3418 RecordDecl *OutermostClass = PatternRD->getOuterLexicalRecordContext();
3419 Diag(PointOfInstantiation,
3420 diag::err_default_member_initializer_not_yet_parsed)
3421 << OutermostClass << Pattern;
3422 Diag(Pattern->getEndLoc(),
3423 diag::note_default_member_initializer_not_yet_parsed);
3424 Instantiation->setInvalidDecl();
3425 return true;
3426 }
3427
3428 InstantiatingTemplate Inst(*this, PointOfInstantiation, Instantiation);
3429 if (Inst.isInvalid())
3430 return true;
3431 if (Inst.isAlreadyInstantiating()) {
3432 // Error out if we hit an instantiation cycle for this initializer.
3433 Diag(PointOfInstantiation, diag::err_default_member_initializer_cycle)
3434 << Instantiation;
3435 return true;
3436 }
3437 PrettyDeclStackTraceEntry CrashInfo(Context, Instantiation, SourceLocation(),
3438 "instantiating default member init");
3439
3440 // Enter the scope of this instantiation. We don't use PushDeclContext because
3441 // we don't have a scope.
3442 ContextRAII SavedContext(*this, Instantiation->getParent());
3443 EnterExpressionEvaluationContext EvalContext(
3444 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
3445 ExprEvalContexts.back().DelayedDefaultInitializationContext = {
3446 PointOfInstantiation, Instantiation, CurContext};
3447
3448 LocalInstantiationScope Scope(*this, true);
3449
3450 // Instantiate the initializer.
3451 ActOnStartCXXInClassMemberInitializer();
3452 CXXThisScopeRAII ThisScope(*this, Instantiation->getParent(), Qualifiers());
3453
3454 ExprResult NewInit = SubstInitializer(OldInit, TemplateArgs,
3455 /*CXXDirectInit=*/false);
3456 Expr *Init = NewInit.get();
3457 assert((!Init || !isa<ParenListExpr>(Init)) && "call-style init in class")(static_cast <bool> ((!Init || !isa<ParenListExpr>
(Init)) && "call-style init in class") ? void (0) : __assert_fail
("(!Init || !isa<ParenListExpr>(Init)) && \"call-style init in class\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3457, __extension__
__PRETTY_FUNCTION__))
;
3458 ActOnFinishCXXInClassMemberInitializer(
3459 Instantiation, Init ? Init->getBeginLoc() : SourceLocation(), Init);
3460
3461 if (auto *L = getASTMutationListener())
3462 L->DefaultMemberInitializerInstantiated(Instantiation);
3463
3464 // Return true if the in-class initializer is still missing.
3465 return !Instantiation->getInClassInitializer();
3466}
3467
3468namespace {
3469 /// A partial specialization whose template arguments have matched
3470 /// a given template-id.
3471 struct PartialSpecMatchResult {
3472 ClassTemplatePartialSpecializationDecl *Partial;
3473 TemplateArgumentList *Args;
3474 };
3475}
3476
3477bool Sema::usesPartialOrExplicitSpecialization(
3478 SourceLocation Loc, ClassTemplateSpecializationDecl *ClassTemplateSpec) {
3479 if (ClassTemplateSpec->getTemplateSpecializationKind() ==
3480 TSK_ExplicitSpecialization)
3481 return true;
3482
3483 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3484 ClassTemplateSpec->getSpecializedTemplate()
3485 ->getPartialSpecializations(PartialSpecs);
3486 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3487 TemplateDeductionInfo Info(Loc);
3488 if (!DeduceTemplateArguments(PartialSpecs[I],
3489 ClassTemplateSpec->getTemplateArgs(), Info))
3490 return true;
3491 }
3492
3493 return false;
3494}
3495
3496/// Get the instantiation pattern to use to instantiate the definition of a
3497/// given ClassTemplateSpecializationDecl (either the pattern of the primary
3498/// template or of a partial specialization).
3499static ActionResult<CXXRecordDecl *>
3500getPatternForClassTemplateSpecialization(
3501 Sema &S, SourceLocation PointOfInstantiation,
3502 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3503 TemplateSpecializationKind TSK) {
3504 Sema::InstantiatingTemplate Inst(S, PointOfInstantiation, ClassTemplateSpec);
3505 if (Inst.isInvalid())
3506 return {/*Invalid=*/true};
3507 if (Inst.isAlreadyInstantiating())
3508 return {/*Invalid=*/false};
3509
3510 llvm::PointerUnion<ClassTemplateDecl *,
3511 ClassTemplatePartialSpecializationDecl *>
3512 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3513 if (!Specialized.is<ClassTemplatePartialSpecializationDecl *>()) {
3514 // Find best matching specialization.
3515 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3516
3517 // C++ [temp.class.spec.match]p1:
3518 // When a class template is used in a context that requires an
3519 // instantiation of the class, it is necessary to determine
3520 // whether the instantiation is to be generated using the primary
3521 // template or one of the partial specializations. This is done by
3522 // matching the template arguments of the class template
3523 // specialization with the template argument lists of the partial
3524 // specializations.
3525 typedef PartialSpecMatchResult MatchResult;
3526 SmallVector<MatchResult, 4> Matched;
3527 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
3528 Template->getPartialSpecializations(PartialSpecs);
3529 TemplateSpecCandidateSet FailedCandidates(PointOfInstantiation);
3530 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I) {
3531 ClassTemplatePartialSpecializationDecl *Partial = PartialSpecs[I];
3532 TemplateDeductionInfo Info(FailedCandidates.getLocation());
3533 if (Sema::TemplateDeductionResult Result = S.DeduceTemplateArguments(
3534 Partial, ClassTemplateSpec->getTemplateArgs(), Info)) {
3535 // Store the failed-deduction information for use in diagnostics, later.
3536 // TODO: Actually use the failed-deduction info?
3537 FailedCandidates.addCandidate().set(
3538 DeclAccessPair::make(Template, AS_public), Partial,
3539 MakeDeductionFailureInfo(S.Context, Result, Info));
3540 (void)Result;
3541 } else {
3542 Matched.push_back(PartialSpecMatchResult());
3543 Matched.back().Partial = Partial;
3544 Matched.back().Args = Info.takeCanonical();
3545 }
3546 }
3547
3548 // If we're dealing with a member template where the template parameters
3549 // have been instantiated, this provides the original template parameters
3550 // from which the member template's parameters were instantiated.
3551
3552 if (Matched.size() >= 1) {
3553 SmallVectorImpl<MatchResult>::iterator Best = Matched.begin();
3554 if (Matched.size() == 1) {
3555 // -- If exactly one matching specialization is found, the
3556 // instantiation is generated from that specialization.
3557 // We don't need to do anything for this.
3558 } else {
3559 // -- If more than one matching specialization is found, the
3560 // partial order rules (14.5.4.2) are used to determine
3561 // whether one of the specializations is more specialized
3562 // than the others. If none of the specializations is more
3563 // specialized than all of the other matching
3564 // specializations, then the use of the class template is
3565 // ambiguous and the program is ill-formed.
3566 for (SmallVectorImpl<MatchResult>::iterator P = Best + 1,
3567 PEnd = Matched.end();
3568 P != PEnd; ++P) {
3569 if (S.getMoreSpecializedPartialSpecialization(
3570 P->Partial, Best->Partial, PointOfInstantiation) ==
3571 P->Partial)
3572 Best = P;
3573 }
3574
3575 // Determine if the best partial specialization is more specialized than
3576 // the others.
3577 bool Ambiguous = false;
3578 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3579 PEnd = Matched.end();
3580 P != PEnd; ++P) {
3581 if (P != Best && S.getMoreSpecializedPartialSpecialization(
3582 P->Partial, Best->Partial,
3583 PointOfInstantiation) != Best->Partial) {
3584 Ambiguous = true;
3585 break;
3586 }
3587 }
3588
3589 if (Ambiguous) {
3590 // Partial ordering did not produce a clear winner. Complain.
3591 Inst.Clear();
3592 ClassTemplateSpec->setInvalidDecl();
3593 S.Diag(PointOfInstantiation,
3594 diag::err_partial_spec_ordering_ambiguous)
3595 << ClassTemplateSpec;
3596
3597 // Print the matching partial specializations.
3598 for (SmallVectorImpl<MatchResult>::iterator P = Matched.begin(),
3599 PEnd = Matched.end();
3600 P != PEnd; ++P)
3601 S.Diag(P->Partial->getLocation(), diag::note_partial_spec_match)
3602 << S.getTemplateArgumentBindingsText(
3603 P->Partial->getTemplateParameters(), *P->Args);
3604
3605 return {/*Invalid=*/true};
3606 }
3607 }
3608
3609 ClassTemplateSpec->setInstantiationOf(Best->Partial, Best->Args);
3610 } else {
3611 // -- If no matches are found, the instantiation is generated
3612 // from the primary template.
3613 }
3614 }
3615
3616 CXXRecordDecl *Pattern = nullptr;
3617 Specialized = ClassTemplateSpec->getSpecializedTemplateOrPartial();
3618 if (auto *PartialSpec =
3619 Specialized.dyn_cast<ClassTemplatePartialSpecializationDecl *>()) {
3620 // Instantiate using the best class template partial specialization.
3621 while (PartialSpec->getInstantiatedFromMember()) {
3622 // If we've found an explicit specialization of this class template,
3623 // stop here and use that as the pattern.
3624 if (PartialSpec->isMemberSpecialization())
3625 break;
3626
3627 PartialSpec = PartialSpec->getInstantiatedFromMember();
3628 }
3629 Pattern = PartialSpec;
3630 } else {
3631 ClassTemplateDecl *Template = ClassTemplateSpec->getSpecializedTemplate();
3632 while (Template->getInstantiatedFromMemberTemplate()) {
3633 // If we've found an explicit specialization of this class template,
3634 // stop here and use that as the pattern.
3635 if (Template->isMemberSpecialization())
3636 break;
3637
3638 Template = Template->getInstantiatedFromMemberTemplate();
3639 }
3640 Pattern = Template->getTemplatedDecl();
3641 }
3642
3643 return Pattern;
3644}
3645
3646bool Sema::InstantiateClassTemplateSpecialization(
3647 SourceLocation PointOfInstantiation,
3648 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3649 TemplateSpecializationKind TSK, bool Complain) {
3650 // Perform the actual instantiation on the canonical declaration.
3651 ClassTemplateSpec = cast<ClassTemplateSpecializationDecl>(
3652 ClassTemplateSpec->getCanonicalDecl());
3653 if (ClassTemplateSpec->isInvalidDecl())
3654 return true;
3655
3656 ActionResult<CXXRecordDecl *> Pattern =
3657 getPatternForClassTemplateSpecialization(*this, PointOfInstantiation,
3658 ClassTemplateSpec, TSK);
3659 if (!Pattern.isUsable())
3660 return Pattern.isInvalid();
3661
3662 return InstantiateClass(
3663 PointOfInstantiation, ClassTemplateSpec, Pattern.get(),
3664 getTemplateInstantiationArgs(ClassTemplateSpec), TSK, Complain);
3665}
3666
3667/// Instantiates the definitions of all of the member
3668/// of the given class, which is an instantiation of a class template
3669/// or a member class of a template.
3670void
3671Sema::InstantiateClassMembers(SourceLocation PointOfInstantiation,
3672 CXXRecordDecl *Instantiation,
3673 const MultiLevelTemplateArgumentList &TemplateArgs,
3674 TemplateSpecializationKind TSK) {
3675 // FIXME: We need to notify the ASTMutationListener that we did all of these
3676 // things, in case we have an explicit instantiation definition in a PCM, a
3677 // module, or preamble, and the declaration is in an imported AST.
3678 assert((static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3682, __extension__
__PRETTY_FUNCTION__))
3679 (TSK == TSK_ExplicitInstantiationDefinition ||(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3682, __extension__
__PRETTY_FUNCTION__))
3680 TSK == TSK_ExplicitInstantiationDeclaration ||(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3682, __extension__
__PRETTY_FUNCTION__))
3681 (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) &&(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3682, __extension__
__PRETTY_FUNCTION__))
3682 "Unexpected template specialization kind!")(static_cast <bool> ((TSK == TSK_ExplicitInstantiationDefinition
|| TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation
&& Instantiation->isLocalClass())) && "Unexpected template specialization kind!"
) ? void (0) : __assert_fail ("(TSK == TSK_ExplicitInstantiationDefinition || TSK == TSK_ExplicitInstantiationDeclaration || (TSK == TSK_ImplicitInstantiation && Instantiation->isLocalClass())) && \"Unexpected template specialization kind!\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3682, __extension__
__PRETTY_FUNCTION__))
;
3683 for (auto *D : Instantiation->decls()) {
3684 bool SuppressNew = false;
3685 if (auto *Function = dyn_cast<FunctionDecl>(D)) {
3686 if (FunctionDecl *Pattern =
3687 Function->getInstantiatedFromMemberFunction()) {
3688
3689 if (Function->isIneligibleOrNotSelected())
3690 continue;
3691
3692 if (Function->getTrailingRequiresClause()) {
3693 ConstraintSatisfaction Satisfaction;
3694 if (CheckFunctionConstraints(Function, Satisfaction) ||
3695 !Satisfaction.IsSatisfied) {
3696 continue;
3697 }
3698 }
3699
3700 if (Function->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3701 continue;
3702
3703 MemberSpecializationInfo *MSInfo =
3704 Function->getMemberSpecializationInfo();
3705 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3705, __extension__
__PRETTY_FUNCTION__))
;
3706 if (MSInfo->getTemplateSpecializationKind()
3707 == TSK_ExplicitSpecialization)
3708 continue;
3709
3710 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3711 Function,
3712 MSInfo->getTemplateSpecializationKind(),
3713 MSInfo->getPointOfInstantiation(),
3714 SuppressNew) ||
3715 SuppressNew)
3716 continue;
3717
3718 // C++11 [temp.explicit]p8:
3719 // An explicit instantiation definition that names a class template
3720 // specialization explicitly instantiates the class template
3721 // specialization and is only an explicit instantiation definition
3722 // of members whose definition is visible at the point of
3723 // instantiation.
3724 if (TSK == TSK_ExplicitInstantiationDefinition && !Pattern->isDefined())
3725 continue;
3726
3727 Function->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3728
3729 if (Function->isDefined()) {
3730 // Let the ASTConsumer know that this function has been explicitly
3731 // instantiated now, and its linkage might have changed.
3732 Consumer.HandleTopLevelDecl(DeclGroupRef(Function));
3733 } else if (TSK == TSK_ExplicitInstantiationDefinition) {
3734 InstantiateFunctionDefinition(PointOfInstantiation, Function);
3735 } else if (TSK == TSK_ImplicitInstantiation) {
3736 PendingLocalImplicitInstantiations.push_back(
3737 std::make_pair(Function, PointOfInstantiation));
3738 }
3739 }
3740 } else if (auto *Var = dyn_cast<VarDecl>(D)) {
3741 if (isa<VarTemplateSpecializationDecl>(Var))
3742 continue;
3743
3744 if (Var->isStaticDataMember()) {
3745 if (Var->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3746 continue;
3747
3748 MemberSpecializationInfo *MSInfo = Var->getMemberSpecializationInfo();
3749 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3749, __extension__
__PRETTY_FUNCTION__))
;
3750 if (MSInfo->getTemplateSpecializationKind()
3751 == TSK_ExplicitSpecialization)
3752 continue;
3753
3754 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3755 Var,
3756 MSInfo->getTemplateSpecializationKind(),
3757 MSInfo->getPointOfInstantiation(),
3758 SuppressNew) ||
3759 SuppressNew)
3760 continue;
3761
3762 if (TSK == TSK_ExplicitInstantiationDefinition) {
3763 // C++0x [temp.explicit]p8:
3764 // An explicit instantiation definition that names a class template
3765 // specialization explicitly instantiates the class template
3766 // specialization and is only an explicit instantiation definition
3767 // of members whose definition is visible at the point of
3768 // instantiation.
3769 if (!Var->getInstantiatedFromStaticDataMember()->getDefinition())
3770 continue;
3771
3772 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3773 InstantiateVariableDefinition(PointOfInstantiation, Var);
3774 } else {
3775 Var->setTemplateSpecializationKind(TSK, PointOfInstantiation);
3776 }
3777 }
3778 } else if (auto *Record = dyn_cast<CXXRecordDecl>(D)) {
3779 if (Record->hasAttr<ExcludeFromExplicitInstantiationAttr>())
3780 continue;
3781
3782 // Always skip the injected-class-name, along with any
3783 // redeclarations of nested classes, since both would cause us
3784 // to try to instantiate the members of a class twice.
3785 // Skip closure types; they'll get instantiated when we instantiate
3786 // the corresponding lambda-expression.
3787 if (Record->isInjectedClassName() || Record->getPreviousDecl() ||
3788 Record->isLambda())
3789 continue;
3790
3791 MemberSpecializationInfo *MSInfo = Record->getMemberSpecializationInfo();
3792 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3792, __extension__
__PRETTY_FUNCTION__))
;
3793
3794 if (MSInfo->getTemplateSpecializationKind()
3795 == TSK_ExplicitSpecialization)
3796 continue;
3797
3798 if (Context.getTargetInfo().getTriple().isOSWindows() &&
3799 TSK == TSK_ExplicitInstantiationDeclaration) {
3800 // On Windows, explicit instantiation decl of the outer class doesn't
3801 // affect the inner class. Typically extern template declarations are
3802 // used in combination with dll import/export annotations, but those
3803 // are not propagated from the outer class templates to inner classes.
3804 // Therefore, do not instantiate inner classes on this platform, so
3805 // that users don't end up with undefined symbols during linking.
3806 continue;
3807 }
3808
3809 if (CheckSpecializationInstantiationRedecl(PointOfInstantiation, TSK,
3810 Record,
3811 MSInfo->getTemplateSpecializationKind(),
3812 MSInfo->getPointOfInstantiation(),
3813 SuppressNew) ||
3814 SuppressNew)
3815 continue;
3816
3817 CXXRecordDecl *Pattern = Record->getInstantiatedFromMemberClass();
3818 assert(Pattern && "Missing instantiated-from-template information")(static_cast <bool> (Pattern && "Missing instantiated-from-template information"
) ? void (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3818, __extension__
__PRETTY_FUNCTION__))
;
3819
3820 if (!Record->getDefinition()) {
3821 if (!Pattern->getDefinition()) {
3822 // C++0x [temp.explicit]p8:
3823 // An explicit instantiation definition that names a class template
3824 // specialization explicitly instantiates the class template
3825 // specialization and is only an explicit instantiation definition
3826 // of members whose definition is visible at the point of
3827 // instantiation.
3828 if (TSK == TSK_ExplicitInstantiationDeclaration) {
3829 MSInfo->setTemplateSpecializationKind(TSK);
3830 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3831 }
3832
3833 continue;
3834 }
3835
3836 InstantiateClass(PointOfInstantiation, Record, Pattern,
3837 TemplateArgs,
3838 TSK);
3839 } else {
3840 if (TSK == TSK_ExplicitInstantiationDefinition &&
3841 Record->getTemplateSpecializationKind() ==
3842 TSK_ExplicitInstantiationDeclaration) {
3843 Record->setTemplateSpecializationKind(TSK);
3844 MarkVTableUsed(PointOfInstantiation, Record, true);
3845 }
3846 }
3847
3848 Pattern = cast_or_null<CXXRecordDecl>(Record->getDefinition());
3849 if (Pattern)
3850 InstantiateClassMembers(PointOfInstantiation, Pattern, TemplateArgs,
3851 TSK);
3852 } else if (auto *Enum = dyn_cast<EnumDecl>(D)) {
3853 MemberSpecializationInfo *MSInfo = Enum->getMemberSpecializationInfo();
3854 assert(MSInfo && "No member specialization information?")(static_cast <bool> (MSInfo && "No member specialization information?"
) ? void (0) : __assert_fail ("MSInfo && \"No member specialization information?\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3854, __extension__
__PRETTY_FUNCTION__))
;
3855
3856 if (MSInfo->getTemplateSpecializationKind()
3857 == TSK_ExplicitSpecialization)
3858 continue;
3859
3860 if (CheckSpecializationInstantiationRedecl(
3861 PointOfInstantiation, TSK, Enum,
3862 MSInfo->getTemplateSpecializationKind(),
3863 MSInfo->getPointOfInstantiation(), SuppressNew) ||
3864 SuppressNew)
3865 continue;
3866
3867 if (Enum->getDefinition())
3868 continue;
3869
3870 EnumDecl *Pattern = Enum->getTemplateInstantiationPattern();
3871 assert(Pattern && "Missing instantiated-from-template information")(static_cast <bool> (Pattern && "Missing instantiated-from-template information"
) ? void (0) : __assert_fail ("Pattern && \"Missing instantiated-from-template information\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3871, __extension__
__PRETTY_FUNCTION__))
;
3872
3873 if (TSK == TSK_ExplicitInstantiationDefinition) {
3874 if (!Pattern->getDefinition())
3875 continue;
3876
3877 InstantiateEnum(PointOfInstantiation, Enum, Pattern, TemplateArgs, TSK);
3878 } else {
3879 MSInfo->setTemplateSpecializationKind(TSK);
3880 MSInfo->setPointOfInstantiation(PointOfInstantiation);
3881 }
3882 } else if (auto *Field = dyn_cast<FieldDecl>(D)) {
3883 // No need to instantiate in-class initializers during explicit
3884 // instantiation.
3885 if (Field->hasInClassInitializer() && TSK == TSK_ImplicitInstantiation) {
3886 CXXRecordDecl *ClassPattern =
3887 Instantiation->getTemplateInstantiationPattern();
3888 DeclContext::lookup_result Lookup =
3889 ClassPattern->lookup(Field->getDeclName());
3890 FieldDecl *Pattern = Lookup.find_first<FieldDecl>();
3891 assert(Pattern)(static_cast <bool> (Pattern) ? void (0) : __assert_fail
("Pattern", "clang/lib/Sema/SemaTemplateInstantiate.cpp", 3891
, __extension__ __PRETTY_FUNCTION__))
;
3892 InstantiateInClassInitializer(PointOfInstantiation, Field, Pattern,
3893 TemplateArgs);
3894 }
3895 }
3896 }
3897}
3898
3899/// Instantiate the definitions of all of the members of the
3900/// given class template specialization, which was named as part of an
3901/// explicit instantiation.
3902void
3903Sema::InstantiateClassTemplateSpecializationMembers(
3904 SourceLocation PointOfInstantiation,
3905 ClassTemplateSpecializationDecl *ClassTemplateSpec,
3906 TemplateSpecializationKind TSK) {
3907 // C++0x [temp.explicit]p7:
3908 // An explicit instantiation that names a class template
3909 // specialization is an explicit instantion of the same kind
3910 // (declaration or definition) of each of its members (not
3911 // including members inherited from base classes) that has not
3912 // been previously explicitly specialized in the translation unit
3913 // containing the explicit instantiation, except as described
3914 // below.
3915 InstantiateClassMembers(PointOfInstantiation, ClassTemplateSpec,
3916 getTemplateInstantiationArgs(ClassTemplateSpec),
3917 TSK);
3918}
3919
3920StmtResult
3921Sema::SubstStmt(Stmt *S, const MultiLevelTemplateArgumentList &TemplateArgs) {
3922 if (!S)
3923 return S;
3924
3925 TemplateInstantiator Instantiator(*this, TemplateArgs,
3926 SourceLocation(),
3927 DeclarationName());
3928 return Instantiator.TransformStmt(S);
3929}
3930
3931bool Sema::SubstTemplateArguments(
3932 ArrayRef<TemplateArgumentLoc> Args,
3933 const MultiLevelTemplateArgumentList &TemplateArgs,
3934 TemplateArgumentListInfo &Out) {
3935 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3936 DeclarationName());
3937 return Instantiator.TransformTemplateArguments(Args.begin(), Args.end(), Out);
3938}
3939
3940ExprResult
3941Sema::SubstExpr(Expr *E, const MultiLevelTemplateArgumentList &TemplateArgs) {
3942 if (!E)
3943 return E;
3944
3945 TemplateInstantiator Instantiator(*this, TemplateArgs,
3946 SourceLocation(),
3947 DeclarationName());
3948 return Instantiator.TransformExpr(E);
3949}
3950
3951ExprResult
3952Sema::SubstConstraintExpr(Expr *E,
3953 const MultiLevelTemplateArgumentList &TemplateArgs) {
3954 if (!E)
3955 return E;
3956
3957 // This is where we need to make sure we 'know' constraint checking needs to
3958 // happen.
3959 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3960 DeclarationName());
3961 return Instantiator.TransformExpr(E);
3962}
3963
3964ExprResult Sema::SubstInitializer(Expr *Init,
3965 const MultiLevelTemplateArgumentList &TemplateArgs,
3966 bool CXXDirectInit) {
3967 TemplateInstantiator Instantiator(*this, TemplateArgs, SourceLocation(),
3968 DeclarationName());
3969 return Instantiator.TransformInitializer(Init, CXXDirectInit);
3970}
3971
3972bool Sema::SubstExprs(ArrayRef<Expr *> Exprs, bool IsCall,
3973 const MultiLevelTemplateArgumentList &TemplateArgs,
3974 SmallVectorImpl<Expr *> &Outputs) {
3975 if (Exprs.empty())
3976 return false;
3977
3978 TemplateInstantiator Instantiator(*this, TemplateArgs,
3979 SourceLocation(),
3980 DeclarationName());
3981 return Instantiator.TransformExprs(Exprs.data(), Exprs.size(),
3982 IsCall, Outputs);
3983}
3984
3985NestedNameSpecifierLoc
3986Sema::SubstNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
3987 const MultiLevelTemplateArgumentList &TemplateArgs) {
3988 if (!NNS)
3989 return NestedNameSpecifierLoc();
3990
3991 TemplateInstantiator Instantiator(*this, TemplateArgs, NNS.getBeginLoc(),
3992 DeclarationName());
3993 return Instantiator.TransformNestedNameSpecifierLoc(NNS);
3994}
3995
3996/// Do template substitution on declaration name info.
3997DeclarationNameInfo
3998Sema::SubstDeclarationNameInfo(const DeclarationNameInfo &NameInfo,
3999 const MultiLevelTemplateArgumentList &TemplateArgs) {
4000 TemplateInstantiator Instantiator(*this, TemplateArgs, NameInfo.getLoc(),
4001 NameInfo.getName());
4002 return Instantiator.TransformDeclarationNameInfo(NameInfo);
4003}
4004
4005TemplateName
4006Sema::SubstTemplateName(NestedNameSpecifierLoc QualifierLoc,
4007 TemplateName Name, SourceLocation Loc,
4008 const MultiLevelTemplateArgumentList &TemplateArgs) {
4009 TemplateInstantiator Instantiator(*this, TemplateArgs, Loc,
4010 DeclarationName());
4011 CXXScopeSpec SS;
4012 SS.Adopt(QualifierLoc);
4013 return Instantiator.TransformTemplateName(SS, Name, Loc);
4014}
4015
4016static const Decl *getCanonicalParmVarDecl(const Decl *D) {
4017 // When storing ParmVarDecls in the local instantiation scope, we always
4018 // want to use the ParmVarDecl from the canonical function declaration,
4019 // since the map is then valid for any redeclaration or definition of that
4020 // function.
4021 if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(D)) {
4022 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
4023 unsigned i = PV->getFunctionScopeIndex();
4024 // This parameter might be from a freestanding function type within the
4025 // function and isn't necessarily referring to one of FD's parameters.
4026 if (i < FD->getNumParams() && FD->getParamDecl(i) == PV)
4027 return FD->getCanonicalDecl()->getParamDecl(i);
4028 }
4029 }
4030 return D;
4031}
4032
4033
4034llvm::PointerUnion<Decl *, LocalInstantiationScope::DeclArgumentPack *> *
4035LocalInstantiationScope::findInstantiationOf(const Decl *D) {
4036 D = getCanonicalParmVarDecl(D);
4037 for (LocalInstantiationScope *Current = this; Current;
4038 Current = Current->Outer) {
4039
4040 // Check if we found something within this scope.
4041 const Decl *CheckD = D;
4042 do {
4043 LocalDeclsMap::iterator Found = Current->LocalDecls.find(CheckD);
4044 if (Found != Current->LocalDecls.end())
4045 return &Found->second;
4046
4047 // If this is a tag declaration, it's possible that we need to look for
4048 // a previous declaration.
4049 if (const TagDecl *Tag = dyn_cast<TagDecl>(CheckD))
4050 CheckD = Tag->getPreviousDecl();
4051 else
4052 CheckD = nullptr;
4053 } while (CheckD);
4054
4055 // If we aren't combined with our outer scope, we're done.
4056 if (!Current->CombineWithOuterScope)
4057 break;
4058 }
4059
4060 // If we're performing a partial substitution during template argument
4061 // deduction, we may not have values for template parameters yet.
4062 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
4063 isa<TemplateTemplateParmDecl>(D))
4064 return nullptr;
4065
4066 // Local types referenced prior to definition may require instantiation.
4067 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
4068 if (RD->isLocalClass())
4069 return nullptr;
4070
4071 // Enumeration types referenced prior to definition may appear as a result of
4072 // error recovery.
4073 if (isa<EnumDecl>(D))
4074 return nullptr;
4075
4076 // Materialized typedefs/type alias for implicit deduction guides may require
4077 // instantiation.
4078 if (isa<TypedefNameDecl>(D) &&
4079 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
4080 return nullptr;
4081
4082 // If we didn't find the decl, then we either have a sema bug, or we have a
4083 // forward reference to a label declaration. Return null to indicate that
4084 // we have an uninstantiated label.
4085 assert(isa<LabelDecl>(D) && "declaration not instantiated in this scope")(static_cast <bool> (isa<LabelDecl>(D) &&
"declaration not instantiated in this scope") ? void (0) : __assert_fail
("isa<LabelDecl>(D) && \"declaration not instantiated in this scope\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4085, __extension__
__PRETTY_FUNCTION__))
;
4086 return nullptr;
4087}
4088
4089void LocalInstantiationScope::InstantiatedLocal(const Decl *D, Decl *Inst) {
4090 D = getCanonicalParmVarDecl(D);
4091 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4092 if (Stored.isNull()) {
4093#ifndef NDEBUG
4094 // It should not be present in any surrounding scope either.
4095 LocalInstantiationScope *Current = this;
4096 while (Current->CombineWithOuterScope && Current->Outer) {
4097 Current = Current->Outer;
4098 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Instantiated local in inner and outer scopes"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4099, __extension__
__PRETTY_FUNCTION__))
4099 "Instantiated local in inner and outer scopes")(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Instantiated local in inner and outer scopes"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Instantiated local in inner and outer scopes\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4099, __extension__
__PRETTY_FUNCTION__))
;
4100 }
4101#endif
4102 Stored = Inst;
4103 } else if (DeclArgumentPack *Pack = Stored.dyn_cast<DeclArgumentPack *>()) {
4104 Pack->push_back(cast<VarDecl>(Inst));
4105 } else {
4106 assert(Stored.get<Decl *>() == Inst && "Already instantiated this local")(static_cast <bool> (Stored.get<Decl *>() == Inst
&& "Already instantiated this local") ? void (0) : __assert_fail
("Stored.get<Decl *>() == Inst && \"Already instantiated this local\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4106, __extension__
__PRETTY_FUNCTION__))
;
4107 }
4108}
4109
4110void LocalInstantiationScope::InstantiatedLocalPackArg(const Decl *D,
4111 VarDecl *Inst) {
4112 D = getCanonicalParmVarDecl(D);
4113 DeclArgumentPack *Pack = LocalDecls[D].get<DeclArgumentPack *>();
4114 Pack->push_back(Inst);
4115}
4116
4117void LocalInstantiationScope::MakeInstantiatedLocalArgPack(const Decl *D) {
4118#ifndef NDEBUG
4119 // This should be the first time we've been told about this decl.
4120 for (LocalInstantiationScope *Current = this;
4121 Current && Current->CombineWithOuterScope; Current = Current->Outer)
4122 assert(Current->LocalDecls.find(D) == Current->LocalDecls.end() &&(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Creating local pack after instantiation of local"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4123, __extension__
__PRETTY_FUNCTION__))
4123 "Creating local pack after instantiation of local")(static_cast <bool> (Current->LocalDecls.find(D) == Current
->LocalDecls.end() && "Creating local pack after instantiation of local"
) ? void (0) : __assert_fail ("Current->LocalDecls.find(D) == Current->LocalDecls.end() && \"Creating local pack after instantiation of local\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4123, __extension__
__PRETTY_FUNCTION__))
;
4124#endif
4125
4126 D = getCanonicalParmVarDecl(D);
4127 llvm::PointerUnion<Decl *, DeclArgumentPack *> &Stored = LocalDecls[D];
4128 DeclArgumentPack *Pack = new DeclArgumentPack;
4129 Stored = Pack;
4130 ArgumentPacks.push_back(Pack);
4131}
4132
4133bool LocalInstantiationScope::isLocalPackExpansion(const Decl *D) {
4134 for (DeclArgumentPack *Pack : ArgumentPacks)
4135 if (llvm::is_contained(*Pack, D))
4136 return true;
4137 return false;
4138}
4139
4140void LocalInstantiationScope::SetPartiallySubstitutedPack(NamedDecl *Pack,
4141 const TemplateArgument *ExplicitArgs,
4142 unsigned NumExplicitArgs) {
4143 assert((!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) &&(static_cast <bool> ((!PartiallySubstitutedPack || PartiallySubstitutedPack
== Pack) && "Already have a partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4144, __extension__
__PRETTY_FUNCTION__))
4144 "Already have a partially-substituted pack")(static_cast <bool> ((!PartiallySubstitutedPack || PartiallySubstitutedPack
== Pack) && "Already have a partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || PartiallySubstitutedPack == Pack) && \"Already have a partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4144, __extension__
__PRETTY_FUNCTION__))
;
4145 assert((!PartiallySubstitutedPack(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4147, __extension__
__PRETTY_FUNCTION__))
4146 || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) &&(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4147, __extension__
__PRETTY_FUNCTION__))
4147 "Wrong number of arguments in partially-substituted pack")(static_cast <bool> ((!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack
== NumExplicitArgs) && "Wrong number of arguments in partially-substituted pack"
) ? void (0) : __assert_fail ("(!PartiallySubstitutedPack || NumArgsInPartiallySubstitutedPack == NumExplicitArgs) && \"Wrong number of arguments in partially-substituted pack\""
, "clang/lib/Sema/SemaTemplateInstantiate.cpp", 4147, __extension__
__PRETTY_FUNCTION__))
;
4148 PartiallySubstitutedPack = Pack;
4149 ArgsInPartiallySubstitutedPack = ExplicitArgs;
4150 NumArgsInPartiallySubstitutedPack = NumExplicitArgs;
4151}
4152
4153NamedDecl *LocalInstantiationScope::getPartiallySubstitutedPack(
4154 const TemplateArgument **ExplicitArgs,
4155 unsigned *NumExplicitArgs) const {
4156 if (ExplicitArgs)
4157 *ExplicitArgs = nullptr;
4158 if (NumExplicitArgs)
4159 *NumExplicitArgs = 0;
4160
4161 for (const LocalInstantiationScope *Current = this; Current;
4162 Current = Current->Outer) {
4163 if (Current->PartiallySubstitutedPack) {
4164 if (ExplicitArgs)
4165 *ExplicitArgs = Current->ArgsInPartiallySubstitutedPack;
4166 if (NumExplicitArgs)
4167 *NumExplicitArgs = Current->NumArgsInPartiallySubstitutedPack;
4168
4169 return Current->PartiallySubstitutedPack;
4170 }
4171
4172 if (!Current->CombineWithOuterScope)
4173 break;
4174 }
4175
4176 return nullptr;
4177}

/build/source/clang/lib/Sema/TreeTransform.h

1//===------- TreeTransform.h - Semantic Tree Transformation -----*- C++ -*-===//
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 a semantic tree transformation that takes a given
9// AST and rebuilds it, possibly transforming some nodes in the process.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
14#define LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H
15
16#include "CoroutineStmtBuilder.h"
17#include "TypeLocBuilder.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/Expr.h"
22#include "clang/AST/ExprConcepts.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/ExprObjC.h"
25#include "clang/AST/ExprOpenMP.h"
26#include "clang/AST/OpenMPClause.h"
27#include "clang/AST/Stmt.h"
28#include "clang/AST/StmtCXX.h"
29#include "clang/AST/StmtObjC.h"
30#include "clang/AST/StmtOpenMP.h"
31#include "clang/Basic/DiagnosticParse.h"
32#include "clang/Basic/OpenMPKinds.h"
33#include "clang/Sema/Designator.h"
34#include "clang/Sema/Lookup.h"
35#include "clang/Sema/Ownership.h"
36#include "clang/Sema/ParsedTemplate.h"
37#include "clang/Sema/ScopeInfo.h"
38#include "clang/Sema/SemaDiagnostic.h"
39#include "clang/Sema/SemaInternal.h"
40#include "llvm/ADT/ArrayRef.h"
41#include "llvm/Support/ErrorHandling.h"
42#include <algorithm>
43#include <optional>
44
45using namespace llvm::omp;
46
47namespace clang {
48using namespace sema;
49
50/// A semantic tree transformation that allows one to transform one
51/// abstract syntax tree into another.
52///
53/// A new tree transformation is defined by creating a new subclass \c X of
54/// \c TreeTransform<X> and then overriding certain operations to provide
55/// behavior specific to that transformation. For example, template
56/// instantiation is implemented as a tree transformation where the
57/// transformation of TemplateTypeParmType nodes involves substituting the
58/// template arguments for their corresponding template parameters; a similar
59/// transformation is performed for non-type template parameters and
60/// template template parameters.
61///
62/// This tree-transformation template uses static polymorphism to allow
63/// subclasses to customize any of its operations. Thus, a subclass can
64/// override any of the transformation or rebuild operators by providing an
65/// operation with the same signature as the default implementation. The
66/// overriding function should not be virtual.
67///
68/// Semantic tree transformations are split into two stages, either of which
69/// can be replaced by a subclass. The "transform" step transforms an AST node
70/// or the parts of an AST node using the various transformation functions,
71/// then passes the pieces on to the "rebuild" step, which constructs a new AST
72/// node of the appropriate kind from the pieces. The default transformation
73/// routines recursively transform the operands to composite AST nodes (e.g.,
74/// the pointee type of a PointerType node) and, if any of those operand nodes
75/// were changed by the transformation, invokes the rebuild operation to create
76/// a new AST node.
77///
78/// Subclasses can customize the transformation at various levels. The
79/// most coarse-grained transformations involve replacing TransformType(),
80/// TransformExpr(), TransformDecl(), TransformNestedNameSpecifierLoc(),
81/// TransformTemplateName(), or TransformTemplateArgument() with entirely
82/// new implementations.
83///
84/// For more fine-grained transformations, subclasses can replace any of the
85/// \c TransformXXX functions (where XXX is the name of an AST node, e.g.,
86/// PointerType, StmtExpr) to alter the transformation. As mentioned previously,
87/// replacing TransformTemplateTypeParmType() allows template instantiation
88/// to substitute template arguments for their corresponding template
89/// parameters. Additionally, subclasses can override the \c RebuildXXX
90/// functions to control how AST nodes are rebuilt when their operands change.
91/// By default, \c TreeTransform will invoke semantic analysis to rebuild
92/// AST nodes. However, certain other tree transformations (e.g, cloning) may
93/// be able to use more efficient rebuild steps.
94///
95/// There are a handful of other functions that can be overridden, allowing one
96/// to avoid traversing nodes that don't need any transformation
97/// (\c AlreadyTransformed()), force rebuilding AST nodes even when their
98/// operands have not changed (\c AlwaysRebuild()), and customize the
99/// default locations and entity names used for type-checking
100/// (\c getBaseLocation(), \c getBaseEntity()).
101template<typename Derived>
102class TreeTransform {
103 /// Private RAII object that helps us forget and then re-remember
104 /// the template argument corresponding to a partially-substituted parameter
105 /// pack.
106 class ForgetPartiallySubstitutedPackRAII {
107 Derived &Self;
108 TemplateArgument Old;
109
110 public:
111 ForgetPartiallySubstitutedPackRAII(Derived &Self) : Self(Self) {
112 Old = Self.ForgetPartiallySubstitutedPack();
113 }
114
115 ~ForgetPartiallySubstitutedPackRAII() {
116 Self.RememberPartiallySubstitutedPack(Old);
117 }
118 };
119
120protected:
121 Sema &SemaRef;
122
123 /// The set of local declarations that have been transformed, for
124 /// cases where we are forced to build new declarations within the transformer
125 /// rather than in the subclass (e.g., lambda closure types).
126 llvm::DenseMap<Decl *, Decl *> TransformedLocalDecls;
127
128public:
129 /// Initializes a new tree transformer.
130 TreeTransform(Sema &SemaRef) : SemaRef(SemaRef) { }
131
132 /// Retrieves a reference to the derived class.
133 Derived &getDerived() { return static_cast<Derived&>(*this); }
134
135 /// Retrieves a reference to the derived class.
136 const Derived &getDerived() const {
137 return static_cast<const Derived&>(*this);
138 }
139
140 static inline ExprResult Owned(Expr *E) { return E; }
141 static inline StmtResult Owned(Stmt *S) { return S; }
142
143 /// Retrieves a reference to the semantic analysis object used for
144 /// this tree transform.
145 Sema &getSema() const { return SemaRef; }
146
147 /// Whether the transformation should always rebuild AST nodes, even
148 /// if none of the children have changed.
149 ///
150 /// Subclasses may override this function to specify when the transformation
151 /// should rebuild all AST nodes.
152 ///
153 /// We must always rebuild all AST nodes when performing variadic template
154 /// pack expansion, in order to avoid violating the AST invariant that each
155 /// statement node appears at most once in its containing declaration.
156 bool AlwaysRebuild() { return SemaRef.ArgumentPackSubstitutionIndex != -1; }
157
158 /// Whether the transformation is forming an expression or statement that
159 /// replaces the original. In this case, we'll reuse mangling numbers from
160 /// existing lambdas.
161 bool ReplacingOriginal() { return false; }
162
163 /// Wether CXXConstructExpr can be skipped when they are implicit.
164 /// They will be reconstructed when used if needed.
165 /// This is useful when the user that cause rebuilding of the
166 /// CXXConstructExpr is outside of the expression at which the TreeTransform
167 /// started.
168 bool AllowSkippingCXXConstructExpr() { return true; }
169
170 /// Returns the location of the entity being transformed, if that
171 /// information was not available elsewhere in the AST.
172 ///
173 /// By default, returns no source-location information. Subclasses can
174 /// provide an alternative implementation that provides better location
175 /// information.
176 SourceLocation getBaseLocation() { return SourceLocation(); }
177
178 /// Returns the name of the entity being transformed, if that
179 /// information was not available elsewhere in the AST.
180 ///
181 /// By default, returns an empty name. Subclasses can provide an alternative
182 /// implementation with a more precise name.
183 DeclarationName getBaseEntity() { return DeclarationName(); }
184
185 /// Sets the "base" location and entity when that
186 /// information is known based on another transformation.
187 ///
188 /// By default, the source location and entity are ignored. Subclasses can
189 /// override this function to provide a customized implementation.
190 void setBase(SourceLocation Loc, DeclarationName Entity) { }
191
192 /// RAII object that temporarily sets the base location and entity
193 /// used for reporting diagnostics in types.
194 class TemporaryBase {
195 TreeTransform &Self;
196 SourceLocation OldLocation;
197 DeclarationName OldEntity;
198
199 public:
200 TemporaryBase(TreeTransform &Self, SourceLocation Location,
201 DeclarationName Entity) : Self(Self) {
202 OldLocation = Self.getDerived().getBaseLocation();
203 OldEntity = Self.getDerived().getBaseEntity();
204
205 if (Location.isValid())
206 Self.getDerived().setBase(Location, Entity);
207 }
208
209 ~TemporaryBase() {
210 Self.getDerived().setBase(OldLocation, OldEntity);
211 }
212 };
213
214 /// Determine whether the given type \p T has already been
215 /// transformed.
216 ///
217 /// Subclasses can provide an alternative implementation of this routine
218 /// to short-circuit evaluation when it is known that a given type will
219 /// not change. For example, template instantiation need not traverse
220 /// non-dependent types.
221 bool AlreadyTransformed(QualType T) {
222 return T.isNull();
223 }
224
225 /// Transform a template parameter depth level.
226 ///
227 /// During a transformation that transforms template parameters, this maps
228 /// an old template parameter depth to a new depth.
229 unsigned TransformTemplateDepth(unsigned Depth) {
230 return Depth;
231 }
232
233 /// Determine whether the given call argument should be dropped, e.g.,
234 /// because it is a default argument.
235 ///
236 /// Subclasses can provide an alternative implementation of this routine to
237 /// determine which kinds of call arguments get dropped. By default,
238 /// CXXDefaultArgument nodes are dropped (prior to transformation).
239 bool DropCallArgument(Expr *E) {
240 return E->isDefaultArgument();
241 }
242
243 /// Determine whether we should expand a pack expansion with the
244 /// given set of parameter packs into separate arguments by repeatedly
245 /// transforming the pattern.
246 ///
247 /// By default, the transformer never tries to expand pack expansions.
248 /// Subclasses can override this routine to provide different behavior.
249 ///
250 /// \param EllipsisLoc The location of the ellipsis that identifies the
251 /// pack expansion.
252 ///
253 /// \param PatternRange The source range that covers the entire pattern of
254 /// the pack expansion.
255 ///
256 /// \param Unexpanded The set of unexpanded parameter packs within the
257 /// pattern.
258 ///
259 /// \param ShouldExpand Will be set to \c true if the transformer should
260 /// expand the corresponding pack expansions into separate arguments. When
261 /// set, \c NumExpansions must also be set.
262 ///
263 /// \param RetainExpansion Whether the caller should add an unexpanded
264 /// pack expansion after all of the expanded arguments. This is used
265 /// when extending explicitly-specified template argument packs per
266 /// C++0x [temp.arg.explicit]p9.
267 ///
268 /// \param NumExpansions The number of separate arguments that will be in
269 /// the expanded form of the corresponding pack expansion. This is both an
270 /// input and an output parameter, which can be set by the caller if the
271 /// number of expansions is known a priori (e.g., due to a prior substitution)
272 /// and will be set by the callee when the number of expansions is known.
273 /// The callee must set this value when \c ShouldExpand is \c true; it may
274 /// set this value in other cases.
275 ///
276 /// \returns true if an error occurred (e.g., because the parameter packs
277 /// are to be instantiated with arguments of different lengths), false
278 /// otherwise. If false, \c ShouldExpand (and possibly \c NumExpansions)
279 /// must be set.
280 bool TryExpandParameterPacks(SourceLocation EllipsisLoc,
281 SourceRange PatternRange,
282 ArrayRef<UnexpandedParameterPack> Unexpanded,
283 bool &ShouldExpand, bool &RetainExpansion,
284 std::optional<unsigned> &NumExpansions) {
285 ShouldExpand = false;
286 return false;
287 }
288
289 /// "Forget" about the partially-substituted pack template argument,
290 /// when performing an instantiation that must preserve the parameter pack
291 /// use.
292 ///
293 /// This routine is meant to be overridden by the template instantiator.
294 TemplateArgument ForgetPartiallySubstitutedPack() {
295 return TemplateArgument();
296 }
297
298 /// "Remember" the partially-substituted pack template argument
299 /// after performing an instantiation that must preserve the parameter pack
300 /// use.
301 ///
302 /// This routine is meant to be overridden by the template instantiator.
303 void RememberPartiallySubstitutedPack(TemplateArgument Arg) { }
304
305 /// Note to the derived class when a function parameter pack is
306 /// being expanded.
307 void ExpandingFunctionParameterPack(ParmVarDecl *Pack) { }
308
309 /// Transforms the given type into another type.
310 ///
311 /// By default, this routine transforms a type by creating a
312 /// TypeSourceInfo for it and delegating to the appropriate
313 /// function. This is expensive, but we don't mind, because
314 /// this method is deprecated anyway; all users should be
315 /// switched to storing TypeSourceInfos.
316 ///
317 /// \returns the transformed type.
318 QualType TransformType(QualType T);
319
320 /// Transforms the given type-with-location into a new
321 /// type-with-location.
322 ///
323 /// By default, this routine transforms a type by delegating to the
324 /// appropriate TransformXXXType to build a new type. Subclasses
325 /// may override this function (to take over all type
326 /// transformations) or some set of the TransformXXXType functions
327 /// to alter the transformation.
328 TypeSourceInfo *TransformType(TypeSourceInfo *DI);
329
330 /// Transform the given type-with-location into a new
331 /// type, collecting location information in the given builder
332 /// as necessary.
333 ///
334 QualType TransformType(TypeLocBuilder &TLB, TypeLoc TL);
335
336 /// Transform a type that is permitted to produce a
337 /// DeducedTemplateSpecializationType.
338 ///
339 /// This is used in the (relatively rare) contexts where it is acceptable
340 /// for transformation to produce a class template type with deduced
341 /// template arguments.
342 /// @{
343 QualType TransformTypeWithDeducedTST(QualType T);
344 TypeSourceInfo *TransformTypeWithDeducedTST(TypeSourceInfo *DI);
345 /// @}
346
347 /// The reason why the value of a statement is not discarded, if any.
348 enum StmtDiscardKind {
349 SDK_Discarded,
350 SDK_NotDiscarded,
351 SDK_StmtExprResult,
352 };
353
354 /// Transform the given statement.
355 ///
356 /// By default, this routine transforms a statement by delegating to the
357 /// appropriate TransformXXXStmt function to transform a specific kind of
358 /// statement or the TransformExpr() function to transform an expression.
359 /// Subclasses may override this function to transform statements using some
360 /// other mechanism.
361 ///
362 /// \returns the transformed statement.
363 StmtResult TransformStmt(Stmt *S, StmtDiscardKind SDK = SDK_Discarded);
364
365 /// Transform the given statement.
366 ///
367 /// By default, this routine transforms a statement by delegating to the
368 /// appropriate TransformOMPXXXClause function to transform a specific kind
369 /// of clause. Subclasses may override this function to transform statements
370 /// using some other mechanism.
371 ///
372 /// \returns the transformed OpenMP clause.
373 OMPClause *TransformOMPClause(OMPClause *S);
374
375 /// Transform the given attribute.
376 ///
377 /// By default, this routine transforms a statement by delegating to the
378 /// appropriate TransformXXXAttr function to transform a specific kind
379 /// of attribute. Subclasses may override this function to transform
380 /// attributed statements/types using some other mechanism.
381 ///
382 /// \returns the transformed attribute
383 const Attr *TransformAttr(const Attr *S);
384
385 // Transform the given statement attribute.
386 //
387 // Delegates to the appropriate TransformXXXAttr function to transform a
388 // specific kind of statement attribute. Unlike the non-statement taking
389 // version of this, this implements all attributes, not just pragmas.
390 const Attr *TransformStmtAttr(const Stmt *OrigS, const Stmt *InstS,
391 const Attr *A);
392
393 // Transform the specified attribute.
394 //
395 // Subclasses should override the transformation of attributes with a pragma
396 // spelling to transform expressions stored within the attribute.
397 //
398 // \returns the transformed attribute.
399#define ATTR(X) \
400 const X##Attr *Transform##X##Attr(const X##Attr *R) { return R; }
401#include "clang/Basic/AttrList.inc"
402
403 // Transform the specified attribute.
404 //
405 // Subclasses should override the transformation of attributes to do
406 // transformation and checking of statement attributes. By default, this
407 // delegates to the non-statement taking version.
408 //
409 // \returns the transformed attribute.
410#define ATTR(X) \
411 const X##Attr *TransformStmt##X##Attr(const Stmt *, const Stmt *, \
412 const X##Attr *A) { \
413 return getDerived().Transform##X##Attr(A); \
414 }
415#include "clang/Basic/AttrList.inc"
416
417 /// Transform the given expression.
418 ///
419 /// By default, this routine transforms an expression by delegating to the
420 /// appropriate TransformXXXExpr function to build a new expression.
421 /// Subclasses may override this function to transform expressions using some
422 /// other mechanism.
423 ///
424 /// \returns the transformed expression.
425 ExprResult TransformExpr(Expr *E);
426
427 /// Transform the given initializer.
428 ///
429 /// By default, this routine transforms an initializer by stripping off the
430 /// semantic nodes added by initialization, then passing the result to
431 /// TransformExpr or TransformExprs.
432 ///
433 /// \returns the transformed initializer.
434 ExprResult TransformInitializer(Expr *Init, bool NotCopyInit);
435
436 /// Transform the given list of expressions.
437 ///
438 /// This routine transforms a list of expressions by invoking
439 /// \c TransformExpr() for each subexpression. However, it also provides
440 /// support for variadic templates by expanding any pack expansions (if the
441 /// derived class permits such expansion) along the way. When pack expansions
442 /// are present, the number of outputs may not equal the number of inputs.
443 ///
444 /// \param Inputs The set of expressions to be transformed.
445 ///
446 /// \param NumInputs The number of expressions in \c Inputs.
447 ///
448 /// \param IsCall If \c true, then this transform is being performed on
449 /// function-call arguments, and any arguments that should be dropped, will
450 /// be.
451 ///
452 /// \param Outputs The transformed input expressions will be added to this
453 /// vector.
454 ///
455 /// \param ArgChanged If non-NULL, will be set \c true if any argument changed
456 /// due to transformation.
457 ///
458 /// \returns true if an error occurred, false otherwise.
459 bool TransformExprs(Expr *const *Inputs, unsigned NumInputs, bool IsCall,
460 SmallVectorImpl<Expr *> &Outputs,
461 bool *ArgChanged = nullptr);
462
463 /// Transform the given declaration, which is referenced from a type
464 /// or expression.
465 ///
466 /// By default, acts as the identity function on declarations, unless the
467 /// transformer has had to transform the declaration itself. Subclasses
468 /// may override this function to provide alternate behavior.
469 Decl *TransformDecl(SourceLocation Loc, Decl *D) {
470 llvm::DenseMap<Decl *, Decl *>::iterator Known
471 = TransformedLocalDecls.find(D);
472 if (Known != TransformedLocalDecls.end())
473 return Known->second;
474
475 return D;
476 }
477
478 /// Transform the specified condition.
479 ///
480 /// By default, this transforms the variable and expression and rebuilds
481 /// the condition.
482 Sema::ConditionResult TransformCondition(SourceLocation Loc, VarDecl *Var,
483 Expr *Expr,
484 Sema::ConditionKind Kind);
485
486 /// Transform the attributes associated with the given declaration and
487 /// place them on the new declaration.
488 ///
489 /// By default, this operation does nothing. Subclasses may override this
490 /// behavior to transform attributes.
491 void transformAttrs(Decl *Old, Decl *New) { }
492
493 /// Note that a local declaration has been transformed by this
494 /// transformer.
495 ///
496 /// Local declarations are typically transformed via a call to
497 /// TransformDefinition. However, in some cases (e.g., lambda expressions),
498 /// the transformer itself has to transform the declarations. This routine
499 /// can be overridden by a subclass that keeps track of such mappings.
500 void transformedLocalDecl(Decl *Old, ArrayRef<Decl *> New) {
501 assert(New.size() == 1 &&(static_cast <bool> (New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? void (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 502, __extension__ __PRETTY_FUNCTION__
))
502 "must override transformedLocalDecl if performing pack expansion")(static_cast <bool> (New.size() == 1 && "must override transformedLocalDecl if performing pack expansion"
) ? void (0) : __assert_fail ("New.size() == 1 && \"must override transformedLocalDecl if performing pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 502, __extension__ __PRETTY_FUNCTION__
))
;
503 TransformedLocalDecls[Old] = New.front();
504 }
505
506 /// Transform the definition of the given declaration.
507 ///
508 /// By default, invokes TransformDecl() to transform the declaration.
509 /// Subclasses may override this function to provide alternate behavior.
510 Decl *TransformDefinition(SourceLocation Loc, Decl *D) {
511 return getDerived().TransformDecl(Loc, D);
512 }
513
514 /// Transform the given declaration, which was the first part of a
515 /// nested-name-specifier in a member access expression.
516 ///
517 /// This specific declaration transformation only applies to the first
518 /// identifier in a nested-name-specifier of a member access expression, e.g.,
519 /// the \c T in \c x->T::member
520 ///
521 /// By default, invokes TransformDecl() to transform the declaration.
522 /// Subclasses may override this function to provide alternate behavior.
523 NamedDecl *TransformFirstQualifierInScope(NamedDecl *D, SourceLocation Loc) {
524 return cast_or_null<NamedDecl>(getDerived().TransformDecl(Loc, D));
525 }
526
527 /// Transform the set of declarations in an OverloadExpr.
528 bool TransformOverloadExprDecls(OverloadExpr *Old, bool RequiresADL,
529 LookupResult &R);
530
531 /// Transform the given nested-name-specifier with source-location
532 /// information.
533 ///
534 /// By default, transforms all of the types and declarations within the
535 /// nested-name-specifier. Subclasses may override this function to provide
536 /// alternate behavior.
537 NestedNameSpecifierLoc
538 TransformNestedNameSpecifierLoc(NestedNameSpecifierLoc NNS,
539 QualType ObjectType = QualType(),
540 NamedDecl *FirstQualifierInScope = nullptr);
541
542 /// Transform the given declaration name.
543 ///
544 /// By default, transforms the types of conversion function, constructor,
545 /// and destructor names and then (if needed) rebuilds the declaration name.
546 /// Identifiers and selectors are returned unmodified. Subclasses may
547 /// override this function to provide alternate behavior.
548 DeclarationNameInfo
549 TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo);
550
551 bool TransformRequiresExprRequirements(ArrayRef<concepts::Requirement *> Reqs,
552 llvm::SmallVectorImpl<concepts::Requirement *> &Transformed);
553 concepts::TypeRequirement *
554 TransformTypeRequirement(concepts::TypeRequirement *Req);
555 concepts::ExprRequirement *
556 TransformExprRequirement(concepts::ExprRequirement *Req);
557 concepts::NestedRequirement *
558 TransformNestedRequirement(concepts::NestedRequirement *Req);
559
560 /// Transform the given template name.
561 ///
562 /// \param SS The nested-name-specifier that qualifies the template
563 /// name. This nested-name-specifier must already have been transformed.
564 ///
565 /// \param Name The template name to transform.
566 ///
567 /// \param NameLoc The source location of the template name.
568 ///
569 /// \param ObjectType If we're translating a template name within a member
570 /// access expression, this is the type of the object whose member template
571 /// is being referenced.
572 ///
573 /// \param FirstQualifierInScope If the first part of a nested-name-specifier
574 /// also refers to a name within the current (lexical) scope, this is the
575 /// declaration it refers to.
576 ///
577 /// By default, transforms the template name by transforming the declarations
578 /// and nested-name-specifiers that occur within the template name.
579 /// Subclasses may override this function to provide alternate behavior.
580 TemplateName
581 TransformTemplateName(CXXScopeSpec &SS, TemplateName Name,
582 SourceLocation NameLoc,
583 QualType ObjectType = QualType(),
584 NamedDecl *FirstQualifierInScope = nullptr,
585 bool AllowInjectedClassName = false);
586
587 /// Transform the given template argument.
588 ///
589 /// By default, this operation transforms the type, expression, or
590 /// declaration stored within the template argument and constructs a
591 /// new template argument from the transformed result. Subclasses may
592 /// override this function to provide alternate behavior.
593 ///
594 /// Returns true if there was an error.
595 bool TransformTemplateArgument(const TemplateArgumentLoc &Input,
596 TemplateArgumentLoc &Output,
597 bool Uneval = false);
598
599 /// Transform the given set of template arguments.
600 ///
601 /// By default, this operation transforms all of the template arguments
602 /// in the input set using \c TransformTemplateArgument(), and appends
603 /// the transformed arguments to the output list.
604 ///
605 /// Note that this overload of \c TransformTemplateArguments() is merely
606 /// a convenience function. Subclasses that wish to override this behavior
607 /// should override the iterator-based member template version.
608 ///
609 /// \param Inputs The set of template arguments to be transformed.
610 ///
611 /// \param NumInputs The number of template arguments in \p Inputs.
612 ///
613 /// \param Outputs The set of transformed template arguments output by this
614 /// routine.
615 ///
616 /// Returns true if an error occurred.
617 bool TransformTemplateArguments(const TemplateArgumentLoc *Inputs,
618 unsigned NumInputs,
619 TemplateArgumentListInfo &Outputs,
620 bool Uneval = false) {
621 return TransformTemplateArguments(Inputs, Inputs + NumInputs, Outputs,
622 Uneval);
623 }
624
625 /// Transform the given set of template arguments.
626 ///
627 /// By default, this operation transforms all of the template arguments
628 /// in the input set using \c TransformTemplateArgument(), and appends
629 /// the transformed arguments to the output list.
630 ///
631 /// \param First An iterator to the first template argument.
632 ///
633 /// \param Last An iterator one step past the last template argument.
634 ///
635 /// \param Outputs The set of transformed template arguments output by this
636 /// routine.
637 ///
638 /// Returns true if an error occurred.
639 template<typename InputIterator>
640 bool TransformTemplateArguments(InputIterator First,
641 InputIterator Last,
642 TemplateArgumentListInfo &Outputs,
643 bool Uneval = false);
644
645 /// Fakes up a TemplateArgumentLoc for a given TemplateArgument.
646 void InventTemplateArgumentLoc(const TemplateArgument &Arg,
647 TemplateArgumentLoc &ArgLoc);
648
649 /// Fakes up a TypeSourceInfo for a type.
650 TypeSourceInfo *InventTypeSourceInfo(QualType T) {
651 return SemaRef.Context.getTrivialTypeSourceInfo(T,
652 getDerived().getBaseLocation());
653 }
654
655#define ABSTRACT_TYPELOC(CLASS, PARENT)
656#define TYPELOC(CLASS, PARENT) \
657 QualType Transform##CLASS##Type(TypeLocBuilder &TLB, CLASS##TypeLoc T);
658#include "clang/AST/TypeLocNodes.def"
659
660 QualType TransformTemplateTypeParmType(TypeLocBuilder &TLB,
661 TemplateTypeParmTypeLoc TL,
662 bool SuppressObjCLifetime);
663 QualType
664 TransformSubstTemplateTypeParmPackType(TypeLocBuilder &TLB,
665 SubstTemplateTypeParmPackTypeLoc TL,
666 bool SuppressObjCLifetime);
667
668 template<typename Fn>
669 QualType TransformFunctionProtoType(TypeLocBuilder &TLB,
670 FunctionProtoTypeLoc TL,
671 CXXRecordDecl *ThisContext,
672 Qualifiers ThisTypeQuals,
673 Fn TransformExceptionSpec);
674
675 bool TransformExceptionSpec(SourceLocation Loc,
676 FunctionProtoType::ExceptionSpecInfo &ESI,
677 SmallVectorImpl<QualType> &Exceptions,
678 bool &Changed);
679
680 StmtResult TransformSEHHandler(Stmt *Handler);
681
682 QualType
683 TransformTemplateSpecializationType(TypeLocBuilder &TLB,
684 TemplateSpecializationTypeLoc TL,
685 TemplateName Template);
686
687 QualType
688 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
689 DependentTemplateSpecializationTypeLoc TL,
690 TemplateName Template,
691 CXXScopeSpec &SS);
692
693 QualType TransformDependentTemplateSpecializationType(
694 TypeLocBuilder &TLB, DependentTemplateSpecializationTypeLoc TL,
695 NestedNameSpecifierLoc QualifierLoc);
696
697 /// Transforms the parameters of a function type into the
698 /// given vectors.
699 ///
700 /// The result vectors should be kept in sync; null entries in the
701 /// variables vector are acceptable.
702 ///
703 /// LastParamTransformed, if non-null, will be set to the index of the last
704 /// parameter on which transfromation was started. In the event of an error,
705 /// this will contain the parameter which failed to instantiate.
706 ///
707 /// Return true on error.
708 bool TransformFunctionTypeParams(
709 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
710 const QualType *ParamTypes,
711 const FunctionProtoType::ExtParameterInfo *ParamInfos,
712 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
713 Sema::ExtParameterInfoBuilder &PInfos, unsigned *LastParamTransformed);
714
715 bool TransformFunctionTypeParams(
716 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
717 const QualType *ParamTypes,
718 const FunctionProtoType::ExtParameterInfo *ParamInfos,
719 SmallVectorImpl<QualType> &PTypes, SmallVectorImpl<ParmVarDecl *> *PVars,
720 Sema::ExtParameterInfoBuilder &PInfos) {
721 return getDerived().TransformFunctionTypeParams(
722 Loc, Params, ParamTypes, ParamInfos, PTypes, PVars, PInfos, nullptr);
723 }
724
725 /// Transforms the parameters of a requires expresison into the given vectors.
726 ///
727 /// The result vectors should be kept in sync; null entries in the
728 /// variables vector are acceptable.
729 ///
730 /// Returns an unset ExprResult on success. Returns an ExprResult the 'not
731 /// satisfied' RequiresExpr if subsitution failed, OR an ExprError, both of
732 /// which are cases where transformation shouldn't continue.
733 ExprResult TransformRequiresTypeParams(
734 SourceLocation KWLoc, SourceLocation RBraceLoc, const RequiresExpr *RE,
735 RequiresExprBodyDecl *Body, ArrayRef<ParmVarDecl *> Params,
736 SmallVectorImpl<QualType> &PTypes,
737 SmallVectorImpl<ParmVarDecl *> &TransParams,
738 Sema::ExtParameterInfoBuilder &PInfos) {
739 if (getDerived().TransformFunctionTypeParams(
740 KWLoc, Params, /*ParamTypes=*/nullptr,
741 /*ParamInfos=*/nullptr, PTypes, &TransParams, PInfos))
742 return ExprError();
743
744 return ExprResult{};
745 }
746
747 /// Transforms a single function-type parameter. Return null
748 /// on error.
749 ///
750 /// \param indexAdjustment - A number to add to the parameter's
751 /// scope index; can be negative
752 ParmVarDecl *TransformFunctionTypeParam(ParmVarDecl *OldParm,
753 int indexAdjustment,
754 std::optional<unsigned> NumExpansions,
755 bool ExpectParameterPack);
756
757 /// Transform the body of a lambda-expression.
758 StmtResult TransformLambdaBody(LambdaExpr *E, Stmt *Body);
759 /// Alternative implementation of TransformLambdaBody that skips transforming
760 /// the body.
761 StmtResult SkipLambdaBody(LambdaExpr *E, Stmt *Body);
762
763 QualType TransformReferenceType(TypeLocBuilder &TLB, ReferenceTypeLoc TL);
764
765 StmtResult TransformCompoundStmt(CompoundStmt *S, bool IsStmtExpr);
766 ExprResult TransformCXXNamedCastExpr(CXXNamedCastExpr *E);
767
768 TemplateParameterList *TransformTemplateParameterList(
769 TemplateParameterList *TPL) {
770 return TPL;
771 }
772
773 ExprResult TransformAddressOfOperand(Expr *E);
774
775 ExprResult TransformDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E,
776 bool IsAddressOfOperand,
777 TypeSourceInfo **RecoveryTSI);
778
779 ExprResult TransformParenDependentScopeDeclRefExpr(
780 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool IsAddressOfOperand,
781 TypeSourceInfo **RecoveryTSI);
782
783 StmtResult TransformOMPExecutableDirective(OMPExecutableDirective *S);
784
785// FIXME: We use LLVM_ATTRIBUTE_NOINLINE because inlining causes a ridiculous
786// amount of stack usage with clang.
787#define STMT(Node, Parent) \
788 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
789 StmtResult Transform##Node(Node *S);
790#define VALUESTMT(Node, Parent) \
791 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
792 StmtResult Transform##Node(Node *S, StmtDiscardKind SDK);
793#define EXPR(Node, Parent) \
794 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
795 ExprResult Transform##Node(Node *E);
796#define ABSTRACT_STMT(Stmt)
797#include "clang/AST/StmtNodes.inc"
798
799#define GEN_CLANG_CLAUSE_CLASS
800#define CLAUSE_CLASS(Enum, Str, Class) \
801 LLVM_ATTRIBUTE_NOINLINE__attribute__((noinline)) \
802 OMPClause *Transform##Class(Class *S);
803#include "llvm/Frontend/OpenMP/OMP.inc"
804
805 /// Build a new qualified type given its unqualified type and type location.
806 ///
807 /// By default, this routine adds type qualifiers only to types that can
808 /// have qualifiers, and silently suppresses those qualifiers that are not
809 /// permitted. Subclasses may override this routine to provide different
810 /// behavior.
811 QualType RebuildQualifiedType(QualType T, QualifiedTypeLoc TL);
812
813 /// Build a new pointer type given its pointee type.
814 ///
815 /// By default, performs semantic analysis when building the pointer type.
816 /// Subclasses may override this routine to provide different behavior.
817 QualType RebuildPointerType(QualType PointeeType, SourceLocation Sigil);
818
819 /// Build a new block pointer type given its pointee type.
820 ///
821 /// By default, performs semantic analysis when building the block pointer
822 /// type. Subclasses may override this routine to provide different behavior.
823 QualType RebuildBlockPointerType(QualType PointeeType, SourceLocation Sigil);
824
825 /// Build a new reference type given the type it references.
826 ///
827 /// By default, performs semantic analysis when building the
828 /// reference type. Subclasses may override this routine to provide
829 /// different behavior.
830 ///
831 /// \param LValue whether the type was written with an lvalue sigil
832 /// or an rvalue sigil.
833 QualType RebuildReferenceType(QualType ReferentType,
834 bool LValue,
835 SourceLocation Sigil);
836
837 /// Build a new member pointer type given the pointee type and the
838 /// class type it refers into.
839 ///
840 /// By default, performs semantic analysis when building the member pointer
841 /// type. Subclasses may override this routine to provide different behavior.
842 QualType RebuildMemberPointerType(QualType PointeeType, QualType ClassType,
843 SourceLocation Sigil);
844
845 QualType RebuildObjCTypeParamType(const ObjCTypeParamDecl *Decl,
846 SourceLocation ProtocolLAngleLoc,
847 ArrayRef<ObjCProtocolDecl *> Protocols,
848 ArrayRef<SourceLocation> ProtocolLocs,
849 SourceLocation ProtocolRAngleLoc);
850
851 /// Build an Objective-C object type.
852 ///
853 /// By default, performs semantic analysis when building the object type.
854 /// Subclasses may override this routine to provide different behavior.
855 QualType RebuildObjCObjectType(QualType BaseType,
856 SourceLocation Loc,
857 SourceLocation TypeArgsLAngleLoc,
858 ArrayRef<TypeSourceInfo *> TypeArgs,
859 SourceLocation TypeArgsRAngleLoc,
860 SourceLocation ProtocolLAngleLoc,
861 ArrayRef<ObjCProtocolDecl *> Protocols,
862 ArrayRef<SourceLocation> ProtocolLocs,
863 SourceLocation ProtocolRAngleLoc);
864
865 /// Build a new Objective-C object pointer type given the pointee type.
866 ///
867 /// By default, directly builds the pointer type, with no additional semantic
868 /// analysis.
869 QualType RebuildObjCObjectPointerType(QualType PointeeType,
870 SourceLocation Star);
871
872 /// Build a new array type given the element type, size
873 /// modifier, size of the array (if known), size expression, and index type
874 /// qualifiers.
875 ///
876 /// By default, performs semantic analysis when building the array type.
877 /// Subclasses may override this routine to provide different behavior.
878 /// Also by default, all of the other Rebuild*Array
879 QualType RebuildArrayType(QualType ElementType,
880 ArrayType::ArraySizeModifier SizeMod,
881 const llvm::APInt *Size,
882 Expr *SizeExpr,
883 unsigned IndexTypeQuals,
884 SourceRange BracketsRange);
885
886 /// Build a new constant array type given the element type, size
887 /// modifier, (known) size of the array, and index type qualifiers.
888 ///
889 /// By default, performs semantic analysis when building the array type.
890 /// Subclasses may override this routine to provide different behavior.
891 QualType RebuildConstantArrayType(QualType ElementType,
892 ArrayType::ArraySizeModifier SizeMod,
893 const llvm::APInt &Size,
894 Expr *SizeExpr,
895 unsigned IndexTypeQuals,
896 SourceRange BracketsRange);
897
898 /// Build a new incomplete array type given the element type, size
899 /// modifier, and index type qualifiers.
900 ///
901 /// By default, performs semantic analysis when building the array type.
902 /// Subclasses may override this routine to provide different behavior.
903 QualType RebuildIncompleteArrayType(QualType ElementType,
904 ArrayType::ArraySizeModifier SizeMod,
905 unsigned IndexTypeQuals,
906 SourceRange BracketsRange);
907
908 /// Build a new variable-length array type given the element type,
909 /// size modifier, size expression, and index type qualifiers.
910 ///
911 /// By default, performs semantic analysis when building the array type.
912 /// Subclasses may override this routine to provide different behavior.
913 QualType RebuildVariableArrayType(QualType ElementType,
914 ArrayType::ArraySizeModifier SizeMod,
915 Expr *SizeExpr,
916 unsigned IndexTypeQuals,
917 SourceRange BracketsRange);
918
919 /// Build a new dependent-sized array type given the element type,
920 /// size modifier, size expression, and index type qualifiers.
921 ///
922 /// By default, performs semantic analysis when building the array type.
923 /// Subclasses may override this routine to provide different behavior.
924 QualType RebuildDependentSizedArrayType(QualType ElementType,
925 ArrayType::ArraySizeModifier SizeMod,
926 Expr *SizeExpr,
927 unsigned IndexTypeQuals,
928 SourceRange BracketsRange);
929
930 /// Build a new vector type given the element type and
931 /// number of elements.
932 ///
933 /// By default, performs semantic analysis when building the vector type.
934 /// Subclasses may override this routine to provide different behavior.
935 QualType RebuildVectorType(QualType ElementType, unsigned NumElements,
936 VectorType::VectorKind VecKind);
937
938 /// Build a new potentially dependently-sized extended vector type
939 /// given the element type and number of elements.
940 ///
941 /// By default, performs semantic analysis when building the vector type.
942 /// Subclasses may override this routine to provide different behavior.
943 QualType RebuildDependentVectorType(QualType ElementType, Expr *SizeExpr,
944 SourceLocation AttributeLoc,
945 VectorType::VectorKind);
946
947 /// Build a new extended vector type given the element type and
948 /// number of elements.
949 ///
950 /// By default, performs semantic analysis when building the vector type.
951 /// Subclasses may override this routine to provide different behavior.
952 QualType RebuildExtVectorType(QualType ElementType, unsigned NumElements,
953 SourceLocation AttributeLoc);
954
955 /// Build a new potentially dependently-sized extended vector type
956 /// given the element type and number of elements.
957 ///
958 /// By default, performs semantic analysis when building the vector type.
959 /// Subclasses may override this routine to provide different behavior.
960 QualType RebuildDependentSizedExtVectorType(QualType ElementType,
961 Expr *SizeExpr,
962 SourceLocation AttributeLoc);
963
964 /// Build a new matrix type given the element type and dimensions.
965 QualType RebuildConstantMatrixType(QualType ElementType, unsigned NumRows,
966 unsigned NumColumns);
967
968 /// Build a new matrix type given the type and dependently-defined
969 /// dimensions.
970 QualType RebuildDependentSizedMatrixType(QualType ElementType, Expr *RowExpr,
971 Expr *ColumnExpr,
972 SourceLocation AttributeLoc);
973
974 /// Build a new DependentAddressSpaceType or return the pointee
975 /// type variable with the correct address space (retrieved from
976 /// AddrSpaceExpr) applied to it. The former will be returned in cases
977 /// where the address space remains dependent.
978 ///
979 /// By default, performs semantic analysis when building the type with address
980 /// space applied. Subclasses may override this routine to provide different
981 /// behavior.
982 QualType RebuildDependentAddressSpaceType(QualType PointeeType,
983 Expr *AddrSpaceExpr,
984 SourceLocation AttributeLoc);
985
986 /// Build a new function type.
987 ///
988 /// By default, performs semantic analysis when building the function type.
989 /// Subclasses may override this routine to provide different behavior.
990 QualType RebuildFunctionProtoType(QualType T,
991 MutableArrayRef<QualType> ParamTypes,
992 const FunctionProtoType::ExtProtoInfo &EPI);
993
994 /// Build a new unprototyped function type.
995 QualType RebuildFunctionNoProtoType(QualType ResultType);
996
997 /// Rebuild an unresolved typename type, given the decl that
998 /// the UnresolvedUsingTypenameDecl was transformed to.
999 QualType RebuildUnresolvedUsingType(SourceLocation NameLoc, Decl *D);
1000
1001 /// Build a new type found via an alias.
1002 QualType RebuildUsingType(UsingShadowDecl *Found, QualType Underlying) {
1003 return SemaRef.Context.getUsingType(Found, Underlying);
1004 }
1005
1006 /// Build a new typedef type.
1007 QualType RebuildTypedefType(TypedefNameDecl *Typedef) {
1008 return SemaRef.Context.getTypeDeclType(Typedef);
1009 }
1010
1011 /// Build a new MacroDefined type.
1012 QualType RebuildMacroQualifiedType(QualType T,
1013 const IdentifierInfo *MacroII) {
1014 return SemaRef.Context.getMacroQualifiedType(T, MacroII);
1015 }
1016
1017 /// Build a new class/struct/union type.
1018 QualType RebuildRecordType(RecordDecl *Record) {
1019 return SemaRef.Context.getTypeDeclType(Record);
1020 }
1021
1022 /// Build a new Enum type.
1023 QualType RebuildEnumType(EnumDecl *Enum) {
1024 return SemaRef.Context.getTypeDeclType(Enum);
1025 }
1026
1027 /// Build a new typeof(expr) type.
1028 ///
1029 /// By default, performs semantic analysis when building the typeof type.
1030 /// Subclasses may override this routine to provide different behavior.
1031 QualType RebuildTypeOfExprType(Expr *Underlying, SourceLocation Loc,
1032 TypeOfKind Kind);
1033
1034 /// Build a new typeof(type) type.
1035 ///
1036 /// By default, builds a new TypeOfType with the given underlying type.
1037 QualType RebuildTypeOfType(QualType Underlying, TypeOfKind Kind);
1038
1039 /// Build a new unary transform type.
1040 QualType RebuildUnaryTransformType(QualType BaseType,
1041 UnaryTransformType::UTTKind UKind,
1042 SourceLocation Loc);
1043
1044 /// Build a new C++11 decltype type.
1045 ///
1046 /// By default, performs semantic analysis when building the decltype type.
1047 /// Subclasses may override this routine to provide different behavior.
1048 QualType RebuildDecltypeType(Expr *Underlying, SourceLocation Loc);
1049
1050 /// Build a new C++11 auto type.
1051 ///
1052 /// By default, builds a new AutoType with the given deduced type.
1053 QualType RebuildAutoType(QualType Deduced, AutoTypeKeyword Keyword,
1054 ConceptDecl *TypeConstraintConcept,
1055 ArrayRef<TemplateArgument> TypeConstraintArgs) {
1056 // Note, IsDependent is always false here: we implicitly convert an 'auto'
1057 // which has been deduced to a dependent type into an undeduced 'auto', so
1058 // that we'll retry deduction after the transformation.
1059 return SemaRef.Context.getAutoType(Deduced, Keyword,
1060 /*IsDependent*/ false, /*IsPack=*/false,
1061 TypeConstraintConcept,
1062 TypeConstraintArgs);
1063 }
1064
1065 /// By default, builds a new DeducedTemplateSpecializationType with the given
1066 /// deduced type.
1067 QualType RebuildDeducedTemplateSpecializationType(TemplateName Template,
1068 QualType Deduced) {
1069 return SemaRef.Context.getDeducedTemplateSpecializationType(
1070 Template, Deduced, /*IsDependent*/ false);
1071 }
1072
1073 /// Build a new template specialization type.
1074 ///
1075 /// By default, performs semantic analysis when building the template
1076 /// specialization type. Subclasses may override this routine to provide
1077 /// different behavior.
1078 QualType RebuildTemplateSpecializationType(TemplateName Template,
1079 SourceLocation TemplateLoc,
1080 TemplateArgumentListInfo &Args);
1081
1082 /// Build a new parenthesized type.
1083 ///
1084 /// By default, builds a new ParenType type from the inner type.
1085 /// Subclasses may override this routine to provide different behavior.
1086 QualType RebuildParenType(QualType InnerType) {
1087 return SemaRef.BuildParenType(InnerType);
1088 }
1089
1090 /// Build a new qualified name type.
1091 ///
1092 /// By default, builds a new ElaboratedType type from the keyword,
1093 /// the nested-name-specifier and the named type.
1094 /// Subclasses may override this routine to provide different behavior.
1095 QualType RebuildElaboratedType(SourceLocation KeywordLoc,
1096 ElaboratedTypeKeyword Keyword,
1097 NestedNameSpecifierLoc QualifierLoc,
1098 QualType Named) {
1099 return SemaRef.Context.getElaboratedType(Keyword,
1100 QualifierLoc.getNestedNameSpecifier(),
1101 Named);
1102 }
1103
1104 /// Build a new typename type that refers to a template-id.
1105 ///
1106 /// By default, builds a new DependentNameType type from the
1107 /// nested-name-specifier and the given type. Subclasses may override
1108 /// this routine to provide different behavior.
1109 QualType RebuildDependentTemplateSpecializationType(
1110 ElaboratedTypeKeyword Keyword,
1111 NestedNameSpecifierLoc QualifierLoc,
1112 SourceLocation TemplateKWLoc,
1113 const IdentifierInfo *Name,
1114 SourceLocation NameLoc,
1115 TemplateArgumentListInfo &Args,
1116 bool AllowInjectedClassName) {
1117 // Rebuild the template name.
1118 // TODO: avoid TemplateName abstraction
1119 CXXScopeSpec SS;
1120 SS.Adopt(QualifierLoc);
1121 TemplateName InstName = getDerived().RebuildTemplateName(
1122 SS, TemplateKWLoc, *Name, NameLoc, QualType(), nullptr,
1123 AllowInjectedClassName);
1124
1125 if (InstName.isNull())
1126 return QualType();
1127
1128 // If it's still dependent, make a dependent specialization.
1129 if (InstName.getAsDependentTemplateName())
1130 return SemaRef.Context.getDependentTemplateSpecializationType(
1131 Keyword, QualifierLoc.getNestedNameSpecifier(), Name,
1132 Args.arguments());
1133
1134 // Otherwise, make an elaborated type wrapping a non-dependent
1135 // specialization.
1136 QualType T =
1137 getDerived().RebuildTemplateSpecializationType(InstName, NameLoc, Args);
1138 if (T.isNull())
1139 return QualType();
1140 return SemaRef.Context.getElaboratedType(
1141 Keyword, QualifierLoc.getNestedNameSpecifier(), T);
1142 }
1143
1144 /// Build a new typename type that refers to an identifier.
1145 ///
1146 /// By default, performs semantic analysis when building the typename type
1147 /// (or elaborated type). Subclasses may override this routine to provide
1148 /// different behavior.
1149 QualType RebuildDependentNameType(ElaboratedTypeKeyword Keyword,
1150 SourceLocation KeywordLoc,
1151 NestedNameSpecifierLoc QualifierLoc,
1152 const IdentifierInfo *Id,
1153 SourceLocation IdLoc,
1154 bool DeducedTSTContext) {
1155 CXXScopeSpec SS;
1156 SS.Adopt(QualifierLoc);
1157
1158 if (QualifierLoc.getNestedNameSpecifier()->isDependent()) {
1159 // If the name is still dependent, just build a new dependent name type.
1160 if (!SemaRef.computeDeclContext(SS))
1161 return SemaRef.Context.getDependentNameType(Keyword,
1162 QualifierLoc.getNestedNameSpecifier(),
1163 Id);
1164 }
1165
1166 if (Keyword == ETK_None || Keyword == ETK_Typename) {
1167 return SemaRef.CheckTypenameType(Keyword, KeywordLoc, QualifierLoc,
1168 *Id, IdLoc, DeducedTSTContext);
1169 }
1170
1171 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForKeyword(Keyword);
1172
1173 // We had a dependent elaborated-type-specifier that has been transformed
1174 // into a non-dependent elaborated-type-specifier. Find the tag we're
1175 // referring to.
1176 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1177 DeclContext *DC = SemaRef.computeDeclContext(SS, false);
1178 if (!DC)
1179 return QualType();
1180
1181 if (SemaRef.RequireCompleteDeclContext(SS, DC))
1182 return QualType();
1183
1184 TagDecl *Tag = nullptr;
1185 SemaRef.LookupQualifiedName(Result, DC);
1186 switch (Result.getResultKind()) {
1187 case LookupResult::NotFound:
1188 case LookupResult::NotFoundInCurrentInstantiation:
1189 break;
1190
1191 case LookupResult::Found:
1192 Tag = Result.getAsSingle<TagDecl>();
1193 break;
1194
1195 case LookupResult::FoundOverloaded:
1196 case LookupResult::FoundUnresolvedValue:
1197 llvm_unreachable("Tag lookup cannot find non-tags")::llvm::llvm_unreachable_internal("Tag lookup cannot find non-tags"
, "clang/lib/Sema/TreeTransform.h", 1197)
;
1198
1199 case LookupResult::Ambiguous:
1200 // Let the LookupResult structure handle ambiguities.
1201 return QualType();
1202 }
1203
1204 if (!Tag) {
1205 // Check where the name exists but isn't a tag type and use that to emit
1206 // better diagnostics.
1207 LookupResult Result(SemaRef, Id, IdLoc, Sema::LookupTagName);
1208 SemaRef.LookupQualifiedName(Result, DC);
1209 switch (Result.getResultKind()) {
1210 case LookupResult::Found:
1211 case LookupResult::FoundOverloaded:
1212 case LookupResult::FoundUnresolvedValue: {
1213 NamedDecl *SomeDecl = Result.getRepresentativeDecl();
1214 Sema::NonTagKind NTK = SemaRef.getNonTagTypeDeclKind(SomeDecl, Kind);
1215 SemaRef.Diag(IdLoc, diag::err_tag_reference_non_tag) << SomeDecl
1216 << NTK << Kind;
1217 SemaRef.Diag(SomeDecl->getLocation(), diag::note_declared_at);
1218 break;
1219 }
1220 default:
1221 SemaRef.Diag(IdLoc, diag::err_not_tag_in_scope)
1222 << Kind << Id << DC << QualifierLoc.getSourceRange();
1223 break;
1224 }
1225 return QualType();
1226 }
1227
1228 if (!SemaRef.isAcceptableTagRedeclaration(Tag, Kind, /*isDefinition*/false,
1229 IdLoc, Id)) {
1230 SemaRef.Diag(KeywordLoc, diag::err_use_with_wrong_tag) << Id;
1231 SemaRef.Diag(Tag->getLocation(), diag::note_previous_use);
1232 return QualType();
1233 }
1234
1235 // Build the elaborated-type-specifier type.
1236 QualType T = SemaRef.Context.getTypeDeclType(Tag);
1237 return SemaRef.Context.getElaboratedType(Keyword,
1238 QualifierLoc.getNestedNameSpecifier(),
1239 T);
1240 }
1241
1242 /// Build a new pack expansion type.
1243 ///
1244 /// By default, builds a new PackExpansionType type from the given pattern.
1245 /// Subclasses may override this routine to provide different behavior.
1246 QualType RebuildPackExpansionType(QualType Pattern, SourceRange PatternRange,
1247 SourceLocation EllipsisLoc,
1248 std::optional<unsigned> NumExpansions) {
1249 return getSema().CheckPackExpansion(Pattern, PatternRange, EllipsisLoc,
1250 NumExpansions);
1251 }
1252
1253 /// Build a new atomic type given its value type.
1254 ///
1255 /// By default, performs semantic analysis when building the atomic type.
1256 /// Subclasses may override this routine to provide different behavior.
1257 QualType RebuildAtomicType(QualType ValueType, SourceLocation KWLoc);
1258
1259 /// Build a new pipe type given its value type.
1260 QualType RebuildPipeType(QualType ValueType, SourceLocation KWLoc,
1261 bool isReadPipe);
1262
1263 /// Build a bit-precise int given its value type.
1264 QualType RebuildBitIntType(bool IsUnsigned, unsigned NumBits,
1265 SourceLocation Loc);
1266
1267 /// Build a dependent bit-precise int given its value type.
1268 QualType RebuildDependentBitIntType(bool IsUnsigned, Expr *NumBitsExpr,
1269 SourceLocation Loc);
1270
1271 /// Build a new template name given a nested name specifier, a flag
1272 /// indicating whether the "template" keyword was provided, and the template
1273 /// that the template name refers to.
1274 ///
1275 /// By default, builds the new template name directly. Subclasses may override
1276 /// this routine to provide different behavior.
1277 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1278 bool TemplateKW,
1279 TemplateDecl *Template);
1280
1281 /// Build a new template name given a nested name specifier and the
1282 /// name that is referred to as a template.
1283 ///
1284 /// By default, performs semantic analysis to determine whether the name can
1285 /// be resolved to a specific template, then builds the appropriate kind of
1286 /// template name. Subclasses may override this routine to provide different
1287 /// behavior.
1288 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1289 SourceLocation TemplateKWLoc,
1290 const IdentifierInfo &Name,
1291 SourceLocation NameLoc, QualType ObjectType,
1292 NamedDecl *FirstQualifierInScope,
1293 bool AllowInjectedClassName);
1294
1295 /// Build a new template name given a nested name specifier and the
1296 /// overloaded operator name that is referred to as a template.
1297 ///
1298 /// By default, performs semantic analysis to determine whether the name can
1299 /// be resolved to a specific template, then builds the appropriate kind of
1300 /// template name. Subclasses may override this routine to provide different
1301 /// behavior.
1302 TemplateName RebuildTemplateName(CXXScopeSpec &SS,
1303 SourceLocation TemplateKWLoc,
1304 OverloadedOperatorKind Operator,
1305 SourceLocation NameLoc, QualType ObjectType,
1306 bool AllowInjectedClassName);
1307
1308 /// Build a new template name given a template template parameter pack
1309 /// and the
1310 ///
1311 /// By default, performs semantic analysis to determine whether the name can
1312 /// be resolved to a specific template, then builds the appropriate kind of
1313 /// template name. Subclasses may override this routine to provide different
1314 /// behavior.
1315 TemplateName RebuildTemplateName(const TemplateArgument &ArgPack,
1316 Decl *AssociatedDecl, unsigned Index,
1317 bool Final) {
1318 return getSema().Context.getSubstTemplateTemplateParmPack(
1319 ArgPack, AssociatedDecl, Index, Final);
1320 }
1321
1322 /// Build a new compound statement.
1323 ///
1324 /// By default, performs semantic analysis to build the new statement.
1325 /// Subclasses may override this routine to provide different behavior.
1326 StmtResult RebuildCompoundStmt(SourceLocation LBraceLoc,
1327 MultiStmtArg Statements,
1328 SourceLocation RBraceLoc,
1329 bool IsStmtExpr) {
1330 return getSema().ActOnCompoundStmt(LBraceLoc, RBraceLoc, Statements,
1331 IsStmtExpr);
1332 }
1333
1334 /// Build a new case statement.
1335 ///
1336 /// By default, performs semantic analysis to build the new statement.
1337 /// Subclasses may override this routine to provide different behavior.
1338 StmtResult RebuildCaseStmt(SourceLocation CaseLoc,
1339 Expr *LHS,
1340 SourceLocation EllipsisLoc,
1341 Expr *RHS,
1342 SourceLocation ColonLoc) {
1343 return getSema().ActOnCaseStmt(CaseLoc, LHS, EllipsisLoc, RHS,
1344 ColonLoc);
1345 }
1346
1347 /// Attach the body to a new case statement.
1348 ///
1349 /// By default, performs semantic analysis to build the new statement.
1350 /// Subclasses may override this routine to provide different behavior.
1351 StmtResult RebuildCaseStmtBody(Stmt *S, Stmt *Body) {
1352 getSema().ActOnCaseStmtBody(S, Body);
1353 return S;
1354 }
1355
1356 /// Build a new default statement.
1357 ///
1358 /// By default, performs semantic analysis to build the new statement.
1359 /// Subclasses may override this routine to provide different behavior.
1360 StmtResult RebuildDefaultStmt(SourceLocation DefaultLoc,
1361 SourceLocation ColonLoc,
1362 Stmt *SubStmt) {
1363 return getSema().ActOnDefaultStmt(DefaultLoc, ColonLoc, SubStmt,
1364 /*CurScope=*/nullptr);
1365 }
1366
1367 /// Build a new label statement.
1368 ///
1369 /// By default, performs semantic analysis to build the new statement.
1370 /// Subclasses may override this routine to provide different behavior.
1371 StmtResult RebuildLabelStmt(SourceLocation IdentLoc, LabelDecl *L,
1372 SourceLocation ColonLoc, Stmt *SubStmt) {
1373 return SemaRef.ActOnLabelStmt(IdentLoc, L, ColonLoc, SubStmt);
1374 }
1375
1376 /// Build a new attributed statement.
1377 ///
1378 /// By default, performs semantic analysis to build the new statement.
1379 /// Subclasses may override this routine to provide different behavior.
1380 StmtResult RebuildAttributedStmt(SourceLocation AttrLoc,
1381 ArrayRef<const Attr *> Attrs,
1382 Stmt *SubStmt) {
1383 return SemaRef.BuildAttributedStmt(AttrLoc, Attrs, SubStmt);
1384 }
1385
1386 /// Build a new "if" statement.
1387 ///
1388 /// By default, performs semantic analysis to build the new statement.
1389 /// Subclasses may override this routine to provide different behavior.
1390 StmtResult RebuildIfStmt(SourceLocation IfLoc, IfStatementKind Kind,
1391 SourceLocation LParenLoc, Sema::ConditionResult Cond,
1392 SourceLocation RParenLoc, Stmt *Init, Stmt *Then,
1393 SourceLocation ElseLoc, Stmt *Else) {
1394 return getSema().ActOnIfStmt(IfLoc, Kind, LParenLoc, Init, Cond, RParenLoc,
1395 Then, ElseLoc, Else);
1396 }
1397
1398 /// Start building a new switch statement.
1399 ///
1400 /// By default, performs semantic analysis to build the new statement.
1401 /// Subclasses may override this routine to provide different behavior.
1402 StmtResult RebuildSwitchStmtStart(SourceLocation SwitchLoc,
1403 SourceLocation LParenLoc, Stmt *Init,
1404 Sema::ConditionResult Cond,
1405 SourceLocation RParenLoc) {
1406 return getSema().ActOnStartOfSwitchStmt(SwitchLoc, LParenLoc, Init, Cond,
1407 RParenLoc);
1408 }
1409
1410 /// Attach the body to the switch statement.
1411 ///
1412 /// By default, performs semantic analysis to build the new statement.
1413 /// Subclasses may override this routine to provide different behavior.
1414 StmtResult RebuildSwitchStmtBody(SourceLocation SwitchLoc,
1415 Stmt *Switch, Stmt *Body) {
1416 return getSema().ActOnFinishSwitchStmt(SwitchLoc, Switch, Body);
1417 }
1418
1419 /// Build a new while statement.
1420 ///
1421 /// By default, performs semantic analysis to build the new statement.
1422 /// Subclasses may override this routine to provide different behavior.
1423 StmtResult RebuildWhileStmt(SourceLocation WhileLoc, SourceLocation LParenLoc,
1424 Sema::ConditionResult Cond,
1425 SourceLocation RParenLoc, Stmt *Body) {
1426 return getSema().ActOnWhileStmt(WhileLoc, LParenLoc, Cond, RParenLoc, Body);
1427 }
1428
1429 /// Build a new do-while statement.
1430 ///
1431 /// By default, performs semantic analysis to build the new statement.
1432 /// Subclasses may override this routine to provide different behavior.
1433 StmtResult RebuildDoStmt(SourceLocation DoLoc, Stmt *Body,
1434 SourceLocation WhileLoc, SourceLocation LParenLoc,
1435 Expr *Cond, SourceLocation RParenLoc) {
1436 return getSema().ActOnDoStmt(DoLoc, Body, WhileLoc, LParenLoc,
1437 Cond, RParenLoc);
1438 }
1439
1440 /// Build a new for statement.
1441 ///
1442 /// By default, performs semantic analysis to build the new statement.
1443 /// Subclasses may override this routine to provide different behavior.
1444 StmtResult RebuildForStmt(SourceLocation ForLoc, SourceLocation LParenLoc,
1445 Stmt *Init, Sema::ConditionResult Cond,
1446 Sema::FullExprArg Inc, SourceLocation RParenLoc,
1447 Stmt *Body) {
1448 return getSema().ActOnForStmt(ForLoc, LParenLoc, Init, Cond,
1449 Inc, RParenLoc, Body);
1450 }
1451
1452 /// Build a new goto statement.
1453 ///
1454 /// By default, performs semantic analysis to build the new statement.
1455 /// Subclasses may override this routine to provide different behavior.
1456 StmtResult RebuildGotoStmt(SourceLocation GotoLoc, SourceLocation LabelLoc,
1457 LabelDecl *Label) {
1458 return getSema().ActOnGotoStmt(GotoLoc, LabelLoc, Label);
1459 }
1460
1461 /// Build a new indirect goto statement.
1462 ///
1463 /// By default, performs semantic analysis to build the new statement.
1464 /// Subclasses may override this routine to provide different behavior.
1465 StmtResult RebuildIndirectGotoStmt(SourceLocation GotoLoc,
1466 SourceLocation StarLoc,
1467 Expr *Target) {
1468 return getSema().ActOnIndirectGotoStmt(GotoLoc, StarLoc, Target);
1469 }
1470
1471 /// Build a new return statement.
1472 ///
1473 /// By default, performs semantic analysis to build the new statement.
1474 /// Subclasses may override this routine to provide different behavior.
1475 StmtResult RebuildReturnStmt(SourceLocation ReturnLoc, Expr *Result) {
1476 return getSema().BuildReturnStmt(ReturnLoc, Result);
1477 }
1478
1479 /// Build a new declaration statement.
1480 ///
1481 /// By default, performs semantic analysis to build the new statement.
1482 /// Subclasses may override this routine to provide different behavior.
1483 StmtResult RebuildDeclStmt(MutableArrayRef<Decl *> Decls,
1484 SourceLocation StartLoc, SourceLocation EndLoc) {
1485 Sema::DeclGroupPtrTy DG = getSema().BuildDeclaratorGroup(Decls);
1486 return getSema().ActOnDeclStmt(DG, StartLoc, EndLoc);
1487 }
1488
1489 /// Build a new inline asm statement.
1490 ///
1491 /// By default, performs semantic analysis to build the new statement.
1492 /// Subclasses may override this routine to provide different behavior.
1493 StmtResult RebuildGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
1494 bool IsVolatile, unsigned NumOutputs,
1495 unsigned NumInputs, IdentifierInfo **Names,
1496 MultiExprArg Constraints, MultiExprArg Exprs,
1497 Expr *AsmString, MultiExprArg Clobbers,
1498 unsigned NumLabels,
1499 SourceLocation RParenLoc) {
1500 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1501 NumInputs, Names, Constraints, Exprs,
1502 AsmString, Clobbers, NumLabels, RParenLoc);
1503 }
1504
1505 /// Build a new MS style inline asm statement.
1506 ///
1507 /// By default, performs semantic analysis to build the new statement.
1508 /// Subclasses may override this routine to provide different behavior.
1509 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1510 ArrayRef<Token> AsmToks,
1511 StringRef AsmString,
1512 unsigned NumOutputs, unsigned NumInputs,
1513 ArrayRef<StringRef> Constraints,
1514 ArrayRef<StringRef> Clobbers,
1515 ArrayRef<Expr*> Exprs,
1516 SourceLocation EndLoc) {
1517 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1518 NumOutputs, NumInputs,
1519 Constraints, Clobbers, Exprs, EndLoc);
1520 }
1521
1522 /// Build a new co_return statement.
1523 ///
1524 /// By default, performs semantic analysis to build the new statement.
1525 /// Subclasses may override this routine to provide different behavior.
1526 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1527 bool IsImplicit) {
1528 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1529 }
1530
1531 /// Build a new co_await expression.
1532 ///
1533 /// By default, performs semantic analysis to build the new expression.
1534 /// Subclasses may override this routine to provide different behavior.
1535 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1536 UnresolvedLookupExpr *OpCoawaitLookup,
1537 bool IsImplicit) {
1538 // This function rebuilds a coawait-expr given its operator.
1539 // For an explicit coawait-expr, the rebuild involves the full set
1540 // of transformations performed by BuildUnresolvedCoawaitExpr(),
1541 // including calling await_transform().
1542 // For an implicit coawait-expr, we need to rebuild the "operator
1543 // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1544 // This mirrors how the implicit CoawaitExpr is originally created
1545 // in Sema::ActOnCoroutineBodyStart().
1546 if (IsImplicit) {
1547 ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1548 CoawaitLoc, Operand, OpCoawaitLookup);
1549 if (Suspend.isInvalid())
1550 return ExprError();
1551 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1552 Suspend.get(), true);
1553 }
1554
1555 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1556