Bug Summary

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

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