Bug Summary

File:build/source/clang/lib/Sema/TreeTransform.h
Warning:line 6342, column 21
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 SemaTemplateInstantiateDecl.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/SemaTemplateInstantiateDecl.cpp

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

1//===--- SemaTemplateInstantiateDecl.cpp - C++ Template Decl 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 for declarations.
9//
10//===----------------------------------------------------------------------===/
11
12#include "TreeTransform.h"
13#include "clang/AST/ASTConsumer.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTMutationListener.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/DeclVisitor.h"
18#include "clang/AST/DependentDiagnostic.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/PrettyDeclStackTrace.h"
22#include "clang/AST/TypeLoc.h"
23#include "clang/Basic/SourceManager.h"
24#include "clang/Basic/TargetInfo.h"
25#include "clang/Sema/EnterExpressionEvaluationContext.h"
26#include "clang/Sema/Initialization.h"
27#include "clang/Sema/Lookup.h"
28#include "clang/Sema/ScopeInfo.h"
29#include "clang/Sema/SemaInternal.h"
30#include "clang/Sema/Template.h"
31#include "clang/Sema/TemplateInstCallback.h"
32#include "llvm/Support/TimeProfiler.h"
33#include <optional>
34
35using namespace clang;
36
37static bool isDeclWithinFunction(const Decl *D) {
38 const DeclContext *DC = D->getDeclContext();
39 if (DC->isFunctionOrMethod())
40 return true;
41
42 if (DC->isRecord())
43 return cast<CXXRecordDecl>(DC)->isLocalClass();
44
45 return false;
46}
47
48template<typename DeclT>
49static bool SubstQualifier(Sema &SemaRef, const DeclT *OldDecl, DeclT *NewDecl,
50 const MultiLevelTemplateArgumentList &TemplateArgs) {
51 if (!OldDecl->getQualifierLoc())
52 return false;
53
54 assert((NewDecl->getFriendObjectKind() ||(static_cast <bool> ((NewDecl->getFriendObjectKind()
|| !OldDecl->getLexicalDeclContext()->isDependentContext
()) && "non-friend with qualified name defined in dependent context"
) ? void (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 56, __extension__
__PRETTY_FUNCTION__))
55 !OldDecl->getLexicalDeclContext()->isDependentContext()) &&(static_cast <bool> ((NewDecl->getFriendObjectKind()
|| !OldDecl->getLexicalDeclContext()->isDependentContext
()) && "non-friend with qualified name defined in dependent context"
) ? void (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 56, __extension__
__PRETTY_FUNCTION__))
56 "non-friend with qualified name defined in dependent context")(static_cast <bool> ((NewDecl->getFriendObjectKind()
|| !OldDecl->getLexicalDeclContext()->isDependentContext
()) && "non-friend with qualified name defined in dependent context"
) ? void (0) : __assert_fail ("(NewDecl->getFriendObjectKind() || !OldDecl->getLexicalDeclContext()->isDependentContext()) && \"non-friend with qualified name defined in dependent context\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 56, __extension__
__PRETTY_FUNCTION__))
;
57 Sema::ContextRAII SavedContext(
58 SemaRef,
59 const_cast<DeclContext *>(NewDecl->getFriendObjectKind()
60 ? NewDecl->getLexicalDeclContext()
61 : OldDecl->getLexicalDeclContext()));
62
63 NestedNameSpecifierLoc NewQualifierLoc
64 = SemaRef.SubstNestedNameSpecifierLoc(OldDecl->getQualifierLoc(),
65 TemplateArgs);
66
67 if (!NewQualifierLoc)
68 return true;
69
70 NewDecl->setQualifierInfo(NewQualifierLoc);
71 return false;
72}
73
74bool TemplateDeclInstantiator::SubstQualifier(const DeclaratorDecl *OldDecl,
75 DeclaratorDecl *NewDecl) {
76 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
77}
78
79bool TemplateDeclInstantiator::SubstQualifier(const TagDecl *OldDecl,
80 TagDecl *NewDecl) {
81 return ::SubstQualifier(SemaRef, OldDecl, NewDecl, TemplateArgs);
82}
83
84// Include attribute instantiation code.
85#include "clang/Sema/AttrTemplateInstantiate.inc"
86
87static void instantiateDependentAlignedAttr(
88 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
89 const AlignedAttr *Aligned, Decl *New, bool IsPackExpansion) {
90 if (Aligned->isAlignmentExpr()) {
91 // The alignment expression is a constant expression.
92 EnterExpressionEvaluationContext Unevaluated(
93 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
94 ExprResult Result = S.SubstExpr(Aligned->getAlignmentExpr(), TemplateArgs);
95 if (!Result.isInvalid())
96 S.AddAlignedAttr(New, *Aligned, Result.getAs<Expr>(), IsPackExpansion);
97 } else {
98 TypeSourceInfo *Result = S.SubstType(Aligned->getAlignmentType(),
99 TemplateArgs, Aligned->getLocation(),
100 DeclarationName());
101 if (Result)
102 S.AddAlignedAttr(New, *Aligned, Result, IsPackExpansion);
103 }
104}
105
106static void instantiateDependentAlignedAttr(
107 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
108 const AlignedAttr *Aligned, Decl *New) {
109 if (!Aligned->isPackExpansion()) {
110 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
111 return;
112 }
113
114 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
115 if (Aligned->isAlignmentExpr())
116 S.collectUnexpandedParameterPacks(Aligned->getAlignmentExpr(),
117 Unexpanded);
118 else
119 S.collectUnexpandedParameterPacks(Aligned->getAlignmentType()->getTypeLoc(),
120 Unexpanded);
121 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 121, __extension__
__PRETTY_FUNCTION__))
;
122
123 // Determine whether we can expand this attribute pack yet.
124 bool Expand = true, RetainExpansion = false;
125 std::optional<unsigned> NumExpansions;
126 // FIXME: Use the actual location of the ellipsis.
127 SourceLocation EllipsisLoc = Aligned->getLocation();
128 if (S.CheckParameterPacksForExpansion(EllipsisLoc, Aligned->getRange(),
129 Unexpanded, TemplateArgs, Expand,
130 RetainExpansion, NumExpansions))
131 return;
132
133 if (!Expand) {
134 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, -1);
135 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, true);
136 } else {
137 for (unsigned I = 0; I != *NumExpansions; ++I) {
138 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(S, I);
139 instantiateDependentAlignedAttr(S, TemplateArgs, Aligned, New, false);
140 }
141 }
142}
143
144static void instantiateDependentAssumeAlignedAttr(
145 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
146 const AssumeAlignedAttr *Aligned, Decl *New) {
147 // The alignment expression is a constant expression.
148 EnterExpressionEvaluationContext Unevaluated(
149 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
150
151 Expr *E, *OE = nullptr;
152 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
153 if (Result.isInvalid())
154 return;
155 E = Result.getAs<Expr>();
156
157 if (Aligned->getOffset()) {
158 Result = S.SubstExpr(Aligned->getOffset(), TemplateArgs);
159 if (Result.isInvalid())
160 return;
161 OE = Result.getAs<Expr>();
162 }
163
164 S.AddAssumeAlignedAttr(New, *Aligned, E, OE);
165}
166
167static void instantiateDependentAlignValueAttr(
168 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
169 const AlignValueAttr *Aligned, Decl *New) {
170 // The alignment expression is a constant expression.
171 EnterExpressionEvaluationContext Unevaluated(
172 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
173 ExprResult Result = S.SubstExpr(Aligned->getAlignment(), TemplateArgs);
174 if (!Result.isInvalid())
175 S.AddAlignValueAttr(New, *Aligned, Result.getAs<Expr>());
176}
177
178static void instantiateDependentAllocAlignAttr(
179 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
180 const AllocAlignAttr *Align, Decl *New) {
181 Expr *Param = IntegerLiteral::Create(
182 S.getASTContext(),
183 llvm::APInt(64, Align->getParamIndex().getSourceIndex()),
184 S.getASTContext().UnsignedLongLongTy, Align->getLocation());
185 S.AddAllocAlignAttr(New, *Align, Param);
186}
187
188static void instantiateDependentAnnotationAttr(
189 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
190 const AnnotateAttr *Attr, Decl *New) {
191 EnterExpressionEvaluationContext Unevaluated(
192 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
193
194 // If the attribute has delayed arguments it will have to instantiate those
195 // and handle them as new arguments for the attribute.
196 bool HasDelayedArgs = Attr->delayedArgs_size();
197
198 ArrayRef<Expr *> ArgsToInstantiate =
199 HasDelayedArgs
200 ? ArrayRef<Expr *>{Attr->delayedArgs_begin(), Attr->delayedArgs_end()}
201 : ArrayRef<Expr *>{Attr->args_begin(), Attr->args_end()};
202
203 SmallVector<Expr *, 4> Args;
204 if (S.SubstExprs(ArgsToInstantiate,
205 /*IsCall=*/false, TemplateArgs, Args))
206 return;
207
208 StringRef Str = Attr->getAnnotation();
209 if (HasDelayedArgs) {
210 if (Args.size() < 1) {
211 S.Diag(Attr->getLoc(), diag::err_attribute_too_few_arguments)
212 << Attr << 1;
213 return;
214 }
215
216 if (!S.checkStringLiteralArgumentAttr(*Attr, Args[0], Str))
217 return;
218
219 llvm::SmallVector<Expr *, 4> ActualArgs;
220 ActualArgs.insert(ActualArgs.begin(), Args.begin() + 1, Args.end());
221 std::swap(Args, ActualArgs);
222 }
223 S.AddAnnotationAttr(New, *Attr, Str, Args);
224}
225
226static Expr *instantiateDependentFunctionAttrCondition(
227 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
228 const Attr *A, Expr *OldCond, const Decl *Tmpl, FunctionDecl *New) {
229 Expr *Cond = nullptr;
230 {
231 Sema::ContextRAII SwitchContext(S, New);
232 EnterExpressionEvaluationContext Unevaluated(
233 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
234 ExprResult Result = S.SubstExpr(OldCond, TemplateArgs);
235 if (Result.isInvalid())
236 return nullptr;
237 Cond = Result.getAs<Expr>();
238 }
239 if (!Cond->isTypeDependent()) {
240 ExprResult Converted = S.PerformContextuallyConvertToBool(Cond);
241 if (Converted.isInvalid())
242 return nullptr;
243 Cond = Converted.get();
244 }
245
246 SmallVector<PartialDiagnosticAt, 8> Diags;
247 if (OldCond->isValueDependent() && !Cond->isValueDependent() &&
248 !Expr::isPotentialConstantExprUnevaluated(Cond, New, Diags)) {
249 S.Diag(A->getLocation(), diag::err_attr_cond_never_constant_expr) << A;
250 for (const auto &P : Diags)
251 S.Diag(P.first, P.second);
252 return nullptr;
253 }
254 return Cond;
255}
256
257static void instantiateDependentEnableIfAttr(
258 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
259 const EnableIfAttr *EIA, const Decl *Tmpl, FunctionDecl *New) {
260 Expr *Cond = instantiateDependentFunctionAttrCondition(
261 S, TemplateArgs, EIA, EIA->getCond(), Tmpl, New);
262
263 if (Cond)
264 New->addAttr(new (S.getASTContext()) EnableIfAttr(S.getASTContext(), *EIA,
265 Cond, EIA->getMessage()));
266}
267
268static void instantiateDependentDiagnoseIfAttr(
269 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
270 const DiagnoseIfAttr *DIA, const Decl *Tmpl, FunctionDecl *New) {
271 Expr *Cond = instantiateDependentFunctionAttrCondition(
272 S, TemplateArgs, DIA, DIA->getCond(), Tmpl, New);
273
274 if (Cond)
275 New->addAttr(new (S.getASTContext()) DiagnoseIfAttr(
276 S.getASTContext(), *DIA, Cond, DIA->getMessage(),
277 DIA->getDiagnosticType(), DIA->getArgDependent(), New));
278}
279
280// Constructs and adds to New a new instance of CUDALaunchBoundsAttr using
281// template A as the base and arguments from TemplateArgs.
282static void instantiateDependentCUDALaunchBoundsAttr(
283 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
284 const CUDALaunchBoundsAttr &Attr, Decl *New) {
285 // The alignment expression is a constant expression.
286 EnterExpressionEvaluationContext Unevaluated(
287 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
288
289 ExprResult Result = S.SubstExpr(Attr.getMaxThreads(), TemplateArgs);
290 if (Result.isInvalid())
291 return;
292 Expr *MaxThreads = Result.getAs<Expr>();
293
294 Expr *MinBlocks = nullptr;
295 if (Attr.getMinBlocks()) {
296 Result = S.SubstExpr(Attr.getMinBlocks(), TemplateArgs);
297 if (Result.isInvalid())
298 return;
299 MinBlocks = Result.getAs<Expr>();
300 }
301
302 S.AddLaunchBoundsAttr(New, Attr, MaxThreads, MinBlocks);
303}
304
305static void
306instantiateDependentModeAttr(Sema &S,
307 const MultiLevelTemplateArgumentList &TemplateArgs,
308 const ModeAttr &Attr, Decl *New) {
309 S.AddModeAttr(New, Attr, Attr.getMode(),
310 /*InInstantiation=*/true);
311}
312
313/// Instantiation of 'declare simd' attribute and its arguments.
314static void instantiateOMPDeclareSimdDeclAttr(
315 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
316 const OMPDeclareSimdDeclAttr &Attr, Decl *New) {
317 // Allow 'this' in clauses with varlists.
318 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
319 New = FTD->getTemplatedDecl();
320 auto *FD = cast<FunctionDecl>(New);
321 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
322 SmallVector<Expr *, 4> Uniforms, Aligneds, Alignments, Linears, Steps;
323 SmallVector<unsigned, 4> LinModifiers;
324
325 auto SubstExpr = [&](Expr *E) -> ExprResult {
326 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
327 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
328 Sema::ContextRAII SavedContext(S, FD);
329 LocalInstantiationScope Local(S);
330 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
331 Local.InstantiatedLocal(
332 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
333 return S.SubstExpr(E, TemplateArgs);
334 }
335 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
336 FD->isCXXInstanceMember());
337 return S.SubstExpr(E, TemplateArgs);
338 };
339
340 // Substitute a single OpenMP clause, which is a potentially-evaluated
341 // full-expression.
342 auto Subst = [&](Expr *E) -> ExprResult {
343 EnterExpressionEvaluationContext Evaluated(
344 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
345 ExprResult Res = SubstExpr(E);
346 if (Res.isInvalid())
347 return Res;
348 return S.ActOnFinishFullExpr(Res.get(), false);
349 };
350
351 ExprResult Simdlen;
352 if (auto *E = Attr.getSimdlen())
353 Simdlen = Subst(E);
354
355 if (Attr.uniforms_size() > 0) {
356 for(auto *E : Attr.uniforms()) {
357 ExprResult Inst = Subst(E);
358 if (Inst.isInvalid())
359 continue;
360 Uniforms.push_back(Inst.get());
361 }
362 }
363
364 auto AI = Attr.alignments_begin();
365 for (auto *E : Attr.aligneds()) {
366 ExprResult Inst = Subst(E);
367 if (Inst.isInvalid())
368 continue;
369 Aligneds.push_back(Inst.get());
370 Inst = ExprEmpty();
371 if (*AI)
372 Inst = S.SubstExpr(*AI, TemplateArgs);
373 Alignments.push_back(Inst.get());
374 ++AI;
375 }
376
377 auto SI = Attr.steps_begin();
378 for (auto *E : Attr.linears()) {
379 ExprResult Inst = Subst(E);
380 if (Inst.isInvalid())
381 continue;
382 Linears.push_back(Inst.get());
383 Inst = ExprEmpty();
384 if (*SI)
385 Inst = S.SubstExpr(*SI, TemplateArgs);
386 Steps.push_back(Inst.get());
387 ++SI;
388 }
389 LinModifiers.append(Attr.modifiers_begin(), Attr.modifiers_end());
390 (void)S.ActOnOpenMPDeclareSimdDirective(
391 S.ConvertDeclToDeclGroup(New), Attr.getBranchState(), Simdlen.get(),
392 Uniforms, Aligneds, Alignments, Linears, LinModifiers, Steps,
393 Attr.getRange());
394}
395
396/// Instantiation of 'declare variant' attribute and its arguments.
397static void instantiateOMPDeclareVariantAttr(
398 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
399 const OMPDeclareVariantAttr &Attr, Decl *New) {
400 // Allow 'this' in clauses with varlists.
401 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(New))
402 New = FTD->getTemplatedDecl();
403 auto *FD = cast<FunctionDecl>(New);
404 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(FD->getDeclContext());
405
406 auto &&SubstExpr = [FD, ThisContext, &S, &TemplateArgs](Expr *E) {
407 if (auto *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
408 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
409 Sema::ContextRAII SavedContext(S, FD);
410 LocalInstantiationScope Local(S);
411 if (FD->getNumParams() > PVD->getFunctionScopeIndex())
412 Local.InstantiatedLocal(
413 PVD, FD->getParamDecl(PVD->getFunctionScopeIndex()));
414 return S.SubstExpr(E, TemplateArgs);
415 }
416 Sema::CXXThisScopeRAII ThisScope(S, ThisContext, Qualifiers(),
417 FD->isCXXInstanceMember());
418 return S.SubstExpr(E, TemplateArgs);
419 };
420
421 // Substitute a single OpenMP clause, which is a potentially-evaluated
422 // full-expression.
423 auto &&Subst = [&SubstExpr, &S](Expr *E) {
424 EnterExpressionEvaluationContext Evaluated(
425 S, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
426 ExprResult Res = SubstExpr(E);
427 if (Res.isInvalid())
428 return Res;
429 return S.ActOnFinishFullExpr(Res.get(), false);
430 };
431
432 ExprResult VariantFuncRef;
433 if (Expr *E = Attr.getVariantFuncRef()) {
434 // Do not mark function as is used to prevent its emission if this is the
435 // only place where it is used.
436 EnterExpressionEvaluationContext Unevaluated(
437 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
438 VariantFuncRef = Subst(E);
439 }
440
441 // Copy the template version of the OMPTraitInfo and run substitute on all
442 // score and condition expressiosn.
443 OMPTraitInfo &TI = S.getASTContext().getNewOMPTraitInfo();
444 TI = *Attr.getTraitInfos();
445
446 // Try to substitute template parameters in score and condition expressions.
447 auto SubstScoreOrConditionExpr = [&S, Subst](Expr *&E, bool) {
448 if (E) {
449 EnterExpressionEvaluationContext Unevaluated(
450 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
451 ExprResult ER = Subst(E);
452 if (ER.isUsable())
453 E = ER.get();
454 else
455 return true;
456 }
457 return false;
458 };
459 if (TI.anyScoreOrCondition(SubstScoreOrConditionExpr))
460 return;
461
462 Expr *E = VariantFuncRef.get();
463
464 // Check function/variant ref for `omp declare variant` but not for `omp
465 // begin declare variant` (which use implicit attributes).
466 std::optional<std::pair<FunctionDecl *, Expr *>> DeclVarData =
467 S.checkOpenMPDeclareVariantFunction(S.ConvertDeclToDeclGroup(New), E, TI,
468 Attr.appendArgs_size(),
469 Attr.getRange());
470
471 if (!DeclVarData)
472 return;
473
474 E = DeclVarData->second;
475 FD = DeclVarData->first;
476
477 if (auto *VariantDRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts())) {
478 if (auto *VariantFD = dyn_cast<FunctionDecl>(VariantDRE->getDecl())) {
479 if (auto *VariantFTD = VariantFD->getDescribedFunctionTemplate()) {
480 if (!VariantFTD->isThisDeclarationADefinition())
481 return;
482 Sema::TentativeAnalysisScope Trap(S);
483 const TemplateArgumentList *TAL = TemplateArgumentList::CreateCopy(
484 S.Context, TemplateArgs.getInnermost());
485
486 auto *SubstFD = S.InstantiateFunctionDeclaration(VariantFTD, TAL,
487 New->getLocation());
488 if (!SubstFD)
489 return;
490 QualType NewType = S.Context.mergeFunctionTypes(
491 SubstFD->getType(), FD->getType(),
492 /* OfBlockPointer */ false,
493 /* Unqualified */ false, /* AllowCXX */ true);
494 if (NewType.isNull())
495 return;
496 S.InstantiateFunctionDefinition(
497 New->getLocation(), SubstFD, /* Recursive */ true,
498 /* DefinitionRequired */ false, /* AtEndOfTU */ false);
499 SubstFD->setInstantiationIsPending(!SubstFD->isDefined());
500 E = DeclRefExpr::Create(S.Context, NestedNameSpecifierLoc(),
501 SourceLocation(), SubstFD,
502 /* RefersToEnclosingVariableOrCapture */ false,
503 /* NameLoc */ SubstFD->getLocation(),
504 SubstFD->getType(), ExprValueKind::VK_PRValue);
505 }
506 }
507 }
508
509 SmallVector<Expr *, 8> NothingExprs;
510 SmallVector<Expr *, 8> NeedDevicePtrExprs;
511 SmallVector<OMPInteropInfo, 4> AppendArgs;
512
513 for (Expr *E : Attr.adjustArgsNothing()) {
514 ExprResult ER = Subst(E);
515 if (ER.isInvalid())
516 continue;
517 NothingExprs.push_back(ER.get());
518 }
519 for (Expr *E : Attr.adjustArgsNeedDevicePtr()) {
520 ExprResult ER = Subst(E);
521 if (ER.isInvalid())
522 continue;
523 NeedDevicePtrExprs.push_back(ER.get());
524 }
525 for (OMPInteropInfo &II : Attr.appendArgs()) {
526 // When prefer_type is implemented for append_args handle them here too.
527 AppendArgs.emplace_back(II.IsTarget, II.IsTargetSync);
528 }
529
530 S.ActOnOpenMPDeclareVariantDirective(
531 FD, E, TI, NothingExprs, NeedDevicePtrExprs, AppendArgs, SourceLocation(),
532 SourceLocation(), Attr.getRange());
533}
534
535static void instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
536 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
537 const AMDGPUFlatWorkGroupSizeAttr &Attr, Decl *New) {
538 // Both min and max expression are constant expressions.
539 EnterExpressionEvaluationContext Unevaluated(
540 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
541
542 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
543 if (Result.isInvalid())
544 return;
545 Expr *MinExpr = Result.getAs<Expr>();
546
547 Result = S.SubstExpr(Attr.getMax(), TemplateArgs);
548 if (Result.isInvalid())
549 return;
550 Expr *MaxExpr = Result.getAs<Expr>();
551
552 S.addAMDGPUFlatWorkGroupSizeAttr(New, Attr, MinExpr, MaxExpr);
553}
554
555static ExplicitSpecifier
556instantiateExplicitSpecifier(Sema &S,
557 const MultiLevelTemplateArgumentList &TemplateArgs,
558 ExplicitSpecifier ES, FunctionDecl *New) {
559 if (!ES.getExpr())
560 return ES;
561 Expr *OldCond = ES.getExpr();
562 Expr *Cond = nullptr;
563 {
564 EnterExpressionEvaluationContext Unevaluated(
565 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
566 ExprResult SubstResult = S.SubstExpr(OldCond, TemplateArgs);
567 if (SubstResult.isInvalid()) {
568 return ExplicitSpecifier::Invalid();
569 }
570 Cond = SubstResult.get();
571 }
572 ExplicitSpecifier Result(Cond, ES.getKind());
573 if (!Cond->isTypeDependent())
574 S.tryResolveExplicitSpecifier(Result);
575 return Result;
576}
577
578static void instantiateDependentAMDGPUWavesPerEUAttr(
579 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
580 const AMDGPUWavesPerEUAttr &Attr, Decl *New) {
581 // Both min and max expression are constant expressions.
582 EnterExpressionEvaluationContext Unevaluated(
583 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
584
585 ExprResult Result = S.SubstExpr(Attr.getMin(), TemplateArgs);
586 if (Result.isInvalid())
587 return;
588 Expr *MinExpr = Result.getAs<Expr>();
589
590 Expr *MaxExpr = nullptr;
591 if (auto Max = Attr.getMax()) {
592 Result = S.SubstExpr(Max, TemplateArgs);
593 if (Result.isInvalid())
594 return;
595 MaxExpr = Result.getAs<Expr>();
596 }
597
598 S.addAMDGPUWavesPerEUAttr(New, Attr, MinExpr, MaxExpr);
599}
600
601// This doesn't take any template parameters, but we have a custom action that
602// needs to happen when the kernel itself is instantiated. We need to run the
603// ItaniumMangler to mark the names required to name this kernel.
604static void instantiateDependentSYCLKernelAttr(
605 Sema &S, const MultiLevelTemplateArgumentList &TemplateArgs,
606 const SYCLKernelAttr &Attr, Decl *New) {
607 New->addAttr(Attr.clone(S.getASTContext()));
608}
609
610/// Determine whether the attribute A might be relevant to the declaration D.
611/// If not, we can skip instantiating it. The attribute may or may not have
612/// been instantiated yet.
613static bool isRelevantAttr(Sema &S, const Decl *D, const Attr *A) {
614 // 'preferred_name' is only relevant to the matching specialization of the
615 // template.
616 if (const auto *PNA = dyn_cast<PreferredNameAttr>(A)) {
617 QualType T = PNA->getTypedefType();
618 const auto *RD = cast<CXXRecordDecl>(D);
619 if (!T->isDependentType() && !RD->isDependentContext() &&
620 !declaresSameEntity(T->getAsCXXRecordDecl(), RD))
621 return false;
622 for (const auto *ExistingPNA : D->specific_attrs<PreferredNameAttr>())
623 if (S.Context.hasSameType(ExistingPNA->getTypedefType(),
624 PNA->getTypedefType()))
625 return false;
626 return true;
627 }
628
629 if (const auto *BA = dyn_cast<BuiltinAttr>(A)) {
630 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
631 switch (BA->getID()) {
632 case Builtin::BIforward:
633 // Do not treat 'std::forward' as a builtin if it takes an rvalue reference
634 // type and returns an lvalue reference type. The library implementation
635 // will produce an error in this case; don't get in its way.
636 if (FD && FD->getNumParams() >= 1 &&
637 FD->getParamDecl(0)->getType()->isRValueReferenceType() &&
638 FD->getReturnType()->isLValueReferenceType()) {
639 return false;
640 }
641 [[fallthrough]];
642 case Builtin::BImove:
643 case Builtin::BImove_if_noexcept:
644 // HACK: Super-old versions of libc++ (3.1 and earlier) provide
645 // std::forward and std::move overloads that sometimes return by value
646 // instead of by reference when building in C++98 mode. Don't treat such
647 // cases as builtins.
648 if (FD && !FD->getReturnType()->isReferenceType())
649 return false;
650 break;
651 }
652 }
653
654 return true;
655}
656
657void Sema::InstantiateAttrsForDecl(
658 const MultiLevelTemplateArgumentList &TemplateArgs, const Decl *Tmpl,
659 Decl *New, LateInstantiatedAttrVec *LateAttrs,
660 LocalInstantiationScope *OuterMostScope) {
661 if (NamedDecl *ND = dyn_cast<NamedDecl>(New)) {
662 // FIXME: This function is called multiple times for the same template
663 // specialization. We should only instantiate attributes that were added
664 // since the previous instantiation.
665 for (const auto *TmplAttr : Tmpl->attrs()) {
666 if (!isRelevantAttr(*this, New, TmplAttr))
667 continue;
668
669 // FIXME: If any of the special case versions from InstantiateAttrs become
670 // applicable to template declaration, we'll need to add them here.
671 CXXThisScopeRAII ThisScope(
672 *this, dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext()),
673 Qualifiers(), ND->isCXXInstanceMember());
674
675 Attr *NewAttr = sema::instantiateTemplateAttributeForDecl(
676 TmplAttr, Context, *this, TemplateArgs);
677 if (NewAttr && isRelevantAttr(*this, New, NewAttr))
678 New->addAttr(NewAttr);
679 }
680 }
681}
682
683static Sema::RetainOwnershipKind
684attrToRetainOwnershipKind(const Attr *A) {
685 switch (A->getKind()) {
686 case clang::attr::CFConsumed:
687 return Sema::RetainOwnershipKind::CF;
688 case clang::attr::OSConsumed:
689 return Sema::RetainOwnershipKind::OS;
690 case clang::attr::NSConsumed:
691 return Sema::RetainOwnershipKind::NS;
692 default:
693 llvm_unreachable("Wrong argument supplied")::llvm::llvm_unreachable_internal("Wrong argument supplied", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 693)
;
694 }
695}
696
697void Sema::InstantiateAttrs(const MultiLevelTemplateArgumentList &TemplateArgs,
698 const Decl *Tmpl, Decl *New,
699 LateInstantiatedAttrVec *LateAttrs,
700 LocalInstantiationScope *OuterMostScope) {
701 for (const auto *TmplAttr : Tmpl->attrs()) {
702 if (!isRelevantAttr(*this, New, TmplAttr))
703 continue;
704
705 // FIXME: This should be generalized to more than just the AlignedAttr.
706 const AlignedAttr *Aligned = dyn_cast<AlignedAttr>(TmplAttr);
707 if (Aligned && Aligned->isAlignmentDependent()) {
708 instantiateDependentAlignedAttr(*this, TemplateArgs, Aligned, New);
709 continue;
710 }
711
712 if (const auto *AssumeAligned = dyn_cast<AssumeAlignedAttr>(TmplAttr)) {
713 instantiateDependentAssumeAlignedAttr(*this, TemplateArgs, AssumeAligned, New);
714 continue;
715 }
716
717 if (const auto *AlignValue = dyn_cast<AlignValueAttr>(TmplAttr)) {
718 instantiateDependentAlignValueAttr(*this, TemplateArgs, AlignValue, New);
719 continue;
720 }
721
722 if (const auto *AllocAlign = dyn_cast<AllocAlignAttr>(TmplAttr)) {
723 instantiateDependentAllocAlignAttr(*this, TemplateArgs, AllocAlign, New);
724 continue;
725 }
726
727 if (const auto *Annotate = dyn_cast<AnnotateAttr>(TmplAttr)) {
728 instantiateDependentAnnotationAttr(*this, TemplateArgs, Annotate, New);
729 continue;
730 }
731
732 if (const auto *EnableIf = dyn_cast<EnableIfAttr>(TmplAttr)) {
733 instantiateDependentEnableIfAttr(*this, TemplateArgs, EnableIf, Tmpl,
734 cast<FunctionDecl>(New));
735 continue;
736 }
737
738 if (const auto *DiagnoseIf = dyn_cast<DiagnoseIfAttr>(TmplAttr)) {
739 instantiateDependentDiagnoseIfAttr(*this, TemplateArgs, DiagnoseIf, Tmpl,
740 cast<FunctionDecl>(New));
741 continue;
742 }
743
744 if (const auto *CUDALaunchBounds =
745 dyn_cast<CUDALaunchBoundsAttr>(TmplAttr)) {
746 instantiateDependentCUDALaunchBoundsAttr(*this, TemplateArgs,
747 *CUDALaunchBounds, New);
748 continue;
749 }
750
751 if (const auto *Mode = dyn_cast<ModeAttr>(TmplAttr)) {
752 instantiateDependentModeAttr(*this, TemplateArgs, *Mode, New);
753 continue;
754 }
755
756 if (const auto *OMPAttr = dyn_cast<OMPDeclareSimdDeclAttr>(TmplAttr)) {
757 instantiateOMPDeclareSimdDeclAttr(*this, TemplateArgs, *OMPAttr, New);
758 continue;
759 }
760
761 if (const auto *OMPAttr = dyn_cast<OMPDeclareVariantAttr>(TmplAttr)) {
762 instantiateOMPDeclareVariantAttr(*this, TemplateArgs, *OMPAttr, New);
763 continue;
764 }
765
766 if (const auto *AMDGPUFlatWorkGroupSize =
767 dyn_cast<AMDGPUFlatWorkGroupSizeAttr>(TmplAttr)) {
768 instantiateDependentAMDGPUFlatWorkGroupSizeAttr(
769 *this, TemplateArgs, *AMDGPUFlatWorkGroupSize, New);
770 }
771
772 if (const auto *AMDGPUFlatWorkGroupSize =
773 dyn_cast<AMDGPUWavesPerEUAttr>(TmplAttr)) {
774 instantiateDependentAMDGPUWavesPerEUAttr(*this, TemplateArgs,
775 *AMDGPUFlatWorkGroupSize, New);
776 }
777
778 // Existing DLL attribute on the instantiation takes precedence.
779 if (TmplAttr->getKind() == attr::DLLExport ||
780 TmplAttr->getKind() == attr::DLLImport) {
781 if (New->hasAttr<DLLExportAttr>() || New->hasAttr<DLLImportAttr>()) {
782 continue;
783 }
784 }
785
786 if (const auto *ABIAttr = dyn_cast<ParameterABIAttr>(TmplAttr)) {
787 AddParameterABIAttr(New, *ABIAttr, ABIAttr->getABI());
788 continue;
789 }
790
791 if (isa<NSConsumedAttr>(TmplAttr) || isa<OSConsumedAttr>(TmplAttr) ||
792 isa<CFConsumedAttr>(TmplAttr)) {
793 AddXConsumedAttr(New, *TmplAttr, attrToRetainOwnershipKind(TmplAttr),
794 /*template instantiation=*/true);
795 continue;
796 }
797
798 if (auto *A = dyn_cast<PointerAttr>(TmplAttr)) {
799 if (!New->hasAttr<PointerAttr>())
800 New->addAttr(A->clone(Context));
801 continue;
802 }
803
804 if (auto *A = dyn_cast<OwnerAttr>(TmplAttr)) {
805 if (!New->hasAttr<OwnerAttr>())
806 New->addAttr(A->clone(Context));
807 continue;
808 }
809
810 if (auto *A = dyn_cast<SYCLKernelAttr>(TmplAttr)) {
811 instantiateDependentSYCLKernelAttr(*this, TemplateArgs, *A, New);
812 continue;
813 }
814
815 assert(!TmplAttr->isPackExpansion())(static_cast <bool> (!TmplAttr->isPackExpansion()) ?
void (0) : __assert_fail ("!TmplAttr->isPackExpansion()",
"clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 815, __extension__
__PRETTY_FUNCTION__))
;
816 if (TmplAttr->isLateParsed() && LateAttrs) {
817 // Late parsed attributes must be instantiated and attached after the
818 // enclosing class has been instantiated. See Sema::InstantiateClass.
819 LocalInstantiationScope *Saved = nullptr;
820 if (CurrentInstantiationScope)
821 Saved = CurrentInstantiationScope->cloneScopes(OuterMostScope);
822 LateAttrs->push_back(LateInstantiatedAttribute(TmplAttr, Saved, New));
823 } else {
824 // Allow 'this' within late-parsed attributes.
825 auto *ND = cast<NamedDecl>(New);
826 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(ND->getDeclContext());
827 CXXThisScopeRAII ThisScope(*this, ThisContext, Qualifiers(),
828 ND->isCXXInstanceMember());
829
830 Attr *NewAttr = sema::instantiateTemplateAttribute(TmplAttr, Context,
831 *this, TemplateArgs);
832 if (NewAttr && isRelevantAttr(*this, New, TmplAttr))
833 New->addAttr(NewAttr);
834 }
835 }
836}
837
838/// Update instantiation attributes after template was late parsed.
839///
840/// Some attributes are evaluated based on the body of template. If it is
841/// late parsed, such attributes cannot be evaluated when declaration is
842/// instantiated. This function is used to update instantiation attributes when
843/// template definition is ready.
844void Sema::updateAttrsForLateParsedTemplate(const Decl *Pattern, Decl *Inst) {
845 for (const auto *Attr : Pattern->attrs()) {
846 if (auto *A = dyn_cast<StrictFPAttr>(Attr)) {
847 if (!Inst->hasAttr<StrictFPAttr>())
848 Inst->addAttr(A->clone(getASTContext()));
849 continue;
850 }
851 }
852}
853
854/// In the MS ABI, we need to instantiate default arguments of dllexported
855/// default constructors along with the constructor definition. This allows IR
856/// gen to emit a constructor closure which calls the default constructor with
857/// its default arguments.
858void Sema::InstantiateDefaultCtorDefaultArgs(CXXConstructorDecl *Ctor) {
859 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && Ctor->isDefaultConstructor()) ?
void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && Ctor->isDefaultConstructor()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 860, __extension__
__PRETTY_FUNCTION__))
860 Ctor->isDefaultConstructor())(static_cast <bool> (Context.getTargetInfo().getCXXABI(
).isMicrosoft() && Ctor->isDefaultConstructor()) ?
void (0) : __assert_fail ("Context.getTargetInfo().getCXXABI().isMicrosoft() && Ctor->isDefaultConstructor()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 860, __extension__
__PRETTY_FUNCTION__))
;
861 unsigned NumParams = Ctor->getNumParams();
862 if (NumParams == 0)
863 return;
864 DLLExportAttr *Attr = Ctor->getAttr<DLLExportAttr>();
865 if (!Attr)
866 return;
867 for (unsigned I = 0; I != NumParams; ++I) {
868 (void)CheckCXXDefaultArgExpr(Attr->getLocation(), Ctor,
869 Ctor->getParamDecl(I));
870 CleanupVarDeclMarking();
871 }
872}
873
874/// Get the previous declaration of a declaration for the purposes of template
875/// instantiation. If this finds a previous declaration, then the previous
876/// declaration of the instantiation of D should be an instantiation of the
877/// result of this function.
878template<typename DeclT>
879static DeclT *getPreviousDeclForInstantiation(DeclT *D) {
880 DeclT *Result = D->getPreviousDecl();
881
882 // If the declaration is within a class, and the previous declaration was
883 // merged from a different definition of that class, then we don't have a
884 // previous declaration for the purpose of template instantiation.
885 if (Result && isa<CXXRecordDecl>(D->getDeclContext()) &&
886 D->getLexicalDeclContext() != Result->getLexicalDeclContext())
887 return nullptr;
888
889 return Result;
890}
891
892Decl *
893TemplateDeclInstantiator::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
894 llvm_unreachable("Translation units cannot be instantiated")::llvm::llvm_unreachable_internal("Translation units cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 894)
;
895}
896
897Decl *TemplateDeclInstantiator::VisitHLSLBufferDecl(HLSLBufferDecl *Decl) {
898 llvm_unreachable("HLSL buffer declarations cannot be instantiated")::llvm::llvm_unreachable_internal("HLSL buffer declarations cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 898)
;
899}
900
901Decl *
902TemplateDeclInstantiator::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
903 llvm_unreachable("pragma comment cannot be instantiated")::llvm::llvm_unreachable_internal("pragma comment cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 903)
;
904}
905
906Decl *TemplateDeclInstantiator::VisitPragmaDetectMismatchDecl(
907 PragmaDetectMismatchDecl *D) {
908 llvm_unreachable("pragma comment cannot be instantiated")::llvm::llvm_unreachable_internal("pragma comment cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 908)
;
909}
910
911Decl *
912TemplateDeclInstantiator::VisitExternCContextDecl(ExternCContextDecl *D) {
913 llvm_unreachable("extern \"C\" context cannot be instantiated")::llvm::llvm_unreachable_internal("extern \"C\" context cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 913)
;
914}
915
916Decl *TemplateDeclInstantiator::VisitMSGuidDecl(MSGuidDecl *D) {
917 llvm_unreachable("GUID declaration cannot be instantiated")::llvm::llvm_unreachable_internal("GUID declaration cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 917)
;
918}
919
920Decl *TemplateDeclInstantiator::VisitUnnamedGlobalConstantDecl(
921 UnnamedGlobalConstantDecl *D) {
922 llvm_unreachable("UnnamedGlobalConstantDecl cannot be instantiated")::llvm::llvm_unreachable_internal("UnnamedGlobalConstantDecl cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 922)
;
923}
924
925Decl *TemplateDeclInstantiator::VisitTemplateParamObjectDecl(
926 TemplateParamObjectDecl *D) {
927 llvm_unreachable("template parameter objects cannot be instantiated")::llvm::llvm_unreachable_internal("template parameter objects cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 927)
;
928}
929
930Decl *
931TemplateDeclInstantiator::VisitLabelDecl(LabelDecl *D) {
932 LabelDecl *Inst = LabelDecl::Create(SemaRef.Context, Owner, D->getLocation(),
933 D->getIdentifier());
934 Owner->addDecl(Inst);
935 return Inst;
936}
937
938Decl *
939TemplateDeclInstantiator::VisitNamespaceDecl(NamespaceDecl *D) {
940 llvm_unreachable("Namespaces cannot be instantiated")::llvm::llvm_unreachable_internal("Namespaces cannot be instantiated"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 940)
;
941}
942
943Decl *
944TemplateDeclInstantiator::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
945 NamespaceAliasDecl *Inst
946 = NamespaceAliasDecl::Create(SemaRef.Context, Owner,
947 D->getNamespaceLoc(),
948 D->getAliasLoc(),
949 D->getIdentifier(),
950 D->getQualifierLoc(),
951 D->getTargetNameLoc(),
952 D->getNamespace());
953 Owner->addDecl(Inst);
954 return Inst;
955}
956
957Decl *TemplateDeclInstantiator::InstantiateTypedefNameDecl(TypedefNameDecl *D,
958 bool IsTypeAlias) {
959 bool Invalid = false;
960 TypeSourceInfo *DI = D->getTypeSourceInfo();
961 if (DI->getType()->isInstantiationDependentType() ||
962 DI->getType()->isVariablyModifiedType()) {
963 DI = SemaRef.SubstType(DI, TemplateArgs,
964 D->getLocation(), D->getDeclName());
965 if (!DI) {
966 Invalid = true;
967 DI = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.Context.IntTy);
968 }
969 } else {
970 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
971 }
972
973 // HACK: 2012-10-23 g++ has a bug where it gets the value kind of ?: wrong.
974 // libstdc++ relies upon this bug in its implementation of common_type. If we
975 // happen to be processing that implementation, fake up the g++ ?:
976 // semantics. See LWG issue 2141 for more information on the bug. The bugs
977 // are fixed in g++ and libstdc++ 4.9.0 (2014-04-22).
978 const DecltypeType *DT = DI->getType()->getAs<DecltypeType>();
979 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D->getDeclContext());
980 if (DT && RD && isa<ConditionalOperator>(DT->getUnderlyingExpr()) &&
981 DT->isReferenceType() &&
982 RD->getEnclosingNamespaceContext() == SemaRef.getStdNamespace() &&
983 RD->getIdentifier() && RD->getIdentifier()->isStr("common_type") &&
984 D->getIdentifier() && D->getIdentifier()->isStr("type") &&
985 SemaRef.getSourceManager().isInSystemHeader(D->getBeginLoc()))
986 // Fold it to the (non-reference) type which g++ would have produced.
987 DI = SemaRef.Context.getTrivialTypeSourceInfo(
988 DI->getType().getNonReferenceType());
989
990 // Create the new typedef
991 TypedefNameDecl *Typedef;
992 if (IsTypeAlias)
993 Typedef = TypeAliasDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
994 D->getLocation(), D->getIdentifier(), DI);
995 else
996 Typedef = TypedefDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
997 D->getLocation(), D->getIdentifier(), DI);
998 if (Invalid)
999 Typedef->setInvalidDecl();
1000
1001 // If the old typedef was the name for linkage purposes of an anonymous
1002 // tag decl, re-establish that relationship for the new typedef.
1003 if (const TagType *oldTagType = D->getUnderlyingType()->getAs<TagType>()) {
1004 TagDecl *oldTag = oldTagType->getDecl();
1005 if (oldTag->getTypedefNameForAnonDecl() == D && !Invalid) {
1006 TagDecl *newTag = DI->getType()->castAs<TagType>()->getDecl();
1007 assert(!newTag->hasNameForLinkage())(static_cast <bool> (!newTag->hasNameForLinkage()) ?
void (0) : __assert_fail ("!newTag->hasNameForLinkage()",
"clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1007, __extension__
__PRETTY_FUNCTION__))
;
1008 newTag->setTypedefNameForAnonDecl(Typedef);
1009 }
1010 }
1011
1012 if (TypedefNameDecl *Prev = getPreviousDeclForInstantiation(D)) {
1013 NamedDecl *InstPrev = SemaRef.FindInstantiatedDecl(D->getLocation(), Prev,
1014 TemplateArgs);
1015 if (!InstPrev)
1016 return nullptr;
1017
1018 TypedefNameDecl *InstPrevTypedef = cast<TypedefNameDecl>(InstPrev);
1019
1020 // If the typedef types are not identical, reject them.
1021 SemaRef.isIncompatibleTypedef(InstPrevTypedef, Typedef);
1022
1023 Typedef->setPreviousDecl(InstPrevTypedef);
1024 }
1025
1026 SemaRef.InstantiateAttrs(TemplateArgs, D, Typedef);
1027
1028 if (D->getUnderlyingType()->getAs<DependentNameType>())
1029 SemaRef.inferGslPointerAttribute(Typedef);
1030
1031 Typedef->setAccess(D->getAccess());
1032 Typedef->setReferenced(D->isReferenced());
1033
1034 return Typedef;
1035}
1036
1037Decl *TemplateDeclInstantiator::VisitTypedefDecl(TypedefDecl *D) {
1038 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/false);
1039 if (Typedef)
1040 Owner->addDecl(Typedef);
1041 return Typedef;
1042}
1043
1044Decl *TemplateDeclInstantiator::VisitTypeAliasDecl(TypeAliasDecl *D) {
1045 Decl *Typedef = InstantiateTypedefNameDecl(D, /*IsTypeAlias=*/true);
1046 if (Typedef)
1047 Owner->addDecl(Typedef);
1048 return Typedef;
1049}
1050
1051Decl *
1052TemplateDeclInstantiator::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1053 // Create a local instantiation scope for this type alias template, which
1054 // will contain the instantiations of the template parameters.
1055 LocalInstantiationScope Scope(SemaRef);
1056
1057 TemplateParameterList *TempParams = D->getTemplateParameters();
1058 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1059 if (!InstParams)
1060 return nullptr;
1061
1062 TypeAliasDecl *Pattern = D->getTemplatedDecl();
1063
1064 TypeAliasTemplateDecl *PrevAliasTemplate = nullptr;
1065 if (getPreviousDeclForInstantiation<TypedefNameDecl>(Pattern)) {
1066 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1067 if (!Found.empty()) {
1068 PrevAliasTemplate = dyn_cast<TypeAliasTemplateDecl>(Found.front());
1069 }
1070 }
1071
1072 TypeAliasDecl *AliasInst = cast_or_null<TypeAliasDecl>(
1073 InstantiateTypedefNameDecl(Pattern, /*IsTypeAlias=*/true));
1074 if (!AliasInst)
1075 return nullptr;
1076
1077 TypeAliasTemplateDecl *Inst
1078 = TypeAliasTemplateDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1079 D->getDeclName(), InstParams, AliasInst);
1080 AliasInst->setDescribedAliasTemplate(Inst);
1081 if (PrevAliasTemplate)
1082 Inst->setPreviousDecl(PrevAliasTemplate);
1083
1084 Inst->setAccess(D->getAccess());
1085
1086 if (!PrevAliasTemplate)
1087 Inst->setInstantiatedFromMemberTemplate(D);
1088
1089 Owner->addDecl(Inst);
1090
1091 return Inst;
1092}
1093
1094Decl *TemplateDeclInstantiator::VisitBindingDecl(BindingDecl *D) {
1095 auto *NewBD = BindingDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1096 D->getIdentifier());
1097 NewBD->setReferenced(D->isReferenced());
1098 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewBD);
1099 return NewBD;
1100}
1101
1102Decl *TemplateDeclInstantiator::VisitDecompositionDecl(DecompositionDecl *D) {
1103 // Transform the bindings first.
1104 SmallVector<BindingDecl*, 16> NewBindings;
1105 for (auto *OldBD : D->bindings())
1106 NewBindings.push_back(cast<BindingDecl>(VisitBindingDecl(OldBD)));
1107 ArrayRef<BindingDecl*> NewBindingArray = NewBindings;
1108
1109 auto *NewDD = cast_or_null<DecompositionDecl>(
1110 VisitVarDecl(D, /*InstantiatingVarTemplate=*/false, &NewBindingArray));
1111
1112 if (!NewDD || NewDD->isInvalidDecl())
1113 for (auto *NewBD : NewBindings)
1114 NewBD->setInvalidDecl();
1115
1116 return NewDD;
1117}
1118
1119Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D) {
1120 return VisitVarDecl(D, /*InstantiatingVarTemplate=*/false);
1121}
1122
1123Decl *TemplateDeclInstantiator::VisitVarDecl(VarDecl *D,
1124 bool InstantiatingVarTemplate,
1125 ArrayRef<BindingDecl*> *Bindings) {
1126
1127 // Do substitution on the type of the declaration
1128 TypeSourceInfo *DI = SemaRef.SubstType(
1129 D->getTypeSourceInfo(), TemplateArgs, D->getTypeSpecStartLoc(),
1130 D->getDeclName(), /*AllowDeducedTST*/true);
1131 if (!DI)
1132 return nullptr;
1133
1134 if (DI->getType()->isFunctionType()) {
1135 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
1136 << D->isStaticDataMember() << DI->getType();
1137 return nullptr;
1138 }
1139
1140 DeclContext *DC = Owner;
1141 if (D->isLocalExternDecl())
1142 SemaRef.adjustContextForLocalExternDecl(DC);
1143
1144 // Build the instantiated declaration.
1145 VarDecl *Var;
1146 if (Bindings)
1147 Var = DecompositionDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1148 D->getLocation(), DI->getType(), DI,
1149 D->getStorageClass(), *Bindings);
1150 else
1151 Var = VarDecl::Create(SemaRef.Context, DC, D->getInnerLocStart(),
1152 D->getLocation(), D->getIdentifier(), DI->getType(),
1153 DI, D->getStorageClass());
1154
1155 // In ARC, infer 'retaining' for variables of retainable type.
1156 if (SemaRef.getLangOpts().ObjCAutoRefCount &&
1157 SemaRef.inferObjCARCLifetime(Var))
1158 Var->setInvalidDecl();
1159
1160 if (SemaRef.getLangOpts().OpenCL)
1161 SemaRef.deduceOpenCLAddressSpace(Var);
1162
1163 // Substitute the nested name specifier, if any.
1164 if (SubstQualifier(D, Var))
1165 return nullptr;
1166
1167 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
1168 StartingScope, InstantiatingVarTemplate);
1169 if (D->isNRVOVariable() && !Var->isInvalidDecl()) {
1170 QualType RT;
1171 if (auto *F = dyn_cast<FunctionDecl>(DC))
1172 RT = F->getReturnType();
1173 else if (isa<BlockDecl>(DC))
1174 RT = cast<FunctionType>(SemaRef.getCurBlock()->FunctionType)
1175 ->getReturnType();
1176 else
1177 llvm_unreachable("Unknown context type")::llvm::llvm_unreachable_internal("Unknown context type", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 1177)
;
1178
1179 // This is the last chance we have of checking copy elision eligibility
1180 // for functions in dependent contexts. The sema actions for building
1181 // the return statement during template instantiation will have no effect
1182 // regarding copy elision, since NRVO propagation runs on the scope exit
1183 // actions, and these are not run on instantiation.
1184 // This might run through some VarDecls which were returned from non-taken
1185 // 'if constexpr' branches, and these will end up being constructed on the
1186 // return slot even if they will never be returned, as a sort of accidental
1187 // 'optimization'. Notably, functions with 'auto' return types won't have it
1188 // deduced by this point. Coupled with the limitation described
1189 // previously, this makes it very hard to support copy elision for these.
1190 Sema::NamedReturnInfo Info = SemaRef.getNamedReturnInfo(Var);
1191 bool NRVO = SemaRef.getCopyElisionCandidate(Info, RT) != nullptr;
1192 Var->setNRVOVariable(NRVO);
1193 }
1194
1195 Var->setImplicit(D->isImplicit());
1196
1197 if (Var->isStaticLocal())
1198 SemaRef.CheckStaticLocalForDllExport(Var);
1199
1200 if (Var->getTLSKind())
1201 SemaRef.CheckThreadLocalForLargeAlignment(Var);
1202
1203 return Var;
1204}
1205
1206Decl *TemplateDeclInstantiator::VisitAccessSpecDecl(AccessSpecDecl *D) {
1207 AccessSpecDecl* AD
1208 = AccessSpecDecl::Create(SemaRef.Context, D->getAccess(), Owner,
1209 D->getAccessSpecifierLoc(), D->getColonLoc());
1210 Owner->addHiddenDecl(AD);
1211 return AD;
1212}
1213
1214Decl *TemplateDeclInstantiator::VisitFieldDecl(FieldDecl *D) {
1215 bool Invalid = false;
1216 TypeSourceInfo *DI = D->getTypeSourceInfo();
1217 if (DI->getType()->isInstantiationDependentType() ||
1218 DI->getType()->isVariablyModifiedType()) {
1219 DI = SemaRef.SubstType(DI, TemplateArgs,
1220 D->getLocation(), D->getDeclName());
1221 if (!DI) {
1222 DI = D->getTypeSourceInfo();
1223 Invalid = true;
1224 } else if (DI->getType()->isFunctionType()) {
1225 // C++ [temp.arg.type]p3:
1226 // If a declaration acquires a function type through a type
1227 // dependent on a template-parameter and this causes a
1228 // declaration that does not use the syntactic form of a
1229 // function declarator to have function type, the program is
1230 // ill-formed.
1231 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1232 << DI->getType();
1233 Invalid = true;
1234 }
1235 } else {
1236 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1237 }
1238
1239 Expr *BitWidth = D->getBitWidth();
1240 if (Invalid)
1241 BitWidth = nullptr;
1242 else if (BitWidth) {
1243 // The bit-width expression is a constant expression.
1244 EnterExpressionEvaluationContext Unevaluated(
1245 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1246
1247 ExprResult InstantiatedBitWidth
1248 = SemaRef.SubstExpr(BitWidth, TemplateArgs);
1249 if (InstantiatedBitWidth.isInvalid()) {
1250 Invalid = true;
1251 BitWidth = nullptr;
1252 } else
1253 BitWidth = InstantiatedBitWidth.getAs<Expr>();
1254 }
1255
1256 FieldDecl *Field = SemaRef.CheckFieldDecl(D->getDeclName(),
1257 DI->getType(), DI,
1258 cast<RecordDecl>(Owner),
1259 D->getLocation(),
1260 D->isMutable(),
1261 BitWidth,
1262 D->getInClassInitStyle(),
1263 D->getInnerLocStart(),
1264 D->getAccess(),
1265 nullptr);
1266 if (!Field) {
1267 cast<Decl>(Owner)->setInvalidDecl();
1268 return nullptr;
1269 }
1270
1271 SemaRef.InstantiateAttrs(TemplateArgs, D, Field, LateAttrs, StartingScope);
1272
1273 if (Field->hasAttrs())
1274 SemaRef.CheckAlignasUnderalignment(Field);
1275
1276 if (Invalid)
1277 Field->setInvalidDecl();
1278
1279 if (!Field->getDeclName()) {
1280 // Keep track of where this decl came from.
1281 SemaRef.Context.setInstantiatedFromUnnamedFieldDecl(Field, D);
1282 }
1283 if (CXXRecordDecl *Parent= dyn_cast<CXXRecordDecl>(Field->getDeclContext())) {
1284 if (Parent->isAnonymousStructOrUnion() &&
1285 Parent->getRedeclContext()->isFunctionOrMethod())
1286 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Field);
1287 }
1288
1289 Field->setImplicit(D->isImplicit());
1290 Field->setAccess(D->getAccess());
1291 Owner->addDecl(Field);
1292
1293 return Field;
1294}
1295
1296Decl *TemplateDeclInstantiator::VisitMSPropertyDecl(MSPropertyDecl *D) {
1297 bool Invalid = false;
1298 TypeSourceInfo *DI = D->getTypeSourceInfo();
1299
1300 if (DI->getType()->isVariablyModifiedType()) {
1301 SemaRef.Diag(D->getLocation(), diag::err_property_is_variably_modified)
1302 << D;
1303 Invalid = true;
1304 } else if (DI->getType()->isInstantiationDependentType()) {
1305 DI = SemaRef.SubstType(DI, TemplateArgs,
1306 D->getLocation(), D->getDeclName());
1307 if (!DI) {
1308 DI = D->getTypeSourceInfo();
1309 Invalid = true;
1310 } else if (DI->getType()->isFunctionType()) {
1311 // C++ [temp.arg.type]p3:
1312 // If a declaration acquires a function type through a type
1313 // dependent on a template-parameter and this causes a
1314 // declaration that does not use the syntactic form of a
1315 // function declarator to have function type, the program is
1316 // ill-formed.
1317 SemaRef.Diag(D->getLocation(), diag::err_field_instantiates_to_function)
1318 << DI->getType();
1319 Invalid = true;
1320 }
1321 } else {
1322 SemaRef.MarkDeclarationsReferencedInType(D->getLocation(), DI->getType());
1323 }
1324
1325 MSPropertyDecl *Property = MSPropertyDecl::Create(
1326 SemaRef.Context, Owner, D->getLocation(), D->getDeclName(), DI->getType(),
1327 DI, D->getBeginLoc(), D->getGetterId(), D->getSetterId());
1328
1329 SemaRef.InstantiateAttrs(TemplateArgs, D, Property, LateAttrs,
1330 StartingScope);
1331
1332 if (Invalid)
1333 Property->setInvalidDecl();
1334
1335 Property->setAccess(D->getAccess());
1336 Owner->addDecl(Property);
1337
1338 return Property;
1339}
1340
1341Decl *TemplateDeclInstantiator::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
1342 NamedDecl **NamedChain =
1343 new (SemaRef.Context)NamedDecl*[D->getChainingSize()];
1344
1345 int i = 0;
1346 for (auto *PI : D->chain()) {
1347 NamedDecl *Next = SemaRef.FindInstantiatedDecl(D->getLocation(), PI,
1348 TemplateArgs);
1349 if (!Next)
1350 return nullptr;
1351
1352 NamedChain[i++] = Next;
1353 }
1354
1355 QualType T = cast<FieldDecl>(NamedChain[i-1])->getType();
1356 IndirectFieldDecl *IndirectField = IndirectFieldDecl::Create(
1357 SemaRef.Context, Owner, D->getLocation(), D->getIdentifier(), T,
1358 {NamedChain, D->getChainingSize()});
1359
1360 for (const auto *Attr : D->attrs())
1361 IndirectField->addAttr(Attr->clone(SemaRef.Context));
1362
1363 IndirectField->setImplicit(D->isImplicit());
1364 IndirectField->setAccess(D->getAccess());
1365 Owner->addDecl(IndirectField);
1366 return IndirectField;
1367}
1368
1369Decl *TemplateDeclInstantiator::VisitFriendDecl(FriendDecl *D) {
1370 // Handle friend type expressions by simply substituting template
1371 // parameters into the pattern type and checking the result.
1372 if (TypeSourceInfo *Ty = D->getFriendType()) {
1373 TypeSourceInfo *InstTy;
1374 // If this is an unsupported friend, don't bother substituting template
1375 // arguments into it. The actual type referred to won't be used by any
1376 // parts of Clang, and may not be valid for instantiating. Just use the
1377 // same info for the instantiated friend.
1378 if (D->isUnsupportedFriend()) {
1379 InstTy = Ty;
1380 } else {
1381 InstTy = SemaRef.SubstType(Ty, TemplateArgs,
1382 D->getLocation(), DeclarationName());
1383 }
1384 if (!InstTy)
1385 return nullptr;
1386
1387 FriendDecl *FD = SemaRef.CheckFriendTypeDecl(D->getBeginLoc(),
1388 D->getFriendLoc(), InstTy);
1389 if (!FD)
1390 return nullptr;
1391
1392 FD->setAccess(AS_public);
1393 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1394 Owner->addDecl(FD);
1395 return FD;
1396 }
1397
1398 NamedDecl *ND = D->getFriendDecl();
1399 assert(ND && "friend decl must be a decl or a type!")(static_cast <bool> (ND && "friend decl must be a decl or a type!"
) ? void (0) : __assert_fail ("ND && \"friend decl must be a decl or a type!\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1399, __extension__
__PRETTY_FUNCTION__))
;
1400
1401 // All of the Visit implementations for the various potential friend
1402 // declarations have to be carefully written to work for friend
1403 // objects, with the most important detail being that the target
1404 // decl should almost certainly not be placed in Owner.
1405 Decl *NewND = Visit(ND);
1406 if (!NewND) return nullptr;
1407
1408 FriendDecl *FD =
1409 FriendDecl::Create(SemaRef.Context, Owner, D->getLocation(),
1410 cast<NamedDecl>(NewND), D->getFriendLoc());
1411 FD->setAccess(AS_public);
1412 FD->setUnsupportedFriend(D->isUnsupportedFriend());
1413 Owner->addDecl(FD);
1414 return FD;
1415}
1416
1417Decl *TemplateDeclInstantiator::VisitStaticAssertDecl(StaticAssertDecl *D) {
1418 Expr *AssertExpr = D->getAssertExpr();
1419
1420 // The expression in a static assertion is a constant expression.
1421 EnterExpressionEvaluationContext Unevaluated(
1422 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1423
1424 ExprResult InstantiatedAssertExpr
1425 = SemaRef.SubstExpr(AssertExpr, TemplateArgs);
1426 if (InstantiatedAssertExpr.isInvalid())
1427 return nullptr;
1428
1429 return SemaRef.BuildStaticAssertDeclaration(D->getLocation(),
1430 InstantiatedAssertExpr.get(),
1431 D->getMessage(),
1432 D->getRParenLoc(),
1433 D->isFailed());
1434}
1435
1436Decl *TemplateDeclInstantiator::VisitEnumDecl(EnumDecl *D) {
1437 EnumDecl *PrevDecl = nullptr;
1438 if (EnumDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1439 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1440 PatternPrev,
1441 TemplateArgs);
1442 if (!Prev) return nullptr;
1443 PrevDecl = cast<EnumDecl>(Prev);
1444 }
1445
1446 EnumDecl *Enum =
1447 EnumDecl::Create(SemaRef.Context, Owner, D->getBeginLoc(),
1448 D->getLocation(), D->getIdentifier(), PrevDecl,
1449 D->isScoped(), D->isScopedUsingClassTag(), D->isFixed());
1450 if (D->isFixed()) {
1451 if (TypeSourceInfo *TI = D->getIntegerTypeSourceInfo()) {
1452 // If we have type source information for the underlying type, it means it
1453 // has been explicitly set by the user. Perform substitution on it before
1454 // moving on.
1455 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1456 TypeSourceInfo *NewTI = SemaRef.SubstType(TI, TemplateArgs, UnderlyingLoc,
1457 DeclarationName());
1458 if (!NewTI || SemaRef.CheckEnumUnderlyingType(NewTI))
1459 Enum->setIntegerType(SemaRef.Context.IntTy);
1460 else
1461 Enum->setIntegerTypeSourceInfo(NewTI);
1462 } else {
1463 assert(!D->getIntegerType()->isDependentType()(static_cast <bool> (!D->getIntegerType()->isDependentType
() && "Dependent type without type source info") ? void
(0) : __assert_fail ("!D->getIntegerType()->isDependentType() && \"Dependent type without type source info\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1464, __extension__
__PRETTY_FUNCTION__))
1464 && "Dependent type without type source info")(static_cast <bool> (!D->getIntegerType()->isDependentType
() && "Dependent type without type source info") ? void
(0) : __assert_fail ("!D->getIntegerType()->isDependentType() && \"Dependent type without type source info\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1464, __extension__
__PRETTY_FUNCTION__))
;
1465 Enum->setIntegerType(D->getIntegerType());
1466 }
1467 }
1468
1469 SemaRef.InstantiateAttrs(TemplateArgs, D, Enum);
1470
1471 Enum->setInstantiationOfMemberEnum(D, TSK_ImplicitInstantiation);
1472 Enum->setAccess(D->getAccess());
1473 // Forward the mangling number from the template to the instantiated decl.
1474 SemaRef.Context.setManglingNumber(Enum, SemaRef.Context.getManglingNumber(D));
1475 // See if the old tag was defined along with a declarator.
1476 // If it did, mark the new tag as being associated with that declarator.
1477 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1478 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Enum, DD);
1479 // See if the old tag was defined along with a typedef.
1480 // If it did, mark the new tag as being associated with that typedef.
1481 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1482 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Enum, TND);
1483 if (SubstQualifier(D, Enum)) return nullptr;
1484 Owner->addDecl(Enum);
1485
1486 EnumDecl *Def = D->getDefinition();
1487 if (Def && Def != D) {
1488 // If this is an out-of-line definition of an enum member template, check
1489 // that the underlying types match in the instantiation of both
1490 // declarations.
1491 if (TypeSourceInfo *TI = Def->getIntegerTypeSourceInfo()) {
1492 SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
1493 QualType DefnUnderlying =
1494 SemaRef.SubstType(TI->getType(), TemplateArgs,
1495 UnderlyingLoc, DeclarationName());
1496 SemaRef.CheckEnumRedeclaration(Def->getLocation(), Def->isScoped(),
1497 DefnUnderlying, /*IsFixed=*/true, Enum);
1498 }
1499 }
1500
1501 // C++11 [temp.inst]p1: The implicit instantiation of a class template
1502 // specialization causes the implicit instantiation of the declarations, but
1503 // not the definitions of scoped member enumerations.
1504 //
1505 // DR1484 clarifies that enumeration definitions inside of a template
1506 // declaration aren't considered entities that can be separately instantiated
1507 // from the rest of the entity they are declared inside of.
1508 if (isDeclWithinFunction(D) ? D == Def : Def && !Enum->isScoped()) {
1509 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Enum);
1510 InstantiateEnumDefinition(Enum, Def);
1511 }
1512
1513 return Enum;
1514}
1515
1516void TemplateDeclInstantiator::InstantiateEnumDefinition(
1517 EnumDecl *Enum, EnumDecl *Pattern) {
1518 Enum->startDefinition();
1519
1520 // Update the location to refer to the definition.
1521 Enum->setLocation(Pattern->getLocation());
1522
1523 SmallVector<Decl*, 4> Enumerators;
1524
1525 EnumConstantDecl *LastEnumConst = nullptr;
1526 for (auto *EC : Pattern->enumerators()) {
1527 // The specified value for the enumerator.
1528 ExprResult Value((Expr *)nullptr);
1529 if (Expr *UninstValue = EC->getInitExpr()) {
1530 // The enumerator's value expression is a constant expression.
1531 EnterExpressionEvaluationContext Unevaluated(
1532 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1533
1534 Value = SemaRef.SubstExpr(UninstValue, TemplateArgs);
1535 }
1536
1537 // Drop the initial value and continue.
1538 bool isInvalid = false;
1539 if (Value.isInvalid()) {
1540 Value = nullptr;
1541 isInvalid = true;
1542 }
1543
1544 EnumConstantDecl *EnumConst
1545 = SemaRef.CheckEnumConstant(Enum, LastEnumConst,
1546 EC->getLocation(), EC->getIdentifier(),
1547 Value.get());
1548
1549 if (isInvalid) {
1550 if (EnumConst)
1551 EnumConst->setInvalidDecl();
1552 Enum->setInvalidDecl();
1553 }
1554
1555 if (EnumConst) {
1556 SemaRef.InstantiateAttrs(TemplateArgs, EC, EnumConst);
1557
1558 EnumConst->setAccess(Enum->getAccess());
1559 Enum->addDecl(EnumConst);
1560 Enumerators.push_back(EnumConst);
1561 LastEnumConst = EnumConst;
1562
1563 if (Pattern->getDeclContext()->isFunctionOrMethod() &&
1564 !Enum->isScoped()) {
1565 // If the enumeration is within a function or method, record the enum
1566 // constant as a local.
1567 SemaRef.CurrentInstantiationScope->InstantiatedLocal(EC, EnumConst);
1568 }
1569 }
1570 }
1571
1572 SemaRef.ActOnEnumBody(Enum->getLocation(), Enum->getBraceRange(), Enum,
1573 Enumerators, nullptr, ParsedAttributesView());
1574}
1575
1576Decl *TemplateDeclInstantiator::VisitEnumConstantDecl(EnumConstantDecl *D) {
1577 llvm_unreachable("EnumConstantDecls can only occur within EnumDecls.")::llvm::llvm_unreachable_internal("EnumConstantDecls can only occur within EnumDecls."
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1577)
;
1578}
1579
1580Decl *
1581TemplateDeclInstantiator::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1582 llvm_unreachable("BuiltinTemplateDecls cannot be instantiated.")::llvm::llvm_unreachable_internal("BuiltinTemplateDecls cannot be instantiated."
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1582)
;
1583}
1584
1585Decl *TemplateDeclInstantiator::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1586 bool isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
1587
1588 // Create a local instantiation scope for this class template, which
1589 // will contain the instantiations of the template parameters.
1590 LocalInstantiationScope Scope(SemaRef);
1591 TemplateParameterList *TempParams = D->getTemplateParameters();
1592 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1593 if (!InstParams)
1594 return nullptr;
1595
1596 CXXRecordDecl *Pattern = D->getTemplatedDecl();
1597
1598 // Instantiate the qualifier. We have to do this first in case
1599 // we're a friend declaration, because if we are then we need to put
1600 // the new declaration in the appropriate context.
1601 NestedNameSpecifierLoc QualifierLoc = Pattern->getQualifierLoc();
1602 if (QualifierLoc) {
1603 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
1604 TemplateArgs);
1605 if (!QualifierLoc)
1606 return nullptr;
1607 }
1608
1609 CXXRecordDecl *PrevDecl = nullptr;
1610 ClassTemplateDecl *PrevClassTemplate = nullptr;
1611
1612 if (!isFriend && getPreviousDeclForInstantiation(Pattern)) {
1613 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1614 if (!Found.empty()) {
1615 PrevClassTemplate = dyn_cast<ClassTemplateDecl>(Found.front());
1616 if (PrevClassTemplate)
1617 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1618 }
1619 }
1620
1621 // If this isn't a friend, then it's a member template, in which
1622 // case we just want to build the instantiation in the
1623 // specialization. If it is a friend, we want to build it in
1624 // the appropriate context.
1625 DeclContext *DC = Owner;
1626 if (isFriend) {
1627 if (QualifierLoc) {
1628 CXXScopeSpec SS;
1629 SS.Adopt(QualifierLoc);
1630 DC = SemaRef.computeDeclContext(SS);
1631 if (!DC) return nullptr;
1632 } else {
1633 DC = SemaRef.FindInstantiatedContext(Pattern->getLocation(),
1634 Pattern->getDeclContext(),
1635 TemplateArgs);
1636 }
1637
1638 // Look for a previous declaration of the template in the owning
1639 // context.
1640 LookupResult R(SemaRef, Pattern->getDeclName(), Pattern->getLocation(),
1641 Sema::LookupOrdinaryName,
1642 SemaRef.forRedeclarationInCurContext());
1643 SemaRef.LookupQualifiedName(R, DC);
1644
1645 if (R.isSingleResult()) {
1646 PrevClassTemplate = R.getAsSingle<ClassTemplateDecl>();
1647 if (PrevClassTemplate)
1648 PrevDecl = PrevClassTemplate->getTemplatedDecl();
1649 }
1650
1651 if (!PrevClassTemplate && QualifierLoc) {
1652 SemaRef.Diag(Pattern->getLocation(), diag::err_not_tag_in_scope)
1653 << D->getTemplatedDecl()->getTagKind() << Pattern->getDeclName() << DC
1654 << QualifierLoc.getSourceRange();
1655 return nullptr;
1656 }
1657 }
1658
1659 CXXRecordDecl *RecordInst = CXXRecordDecl::Create(
1660 SemaRef.Context, Pattern->getTagKind(), DC, Pattern->getBeginLoc(),
1661 Pattern->getLocation(), Pattern->getIdentifier(), PrevDecl,
1662 /*DelayTypeCreation=*/true);
1663 if (QualifierLoc)
1664 RecordInst->setQualifierInfo(QualifierLoc);
1665
1666 SemaRef.InstantiateAttrsForDecl(TemplateArgs, Pattern, RecordInst, LateAttrs,
1667 StartingScope);
1668
1669 ClassTemplateDecl *Inst
1670 = ClassTemplateDecl::Create(SemaRef.Context, DC, D->getLocation(),
1671 D->getIdentifier(), InstParams, RecordInst);
1672 RecordInst->setDescribedClassTemplate(Inst);
1673
1674 if (isFriend) {
1675 assert(!Owner->isDependentContext())(static_cast <bool> (!Owner->isDependentContext()) ?
void (0) : __assert_fail ("!Owner->isDependentContext()",
"clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1675, __extension__
__PRETTY_FUNCTION__))
;
1676 Inst->setLexicalDeclContext(Owner);
1677 RecordInst->setLexicalDeclContext(Owner);
1678
1679 if (PrevClassTemplate) {
1680 Inst->setCommonPtr(PrevClassTemplate->getCommonPtr());
1681 RecordInst->setTypeForDecl(
1682 PrevClassTemplate->getTemplatedDecl()->getTypeForDecl());
1683 const ClassTemplateDecl *MostRecentPrevCT =
1684 PrevClassTemplate->getMostRecentDecl();
1685 TemplateParameterList *PrevParams =
1686 MostRecentPrevCT->getTemplateParameters();
1687
1688 // Make sure the parameter lists match.
1689 if (!SemaRef.TemplateParameterListsAreEqual(
1690 RecordInst, InstParams, MostRecentPrevCT->getTemplatedDecl(),
1691 PrevParams, true, Sema::TPL_TemplateMatch))
1692 return nullptr;
1693
1694 // Do some additional validation, then merge default arguments
1695 // from the existing declarations.
1696 if (SemaRef.CheckTemplateParameterList(InstParams, PrevParams,
1697 Sema::TPC_ClassTemplate))
1698 return nullptr;
1699
1700 Inst->setAccess(PrevClassTemplate->getAccess());
1701 } else {
1702 Inst->setAccess(D->getAccess());
1703 }
1704
1705 Inst->setObjectOfFriendDecl();
1706 // TODO: do we want to track the instantiation progeny of this
1707 // friend target decl?
1708 } else {
1709 Inst->setAccess(D->getAccess());
1710 if (!PrevClassTemplate)
1711 Inst->setInstantiatedFromMemberTemplate(D);
1712 }
1713
1714 Inst->setPreviousDecl(PrevClassTemplate);
1715
1716 // Trigger creation of the type for the instantiation.
1717 SemaRef.Context.getInjectedClassNameType(
1718 RecordInst, Inst->getInjectedClassNameSpecialization());
1719
1720 // Finish handling of friends.
1721 if (isFriend) {
1722 DC->makeDeclVisibleInContext(Inst);
1723 return Inst;
1724 }
1725
1726 if (D->isOutOfLine()) {
1727 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1728 RecordInst->setLexicalDeclContext(D->getLexicalDeclContext());
1729 }
1730
1731 Owner->addDecl(Inst);
1732
1733 if (!PrevClassTemplate) {
1734 // Queue up any out-of-line partial specializations of this member
1735 // class template; the client will force their instantiation once
1736 // the enclosing class has been instantiated.
1737 SmallVector<ClassTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1738 D->getPartialSpecializations(PartialSpecs);
1739 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1740 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1741 OutOfLinePartialSpecs.push_back(std::make_pair(Inst, PartialSpecs[I]));
1742 }
1743
1744 return Inst;
1745}
1746
1747Decl *
1748TemplateDeclInstantiator::VisitClassTemplatePartialSpecializationDecl(
1749 ClassTemplatePartialSpecializationDecl *D) {
1750 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
1751
1752 // Lookup the already-instantiated declaration in the instantiation
1753 // of the class template and return that.
1754 DeclContext::lookup_result Found
1755 = Owner->lookup(ClassTemplate->getDeclName());
1756 if (Found.empty())
1757 return nullptr;
1758
1759 ClassTemplateDecl *InstClassTemplate
1760 = dyn_cast<ClassTemplateDecl>(Found.front());
1761 if (!InstClassTemplate)
1762 return nullptr;
1763
1764 if (ClassTemplatePartialSpecializationDecl *Result
1765 = InstClassTemplate->findPartialSpecInstantiatedFromMember(D))
1766 return Result;
1767
1768 return InstantiateClassTemplatePartialSpecialization(InstClassTemplate, D);
1769}
1770
1771Decl *TemplateDeclInstantiator::VisitVarTemplateDecl(VarTemplateDecl *D) {
1772 assert(D->getTemplatedDecl()->isStaticDataMember() &&(static_cast <bool> (D->getTemplatedDecl()->isStaticDataMember
() && "Only static data member templates are allowed."
) ? void (0) : __assert_fail ("D->getTemplatedDecl()->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1773, __extension__
__PRETTY_FUNCTION__))
1773 "Only static data member templates are allowed.")(static_cast <bool> (D->getTemplatedDecl()->isStaticDataMember
() && "Only static data member templates are allowed."
) ? void (0) : __assert_fail ("D->getTemplatedDecl()->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1773, __extension__
__PRETTY_FUNCTION__))
;
1774
1775 // Create a local instantiation scope for this variable template, which
1776 // will contain the instantiations of the template parameters.
1777 LocalInstantiationScope Scope(SemaRef);
1778 TemplateParameterList *TempParams = D->getTemplateParameters();
1779 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1780 if (!InstParams)
1781 return nullptr;
1782
1783 VarDecl *Pattern = D->getTemplatedDecl();
1784 VarTemplateDecl *PrevVarTemplate = nullptr;
1785
1786 if (getPreviousDeclForInstantiation(Pattern)) {
1787 DeclContext::lookup_result Found = Owner->lookup(Pattern->getDeclName());
1788 if (!Found.empty())
1789 PrevVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1790 }
1791
1792 VarDecl *VarInst =
1793 cast_or_null<VarDecl>(VisitVarDecl(Pattern,
1794 /*InstantiatingVarTemplate=*/true));
1795 if (!VarInst) return nullptr;
1796
1797 DeclContext *DC = Owner;
1798
1799 VarTemplateDecl *Inst = VarTemplateDecl::Create(
1800 SemaRef.Context, DC, D->getLocation(), D->getIdentifier(), InstParams,
1801 VarInst);
1802 VarInst->setDescribedVarTemplate(Inst);
1803 Inst->setPreviousDecl(PrevVarTemplate);
1804
1805 Inst->setAccess(D->getAccess());
1806 if (!PrevVarTemplate)
1807 Inst->setInstantiatedFromMemberTemplate(D);
1808
1809 if (D->isOutOfLine()) {
1810 Inst->setLexicalDeclContext(D->getLexicalDeclContext());
1811 VarInst->setLexicalDeclContext(D->getLexicalDeclContext());
1812 }
1813
1814 Owner->addDecl(Inst);
1815
1816 if (!PrevVarTemplate) {
1817 // Queue up any out-of-line partial specializations of this member
1818 // variable template; the client will force their instantiation once
1819 // the enclosing class has been instantiated.
1820 SmallVector<VarTemplatePartialSpecializationDecl *, 4> PartialSpecs;
1821 D->getPartialSpecializations(PartialSpecs);
1822 for (unsigned I = 0, N = PartialSpecs.size(); I != N; ++I)
1823 if (PartialSpecs[I]->getFirstDecl()->isOutOfLine())
1824 OutOfLineVarPartialSpecs.push_back(
1825 std::make_pair(Inst, PartialSpecs[I]));
1826 }
1827
1828 return Inst;
1829}
1830
1831Decl *TemplateDeclInstantiator::VisitVarTemplatePartialSpecializationDecl(
1832 VarTemplatePartialSpecializationDecl *D) {
1833 assert(D->isStaticDataMember() &&(static_cast <bool> (D->isStaticDataMember() &&
"Only static data member templates are allowed.") ? void (0)
: __assert_fail ("D->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1834, __extension__
__PRETTY_FUNCTION__))
1834 "Only static data member templates are allowed.")(static_cast <bool> (D->isStaticDataMember() &&
"Only static data member templates are allowed.") ? void (0)
: __assert_fail ("D->isStaticDataMember() && \"Only static data member templates are allowed.\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1834, __extension__
__PRETTY_FUNCTION__))
;
1835
1836 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
1837
1838 // Lookup the already-instantiated declaration and return that.
1839 DeclContext::lookup_result Found = Owner->lookup(VarTemplate->getDeclName());
1840 assert(!Found.empty() && "Instantiation found nothing?")(static_cast <bool> (!Found.empty() && "Instantiation found nothing?"
) ? void (0) : __assert_fail ("!Found.empty() && \"Instantiation found nothing?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1840, __extension__
__PRETTY_FUNCTION__))
;
1841
1842 VarTemplateDecl *InstVarTemplate = dyn_cast<VarTemplateDecl>(Found.front());
1843 assert(InstVarTemplate && "Instantiation did not find a variable template?")(static_cast <bool> (InstVarTemplate && "Instantiation did not find a variable template?"
) ? void (0) : __assert_fail ("InstVarTemplate && \"Instantiation did not find a variable template?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1843, __extension__
__PRETTY_FUNCTION__))
;
1844
1845 if (VarTemplatePartialSpecializationDecl *Result =
1846 InstVarTemplate->findPartialSpecInstantiatedFromMember(D))
1847 return Result;
1848
1849 return InstantiateVarTemplatePartialSpecialization(InstVarTemplate, D);
1850}
1851
1852Decl *
1853TemplateDeclInstantiator::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1854 // Create a local instantiation scope for this function template, which
1855 // will contain the instantiations of the template parameters and then get
1856 // merged with the local instantiation scope for the function template
1857 // itself.
1858 LocalInstantiationScope Scope(SemaRef);
1859 Sema::ConstraintEvalRAII<TemplateDeclInstantiator> RAII(*this);
1860
1861 TemplateParameterList *TempParams = D->getTemplateParameters();
1862 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
1863 if (!InstParams)
1864 return nullptr;
1865
1866 FunctionDecl *Instantiated = nullptr;
1867 if (CXXMethodDecl *DMethod = dyn_cast<CXXMethodDecl>(D->getTemplatedDecl()))
1868 Instantiated = cast_or_null<FunctionDecl>(VisitCXXMethodDecl(DMethod,
1869 InstParams));
1870 else
1871 Instantiated = cast_or_null<FunctionDecl>(VisitFunctionDecl(
1872 D->getTemplatedDecl(),
1873 InstParams));
1874
1875 if (!Instantiated)
1876 return nullptr;
1877
1878 // Link the instantiated function template declaration to the function
1879 // template from which it was instantiated.
1880 FunctionTemplateDecl *InstTemplate
1881 = Instantiated->getDescribedFunctionTemplate();
1882 InstTemplate->setAccess(D->getAccess());
1883 assert(InstTemplate &&(static_cast <bool> (InstTemplate && "VisitFunctionDecl/CXXMethodDecl didn't create a template!"
) ? void (0) : __assert_fail ("InstTemplate && \"VisitFunctionDecl/CXXMethodDecl didn't create a template!\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1884, __extension__
__PRETTY_FUNCTION__))
1884 "VisitFunctionDecl/CXXMethodDecl didn't create a template!")(static_cast <bool> (InstTemplate && "VisitFunctionDecl/CXXMethodDecl didn't create a template!"
) ? void (0) : __assert_fail ("InstTemplate && \"VisitFunctionDecl/CXXMethodDecl didn't create a template!\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1884, __extension__
__PRETTY_FUNCTION__))
;
1885
1886 bool isFriend = (InstTemplate->getFriendObjectKind() != Decl::FOK_None);
1887
1888 // Link the instantiation back to the pattern *unless* this is a
1889 // non-definition friend declaration.
1890 if (!InstTemplate->getInstantiatedFromMemberTemplate() &&
1891 !(isFriend && !D->getTemplatedDecl()->isThisDeclarationADefinition()))
1892 InstTemplate->setInstantiatedFromMemberTemplate(D);
1893
1894 // Make declarations visible in the appropriate context.
1895 if (!isFriend) {
1896 Owner->addDecl(InstTemplate);
1897 } else if (InstTemplate->getDeclContext()->isRecord() &&
1898 !getPreviousDeclForInstantiation(D)) {
1899 SemaRef.CheckFriendAccess(InstTemplate);
1900 }
1901
1902 return InstTemplate;
1903}
1904
1905Decl *TemplateDeclInstantiator::VisitCXXRecordDecl(CXXRecordDecl *D) {
1906 CXXRecordDecl *PrevDecl = nullptr;
1907 if (CXXRecordDecl *PatternPrev = getPreviousDeclForInstantiation(D)) {
1908 NamedDecl *Prev = SemaRef.FindInstantiatedDecl(D->getLocation(),
1909 PatternPrev,
1910 TemplateArgs);
1911 if (!Prev) return nullptr;
1912 PrevDecl = cast<CXXRecordDecl>(Prev);
1913 }
1914
1915 CXXRecordDecl *Record = nullptr;
1916 bool IsInjectedClassName = D->isInjectedClassName();
1917 if (D->isLambda())
1918 Record = CXXRecordDecl::CreateLambda(
1919 SemaRef.Context, Owner, D->getLambdaTypeInfo(), D->getLocation(),
1920 D->getLambdaDependencyKind(), D->isGenericLambda(),
1921 D->getLambdaCaptureDefault());
1922 else
1923 Record = CXXRecordDecl::Create(SemaRef.Context, D->getTagKind(), Owner,
1924 D->getBeginLoc(), D->getLocation(),
1925 D->getIdentifier(), PrevDecl,
1926 /*DelayTypeCreation=*/IsInjectedClassName);
1927 // Link the type of the injected-class-name to that of the outer class.
1928 if (IsInjectedClassName)
1929 (void)SemaRef.Context.getTypeDeclType(Record, cast<CXXRecordDecl>(Owner));
1930
1931 // Substitute the nested name specifier, if any.
1932 if (SubstQualifier(D, Record))
1933 return nullptr;
1934
1935 SemaRef.InstantiateAttrsForDecl(TemplateArgs, D, Record, LateAttrs,
1936 StartingScope);
1937
1938 Record->setImplicit(D->isImplicit());
1939 // FIXME: Check against AS_none is an ugly hack to work around the issue that
1940 // the tag decls introduced by friend class declarations don't have an access
1941 // specifier. Remove once this area of the code gets sorted out.
1942 if (D->getAccess() != AS_none)
1943 Record->setAccess(D->getAccess());
1944 if (!IsInjectedClassName)
1945 Record->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
1946
1947 // If the original function was part of a friend declaration,
1948 // inherit its namespace state.
1949 if (D->getFriendObjectKind())
1950 Record->setObjectOfFriendDecl();
1951
1952 // Make sure that anonymous structs and unions are recorded.
1953 if (D->isAnonymousStructOrUnion())
1954 Record->setAnonymousStructOrUnion(true);
1955
1956 if (D->isLocalClass())
1957 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Record);
1958
1959 // Forward the mangling number from the template to the instantiated decl.
1960 SemaRef.Context.setManglingNumber(Record,
1961 SemaRef.Context.getManglingNumber(D));
1962
1963 // See if the old tag was defined along with a declarator.
1964 // If it did, mark the new tag as being associated with that declarator.
1965 if (DeclaratorDecl *DD = SemaRef.Context.getDeclaratorForUnnamedTagDecl(D))
1966 SemaRef.Context.addDeclaratorForUnnamedTagDecl(Record, DD);
1967
1968 // See if the old tag was defined along with a typedef.
1969 // If it did, mark the new tag as being associated with that typedef.
1970 if (TypedefNameDecl *TND = SemaRef.Context.getTypedefNameForUnnamedTagDecl(D))
1971 SemaRef.Context.addTypedefNameForUnnamedTagDecl(Record, TND);
1972
1973 Owner->addDecl(Record);
1974
1975 // DR1484 clarifies that the members of a local class are instantiated as part
1976 // of the instantiation of their enclosing entity.
1977 if (D->isCompleteDefinition() && D->isLocalClass()) {
1978 Sema::LocalEagerInstantiationScope LocalInstantiations(SemaRef);
1979
1980 SemaRef.InstantiateClass(D->getLocation(), Record, D, TemplateArgs,
1981 TSK_ImplicitInstantiation,
1982 /*Complain=*/true);
1983
1984 // For nested local classes, we will instantiate the members when we
1985 // reach the end of the outermost (non-nested) local class.
1986 if (!D->isCXXClassMember())
1987 SemaRef.InstantiateClassMembers(D->getLocation(), Record, TemplateArgs,
1988 TSK_ImplicitInstantiation);
1989
1990 // This class may have local implicit instantiations that need to be
1991 // performed within this scope.
1992 LocalInstantiations.perform();
1993 }
1994
1995 SemaRef.DiagnoseUnusedNestedTypedefs(Record);
1996
1997 if (IsInjectedClassName)
1998 assert(Record->isInjectedClassName() && "Broken injected-class-name")(static_cast <bool> (Record->isInjectedClassName() &&
"Broken injected-class-name") ? void (0) : __assert_fail ("Record->isInjectedClassName() && \"Broken injected-class-name\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 1998, __extension__
__PRETTY_FUNCTION__))
;
1999
2000 return Record;
2001}
2002
2003/// Adjust the given function type for an instantiation of the
2004/// given declaration, to cope with modifications to the function's type that
2005/// aren't reflected in the type-source information.
2006///
2007/// \param D The declaration we're instantiating.
2008/// \param TInfo The already-instantiated type.
2009static QualType adjustFunctionTypeForInstantiation(ASTContext &Context,
2010 FunctionDecl *D,
2011 TypeSourceInfo *TInfo) {
2012 const FunctionProtoType *OrigFunc
2013 = D->getType()->castAs<FunctionProtoType>();
2014 const FunctionProtoType *NewFunc
2015 = TInfo->getType()->castAs<FunctionProtoType>();
2016 if (OrigFunc->getExtInfo() == NewFunc->getExtInfo())
2017 return TInfo->getType();
2018
2019 FunctionProtoType::ExtProtoInfo NewEPI = NewFunc->getExtProtoInfo();
2020 NewEPI.ExtInfo = OrigFunc->getExtInfo();
2021 return Context.getFunctionType(NewFunc->getReturnType(),
2022 NewFunc->getParamTypes(), NewEPI);
2023}
2024
2025/// Normal class members are of more specific types and therefore
2026/// don't make it here. This function serves three purposes:
2027/// 1) instantiating function templates
2028/// 2) substituting friend and local function declarations
2029/// 3) substituting deduction guide declarations for nested class templates
2030Decl *TemplateDeclInstantiator::VisitFunctionDecl(
2031 FunctionDecl *D, TemplateParameterList *TemplateParams,
2032 RewriteKind FunctionRewriteKind) {
2033 // Check whether there is already a function template specialization for
2034 // this declaration.
2035 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2036 if (FunctionTemplate && !TemplateParams) {
2037 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2038
2039 void *InsertPos = nullptr;
2040 FunctionDecl *SpecFunc
2041 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2042
2043 // If we already have a function template specialization, return it.
2044 if (SpecFunc)
2045 return SpecFunc;
2046 }
2047
2048 bool isFriend;
2049 if (FunctionTemplate)
2050 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2051 else
2052 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2053
2054 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2055 Owner->isFunctionOrMethod() ||
2056 !(isa<Decl>(Owner) &&
2057 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2058 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2059
2060 ExplicitSpecifier InstantiatedExplicitSpecifier;
2061 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2062 InstantiatedExplicitSpecifier = instantiateExplicitSpecifier(
2063 SemaRef, TemplateArgs, DGuide->getExplicitSpecifier(), DGuide);
2064 if (InstantiatedExplicitSpecifier.isInvalid())
2065 return nullptr;
2066 }
2067
2068 SmallVector<ParmVarDecl *, 4> Params;
2069 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2070 if (!TInfo)
2071 return nullptr;
2072 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2073
2074 if (TemplateParams && TemplateParams->size()) {
2075 auto *LastParam =
2076 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2077 if (LastParam && LastParam->isImplicit() &&
2078 LastParam->hasTypeConstraint()) {
2079 // In abbreviated templates, the type-constraints of invented template
2080 // type parameters are instantiated with the function type, invalidating
2081 // the TemplateParameterList which relied on the template type parameter
2082 // not having a type constraint. Recreate the TemplateParameterList with
2083 // the updated parameter list.
2084 TemplateParams = TemplateParameterList::Create(
2085 SemaRef.Context, TemplateParams->getTemplateLoc(),
2086 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2087 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2088 }
2089 }
2090
2091 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2092 if (QualifierLoc) {
2093 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2094 TemplateArgs);
2095 if (!QualifierLoc)
2096 return nullptr;
2097 }
2098
2099 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2100
2101 // If we're instantiating a local function declaration, put the result
2102 // in the enclosing namespace; otherwise we need to find the instantiated
2103 // context.
2104 DeclContext *DC;
2105 if (D->isLocalExternDecl()) {
2106 DC = Owner;
2107 SemaRef.adjustContextForLocalExternDecl(DC);
2108 } else if (isFriend && QualifierLoc) {
2109 CXXScopeSpec SS;
2110 SS.Adopt(QualifierLoc);
2111 DC = SemaRef.computeDeclContext(SS);
2112 if (!DC) return nullptr;
2113 } else {
2114 DC = SemaRef.FindInstantiatedContext(D->getLocation(), D->getDeclContext(),
2115 TemplateArgs);
2116 }
2117
2118 DeclarationNameInfo NameInfo
2119 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2120
2121 if (FunctionRewriteKind != RewriteKind::None)
2122 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2123
2124 FunctionDecl *Function;
2125 if (auto *DGuide = dyn_cast<CXXDeductionGuideDecl>(D)) {
2126 Function = CXXDeductionGuideDecl::Create(
2127 SemaRef.Context, DC, D->getInnerLocStart(),
2128 InstantiatedExplicitSpecifier, NameInfo, T, TInfo,
2129 D->getSourceRange().getEnd());
2130 if (DGuide->isCopyDeductionCandidate())
2131 cast<CXXDeductionGuideDecl>(Function)->setIsCopyDeductionCandidate();
2132 Function->setAccess(D->getAccess());
2133 } else {
2134 Function = FunctionDecl::Create(
2135 SemaRef.Context, DC, D->getInnerLocStart(), NameInfo, T, TInfo,
2136 D->getCanonicalDecl()->getStorageClass(), D->UsesFPIntrin(),
2137 D->isInlineSpecified(), D->hasWrittenPrototype(), D->getConstexprKind(),
2138 TrailingRequiresClause);
2139 Function->setFriendConstraintRefersToEnclosingTemplate(
2140 D->FriendConstraintRefersToEnclosingTemplate());
2141 Function->setRangeEnd(D->getSourceRange().getEnd());
2142 }
2143
2144 if (D->isInlined())
2145 Function->setImplicitlyInline();
2146
2147 if (QualifierLoc)
2148 Function->setQualifierInfo(QualifierLoc);
2149
2150 if (D->isLocalExternDecl())
2151 Function->setLocalExternDecl();
2152
2153 DeclContext *LexicalDC = Owner;
2154 if (!isFriend && D->isOutOfLine() && !D->isLocalExternDecl()) {
2155 assert(D->getDeclContext()->isFileContext())(static_cast <bool> (D->getDeclContext()->isFileContext
()) ? void (0) : __assert_fail ("D->getDeclContext()->isFileContext()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2155, __extension__
__PRETTY_FUNCTION__))
;
2156 LexicalDC = D->getDeclContext();
2157 }
2158 else if (D->isLocalExternDecl()) {
2159 LexicalDC = SemaRef.CurContext;
2160 }
2161
2162 Function->setLexicalDeclContext(LexicalDC);
2163
2164 // Attach the parameters
2165 for (unsigned P = 0; P < Params.size(); ++P)
2166 if (Params[P])
2167 Params[P]->setOwningFunction(Function);
2168 Function->setParams(Params);
2169
2170 if (TrailingRequiresClause)
2171 Function->setTrailingRequiresClause(TrailingRequiresClause);
2172
2173 if (TemplateParams) {
2174 // Our resulting instantiation is actually a function template, since we
2175 // are substituting only the outer template parameters. For example, given
2176 //
2177 // template<typename T>
2178 // struct X {
2179 // template<typename U> friend void f(T, U);
2180 // };
2181 //
2182 // X<int> x;
2183 //
2184 // We are instantiating the friend function template "f" within X<int>,
2185 // which means substituting int for T, but leaving "f" as a friend function
2186 // template.
2187 // Build the function template itself.
2188 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, DC,
2189 Function->getLocation(),
2190 Function->getDeclName(),
2191 TemplateParams, Function);
2192 Function->setDescribedFunctionTemplate(FunctionTemplate);
2193
2194 FunctionTemplate->setLexicalDeclContext(LexicalDC);
2195
2196 if (isFriend && D->isThisDeclarationADefinition()) {
2197 FunctionTemplate->setInstantiatedFromMemberTemplate(
2198 D->getDescribedFunctionTemplate());
2199 }
2200 } else if (FunctionTemplate) {
2201 // Record this function template specialization.
2202 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2203 Function->setFunctionTemplateSpecialization(FunctionTemplate,
2204 TemplateArgumentList::CreateCopy(SemaRef.Context,
2205 Innermost),
2206 /*InsertPos=*/nullptr);
2207 } else if (isFriend && D->isThisDeclarationADefinition()) {
2208 // Do not connect the friend to the template unless it's actually a
2209 // definition. We don't want non-template functions to be marked as being
2210 // template instantiations.
2211 Function->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2212 } else if (!isFriend) {
2213 // If this is not a function template, and this is not a friend (that is,
2214 // this is a locally declared function), save the instantiation relationship
2215 // for the purposes of constraint instantiation.
2216 Function->setInstantiatedFromDecl(D);
2217 }
2218
2219 if (isFriend) {
2220 Function->setObjectOfFriendDecl();
2221 if (FunctionTemplateDecl *FT = Function->getDescribedFunctionTemplate())
2222 FT->setObjectOfFriendDecl();
2223 }
2224
2225 if (InitFunctionInstantiation(Function, D))
2226 Function->setInvalidDecl();
2227
2228 bool IsExplicitSpecialization = false;
2229
2230 LookupResult Previous(
2231 SemaRef, Function->getDeclName(), SourceLocation(),
2232 D->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
2233 : Sema::LookupOrdinaryName,
2234 D->isLocalExternDecl() ? Sema::ForExternalRedeclaration
2235 : SemaRef.forRedeclarationInCurContext());
2236
2237 if (DependentFunctionTemplateSpecializationInfo *Info
2238 = D->getDependentSpecializationInfo()) {
2239 assert(isFriend && "non-friend has dependent specialization info?")(static_cast <bool> (isFriend && "non-friend has dependent specialization info?"
) ? void (0) : __assert_fail ("isFriend && \"non-friend has dependent specialization info?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2239, __extension__
__PRETTY_FUNCTION__))
;
2240
2241 // Instantiate the explicit template arguments.
2242 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2243 Info->getRAngleLoc());
2244 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2245 ExplicitArgs))
2246 return nullptr;
2247
2248 // Map the candidate templates to their instantiations.
2249 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2250 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2251 Info->getTemplate(I),
2252 TemplateArgs);
2253 if (!Temp) return nullptr;
2254
2255 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2256 }
2257
2258 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2259 &ExplicitArgs,
2260 Previous))
2261 Function->setInvalidDecl();
2262
2263 IsExplicitSpecialization = true;
2264 } else if (const ASTTemplateArgumentListInfo *Info =
2265 D->getTemplateSpecializationArgsAsWritten()) {
2266 // The name of this function was written as a template-id.
2267 SemaRef.LookupQualifiedName(Previous, DC);
2268
2269 // Instantiate the explicit template arguments.
2270 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2271 Info->getRAngleLoc());
2272 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2273 ExplicitArgs))
2274 return nullptr;
2275
2276 if (SemaRef.CheckFunctionTemplateSpecialization(Function,
2277 &ExplicitArgs,
2278 Previous))
2279 Function->setInvalidDecl();
2280
2281 IsExplicitSpecialization = true;
2282 } else if (TemplateParams || !FunctionTemplate) {
2283 // Look only into the namespace where the friend would be declared to
2284 // find a previous declaration. This is the innermost enclosing namespace,
2285 // as described in ActOnFriendFunctionDecl.
2286 SemaRef.LookupQualifiedName(Previous, DC->getRedeclContext());
2287
2288 // In C++, the previous declaration we find might be a tag type
2289 // (class or enum). In this case, the new declaration will hide the
2290 // tag type. Note that this does not apply if we're declaring a
2291 // typedef (C++ [dcl.typedef]p4).
2292 if (Previous.isSingleTagDecl())
2293 Previous.clear();
2294
2295 // Filter out previous declarations that don't match the scope. The only
2296 // effect this has is to remove declarations found in inline namespaces
2297 // for friend declarations with unqualified names.
2298 if (isFriend && !QualifierLoc) {
2299 SemaRef.FilterLookupForScope(Previous, DC, /*Scope=*/ nullptr,
2300 /*ConsiderLinkage=*/ true,
2301 QualifierLoc.hasQualifier());
2302 }
2303 }
2304
2305 // Per [temp.inst], default arguments in function declarations at local scope
2306 // are instantiated along with the enclosing declaration. For example:
2307 //
2308 // template<typename T>
2309 // void ft() {
2310 // void f(int = []{ return T::value; }());
2311 // }
2312 // template void ft<int>(); // error: type 'int' cannot be used prior
2313 // to '::' because it has no members
2314 //
2315 // The error is issued during instantiation of ft<int>() because substitution
2316 // into the default argument fails; the default argument is instantiated even
2317 // though it is never used.
2318 if (Function->isLocalExternDecl()) {
2319 for (ParmVarDecl *PVD : Function->parameters()) {
2320 if (!PVD->hasDefaultArg())
2321 continue;
2322 if (SemaRef.SubstDefaultArgument(D->getInnerLocStart(), PVD, TemplateArgs)) {
2323 // If substitution fails, the default argument is set to a
2324 // RecoveryExpr that wraps the uninstantiated default argument so
2325 // that downstream diagnostics are omitted.
2326 Expr *UninstExpr = PVD->getUninstantiatedDefaultArg();
2327 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2328 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2329 { UninstExpr }, UninstExpr->getType());
2330 if (ErrorResult.isUsable())
2331 PVD->setDefaultArg(ErrorResult.get());
2332 }
2333 }
2334 }
2335
2336 SemaRef.CheckFunctionDeclaration(/*Scope*/ nullptr, Function, Previous,
2337 IsExplicitSpecialization,
2338 Function->isThisDeclarationADefinition());
2339
2340 // Check the template parameter list against the previous declaration. The
2341 // goal here is to pick up default arguments added since the friend was
2342 // declared; we know the template parameter lists match, since otherwise
2343 // we would not have picked this template as the previous declaration.
2344 if (isFriend && TemplateParams && FunctionTemplate->getPreviousDecl()) {
2345 SemaRef.CheckTemplateParameterList(
2346 TemplateParams,
2347 FunctionTemplate->getPreviousDecl()->getTemplateParameters(),
2348 Function->isThisDeclarationADefinition()
2349 ? Sema::TPC_FriendFunctionTemplateDefinition
2350 : Sema::TPC_FriendFunctionTemplate);
2351 }
2352
2353 // If we're introducing a friend definition after the first use, trigger
2354 // instantiation.
2355 // FIXME: If this is a friend function template definition, we should check
2356 // to see if any specializations have been used.
2357 if (isFriend && D->isThisDeclarationADefinition() && Function->isUsed(false)) {
2358 if (MemberSpecializationInfo *MSInfo =
2359 Function->getMemberSpecializationInfo()) {
2360 if (MSInfo->getPointOfInstantiation().isInvalid()) {
2361 SourceLocation Loc = D->getLocation(); // FIXME
2362 MSInfo->setPointOfInstantiation(Loc);
2363 SemaRef.PendingLocalImplicitInstantiations.push_back(
2364 std::make_pair(Function, Loc));
2365 }
2366 }
2367 }
2368
2369 if (D->isExplicitlyDefaulted()) {
2370 if (SubstDefaultedFunction(Function, D))
2371 return nullptr;
2372 }
2373 if (D->isDeleted())
2374 SemaRef.SetDeclDeleted(Function, D->getLocation());
2375
2376 NamedDecl *PrincipalDecl =
2377 (TemplateParams ? cast<NamedDecl>(FunctionTemplate) : Function);
2378
2379 // If this declaration lives in a different context from its lexical context,
2380 // add it to the corresponding lookup table.
2381 if (isFriend ||
2382 (Function->isLocalExternDecl() && !Function->getPreviousDecl()))
2383 DC->makeDeclVisibleInContext(PrincipalDecl);
2384
2385 if (Function->isOverloadedOperator() && !DC->isRecord() &&
2386 PrincipalDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
2387 PrincipalDecl->setNonMemberOperator();
2388
2389 return Function;
2390}
2391
2392Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(
2393 CXXMethodDecl *D, TemplateParameterList *TemplateParams,
2394 std::optional<const ASTTemplateArgumentListInfo *>
2395 ClassScopeSpecializationArgs,
2396 RewriteKind FunctionRewriteKind) {
2397 FunctionTemplateDecl *FunctionTemplate = D->getDescribedFunctionTemplate();
2398 if (FunctionTemplate && !TemplateParams) {
2399 // We are creating a function template specialization from a function
2400 // template. Check whether there is already a function template
2401 // specialization for this particular set of template arguments.
2402 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2403
2404 void *InsertPos = nullptr;
2405 FunctionDecl *SpecFunc
2406 = FunctionTemplate->findSpecialization(Innermost, InsertPos);
2407
2408 // If we already have a function template specialization, return it.
2409 if (SpecFunc)
2410 return SpecFunc;
2411 }
2412
2413 bool isFriend;
2414 if (FunctionTemplate)
2415 isFriend = (FunctionTemplate->getFriendObjectKind() != Decl::FOK_None);
2416 else
2417 isFriend = (D->getFriendObjectKind() != Decl::FOK_None);
2418
2419 bool MergeWithParentScope = (TemplateParams != nullptr) ||
2420 !(isa<Decl>(Owner) &&
2421 cast<Decl>(Owner)->isDefinedOutsideFunctionOrMethod());
2422 LocalInstantiationScope Scope(SemaRef, MergeWithParentScope);
2423
2424 // Instantiate enclosing template arguments for friends.
2425 SmallVector<TemplateParameterList *, 4> TempParamLists;
2426 unsigned NumTempParamLists = 0;
2427 if (isFriend && (NumTempParamLists = D->getNumTemplateParameterLists())) {
2428 TempParamLists.resize(NumTempParamLists);
2429 for (unsigned I = 0; I != NumTempParamLists; ++I) {
2430 TemplateParameterList *TempParams = D->getTemplateParameterList(I);
2431 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
2432 if (!InstParams)
2433 return nullptr;
2434 TempParamLists[I] = InstParams;
2435 }
2436 }
2437
2438 ExplicitSpecifier InstantiatedExplicitSpecifier =
2439 instantiateExplicitSpecifier(SemaRef, TemplateArgs,
2440 ExplicitSpecifier::getFromDecl(D), D);
2441 if (InstantiatedExplicitSpecifier.isInvalid())
2442 return nullptr;
2443
2444 // Implicit destructors/constructors created for local classes in
2445 // DeclareImplicit* (see SemaDeclCXX.cpp) might not have an associated TSI.
2446 // Unfortunately there isn't enough context in those functions to
2447 // conditionally populate the TSI without breaking non-template related use
2448 // cases. Populate TSIs prior to calling SubstFunctionType to make sure we get
2449 // a proper transformation.
2450 if (cast<CXXRecordDecl>(D->getParent())->isLambda() &&
2451 !D->getTypeSourceInfo() &&
2452 isa<CXXConstructorDecl, CXXDestructorDecl>(D)) {
2453 TypeSourceInfo *TSI =
2454 SemaRef.Context.getTrivialTypeSourceInfo(D->getType());
2455 D->setTypeSourceInfo(TSI);
2456 }
2457
2458 SmallVector<ParmVarDecl *, 4> Params;
2459 TypeSourceInfo *TInfo = SubstFunctionType(D, Params);
2460 if (!TInfo)
2461 return nullptr;
2462 QualType T = adjustFunctionTypeForInstantiation(SemaRef.Context, D, TInfo);
2463
2464 if (TemplateParams && TemplateParams->size()) {
2465 auto *LastParam =
2466 dyn_cast<TemplateTypeParmDecl>(TemplateParams->asArray().back());
2467 if (LastParam && LastParam->isImplicit() &&
2468 LastParam->hasTypeConstraint()) {
2469 // In abbreviated templates, the type-constraints of invented template
2470 // type parameters are instantiated with the function type, invalidating
2471 // the TemplateParameterList which relied on the template type parameter
2472 // not having a type constraint. Recreate the TemplateParameterList with
2473 // the updated parameter list.
2474 TemplateParams = TemplateParameterList::Create(
2475 SemaRef.Context, TemplateParams->getTemplateLoc(),
2476 TemplateParams->getLAngleLoc(), TemplateParams->asArray(),
2477 TemplateParams->getRAngleLoc(), TemplateParams->getRequiresClause());
2478 }
2479 }
2480
2481 NestedNameSpecifierLoc QualifierLoc = D->getQualifierLoc();
2482 if (QualifierLoc) {
2483 QualifierLoc = SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc,
2484 TemplateArgs);
2485 if (!QualifierLoc)
2486 return nullptr;
2487 }
2488
2489 DeclContext *DC = Owner;
2490 if (isFriend) {
2491 if (QualifierLoc) {
2492 CXXScopeSpec SS;
2493 SS.Adopt(QualifierLoc);
2494 DC = SemaRef.computeDeclContext(SS);
2495
2496 if (DC && SemaRef.RequireCompleteDeclContext(SS, DC))
2497 return nullptr;
2498 } else {
2499 DC = SemaRef.FindInstantiatedContext(D->getLocation(),
2500 D->getDeclContext(),
2501 TemplateArgs);
2502 }
2503 if (!DC) return nullptr;
2504 }
2505
2506 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
2507 Expr *TrailingRequiresClause = D->getTrailingRequiresClause();
2508
2509 DeclarationNameInfo NameInfo
2510 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
2511
2512 if (FunctionRewriteKind != RewriteKind::None)
2513 adjustForRewrite(FunctionRewriteKind, D, T, TInfo, NameInfo);
2514
2515 // Build the instantiated method declaration.
2516 CXXMethodDecl *Method = nullptr;
2517
2518 SourceLocation StartLoc = D->getInnerLocStart();
2519 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(D)) {
2520 Method = CXXConstructorDecl::Create(
2521 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2522 InstantiatedExplicitSpecifier, Constructor->UsesFPIntrin(),
2523 Constructor->isInlineSpecified(), false,
2524 Constructor->getConstexprKind(), InheritedConstructor(),
2525 TrailingRequiresClause);
2526 Method->setRangeEnd(Constructor->getEndLoc());
2527 if (Constructor->isDefaultConstructor() ||
2528 Constructor->isCopyOrMoveConstructor())
2529 Method->setIneligibleOrNotSelected(true);
2530 } else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(D)) {
2531 Method = CXXDestructorDecl::Create(
2532 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2533 Destructor->UsesFPIntrin(), Destructor->isInlineSpecified(), false,
2534 Destructor->getConstexprKind(), TrailingRequiresClause);
2535 Method->setIneligibleOrNotSelected(true);
2536 Method->setRangeEnd(Destructor->getEndLoc());
2537 Method->setDeclName(SemaRef.Context.DeclarationNames.getCXXDestructorName(
2538 SemaRef.Context.getCanonicalType(
2539 SemaRef.Context.getTypeDeclType(Record))));
2540 } else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
2541 Method = CXXConversionDecl::Create(
2542 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo,
2543 Conversion->UsesFPIntrin(), Conversion->isInlineSpecified(),
2544 InstantiatedExplicitSpecifier, Conversion->getConstexprKind(),
2545 Conversion->getEndLoc(), TrailingRequiresClause);
2546 } else {
2547 StorageClass SC = D->isStatic() ? SC_Static : SC_None;
2548 Method = CXXMethodDecl::Create(
2549 SemaRef.Context, Record, StartLoc, NameInfo, T, TInfo, SC,
2550 D->UsesFPIntrin(), D->isInlineSpecified(), D->getConstexprKind(),
2551 D->getEndLoc(), TrailingRequiresClause);
2552 if (D->isMoveAssignmentOperator() || D->isCopyAssignmentOperator())
2553 Method->setIneligibleOrNotSelected(true);
2554 }
2555
2556 if (D->isInlined())
2557 Method->setImplicitlyInline();
2558
2559 if (QualifierLoc)
2560 Method->setQualifierInfo(QualifierLoc);
2561
2562 if (TemplateParams) {
2563 // Our resulting instantiation is actually a function template, since we
2564 // are substituting only the outer template parameters. For example, given
2565 //
2566 // template<typename T>
2567 // struct X {
2568 // template<typename U> void f(T, U);
2569 // };
2570 //
2571 // X<int> x;
2572 //
2573 // We are instantiating the member template "f" within X<int>, which means
2574 // substituting int for T, but leaving "f" as a member function template.
2575 // Build the function template itself.
2576 FunctionTemplate = FunctionTemplateDecl::Create(SemaRef.Context, Record,
2577 Method->getLocation(),
2578 Method->getDeclName(),
2579 TemplateParams, Method);
2580 if (isFriend) {
2581 FunctionTemplate->setLexicalDeclContext(Owner);
2582 FunctionTemplate->setObjectOfFriendDecl();
2583 } else if (D->isOutOfLine())
2584 FunctionTemplate->setLexicalDeclContext(D->getLexicalDeclContext());
2585 Method->setDescribedFunctionTemplate(FunctionTemplate);
2586 } else if (FunctionTemplate) {
2587 // Record this function template specialization.
2588 ArrayRef<TemplateArgument> Innermost = TemplateArgs.getInnermost();
2589 Method->setFunctionTemplateSpecialization(FunctionTemplate,
2590 TemplateArgumentList::CreateCopy(SemaRef.Context,
2591 Innermost),
2592 /*InsertPos=*/nullptr);
2593 } else if (!isFriend) {
2594 // Record that this is an instantiation of a member function.
2595 Method->setInstantiationOfMemberFunction(D, TSK_ImplicitInstantiation);
2596 }
2597
2598 // If we are instantiating a member function defined
2599 // out-of-line, the instantiation will have the same lexical
2600 // context (which will be a namespace scope) as the template.
2601 if (isFriend) {
2602 if (NumTempParamLists)
2603 Method->setTemplateParameterListsInfo(
2604 SemaRef.Context,
2605 llvm::ArrayRef(TempParamLists.data(), NumTempParamLists));
2606
2607 Method->setLexicalDeclContext(Owner);
2608 Method->setObjectOfFriendDecl();
2609 } else if (D->isOutOfLine())
2610 Method->setLexicalDeclContext(D->getLexicalDeclContext());
2611
2612 // Attach the parameters
2613 for (unsigned P = 0; P < Params.size(); ++P)
2614 Params[P]->setOwningFunction(Method);
2615 Method->setParams(Params);
2616
2617 if (InitMethodInstantiation(Method, D))
2618 Method->setInvalidDecl();
2619
2620 LookupResult Previous(SemaRef, NameInfo, Sema::LookupOrdinaryName,
2621 Sema::ForExternalRedeclaration);
2622
2623 bool IsExplicitSpecialization = false;
2624
2625 // If the name of this function was written as a template-id, instantiate
2626 // the explicit template arguments.
2627 if (DependentFunctionTemplateSpecializationInfo *Info
2628 = D->getDependentSpecializationInfo()) {
2629 assert(isFriend && "non-friend has dependent specialization info?")(static_cast <bool> (isFriend && "non-friend has dependent specialization info?"
) ? void (0) : __assert_fail ("isFriend && \"non-friend has dependent specialization info?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2629, __extension__
__PRETTY_FUNCTION__))
;
2630
2631 // Instantiate the explicit template arguments.
2632 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2633 Info->getRAngleLoc());
2634 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2635 ExplicitArgs))
2636 return nullptr;
2637
2638 // Map the candidate templates to their instantiations.
2639 for (unsigned I = 0, E = Info->getNumTemplates(); I != E; ++I) {
2640 Decl *Temp = SemaRef.FindInstantiatedDecl(D->getLocation(),
2641 Info->getTemplate(I),
2642 TemplateArgs);
2643 if (!Temp) return nullptr;
2644
2645 Previous.addDecl(cast<FunctionTemplateDecl>(Temp));
2646 }
2647
2648 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2649 &ExplicitArgs,
2650 Previous))
2651 Method->setInvalidDecl();
2652
2653 IsExplicitSpecialization = true;
2654 } else if (const ASTTemplateArgumentListInfo *Info =
2655 ClassScopeSpecializationArgs.value_or(
2656 D->getTemplateSpecializationArgsAsWritten())) {
2657 SemaRef.LookupQualifiedName(Previous, DC);
2658
2659 TemplateArgumentListInfo ExplicitArgs(Info->getLAngleLoc(),
2660 Info->getRAngleLoc());
2661 if (SemaRef.SubstTemplateArguments(Info->arguments(), TemplateArgs,
2662 ExplicitArgs))
2663 return nullptr;
2664
2665 if (SemaRef.CheckFunctionTemplateSpecialization(Method,
2666 &ExplicitArgs,
2667 Previous))
2668 Method->setInvalidDecl();
2669
2670 IsExplicitSpecialization = true;
2671 } else if (ClassScopeSpecializationArgs) {
2672 // Class-scope explicit specialization written without explicit template
2673 // arguments.
2674 SemaRef.LookupQualifiedName(Previous, DC);
2675 if (SemaRef.CheckFunctionTemplateSpecialization(Method, nullptr, Previous))
2676 Method->setInvalidDecl();
2677
2678 IsExplicitSpecialization = true;
2679 } else if (!FunctionTemplate || TemplateParams || isFriend) {
2680 SemaRef.LookupQualifiedName(Previous, Record);
2681
2682 // In C++, the previous declaration we find might be a tag type
2683 // (class or enum). In this case, the new declaration will hide the
2684 // tag type. Note that this does not apply if we're declaring a
2685 // typedef (C++ [dcl.typedef]p4).
2686 if (Previous.isSingleTagDecl())
2687 Previous.clear();
2688 }
2689
2690 // Per [temp.inst], default arguments in member functions of local classes
2691 // are instantiated along with the member function declaration. For example:
2692 //
2693 // template<typename T>
2694 // void ft() {
2695 // struct lc {
2696 // int operator()(int p = []{ return T::value; }());
2697 // };
2698 // }
2699 // template void ft<int>(); // error: type 'int' cannot be used prior
2700 // to '::'because it has no members
2701 //
2702 // The error is issued during instantiation of ft<int>()::lc::operator()
2703 // because substitution into the default argument fails; the default argument
2704 // is instantiated even though it is never used.
2705 if (D->isInLocalScopeForInstantiation()) {
2706 for (unsigned P = 0; P < Params.size(); ++P) {
2707 if (!Params[P]->hasDefaultArg())
2708 continue;
2709 if (SemaRef.SubstDefaultArgument(StartLoc, Params[P], TemplateArgs)) {
2710 // If substitution fails, the default argument is set to a
2711 // RecoveryExpr that wraps the uninstantiated default argument so
2712 // that downstream diagnostics are omitted.
2713 Expr *UninstExpr = Params[P]->getUninstantiatedDefaultArg();
2714 ExprResult ErrorResult = SemaRef.CreateRecoveryExpr(
2715 UninstExpr->getBeginLoc(), UninstExpr->getEndLoc(),
2716 { UninstExpr }, UninstExpr->getType());
2717 if (ErrorResult.isUsable())
2718 Params[P]->setDefaultArg(ErrorResult.get());
2719 }
2720 }
2721 }
2722
2723 SemaRef.CheckFunctionDeclaration(nullptr, Method, Previous,
2724 IsExplicitSpecialization,
2725 Method->isThisDeclarationADefinition());
2726
2727 if (D->isPure())
2728 SemaRef.CheckPureMethod(Method, SourceRange());
2729
2730 // Propagate access. For a non-friend declaration, the access is
2731 // whatever we're propagating from. For a friend, it should be the
2732 // previous declaration we just found.
2733 if (isFriend && Method->getPreviousDecl())
2734 Method->setAccess(Method->getPreviousDecl()->getAccess());
2735 else
2736 Method->setAccess(D->getAccess());
2737 if (FunctionTemplate)
2738 FunctionTemplate->setAccess(Method->getAccess());
2739
2740 SemaRef.CheckOverrideControl(Method);
2741
2742 // If a function is defined as defaulted or deleted, mark it as such now.
2743 if (D->isExplicitlyDefaulted()) {
2744 if (SubstDefaultedFunction(Method, D))
2745 return nullptr;
2746 }
2747 if (D->isDeletedAsWritten())
2748 SemaRef.SetDeclDeleted(Method, Method->getLocation());
2749
2750 // If this is an explicit specialization, mark the implicitly-instantiated
2751 // template specialization as being an explicit specialization too.
2752 // FIXME: Is this necessary?
2753 if (IsExplicitSpecialization && !isFriend)
2754 SemaRef.CompleteMemberSpecialization(Method, Previous);
2755
2756 // If there's a function template, let our caller handle it.
2757 if (FunctionTemplate) {
2758 // do nothing
2759
2760 // Don't hide a (potentially) valid declaration with an invalid one.
2761 } else if (Method->isInvalidDecl() && !Previous.empty()) {
2762 // do nothing
2763
2764 // Otherwise, check access to friends and make them visible.
2765 } else if (isFriend) {
2766 // We only need to re-check access for methods which we didn't
2767 // manage to match during parsing.
2768 if (!D->getPreviousDecl())
2769 SemaRef.CheckFriendAccess(Method);
2770
2771 Record->makeDeclVisibleInContext(Method);
2772
2773 // Otherwise, add the declaration. We don't need to do this for
2774 // class-scope specializations because we'll have matched them with
2775 // the appropriate template.
2776 } else {
2777 Owner->addDecl(Method);
2778 }
2779
2780 // PR17480: Honor the used attribute to instantiate member function
2781 // definitions
2782 if (Method->hasAttr<UsedAttr>()) {
2783 if (const auto *A = dyn_cast<CXXRecordDecl>(Owner)) {
2784 SourceLocation Loc;
2785 if (const MemberSpecializationInfo *MSInfo =
2786 A->getMemberSpecializationInfo())
2787 Loc = MSInfo->getPointOfInstantiation();
2788 else if (const auto *Spec = dyn_cast<ClassTemplateSpecializationDecl>(A))
2789 Loc = Spec->getPointOfInstantiation();
2790 SemaRef.MarkFunctionReferenced(Loc, Method);
2791 }
2792 }
2793
2794 return Method;
2795}
2796
2797Decl *TemplateDeclInstantiator::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
2798 return VisitCXXMethodDecl(D);
2799}
2800
2801Decl *TemplateDeclInstantiator::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
2802 return VisitCXXMethodDecl(D);
2803}
2804
2805Decl *TemplateDeclInstantiator::VisitCXXConversionDecl(CXXConversionDecl *D) {
2806 return VisitCXXMethodDecl(D);
2807}
2808
2809Decl *TemplateDeclInstantiator::VisitParmVarDecl(ParmVarDecl *D) {
2810 return SemaRef.SubstParmVarDecl(D, TemplateArgs, /*indexAdjustment*/ 0,
2811 std::nullopt,
2812 /*ExpectParameterPack=*/false);
2813}
2814
2815Decl *TemplateDeclInstantiator::VisitTemplateTypeParmDecl(
2816 TemplateTypeParmDecl *D) {
2817 assert(D->getTypeForDecl()->isTemplateTypeParmType())(static_cast <bool> (D->getTypeForDecl()->isTemplateTypeParmType
()) ? void (0) : __assert_fail ("D->getTypeForDecl()->isTemplateTypeParmType()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2817, __extension__
__PRETTY_FUNCTION__))
;
2818
2819 std::optional<unsigned> NumExpanded;
2820
2821 if (const TypeConstraint *TC = D->getTypeConstraint()) {
2822 if (D->isPackExpansion() && !D->isExpandedParameterPack()) {
2823 assert(TC->getTemplateArgsAsWritten() &&(static_cast <bool> (TC->getTemplateArgsAsWritten() &&
"type parameter can only be an expansion when explicit arguments "
"are specified") ? void (0) : __assert_fail ("TC->getTemplateArgsAsWritten() && \"type parameter can only be an expansion when explicit arguments \" \"are specified\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2825, __extension__
__PRETTY_FUNCTION__))
2824 "type parameter can only be an expansion when explicit arguments "(static_cast <bool> (TC->getTemplateArgsAsWritten() &&
"type parameter can only be an expansion when explicit arguments "
"are specified") ? void (0) : __assert_fail ("TC->getTemplateArgsAsWritten() && \"type parameter can only be an expansion when explicit arguments \" \"are specified\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2825, __extension__
__PRETTY_FUNCTION__))
2825 "are specified")(static_cast <bool> (TC->getTemplateArgsAsWritten() &&
"type parameter can only be an expansion when explicit arguments "
"are specified") ? void (0) : __assert_fail ("TC->getTemplateArgsAsWritten() && \"type parameter can only be an expansion when explicit arguments \" \"are specified\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 2825, __extension__
__PRETTY_FUNCTION__))
;
2826 // The template type parameter pack's type is a pack expansion of types.
2827 // Determine whether we need to expand this parameter pack into separate
2828 // types.
2829 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2830 for (auto &ArgLoc : TC->getTemplateArgsAsWritten()->arguments())
2831 SemaRef.collectUnexpandedParameterPacks(ArgLoc, Unexpanded);
2832
2833 // Determine whether the set of unexpanded parameter packs can and should
2834 // be expanded.
2835 bool Expand = true;
2836 bool RetainExpansion = false;
2837 if (SemaRef.CheckParameterPacksForExpansion(
2838 cast<CXXFoldExpr>(TC->getImmediatelyDeclaredConstraint())
2839 ->getEllipsisLoc(),
2840 SourceRange(TC->getConceptNameLoc(),
2841 TC->hasExplicitTemplateArgs() ?
2842 TC->getTemplateArgsAsWritten()->getRAngleLoc() :
2843 TC->getConceptNameInfo().getEndLoc()),
2844 Unexpanded, TemplateArgs, Expand, RetainExpansion, NumExpanded))
2845 return nullptr;
2846 }
2847 }
2848
2849 TemplateTypeParmDecl *Inst = TemplateTypeParmDecl::Create(
2850 SemaRef.Context, Owner, D->getBeginLoc(), D->getLocation(),
2851 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(), D->getIndex(),
2852 D->getIdentifier(), D->wasDeclaredWithTypename(), D->isParameterPack(),
2853 D->hasTypeConstraint(), NumExpanded);
2854
2855 Inst->setAccess(AS_public);
2856 Inst->setImplicit(D->isImplicit());
2857 if (auto *TC = D->getTypeConstraint()) {
2858 if (!D->isImplicit()) {
2859 // Invented template parameter type constraints will be instantiated
2860 // with the corresponding auto-typed parameter as it might reference
2861 // other parameters.
2862 if (SemaRef.SubstTypeConstraint(Inst, TC, TemplateArgs,
2863 EvaluateConstraints))
2864 return nullptr;
2865 }
2866 }
2867 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
2868 TypeSourceInfo *InstantiatedDefaultArg =
2869 SemaRef.SubstType(D->getDefaultArgumentInfo(), TemplateArgs,
2870 D->getDefaultArgumentLoc(), D->getDeclName());
2871 if (InstantiatedDefaultArg)
2872 Inst->setDefaultArgument(InstantiatedDefaultArg);
2873 }
2874
2875 // Introduce this template parameter's instantiation into the instantiation
2876 // scope.
2877 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Inst);
2878
2879 return Inst;
2880}
2881
2882Decl *TemplateDeclInstantiator::VisitNonTypeTemplateParmDecl(
2883 NonTypeTemplateParmDecl *D) {
2884 // Substitute into the type of the non-type template parameter.
2885 TypeLoc TL = D->getTypeSourceInfo()->getTypeLoc();
2886 SmallVector<TypeSourceInfo *, 4> ExpandedParameterPackTypesAsWritten;
2887 SmallVector<QualType, 4> ExpandedParameterPackTypes;
2888 bool IsExpandedParameterPack = false;
2889 TypeSourceInfo *DI;
2890 QualType T;
2891 bool Invalid = false;
2892
2893 if (D->isExpandedParameterPack()) {
2894 // The non-type template parameter pack is an already-expanded pack
2895 // expansion of types. Substitute into each of the expanded types.
2896 ExpandedParameterPackTypes.reserve(D->getNumExpansionTypes());
2897 ExpandedParameterPackTypesAsWritten.reserve(D->getNumExpansionTypes());
2898 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2899 TypeSourceInfo *NewDI =
2900 SemaRef.SubstType(D->getExpansionTypeSourceInfo(I), TemplateArgs,
2901 D->getLocation(), D->getDeclName());
2902 if (!NewDI)
2903 return nullptr;
2904
2905 QualType NewT =
2906 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2907 if (NewT.isNull())
2908 return nullptr;
2909
2910 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2911 ExpandedParameterPackTypes.push_back(NewT);
2912 }
2913
2914 IsExpandedParameterPack = true;
2915 DI = D->getTypeSourceInfo();
2916 T = DI->getType();
2917 } else if (D->isPackExpansion()) {
2918 // The non-type template parameter pack's type is a pack expansion of types.
2919 // Determine whether we need to expand this parameter pack into separate
2920 // types.
2921 PackExpansionTypeLoc Expansion = TL.castAs<PackExpansionTypeLoc>();
2922 TypeLoc Pattern = Expansion.getPatternLoc();
2923 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2924 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
2925
2926 // Determine whether the set of unexpanded parameter packs can and should
2927 // be expanded.
2928 bool Expand = true;
2929 bool RetainExpansion = false;
2930 std::optional<unsigned> OrigNumExpansions =
2931 Expansion.getTypePtr()->getNumExpansions();
2932 std::optional<unsigned> NumExpansions = OrigNumExpansions;
2933 if (SemaRef.CheckParameterPacksForExpansion(Expansion.getEllipsisLoc(),
2934 Pattern.getSourceRange(),
2935 Unexpanded,
2936 TemplateArgs,
2937 Expand, RetainExpansion,
2938 NumExpansions))
2939 return nullptr;
2940
2941 if (Expand) {
2942 for (unsigned I = 0; I != *NumExpansions; ++I) {
2943 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
2944 TypeSourceInfo *NewDI = SemaRef.SubstType(Pattern, TemplateArgs,
2945 D->getLocation(),
2946 D->getDeclName());
2947 if (!NewDI)
2948 return nullptr;
2949
2950 QualType NewT =
2951 SemaRef.CheckNonTypeTemplateParameterType(NewDI, D->getLocation());
2952 if (NewT.isNull())
2953 return nullptr;
2954
2955 ExpandedParameterPackTypesAsWritten.push_back(NewDI);
2956 ExpandedParameterPackTypes.push_back(NewT);
2957 }
2958
2959 // Note that we have an expanded parameter pack. The "type" of this
2960 // expanded parameter pack is the original expansion type, but callers
2961 // will end up using the expanded parameter pack types for type-checking.
2962 IsExpandedParameterPack = true;
2963 DI = D->getTypeSourceInfo();
2964 T = DI->getType();
2965 } else {
2966 // We cannot fully expand the pack expansion now, so substitute into the
2967 // pattern and create a new pack expansion type.
2968 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
2969 TypeSourceInfo *NewPattern = SemaRef.SubstType(Pattern, TemplateArgs,
2970 D->getLocation(),
2971 D->getDeclName());
2972 if (!NewPattern)
2973 return nullptr;
2974
2975 SemaRef.CheckNonTypeTemplateParameterType(NewPattern, D->getLocation());
2976 DI = SemaRef.CheckPackExpansion(NewPattern, Expansion.getEllipsisLoc(),
2977 NumExpansions);
2978 if (!DI)
2979 return nullptr;
2980
2981 T = DI->getType();
2982 }
2983 } else {
2984 // Simple case: substitution into a parameter that is not a parameter pack.
2985 DI = SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
2986 D->getLocation(), D->getDeclName());
2987 if (!DI)
2988 return nullptr;
2989
2990 // Check that this type is acceptable for a non-type template parameter.
2991 T = SemaRef.CheckNonTypeTemplateParameterType(DI, D->getLocation());
2992 if (T.isNull()) {
2993 T = SemaRef.Context.IntTy;
2994 Invalid = true;
2995 }
2996 }
2997
2998 NonTypeTemplateParmDecl *Param;
2999 if (IsExpandedParameterPack)
3000 Param = NonTypeTemplateParmDecl::Create(
3001 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3002 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3003 D->getPosition(), D->getIdentifier(), T, DI, ExpandedParameterPackTypes,
3004 ExpandedParameterPackTypesAsWritten);
3005 else
3006 Param = NonTypeTemplateParmDecl::Create(
3007 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3008 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3009 D->getPosition(), D->getIdentifier(), T, D->isParameterPack(), DI);
3010
3011 if (AutoTypeLoc AutoLoc = DI->getTypeLoc().getContainedAutoTypeLoc())
3012 if (AutoLoc.isConstrained())
3013 // Note: We attach the uninstantiated constriant here, so that it can be
3014 // instantiated relative to the top level, like all our other constraints.
3015 if (SemaRef.AttachTypeConstraint(
3016 AutoLoc, Param, D,
3017 IsExpandedParameterPack
3018 ? DI->getTypeLoc().getAs<PackExpansionTypeLoc>()
3019 .getEllipsisLoc()
3020 : SourceLocation()))
3021 Invalid = true;
3022
3023 Param->setAccess(AS_public);
3024 Param->setImplicit(D->isImplicit());
3025 if (Invalid)
3026 Param->setInvalidDecl();
3027
3028 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3029 EnterExpressionEvaluationContext ConstantEvaluated(
3030 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
3031 ExprResult Value = SemaRef.SubstExpr(D->getDefaultArgument(), TemplateArgs);
3032 if (!Value.isInvalid())
3033 Param->setDefaultArgument(Value.get());
3034 }
3035
3036 // Introduce this template parameter's instantiation into the instantiation
3037 // scope.
3038 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3039 return Param;
3040}
3041
3042static void collectUnexpandedParameterPacks(
3043 Sema &S,
3044 TemplateParameterList *Params,
3045 SmallVectorImpl<UnexpandedParameterPack> &Unexpanded) {
3046 for (const auto &P : *Params) {
3047 if (P->isTemplateParameterPack())
3048 continue;
3049 if (NonTypeTemplateParmDecl *NTTP = dyn_cast<NonTypeTemplateParmDecl>(P))
3050 S.collectUnexpandedParameterPacks(NTTP->getTypeSourceInfo()->getTypeLoc(),
3051 Unexpanded);
3052 if (TemplateTemplateParmDecl *TTP = dyn_cast<TemplateTemplateParmDecl>(P))
3053 collectUnexpandedParameterPacks(S, TTP->getTemplateParameters(),
3054 Unexpanded);
3055 }
3056}
3057
3058Decl *
3059TemplateDeclInstantiator::VisitTemplateTemplateParmDecl(
3060 TemplateTemplateParmDecl *D) {
3061 // Instantiate the template parameter list of the template template parameter.
3062 TemplateParameterList *TempParams = D->getTemplateParameters();
3063 TemplateParameterList *InstParams;
3064 SmallVector<TemplateParameterList*, 8> ExpandedParams;
3065
3066 bool IsExpandedParameterPack = false;
3067
3068 if (D->isExpandedParameterPack()) {
3069 // The template template parameter pack is an already-expanded pack
3070 // expansion of template parameters. Substitute into each of the expanded
3071 // parameters.
3072 ExpandedParams.reserve(D->getNumExpansionTemplateParameters());
3073 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
3074 I != N; ++I) {
3075 LocalInstantiationScope Scope(SemaRef);
3076 TemplateParameterList *Expansion =
3077 SubstTemplateParams(D->getExpansionTemplateParameters(I));
3078 if (!Expansion)
3079 return nullptr;
3080 ExpandedParams.push_back(Expansion);
3081 }
3082
3083 IsExpandedParameterPack = true;
3084 InstParams = TempParams;
3085 } else if (D->isPackExpansion()) {
3086 // The template template parameter pack expands to a pack of template
3087 // template parameters. Determine whether we need to expand this parameter
3088 // pack into separate parameters.
3089 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3090 collectUnexpandedParameterPacks(SemaRef, D->getTemplateParameters(),
3091 Unexpanded);
3092
3093 // Determine whether the set of unexpanded parameter packs can and should
3094 // be expanded.
3095 bool Expand = true;
3096 bool RetainExpansion = false;
3097 std::optional<unsigned> NumExpansions;
3098 if (SemaRef.CheckParameterPacksForExpansion(D->getLocation(),
3099 TempParams->getSourceRange(),
3100 Unexpanded,
3101 TemplateArgs,
3102 Expand, RetainExpansion,
3103 NumExpansions))
3104 return nullptr;
3105
3106 if (Expand) {
3107 for (unsigned I = 0; I != *NumExpansions; ++I) {
3108 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3109 LocalInstantiationScope Scope(SemaRef);
3110 TemplateParameterList *Expansion = SubstTemplateParams(TempParams);
3111 if (!Expansion)
3112 return nullptr;
3113 ExpandedParams.push_back(Expansion);
3114 }
3115
3116 // Note that we have an expanded parameter pack. The "type" of this
3117 // expanded parameter pack is the original expansion type, but callers
3118 // will end up using the expanded parameter pack types for type-checking.
3119 IsExpandedParameterPack = true;
3120 InstParams = TempParams;
3121 } else {
3122 // We cannot fully expand the pack expansion now, so just substitute
3123 // into the pattern.
3124 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3125
3126 LocalInstantiationScope Scope(SemaRef);
3127 InstParams = SubstTemplateParams(TempParams);
3128 if (!InstParams)
3129 return nullptr;
3130 }
3131 } else {
3132 // Perform the actual substitution of template parameters within a new,
3133 // local instantiation scope.
3134 LocalInstantiationScope Scope(SemaRef);
3135 InstParams = SubstTemplateParams(TempParams);
3136 if (!InstParams)
3137 return nullptr;
3138 }
3139
3140 // Build the template template parameter.
3141 TemplateTemplateParmDecl *Param;
3142 if (IsExpandedParameterPack)
3143 Param = TemplateTemplateParmDecl::Create(
3144 SemaRef.Context, Owner, D->getLocation(),
3145 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3146 D->getPosition(), D->getIdentifier(), InstParams, ExpandedParams);
3147 else
3148 Param = TemplateTemplateParmDecl::Create(
3149 SemaRef.Context, Owner, D->getLocation(),
3150 D->getDepth() - TemplateArgs.getNumSubstitutedLevels(),
3151 D->getPosition(), D->isParameterPack(), D->getIdentifier(), InstParams);
3152 if (D->hasDefaultArgument() && !D->defaultArgumentWasInherited()) {
3153 NestedNameSpecifierLoc QualifierLoc =
3154 D->getDefaultArgument().getTemplateQualifierLoc();
3155 QualifierLoc =
3156 SemaRef.SubstNestedNameSpecifierLoc(QualifierLoc, TemplateArgs);
3157 TemplateName TName = SemaRef.SubstTemplateName(
3158 QualifierLoc, D->getDefaultArgument().getArgument().getAsTemplate(),
3159 D->getDefaultArgument().getTemplateNameLoc(), TemplateArgs);
3160 if (!TName.isNull())
3161 Param->setDefaultArgument(
3162 SemaRef.Context,
3163 TemplateArgumentLoc(SemaRef.Context, TemplateArgument(TName),
3164 D->getDefaultArgument().getTemplateQualifierLoc(),
3165 D->getDefaultArgument().getTemplateNameLoc()));
3166 }
3167 Param->setAccess(AS_public);
3168 Param->setImplicit(D->isImplicit());
3169
3170 // Introduce this template parameter's instantiation into the instantiation
3171 // scope.
3172 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, Param);
3173
3174 return Param;
3175}
3176
3177Decl *TemplateDeclInstantiator::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
3178 // Using directives are never dependent (and never contain any types or
3179 // expressions), so they require no explicit instantiation work.
3180
3181 UsingDirectiveDecl *Inst
3182 = UsingDirectiveDecl::Create(SemaRef.Context, Owner, D->getLocation(),
3183 D->getNamespaceKeyLocation(),
3184 D->getQualifierLoc(),
3185 D->getIdentLocation(),
3186 D->getNominatedNamespace(),
3187 D->getCommonAncestor());
3188
3189 // Add the using directive to its declaration context
3190 // only if this is not a function or method.
3191 if (!Owner->isFunctionOrMethod())
3192 Owner->addDecl(Inst);
3193
3194 return Inst;
3195}
3196
3197Decl *TemplateDeclInstantiator::VisitBaseUsingDecls(BaseUsingDecl *D,
3198 BaseUsingDecl *Inst,
3199 LookupResult *Lookup) {
3200
3201 bool isFunctionScope = Owner->isFunctionOrMethod();
3202
3203 for (auto *Shadow : D->shadows()) {
3204 // FIXME: UsingShadowDecl doesn't preserve its immediate target, so
3205 // reconstruct it in the case where it matters. Hm, can we extract it from
3206 // the DeclSpec when parsing and save it in the UsingDecl itself?
3207 NamedDecl *OldTarget = Shadow->getTargetDecl();
3208 if (auto *CUSD = dyn_cast<ConstructorUsingShadowDecl>(Shadow))
3209 if (auto *BaseShadow = CUSD->getNominatedBaseClassShadowDecl())
3210 OldTarget = BaseShadow;
3211
3212 NamedDecl *InstTarget = nullptr;
3213 if (auto *EmptyD =
3214 dyn_cast<UnresolvedUsingIfExistsDecl>(Shadow->getTargetDecl())) {
3215 InstTarget = UnresolvedUsingIfExistsDecl::Create(
3216 SemaRef.Context, Owner, EmptyD->getLocation(), EmptyD->getDeclName());
3217 } else {
3218 InstTarget = cast_or_null<NamedDecl>(SemaRef.FindInstantiatedDecl(
3219 Shadow->getLocation(), OldTarget, TemplateArgs));
3220 }
3221 if (!InstTarget)
3222 return nullptr;
3223
3224 UsingShadowDecl *PrevDecl = nullptr;
3225 if (Lookup &&
3226 SemaRef.CheckUsingShadowDecl(Inst, InstTarget, *Lookup, PrevDecl))
3227 continue;
3228
3229 if (UsingShadowDecl *OldPrev = getPreviousDeclForInstantiation(Shadow))
3230 PrevDecl = cast_or_null<UsingShadowDecl>(SemaRef.FindInstantiatedDecl(
3231 Shadow->getLocation(), OldPrev, TemplateArgs));
3232
3233 UsingShadowDecl *InstShadow = SemaRef.BuildUsingShadowDecl(
3234 /*Scope*/ nullptr, Inst, InstTarget, PrevDecl);
3235 SemaRef.Context.setInstantiatedFromUsingShadowDecl(InstShadow, Shadow);
3236
3237 if (isFunctionScope)
3238 SemaRef.CurrentInstantiationScope->InstantiatedLocal(Shadow, InstShadow);
3239 }
3240
3241 return Inst;
3242}
3243
3244Decl *TemplateDeclInstantiator::VisitUsingDecl(UsingDecl *D) {
3245
3246 // The nested name specifier may be dependent, for example
3247 // template <typename T> struct t {
3248 // struct s1 { T f1(); };
3249 // struct s2 : s1 { using s1::f1; };
3250 // };
3251 // template struct t<int>;
3252 // Here, in using s1::f1, s1 refers to t<T>::s1;
3253 // we need to substitute for t<int>::s1.
3254 NestedNameSpecifierLoc QualifierLoc
3255 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3256 TemplateArgs);
3257 if (!QualifierLoc)
3258 return nullptr;
3259
3260 // For an inheriting constructor declaration, the name of the using
3261 // declaration is the name of a constructor in this class, not in the
3262 // base class.
3263 DeclarationNameInfo NameInfo = D->getNameInfo();
3264 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3265 if (auto *RD = dyn_cast<CXXRecordDecl>(SemaRef.CurContext))
3266 NameInfo.setName(SemaRef.Context.DeclarationNames.getCXXConstructorName(
3267 SemaRef.Context.getCanonicalType(SemaRef.Context.getRecordType(RD))));
3268
3269 // We only need to do redeclaration lookups if we're in a class scope (in
3270 // fact, it's not really even possible in non-class scopes).
3271 bool CheckRedeclaration = Owner->isRecord();
3272 LookupResult Prev(SemaRef, NameInfo, Sema::LookupUsingDeclName,
3273 Sema::ForVisibleRedeclaration);
3274
3275 UsingDecl *NewUD = UsingDecl::Create(SemaRef.Context, Owner,
3276 D->getUsingLoc(),
3277 QualifierLoc,
3278 NameInfo,
3279 D->hasTypename());
3280
3281 CXXScopeSpec SS;
3282 SS.Adopt(QualifierLoc);
3283 if (CheckRedeclaration) {
3284 Prev.setHideTags(false);
3285 SemaRef.LookupQualifiedName(Prev, Owner);
3286
3287 // Check for invalid redeclarations.
3288 if (SemaRef.CheckUsingDeclRedeclaration(D->getUsingLoc(),
3289 D->hasTypename(), SS,
3290 D->getLocation(), Prev))
3291 NewUD->setInvalidDecl();
3292 }
3293
3294 if (!NewUD->isInvalidDecl() &&
3295 SemaRef.CheckUsingDeclQualifier(D->getUsingLoc(), D->hasTypename(), SS,
3296 NameInfo, D->getLocation(), nullptr, D))
3297 NewUD->setInvalidDecl();
3298
3299 SemaRef.Context.setInstantiatedFromUsingDecl(NewUD, D);
3300 NewUD->setAccess(D->getAccess());
3301 Owner->addDecl(NewUD);
3302
3303 // Don't process the shadow decls for an invalid decl.
3304 if (NewUD->isInvalidDecl())
3305 return NewUD;
3306
3307 // If the using scope was dependent, or we had dependent bases, we need to
3308 // recheck the inheritance
3309 if (NameInfo.getName().getNameKind() == DeclarationName::CXXConstructorName)
3310 SemaRef.CheckInheritingConstructorUsingDecl(NewUD);
3311
3312 return VisitBaseUsingDecls(D, NewUD, CheckRedeclaration ? &Prev : nullptr);
3313}
3314
3315Decl *TemplateDeclInstantiator::VisitUsingEnumDecl(UsingEnumDecl *D) {
3316 // Cannot be a dependent type, but still could be an instantiation
3317 EnumDecl *EnumD = cast_or_null<EnumDecl>(SemaRef.FindInstantiatedDecl(
3318 D->getLocation(), D->getEnumDecl(), TemplateArgs));
3319
3320 if (SemaRef.RequireCompleteEnumDecl(EnumD, EnumD->getLocation()))
3321 return nullptr;
3322
3323 TypeSourceInfo *TSI = SemaRef.SubstType(D->getEnumType(), TemplateArgs,
3324 D->getLocation(), D->getDeclName());
3325 UsingEnumDecl *NewUD =
3326 UsingEnumDecl::Create(SemaRef.Context, Owner, D->getUsingLoc(),
3327 D->getEnumLoc(), D->getLocation(), TSI);
3328
3329 SemaRef.Context.setInstantiatedFromUsingEnumDecl(NewUD, D);
3330 NewUD->setAccess(D->getAccess());
3331 Owner->addDecl(NewUD);
3332
3333 // Don't process the shadow decls for an invalid decl.
3334 if (NewUD->isInvalidDecl())
3335 return NewUD;
3336
3337 // We don't have to recheck for duplication of the UsingEnumDecl itself, as it
3338 // cannot be dependent, and will therefore have been checked during template
3339 // definition.
3340
3341 return VisitBaseUsingDecls(D, NewUD, nullptr);
3342}
3343
3344Decl *TemplateDeclInstantiator::VisitUsingShadowDecl(UsingShadowDecl *D) {
3345 // Ignore these; we handle them in bulk when processing the UsingDecl.
3346 return nullptr;
3347}
3348
3349Decl *TemplateDeclInstantiator::VisitConstructorUsingShadowDecl(
3350 ConstructorUsingShadowDecl *D) {
3351 // Ignore these; we handle them in bulk when processing the UsingDecl.
3352 return nullptr;
3353}
3354
3355template <typename T>
3356Decl *TemplateDeclInstantiator::instantiateUnresolvedUsingDecl(
3357 T *D, bool InstantiatingPackElement) {
3358 // If this is a pack expansion, expand it now.
3359 if (D->isPackExpansion() && !InstantiatingPackElement) {
3360 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
3361 SemaRef.collectUnexpandedParameterPacks(D->getQualifierLoc(), Unexpanded);
3362 SemaRef.collectUnexpandedParameterPacks(D->getNameInfo(), Unexpanded);
3363
3364 // Determine whether the set of unexpanded parameter packs can and should
3365 // be expanded.
3366 bool Expand = true;
3367 bool RetainExpansion = false;
3368 std::optional<unsigned> NumExpansions;
3369 if (SemaRef.CheckParameterPacksForExpansion(
3370 D->getEllipsisLoc(), D->getSourceRange(), Unexpanded, TemplateArgs,
3371 Expand, RetainExpansion, NumExpansions))
3372 return nullptr;
3373
3374 // This declaration cannot appear within a function template signature,
3375 // so we can't have a partial argument list for a parameter pack.
3376 assert(!RetainExpansion &&(static_cast <bool> (!RetainExpansion && "should never need to retain an expansion for UsingPackDecl"
) ? void (0) : __assert_fail ("!RetainExpansion && \"should never need to retain an expansion for UsingPackDecl\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3377, __extension__
__PRETTY_FUNCTION__))
3377 "should never need to retain an expansion for UsingPackDecl")(static_cast <bool> (!RetainExpansion && "should never need to retain an expansion for UsingPackDecl"
) ? void (0) : __assert_fail ("!RetainExpansion && \"should never need to retain an expansion for UsingPackDecl\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3377, __extension__
__PRETTY_FUNCTION__))
;
3378
3379 if (!Expand) {
3380 // We cannot fully expand the pack expansion now, so substitute into the
3381 // pattern and create a new pack expansion.
3382 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, -1);
3383 return instantiateUnresolvedUsingDecl(D, true);
3384 }
3385
3386 // Within a function, we don't have any normal way to check for conflicts
3387 // between shadow declarations from different using declarations in the
3388 // same pack expansion, but this is always ill-formed because all expansions
3389 // must produce (conflicting) enumerators.
3390 //
3391 // Sadly we can't just reject this in the template definition because it
3392 // could be valid if the pack is empty or has exactly one expansion.
3393 if (D->getDeclContext()->isFunctionOrMethod() && *NumExpansions > 1) {
3394 SemaRef.Diag(D->getEllipsisLoc(),
3395 diag::err_using_decl_redeclaration_expansion);
3396 return nullptr;
3397 }
3398
3399 // Instantiate the slices of this pack and build a UsingPackDecl.
3400 SmallVector<NamedDecl*, 8> Expansions;
3401 for (unsigned I = 0; I != *NumExpansions; ++I) {
3402 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
3403 Decl *Slice = instantiateUnresolvedUsingDecl(D, true);
3404 if (!Slice)
3405 return nullptr;
3406 // Note that we can still get unresolved using declarations here, if we
3407 // had arguments for all packs but the pattern also contained other
3408 // template arguments (this only happens during partial substitution, eg
3409 // into the body of a generic lambda in a function template).
3410 Expansions.push_back(cast<NamedDecl>(Slice));
3411 }
3412
3413 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3414 if (isDeclWithinFunction(D))
3415 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3416 return NewD;
3417 }
3418
3419 UnresolvedUsingTypenameDecl *TD = dyn_cast<UnresolvedUsingTypenameDecl>(D);
3420 SourceLocation TypenameLoc = TD ? TD->getTypenameLoc() : SourceLocation();
3421
3422 NestedNameSpecifierLoc QualifierLoc
3423 = SemaRef.SubstNestedNameSpecifierLoc(D->getQualifierLoc(),
3424 TemplateArgs);
3425 if (!QualifierLoc)
3426 return nullptr;
3427
3428 CXXScopeSpec SS;
3429 SS.Adopt(QualifierLoc);
3430
3431 DeclarationNameInfo NameInfo
3432 = SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
3433
3434 // Produce a pack expansion only if we're not instantiating a particular
3435 // slice of a pack expansion.
3436 bool InstantiatingSlice = D->getEllipsisLoc().isValid() &&
3437 SemaRef.ArgumentPackSubstitutionIndex != -1;
3438 SourceLocation EllipsisLoc =
3439 InstantiatingSlice ? SourceLocation() : D->getEllipsisLoc();
3440
3441 bool IsUsingIfExists = D->template hasAttr<UsingIfExistsAttr>();
3442 NamedDecl *UD = SemaRef.BuildUsingDeclaration(
3443 /*Scope*/ nullptr, D->getAccess(), D->getUsingLoc(),
3444 /*HasTypename*/ TD, TypenameLoc, SS, NameInfo, EllipsisLoc,
3445 ParsedAttributesView(),
3446 /*IsInstantiation*/ true, IsUsingIfExists);
3447 if (UD) {
3448 SemaRef.InstantiateAttrs(TemplateArgs, D, UD);
3449 SemaRef.Context.setInstantiatedFromUsingDecl(UD, D);
3450 }
3451
3452 return UD;
3453}
3454
3455Decl *TemplateDeclInstantiator::VisitUnresolvedUsingTypenameDecl(
3456 UnresolvedUsingTypenameDecl *D) {
3457 return instantiateUnresolvedUsingDecl(D);
3458}
3459
3460Decl *TemplateDeclInstantiator::VisitUnresolvedUsingValueDecl(
3461 UnresolvedUsingValueDecl *D) {
3462 return instantiateUnresolvedUsingDecl(D);
3463}
3464
3465Decl *TemplateDeclInstantiator::VisitUnresolvedUsingIfExistsDecl(
3466 UnresolvedUsingIfExistsDecl *D) {
3467 llvm_unreachable("referring to unresolved decl out of UsingShadowDecl")::llvm::llvm_unreachable_internal("referring to unresolved decl out of UsingShadowDecl"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3467)
;
3468}
3469
3470Decl *TemplateDeclInstantiator::VisitUsingPackDecl(UsingPackDecl *D) {
3471 SmallVector<NamedDecl*, 8> Expansions;
3472 for (auto *UD : D->expansions()) {
3473 if (NamedDecl *NewUD =
3474 SemaRef.FindInstantiatedDecl(D->getLocation(), UD, TemplateArgs))
3475 Expansions.push_back(NewUD);
3476 else
3477 return nullptr;
3478 }
3479
3480 auto *NewD = SemaRef.BuildUsingPackDecl(D, Expansions);
3481 if (isDeclWithinFunction(D))
3482 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewD);
3483 return NewD;
3484}
3485
3486Decl *TemplateDeclInstantiator::VisitClassScopeFunctionSpecializationDecl(
3487 ClassScopeFunctionSpecializationDecl *Decl) {
3488 CXXMethodDecl *OldFD = Decl->getSpecialization();
3489 return cast_or_null<CXXMethodDecl>(
3490 VisitCXXMethodDecl(OldFD, nullptr, Decl->getTemplateArgsAsWritten()));
3491}
3492
3493Decl *TemplateDeclInstantiator::VisitOMPThreadPrivateDecl(
3494 OMPThreadPrivateDecl *D) {
3495 SmallVector<Expr *, 5> Vars;
3496 for (auto *I : D->varlists()) {
3497 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3498 assert(isa<DeclRefExpr>(Var) && "threadprivate arg is not a DeclRefExpr")(static_cast <bool> (isa<DeclRefExpr>(Var) &&
"threadprivate arg is not a DeclRefExpr") ? void (0) : __assert_fail
("isa<DeclRefExpr>(Var) && \"threadprivate arg is not a DeclRefExpr\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3498, __extension__
__PRETTY_FUNCTION__))
;
3499 Vars.push_back(Var);
3500 }
3501
3502 OMPThreadPrivateDecl *TD =
3503 SemaRef.CheckOMPThreadPrivateDecl(D->getLocation(), Vars);
3504
3505 TD->setAccess(AS_public);
3506 Owner->addDecl(TD);
3507
3508 return TD;
3509}
3510
3511Decl *TemplateDeclInstantiator::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
3512 SmallVector<Expr *, 5> Vars;
3513 for (auto *I : D->varlists()) {
3514 Expr *Var = SemaRef.SubstExpr(I, TemplateArgs).get();
3515 assert(isa<DeclRefExpr>(Var) && "allocate arg is not a DeclRefExpr")(static_cast <bool> (isa<DeclRefExpr>(Var) &&
"allocate arg is not a DeclRefExpr") ? void (0) : __assert_fail
("isa<DeclRefExpr>(Var) && \"allocate arg is not a DeclRefExpr\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3515, __extension__
__PRETTY_FUNCTION__))
;
3516 Vars.push_back(Var);
3517 }
3518 SmallVector<OMPClause *, 4> Clauses;
3519 // Copy map clauses from the original mapper.
3520 for (OMPClause *C : D->clauselists()) {
3521 OMPClause *IC = nullptr;
3522 if (auto *AC = dyn_cast<OMPAllocatorClause>(C)) {
3523 ExprResult NewE = SemaRef.SubstExpr(AC->getAllocator(), TemplateArgs);
3524 if (!NewE.isUsable())
3525 continue;
3526 IC = SemaRef.ActOnOpenMPAllocatorClause(
3527 NewE.get(), AC->getBeginLoc(), AC->getLParenLoc(), AC->getEndLoc());
3528 } else if (auto *AC = dyn_cast<OMPAlignClause>(C)) {
3529 ExprResult NewE = SemaRef.SubstExpr(AC->getAlignment(), TemplateArgs);
3530 if (!NewE.isUsable())
3531 continue;
3532 IC = SemaRef.ActOnOpenMPAlignClause(NewE.get(), AC->getBeginLoc(),
3533 AC->getLParenLoc(), AC->getEndLoc());
3534 // If align clause value ends up being invalid, this can end up null.
3535 if (!IC)
3536 continue;
3537 }
3538 Clauses.push_back(IC);
3539 }
3540
3541 Sema::DeclGroupPtrTy Res = SemaRef.ActOnOpenMPAllocateDirective(
3542 D->getLocation(), Vars, Clauses, Owner);
3543 if (Res.get().isNull())
3544 return nullptr;
3545 return Res.get().getSingleDecl();
3546}
3547
3548Decl *TemplateDeclInstantiator::VisitOMPRequiresDecl(OMPRequiresDecl *D) {
3549 llvm_unreachable(::llvm::llvm_unreachable_internal("Requires directive cannot be instantiated within a dependent context"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3550)
3550 "Requires directive cannot be instantiated within a dependent context")::llvm::llvm_unreachable_internal("Requires directive cannot be instantiated within a dependent context"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3550)
;
3551}
3552
3553Decl *TemplateDeclInstantiator::VisitOMPDeclareReductionDecl(
3554 OMPDeclareReductionDecl *D) {
3555 // Instantiate type and check if it is allowed.
3556 const bool RequiresInstantiation =
3557 D->getType()->isDependentType() ||
3558 D->getType()->isInstantiationDependentType() ||
3559 D->getType()->containsUnexpandedParameterPack();
3560 QualType SubstReductionType;
3561 if (RequiresInstantiation) {
3562 SubstReductionType = SemaRef.ActOnOpenMPDeclareReductionType(
3563 D->getLocation(),
3564 ParsedType::make(SemaRef.SubstType(
3565 D->getType(), TemplateArgs, D->getLocation(), DeclarationName())));
3566 } else {
3567 SubstReductionType = D->getType();
3568 }
3569 if (SubstReductionType.isNull())
3570 return nullptr;
3571 Expr *Combiner = D->getCombiner();
3572 Expr *Init = D->getInitializer();
3573 bool IsCorrect = true;
3574 // Create instantiated copy.
3575 std::pair<QualType, SourceLocation> ReductionTypes[] = {
3576 std::make_pair(SubstReductionType, D->getLocation())};
3577 auto *PrevDeclInScope = D->getPrevDeclInScope();
3578 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3579 PrevDeclInScope = cast<OMPDeclareReductionDecl>(
3580 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3581 ->get<Decl *>());
3582 }
3583 auto DRD = SemaRef.ActOnOpenMPDeclareReductionDirectiveStart(
3584 /*S=*/nullptr, Owner, D->getDeclName(), ReductionTypes, D->getAccess(),
3585 PrevDeclInScope);
3586 auto *NewDRD = cast<OMPDeclareReductionDecl>(DRD.get().getSingleDecl());
3587 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDRD);
3588 Expr *SubstCombiner = nullptr;
3589 Expr *SubstInitializer = nullptr;
3590 // Combiners instantiation sequence.
3591 if (Combiner) {
3592 SemaRef.ActOnOpenMPDeclareReductionCombinerStart(
3593 /*S=*/nullptr, NewDRD);
3594 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3595 cast<DeclRefExpr>(D->getCombinerIn())->getDecl(),
3596 cast<DeclRefExpr>(NewDRD->getCombinerIn())->getDecl());
3597 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3598 cast<DeclRefExpr>(D->getCombinerOut())->getDecl(),
3599 cast<DeclRefExpr>(NewDRD->getCombinerOut())->getDecl());
3600 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3601 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3602 ThisContext);
3603 SubstCombiner = SemaRef.SubstExpr(Combiner, TemplateArgs).get();
3604 SemaRef.ActOnOpenMPDeclareReductionCombinerEnd(NewDRD, SubstCombiner);
3605 }
3606 // Initializers instantiation sequence.
3607 if (Init) {
3608 VarDecl *OmpPrivParm = SemaRef.ActOnOpenMPDeclareReductionInitializerStart(
3609 /*S=*/nullptr, NewDRD);
3610 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3611 cast<DeclRefExpr>(D->getInitOrig())->getDecl(),
3612 cast<DeclRefExpr>(NewDRD->getInitOrig())->getDecl());
3613 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3614 cast<DeclRefExpr>(D->getInitPriv())->getDecl(),
3615 cast<DeclRefExpr>(NewDRD->getInitPriv())->getDecl());
3616 if (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit) {
3617 SubstInitializer = SemaRef.SubstExpr(Init, TemplateArgs).get();
3618 } else {
3619 auto *OldPrivParm =
3620 cast<VarDecl>(cast<DeclRefExpr>(D->getInitPriv())->getDecl());
3621 IsCorrect = IsCorrect && OldPrivParm->hasInit();
3622 if (IsCorrect)
3623 SemaRef.InstantiateVariableInitializer(OmpPrivParm, OldPrivParm,
3624 TemplateArgs);
3625 }
3626 SemaRef.ActOnOpenMPDeclareReductionInitializerEnd(NewDRD, SubstInitializer,
3627 OmpPrivParm);
3628 }
3629 IsCorrect = IsCorrect && SubstCombiner &&
3630 (!Init ||
3631 (D->getInitializerKind() == OMPDeclareReductionDecl::CallInit &&
3632 SubstInitializer) ||
3633 (D->getInitializerKind() != OMPDeclareReductionDecl::CallInit &&
3634 !SubstInitializer));
3635
3636 (void)SemaRef.ActOnOpenMPDeclareReductionDirectiveEnd(
3637 /*S=*/nullptr, DRD, IsCorrect && !D->isInvalidDecl());
3638
3639 return NewDRD;
3640}
3641
3642Decl *
3643TemplateDeclInstantiator::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
3644 // Instantiate type and check if it is allowed.
3645 const bool RequiresInstantiation =
3646 D->getType()->isDependentType() ||
3647 D->getType()->isInstantiationDependentType() ||
3648 D->getType()->containsUnexpandedParameterPack();
3649 QualType SubstMapperTy;
3650 DeclarationName VN = D->getVarName();
3651 if (RequiresInstantiation) {
3652 SubstMapperTy = SemaRef.ActOnOpenMPDeclareMapperType(
3653 D->getLocation(),
3654 ParsedType::make(SemaRef.SubstType(D->getType(), TemplateArgs,
3655 D->getLocation(), VN)));
3656 } else {
3657 SubstMapperTy = D->getType();
3658 }
3659 if (SubstMapperTy.isNull())
3660 return nullptr;
3661 // Create an instantiated copy of mapper.
3662 auto *PrevDeclInScope = D->getPrevDeclInScope();
3663 if (PrevDeclInScope && !PrevDeclInScope->isInvalidDecl()) {
3664 PrevDeclInScope = cast<OMPDeclareMapperDecl>(
3665 SemaRef.CurrentInstantiationScope->findInstantiationOf(PrevDeclInScope)
3666 ->get<Decl *>());
3667 }
3668 bool IsCorrect = true;
3669 SmallVector<OMPClause *, 6> Clauses;
3670 // Instantiate the mapper variable.
3671 DeclarationNameInfo DirName;
3672 SemaRef.StartOpenMPDSABlock(llvm::omp::OMPD_declare_mapper, DirName,
3673 /*S=*/nullptr,
3674 (*D->clauselist_begin())->getBeginLoc());
3675 ExprResult MapperVarRef = SemaRef.ActOnOpenMPDeclareMapperDirectiveVarDecl(
3676 /*S=*/nullptr, SubstMapperTy, D->getLocation(), VN);
3677 SemaRef.CurrentInstantiationScope->InstantiatedLocal(
3678 cast<DeclRefExpr>(D->getMapperVarRef())->getDecl(),
3679 cast<DeclRefExpr>(MapperVarRef.get())->getDecl());
3680 auto *ThisContext = dyn_cast_or_null<CXXRecordDecl>(Owner);
3681 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, Qualifiers(),
3682 ThisContext);
3683 // Instantiate map clauses.
3684 for (OMPClause *C : D->clauselists()) {
3685 auto *OldC = cast<OMPMapClause>(C);
3686 SmallVector<Expr *, 4> NewVars;
3687 for (Expr *OE : OldC->varlists()) {
3688 Expr *NE = SemaRef.SubstExpr(OE, TemplateArgs).get();
3689 if (!NE) {
3690 IsCorrect = false;
3691 break;
3692 }
3693 NewVars.push_back(NE);
3694 }
3695 if (!IsCorrect)
3696 break;
3697 NestedNameSpecifierLoc NewQualifierLoc =
3698 SemaRef.SubstNestedNameSpecifierLoc(OldC->getMapperQualifierLoc(),
3699 TemplateArgs);
3700 CXXScopeSpec SS;
3701 SS.Adopt(NewQualifierLoc);
3702 DeclarationNameInfo NewNameInfo =
3703 SemaRef.SubstDeclarationNameInfo(OldC->getMapperIdInfo(), TemplateArgs);
3704 OMPVarListLocTy Locs(OldC->getBeginLoc(), OldC->getLParenLoc(),
3705 OldC->getEndLoc());
3706 OMPClause *NewC = SemaRef.ActOnOpenMPMapClause(
3707 OldC->getIteratorModifier(), OldC->getMapTypeModifiers(),
3708 OldC->getMapTypeModifiersLoc(), SS, NewNameInfo, OldC->getMapType(),
3709 OldC->isImplicitMapType(), OldC->getMapLoc(), OldC->getColonLoc(),
3710 NewVars, Locs);
3711 Clauses.push_back(NewC);
3712 }
3713 SemaRef.EndOpenMPDSABlock(nullptr);
3714 if (!IsCorrect)
3715 return nullptr;
3716 Sema::DeclGroupPtrTy DG = SemaRef.ActOnOpenMPDeclareMapperDirective(
3717 /*S=*/nullptr, Owner, D->getDeclName(), SubstMapperTy, D->getLocation(),
3718 VN, D->getAccess(), MapperVarRef.get(), Clauses, PrevDeclInScope);
3719 Decl *NewDMD = DG.get().getSingleDecl();
3720 SemaRef.CurrentInstantiationScope->InstantiatedLocal(D, NewDMD);
3721 return NewDMD;
3722}
3723
3724Decl *TemplateDeclInstantiator::VisitOMPCapturedExprDecl(
3725 OMPCapturedExprDecl * /*D*/) {
3726 llvm_unreachable("Should not be met in templates")::llvm::llvm_unreachable_internal("Should not be met in templates"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3726)
;
3727}
3728
3729Decl *TemplateDeclInstantiator::VisitFunctionDecl(FunctionDecl *D) {
3730 return VisitFunctionDecl(D, nullptr);
3731}
3732
3733Decl *
3734TemplateDeclInstantiator::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
3735 Decl *Inst = VisitFunctionDecl(D, nullptr);
3736 if (Inst && !D->getDescribedFunctionTemplate())
3737 Owner->addDecl(Inst);
3738 return Inst;
3739}
3740
3741Decl *TemplateDeclInstantiator::VisitCXXMethodDecl(CXXMethodDecl *D) {
3742 return VisitCXXMethodDecl(D, nullptr);
3743}
3744
3745Decl *TemplateDeclInstantiator::VisitRecordDecl(RecordDecl *D) {
3746 llvm_unreachable("There are only CXXRecordDecls in C++")::llvm::llvm_unreachable_internal("There are only CXXRecordDecls in C++"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3746)
;
3747}
3748
3749Decl *
3750TemplateDeclInstantiator::VisitClassTemplateSpecializationDecl(
3751 ClassTemplateSpecializationDecl *D) {
3752 // As a MS extension, we permit class-scope explicit specialization
3753 // of member class templates.
3754 ClassTemplateDecl *ClassTemplate = D->getSpecializedTemplate();
3755 assert(ClassTemplate->getDeclContext()->isRecord() &&(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
3756 D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
3757 "can only instantiate an explicit specialization "(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
3758 "for a member class template")(static_cast <bool> (ClassTemplate->getDeclContext()
->isRecord() && D->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization && "can only instantiate an explicit specialization "
"for a member class template") ? void (0) : __assert_fail ("ClassTemplate->getDeclContext()->isRecord() && D->getTemplateSpecializationKind() == TSK_ExplicitSpecialization && \"can only instantiate an explicit specialization \" \"for a member class template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3758, __extension__
__PRETTY_FUNCTION__))
;
3759
3760 // Lookup the already-instantiated declaration in the instantiation
3761 // of the class template.
3762 ClassTemplateDecl *InstClassTemplate =
3763 cast_or_null<ClassTemplateDecl>(SemaRef.FindInstantiatedDecl(
3764 D->getLocation(), ClassTemplate, TemplateArgs));
3765 if (!InstClassTemplate)
3766 return nullptr;
3767
3768 // Substitute into the template arguments of the class template explicit
3769 // specialization.
3770 TemplateSpecializationTypeLoc Loc = D->getTypeAsWritten()->getTypeLoc().
3771 castAs<TemplateSpecializationTypeLoc>();
3772 TemplateArgumentListInfo InstTemplateArgs(Loc.getLAngleLoc(),
3773 Loc.getRAngleLoc());
3774 SmallVector<TemplateArgumentLoc, 4> ArgLocs;
3775 for (unsigned I = 0; I != Loc.getNumArgs(); ++I)
3776 ArgLocs.push_back(Loc.getArgLoc(I));
3777 if (SemaRef.SubstTemplateArguments(ArgLocs, TemplateArgs, InstTemplateArgs))
3778 return nullptr;
3779
3780 // Check that the template argument list is well-formed for this
3781 // class template.
3782 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3783 if (SemaRef.CheckTemplateArgumentList(InstClassTemplate, D->getLocation(),
3784 InstTemplateArgs, false,
3785 SugaredConverted, CanonicalConverted,
3786 /*UpdateArgsWithConversions=*/true))
3787 return nullptr;
3788
3789 // Figure out where to insert this class template explicit specialization
3790 // in the member template's set of class template explicit specializations.
3791 void *InsertPos = nullptr;
3792 ClassTemplateSpecializationDecl *PrevDecl =
3793 InstClassTemplate->findSpecialization(CanonicalConverted, InsertPos);
3794
3795 // Check whether we've already seen a conflicting instantiation of this
3796 // declaration (for instance, if there was a prior implicit instantiation).
3797 bool Ignored;
3798 if (PrevDecl &&
3799 SemaRef.CheckSpecializationInstantiationRedecl(D->getLocation(),
3800 D->getSpecializationKind(),
3801 PrevDecl,
3802 PrevDecl->getSpecializationKind(),
3803 PrevDecl->getPointOfInstantiation(),
3804 Ignored))
3805 return nullptr;
3806
3807 // If PrevDecl was a definition and D is also a definition, diagnose.
3808 // This happens in cases like:
3809 //
3810 // template<typename T, typename U>
3811 // struct Outer {
3812 // template<typename X> struct Inner;
3813 // template<> struct Inner<T> {};
3814 // template<> struct Inner<U> {};
3815 // };
3816 //
3817 // Outer<int, int> outer; // error: the explicit specializations of Inner
3818 // // have the same signature.
3819 if (PrevDecl && PrevDecl->getDefinition() &&
3820 D->isThisDeclarationADefinition()) {
3821 SemaRef.Diag(D->getLocation(), diag::err_redefinition) << PrevDecl;
3822 SemaRef.Diag(PrevDecl->getDefinition()->getLocation(),
3823 diag::note_previous_definition);
3824 return nullptr;
3825 }
3826
3827 // Create the class template partial specialization declaration.
3828 ClassTemplateSpecializationDecl *InstD =
3829 ClassTemplateSpecializationDecl::Create(
3830 SemaRef.Context, D->getTagKind(), Owner, D->getBeginLoc(),
3831 D->getLocation(), InstClassTemplate, CanonicalConverted, PrevDecl);
3832
3833 // Add this partial specialization to the set of class template partial
3834 // specializations.
3835 if (!PrevDecl)
3836 InstClassTemplate->AddSpecialization(InstD, InsertPos);
3837
3838 // Substitute the nested name specifier, if any.
3839 if (SubstQualifier(D, InstD))
3840 return nullptr;
3841
3842 // Build the canonical type that describes the converted template
3843 // arguments of the class template explicit specialization.
3844 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
3845 TemplateName(InstClassTemplate), CanonicalConverted,
3846 SemaRef.Context.getRecordType(InstD));
3847
3848 // Build the fully-sugared type for this class template
3849 // specialization as the user wrote in the specialization
3850 // itself. This means that we'll pretty-print the type retrieved
3851 // from the specialization's declaration the way that the user
3852 // actually wrote the specialization, rather than formatting the
3853 // name based on the "canonical" representation used to store the
3854 // template arguments in the specialization.
3855 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
3856 TemplateName(InstClassTemplate), D->getLocation(), InstTemplateArgs,
3857 CanonType);
3858
3859 InstD->setAccess(D->getAccess());
3860 InstD->setInstantiationOfMemberClass(D, TSK_ImplicitInstantiation);
3861 InstD->setSpecializationKind(D->getSpecializationKind());
3862 InstD->setTypeAsWritten(WrittenTy);
3863 InstD->setExternLoc(D->getExternLoc());
3864 InstD->setTemplateKeywordLoc(D->getTemplateKeywordLoc());
3865
3866 Owner->addDecl(InstD);
3867
3868 // Instantiate the members of the class-scope explicit specialization eagerly.
3869 // We don't have support for lazy instantiation of an explicit specialization
3870 // yet, and MSVC eagerly instantiates in this case.
3871 // FIXME: This is wrong in standard C++.
3872 if (D->isThisDeclarationADefinition() &&
3873 SemaRef.InstantiateClass(D->getLocation(), InstD, D, TemplateArgs,
3874 TSK_ImplicitInstantiation,
3875 /*Complain=*/true))
3876 return nullptr;
3877
3878 return InstD;
3879}
3880
3881Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3882 VarTemplateSpecializationDecl *D) {
3883
3884 TemplateArgumentListInfo VarTemplateArgsInfo;
3885 VarTemplateDecl *VarTemplate = D->getSpecializedTemplate();
3886 assert(VarTemplate &&(static_cast <bool> (VarTemplate && "A template specialization without specialized template?"
) ? void (0) : __assert_fail ("VarTemplate && \"A template specialization without specialized template?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3887, __extension__
__PRETTY_FUNCTION__))
3887 "A template specialization without specialized template?")(static_cast <bool> (VarTemplate && "A template specialization without specialized template?"
) ? void (0) : __assert_fail ("VarTemplate && \"A template specialization without specialized template?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3887, __extension__
__PRETTY_FUNCTION__))
;
3888
3889 VarTemplateDecl *InstVarTemplate =
3890 cast_or_null<VarTemplateDecl>(SemaRef.FindInstantiatedDecl(
3891 D->getLocation(), VarTemplate, TemplateArgs));
3892 if (!InstVarTemplate)
3893 return nullptr;
3894
3895 // Substitute the current template arguments.
3896 if (const ASTTemplateArgumentListInfo *TemplateArgsInfo =
3897 D->getTemplateArgsInfo()) {
3898 VarTemplateArgsInfo.setLAngleLoc(TemplateArgsInfo->getLAngleLoc());
3899 VarTemplateArgsInfo.setRAngleLoc(TemplateArgsInfo->getRAngleLoc());
3900
3901 if (SemaRef.SubstTemplateArguments(TemplateArgsInfo->arguments(),
3902 TemplateArgs, VarTemplateArgsInfo))
3903 return nullptr;
3904 }
3905
3906 // Check that the template argument list is well-formed for this template.
3907 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
3908 if (SemaRef.CheckTemplateArgumentList(InstVarTemplate, D->getLocation(),
3909 VarTemplateArgsInfo, false,
3910 SugaredConverted, CanonicalConverted,
3911 /*UpdateArgsWithConversions=*/true))
3912 return nullptr;
3913
3914 // Check whether we've already seen a declaration of this specialization.
3915 void *InsertPos = nullptr;
3916 VarTemplateSpecializationDecl *PrevDecl =
3917 InstVarTemplate->findSpecialization(CanonicalConverted, InsertPos);
3918
3919 // Check whether we've already seen a conflicting instantiation of this
3920 // declaration (for instance, if there was a prior implicit instantiation).
3921 bool Ignored;
3922 if (PrevDecl && SemaRef.CheckSpecializationInstantiationRedecl(
3923 D->getLocation(), D->getSpecializationKind(), PrevDecl,
3924 PrevDecl->getSpecializationKind(),
3925 PrevDecl->getPointOfInstantiation(), Ignored))
3926 return nullptr;
3927
3928 return VisitVarTemplateSpecializationDecl(
3929 InstVarTemplate, D, VarTemplateArgsInfo, CanonicalConverted, PrevDecl);
3930}
3931
3932Decl *TemplateDeclInstantiator::VisitVarTemplateSpecializationDecl(
3933 VarTemplateDecl *VarTemplate, VarDecl *D,
3934 const TemplateArgumentListInfo &TemplateArgsInfo,
3935 ArrayRef<TemplateArgument> Converted,
3936 VarTemplateSpecializationDecl *PrevDecl) {
3937
3938 // Do substitution on the type of the declaration
3939 TypeSourceInfo *DI =
3940 SemaRef.SubstType(D->getTypeSourceInfo(), TemplateArgs,
3941 D->getTypeSpecStartLoc(), D->getDeclName());
3942 if (!DI)
3943 return nullptr;
3944
3945 if (DI->getType()->isFunctionType()) {
3946 SemaRef.Diag(D->getLocation(), diag::err_variable_instantiates_to_function)
3947 << D->isStaticDataMember() << DI->getType();
3948 return nullptr;
3949 }
3950
3951 // Build the instantiated declaration
3952 VarTemplateSpecializationDecl *Var = VarTemplateSpecializationDecl::Create(
3953 SemaRef.Context, Owner, D->getInnerLocStart(), D->getLocation(),
3954 VarTemplate, DI->getType(), DI, D->getStorageClass(), Converted);
3955 Var->setTemplateArgsInfo(TemplateArgsInfo);
3956 if (!PrevDecl) {
3957 void *InsertPos = nullptr;
3958 VarTemplate->findSpecialization(Converted, InsertPos);
3959 VarTemplate->AddSpecialization(Var, InsertPos);
3960 }
3961
3962 if (SemaRef.getLangOpts().OpenCL)
3963 SemaRef.deduceOpenCLAddressSpace(Var);
3964
3965 // Substitute the nested name specifier, if any.
3966 if (SubstQualifier(D, Var))
3967 return nullptr;
3968
3969 SemaRef.BuildVariableInstantiation(Var, D, TemplateArgs, LateAttrs, Owner,
3970 StartingScope, false, PrevDecl);
3971
3972 return Var;
3973}
3974
3975Decl *TemplateDeclInstantiator::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D) {
3976 llvm_unreachable("@defs is not supported in Objective-C++")::llvm::llvm_unreachable_internal("@defs is not supported in Objective-C++"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3976)
;
3977}
3978
3979Decl *TemplateDeclInstantiator::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
3980 // FIXME: We need to be able to instantiate FriendTemplateDecls.
3981 unsigned DiagID = SemaRef.getDiagnostics().getCustomDiagID(
3982 DiagnosticsEngine::Error,
3983 "cannot instantiate %0 yet");
3984 SemaRef.Diag(D->getLocation(), DiagID)
3985 << D->getDeclKindName();
3986
3987 return nullptr;
3988}
3989
3990Decl *TemplateDeclInstantiator::VisitConceptDecl(ConceptDecl *D) {
3991 llvm_unreachable("Concept definitions cannot reside inside a template")::llvm::llvm_unreachable_internal("Concept definitions cannot reside inside a template"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3991)
;
3992}
3993
3994Decl *TemplateDeclInstantiator::VisitImplicitConceptSpecializationDecl(
3995 ImplicitConceptSpecializationDecl *D) {
3996 llvm_unreachable("Concept specializations cannot reside inside a template")::llvm::llvm_unreachable_internal("Concept specializations cannot reside inside a template"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 3996)
;
3997}
3998
3999Decl *
4000TemplateDeclInstantiator::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
4001 return RequiresExprBodyDecl::Create(SemaRef.Context, D->getDeclContext(),
4002 D->getBeginLoc());
4003}
4004
4005Decl *TemplateDeclInstantiator::VisitDecl(Decl *D) {
4006 llvm_unreachable("Unexpected decl")::llvm::llvm_unreachable_internal("Unexpected decl", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4006)
;
4007}
4008
4009Decl *Sema::SubstDecl(Decl *D, DeclContext *Owner,
4010 const MultiLevelTemplateArgumentList &TemplateArgs) {
4011 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4012 if (D->isInvalidDecl())
4013 return nullptr;
4014
4015 Decl *SubstD;
4016 runWithSufficientStackSpace(D->getLocation(), [&] {
4017 SubstD = Instantiator.Visit(D);
4018 });
4019 return SubstD;
4020}
4021
4022void TemplateDeclInstantiator::adjustForRewrite(RewriteKind RK,
4023 FunctionDecl *Orig, QualType &T,
4024 TypeSourceInfo *&TInfo,
4025 DeclarationNameInfo &NameInfo) {
4026 assert(RK == RewriteKind::RewriteSpaceshipAsEqualEqual)(static_cast <bool> (RK == RewriteKind::RewriteSpaceshipAsEqualEqual
) ? void (0) : __assert_fail ("RK == RewriteKind::RewriteSpaceshipAsEqualEqual"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4026, __extension__
__PRETTY_FUNCTION__))
;
4027
4028 // C++2a [class.compare.default]p3:
4029 // the return type is replaced with bool
4030 auto *FPT = T->castAs<FunctionProtoType>();
4031 T = SemaRef.Context.getFunctionType(
4032 SemaRef.Context.BoolTy, FPT->getParamTypes(), FPT->getExtProtoInfo());
4033
4034 // Update the return type in the source info too. The most straightforward
4035 // way is to create new TypeSourceInfo for the new type. Use the location of
4036 // the '= default' as the location of the new type.
4037 //
4038 // FIXME: Set the correct return type when we initially transform the type,
4039 // rather than delaying it to now.
4040 TypeSourceInfo *NewTInfo =
4041 SemaRef.Context.getTrivialTypeSourceInfo(T, Orig->getEndLoc());
4042 auto OldLoc = TInfo->getTypeLoc().getAsAdjusted<FunctionProtoTypeLoc>();
4043 assert(OldLoc && "type of function is not a function type?")(static_cast <bool> (OldLoc && "type of function is not a function type?"
) ? void (0) : __assert_fail ("OldLoc && \"type of function is not a function type?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4043, __extension__
__PRETTY_FUNCTION__))
;
4044 auto NewLoc = NewTInfo->getTypeLoc().castAs<FunctionProtoTypeLoc>();
4045 for (unsigned I = 0, N = OldLoc.getNumParams(); I != N; ++I)
4046 NewLoc.setParam(I, OldLoc.getParam(I));
4047 TInfo = NewTInfo;
4048
4049 // and the declarator-id is replaced with operator==
4050 NameInfo.setName(
4051 SemaRef.Context.DeclarationNames.getCXXOperatorName(OO_EqualEqual));
4052}
4053
4054FunctionDecl *Sema::SubstSpaceshipAsEqualEqual(CXXRecordDecl *RD,
4055 FunctionDecl *Spaceship) {
4056 if (Spaceship->isInvalidDecl())
4057 return nullptr;
4058
4059 // C++2a [class.compare.default]p3:
4060 // an == operator function is declared implicitly [...] with the same
4061 // access and function-definition and in the same class scope as the
4062 // three-way comparison operator function
4063 MultiLevelTemplateArgumentList NoTemplateArgs;
4064 NoTemplateArgs.setKind(TemplateSubstitutionKind::Rewrite);
4065 NoTemplateArgs.addOuterRetainedLevels(RD->getTemplateDepth());
4066 TemplateDeclInstantiator Instantiator(*this, RD, NoTemplateArgs);
4067 Decl *R;
4068 if (auto *MD = dyn_cast<CXXMethodDecl>(Spaceship)) {
4069 R = Instantiator.VisitCXXMethodDecl(
4070 MD, nullptr, std::nullopt,
4071 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4072 } else {
4073 assert(Spaceship->getFriendObjectKind() &&(static_cast <bool> (Spaceship->getFriendObjectKind(
) && "defaulted spaceship is neither a member nor a friend"
) ? void (0) : __assert_fail ("Spaceship->getFriendObjectKind() && \"defaulted spaceship is neither a member nor a friend\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4074, __extension__
__PRETTY_FUNCTION__))
4074 "defaulted spaceship is neither a member nor a friend")(static_cast <bool> (Spaceship->getFriendObjectKind(
) && "defaulted spaceship is neither a member nor a friend"
) ? void (0) : __assert_fail ("Spaceship->getFriendObjectKind() && \"defaulted spaceship is neither a member nor a friend\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4074, __extension__
__PRETTY_FUNCTION__))
;
4075
4076 R = Instantiator.VisitFunctionDecl(
4077 Spaceship, nullptr,
4078 TemplateDeclInstantiator::RewriteKind::RewriteSpaceshipAsEqualEqual);
4079 if (!R)
4080 return nullptr;
4081
4082 FriendDecl *FD =
4083 FriendDecl::Create(Context, RD, Spaceship->getLocation(),
4084 cast<NamedDecl>(R), Spaceship->getBeginLoc());
4085 FD->setAccess(AS_public);
4086 RD->addDecl(FD);
4087 }
4088 return cast_or_null<FunctionDecl>(R);
4089}
4090
4091/// Instantiates a nested template parameter list in the current
4092/// instantiation context.
4093///
4094/// \param L The parameter list to instantiate
4095///
4096/// \returns NULL if there was an error
4097TemplateParameterList *
4098TemplateDeclInstantiator::SubstTemplateParams(TemplateParameterList *L) {
4099 // Get errors for all the parameters before bailing out.
4100 bool Invalid = false;
4101
4102 unsigned N = L->size();
4103 typedef SmallVector<NamedDecl *, 8> ParamVector;
4104 ParamVector Params;
4105 Params.reserve(N);
4106 for (auto &P : *L) {
4107 NamedDecl *D = cast_or_null<NamedDecl>(Visit(P));
4108 Params.push_back(D);
4109 Invalid = Invalid || !D || D->isInvalidDecl();
4110 }
4111
4112 // Clean up if we had an error.
4113 if (Invalid)
4114 return nullptr;
4115
4116 Expr *InstRequiresClause = L->getRequiresClause();
4117
4118 TemplateParameterList *InstL
4119 = TemplateParameterList::Create(SemaRef.Context, L->getTemplateLoc(),
4120 L->getLAngleLoc(), Params,
4121 L->getRAngleLoc(), InstRequiresClause);
4122 return InstL;
4123}
4124
4125TemplateParameterList *
4126Sema::SubstTemplateParams(TemplateParameterList *Params, DeclContext *Owner,
4127 const MultiLevelTemplateArgumentList &TemplateArgs,
4128 bool EvaluateConstraints) {
4129 TemplateDeclInstantiator Instantiator(*this, Owner, TemplateArgs);
4130 Instantiator.setEvaluateConstraints(EvaluateConstraints);
4131 return Instantiator.SubstTemplateParams(Params);
4132}
4133
4134/// Instantiate the declaration of a class template partial
4135/// specialization.
4136///
4137/// \param ClassTemplate the (instantiated) class template that is partially
4138// specialized by the instantiation of \p PartialSpec.
4139///
4140/// \param PartialSpec the (uninstantiated) class template partial
4141/// specialization that we are instantiating.
4142///
4143/// \returns The instantiated partial specialization, if successful; otherwise,
4144/// NULL to indicate an error.
4145ClassTemplatePartialSpecializationDecl *
4146TemplateDeclInstantiator::InstantiateClassTemplatePartialSpecialization(
4147 ClassTemplateDecl *ClassTemplate,
4148 ClassTemplatePartialSpecializationDecl *PartialSpec) {
4149 // Create a local instantiation scope for this class template partial
4150 // specialization, which will contain the instantiations of the template
4151 // parameters.
4152 LocalInstantiationScope Scope(SemaRef);
4153
4154 // Substitute into the template parameters of the class template partial
4155 // specialization.
4156 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4157 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4158 if (!InstParams)
4159 return nullptr;
4160
4161 // Substitute into the template arguments of the class template partial
4162 // specialization.
4163 const ASTTemplateArgumentListInfo *TemplArgInfo
4164 = PartialSpec->getTemplateArgsAsWritten();
4165 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4166 TemplArgInfo->RAngleLoc);
4167 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4168 InstTemplateArgs))
4169 return nullptr;
4170
4171 // Check that the template argument list is well-formed for this
4172 // class template.
4173 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4174 if (SemaRef.CheckTemplateArgumentList(
4175 ClassTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4176 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4177 return nullptr;
4178
4179 // Check these arguments are valid for a template partial specialization.
4180 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4181 PartialSpec->getLocation(), ClassTemplate, InstTemplateArgs.size(),
4182 CanonicalConverted))
4183 return nullptr;
4184
4185 // Figure out where to insert this class template partial specialization
4186 // in the member template's set of class template partial specializations.
4187 void *InsertPos = nullptr;
4188 ClassTemplateSpecializationDecl *PrevDecl =
4189 ClassTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4190 InsertPos);
4191
4192 // Build the canonical type that describes the converted template
4193 // arguments of the class template partial specialization.
4194 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4195 TemplateName(ClassTemplate), CanonicalConverted);
4196
4197 // Build the fully-sugared type for this class template
4198 // specialization as the user wrote in the specialization
4199 // itself. This means that we'll pretty-print the type retrieved
4200 // from the specialization's declaration the way that the user
4201 // actually wrote the specialization, rather than formatting the
4202 // name based on the "canonical" representation used to store the
4203 // template arguments in the specialization.
4204 TypeSourceInfo *WrittenTy
4205 = SemaRef.Context.getTemplateSpecializationTypeInfo(
4206 TemplateName(ClassTemplate),
4207 PartialSpec->getLocation(),
4208 InstTemplateArgs,
4209 CanonType);
4210
4211 if (PrevDecl) {
4212 // We've already seen a partial specialization with the same template
4213 // parameters and template arguments. This can happen, for example, when
4214 // substituting the outer template arguments ends up causing two
4215 // class template partial specializations of a member class template
4216 // to have identical forms, e.g.,
4217 //
4218 // template<typename T, typename U>
4219 // struct Outer {
4220 // template<typename X, typename Y> struct Inner;
4221 // template<typename Y> struct Inner<T, Y>;
4222 // template<typename Y> struct Inner<U, Y>;
4223 // };
4224 //
4225 // Outer<int, int> outer; // error: the partial specializations of Inner
4226 // // have the same signature.
4227 SemaRef.Diag(PartialSpec->getLocation(), diag::err_partial_spec_redeclared)
4228 << WrittenTy->getType();
4229 SemaRef.Diag(PrevDecl->getLocation(), diag::note_prev_partial_spec_here)
4230 << SemaRef.Context.getTypeDeclType(PrevDecl);
4231 return nullptr;
4232 }
4233
4234
4235 // Create the class template partial specialization declaration.
4236 ClassTemplatePartialSpecializationDecl *InstPartialSpec =
4237 ClassTemplatePartialSpecializationDecl::Create(
4238 SemaRef.Context, PartialSpec->getTagKind(), Owner,
4239 PartialSpec->getBeginLoc(), PartialSpec->getLocation(), InstParams,
4240 ClassTemplate, CanonicalConverted, InstTemplateArgs, CanonType,
4241 nullptr);
4242 // Substitute the nested name specifier, if any.
4243 if (SubstQualifier(PartialSpec, InstPartialSpec))
4244 return nullptr;
4245
4246 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4247 InstPartialSpec->setTypeAsWritten(WrittenTy);
4248
4249 // Check the completed partial specialization.
4250 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4251
4252 // Add this partial specialization to the set of class template partial
4253 // specializations.
4254 ClassTemplate->AddPartialSpecialization(InstPartialSpec,
4255 /*InsertPos=*/nullptr);
4256 return InstPartialSpec;
4257}
4258
4259/// Instantiate the declaration of a variable template partial
4260/// specialization.
4261///
4262/// \param VarTemplate the (instantiated) variable template that is partially
4263/// specialized by the instantiation of \p PartialSpec.
4264///
4265/// \param PartialSpec the (uninstantiated) variable template partial
4266/// specialization that we are instantiating.
4267///
4268/// \returns The instantiated partial specialization, if successful; otherwise,
4269/// NULL to indicate an error.
4270VarTemplatePartialSpecializationDecl *
4271TemplateDeclInstantiator::InstantiateVarTemplatePartialSpecialization(
4272 VarTemplateDecl *VarTemplate,
4273 VarTemplatePartialSpecializationDecl *PartialSpec) {
4274 // Create a local instantiation scope for this variable template partial
4275 // specialization, which will contain the instantiations of the template
4276 // parameters.
4277 LocalInstantiationScope Scope(SemaRef);
4278
4279 // Substitute into the template parameters of the variable template partial
4280 // specialization.
4281 TemplateParameterList *TempParams = PartialSpec->getTemplateParameters();
4282 TemplateParameterList *InstParams = SubstTemplateParams(TempParams);
4283 if (!InstParams)
4284 return nullptr;
4285
4286 // Substitute into the template arguments of the variable template partial
4287 // specialization.
4288 const ASTTemplateArgumentListInfo *TemplArgInfo
4289 = PartialSpec->getTemplateArgsAsWritten();
4290 TemplateArgumentListInfo InstTemplateArgs(TemplArgInfo->LAngleLoc,
4291 TemplArgInfo->RAngleLoc);
4292 if (SemaRef.SubstTemplateArguments(TemplArgInfo->arguments(), TemplateArgs,
4293 InstTemplateArgs))
4294 return nullptr;
4295
4296 // Check that the template argument list is well-formed for this
4297 // class template.
4298 SmallVector<TemplateArgument, 4> SugaredConverted, CanonicalConverted;
4299 if (SemaRef.CheckTemplateArgumentList(
4300 VarTemplate, PartialSpec->getLocation(), InstTemplateArgs,
4301 /*PartialTemplateArgs=*/false, SugaredConverted, CanonicalConverted))
4302 return nullptr;
4303
4304 // Check these arguments are valid for a template partial specialization.
4305 if (SemaRef.CheckTemplatePartialSpecializationArgs(
4306 PartialSpec->getLocation(), VarTemplate, InstTemplateArgs.size(),
4307 CanonicalConverted))
4308 return nullptr;
4309
4310 // Figure out where to insert this variable template partial specialization
4311 // in the member template's set of variable template partial specializations.
4312 void *InsertPos = nullptr;
4313 VarTemplateSpecializationDecl *PrevDecl =
4314 VarTemplate->findPartialSpecialization(CanonicalConverted, InstParams,
4315 InsertPos);
4316
4317 // Build the canonical type that describes the converted template
4318 // arguments of the variable template partial specialization.
4319 QualType CanonType = SemaRef.Context.getTemplateSpecializationType(
4320 TemplateName(VarTemplate), CanonicalConverted);
4321
4322 // Build the fully-sugared type for this variable template
4323 // specialization as the user wrote in the specialization
4324 // itself. This means that we'll pretty-print the type retrieved
4325 // from the specialization's declaration the way that the user
4326 // actually wrote the specialization, rather than formatting the
4327 // name based on the "canonical" representation used to store the
4328 // template arguments in the specialization.
4329 TypeSourceInfo *WrittenTy = SemaRef.Context.getTemplateSpecializationTypeInfo(
4330 TemplateName(VarTemplate), PartialSpec->getLocation(), InstTemplateArgs,
4331 CanonType);
4332
4333 if (PrevDecl) {
4334 // We've already seen a partial specialization with the same template
4335 // parameters and template arguments. This can happen, for example, when
4336 // substituting the outer template arguments ends up causing two
4337 // variable template partial specializations of a member variable template
4338 // to have identical forms, e.g.,
4339 //
4340 // template<typename T, typename U>
4341 // struct Outer {
4342 // template<typename X, typename Y> pair<X,Y> p;
4343 // template<typename Y> pair<T, Y> p;
4344 // template<typename Y> pair<U, Y> p;
4345 // };
4346 //
4347 // Outer<int, int> outer; // error: the partial specializations of Inner
4348 // // have the same signature.
4349 SemaRef.Diag(PartialSpec->getLocation(),
4350 diag::err_var_partial_spec_redeclared)
4351 << WrittenTy->getType();
4352 SemaRef.Diag(PrevDecl->getLocation(),
4353 diag::note_var_prev_partial_spec_here);
4354 return nullptr;
4355 }
4356
4357 // Do substitution on the type of the declaration
4358 TypeSourceInfo *DI = SemaRef.SubstType(
4359 PartialSpec->getTypeSourceInfo(), TemplateArgs,
4360 PartialSpec->getTypeSpecStartLoc(), PartialSpec->getDeclName());
4361 if (!DI)
4362 return nullptr;
4363
4364 if (DI->getType()->isFunctionType()) {
4365 SemaRef.Diag(PartialSpec->getLocation(),
4366 diag::err_variable_instantiates_to_function)
4367 << PartialSpec->isStaticDataMember() << DI->getType();
4368 return nullptr;
4369 }
4370
4371 // Create the variable template partial specialization declaration.
4372 VarTemplatePartialSpecializationDecl *InstPartialSpec =
4373 VarTemplatePartialSpecializationDecl::Create(
4374 SemaRef.Context, Owner, PartialSpec->getInnerLocStart(),
4375 PartialSpec->getLocation(), InstParams, VarTemplate, DI->getType(),
4376 DI, PartialSpec->getStorageClass(), CanonicalConverted,
4377 InstTemplateArgs);
4378
4379 // Substitute the nested name specifier, if any.
4380 if (SubstQualifier(PartialSpec, InstPartialSpec))
4381 return nullptr;
4382
4383 InstPartialSpec->setInstantiatedFromMember(PartialSpec);
4384 InstPartialSpec->setTypeAsWritten(WrittenTy);
4385
4386 // Check the completed partial specialization.
4387 SemaRef.CheckTemplatePartialSpecialization(InstPartialSpec);
4388
4389 // Add this partial specialization to the set of variable template partial
4390 // specializations. The instantiation of the initializer is not necessary.
4391 VarTemplate->AddPartialSpecialization(InstPartialSpec, /*InsertPos=*/nullptr);
4392
4393 SemaRef.BuildVariableInstantiation(InstPartialSpec, PartialSpec, TemplateArgs,
4394 LateAttrs, Owner, StartingScope);
4395
4396 return InstPartialSpec;
4397}
4398
4399TypeSourceInfo*
4400TemplateDeclInstantiator::SubstFunctionType(FunctionDecl *D,
4401 SmallVectorImpl<ParmVarDecl *> &Params) {
4402 TypeSourceInfo *OldTInfo = D->getTypeSourceInfo();
4403 assert(OldTInfo && "substituting function without type source info")(static_cast <bool> (OldTInfo && "substituting function without type source info"
) ? void (0) : __assert_fail ("OldTInfo && \"substituting function without type source info\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4403, __extension__
__PRETTY_FUNCTION__))
;
4404 assert(Params.empty() && "parameter vector is non-empty at start")(static_cast <bool> (Params.empty() && "parameter vector is non-empty at start"
) ? void (0) : __assert_fail ("Params.empty() && \"parameter vector is non-empty at start\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4404, __extension__
__PRETTY_FUNCTION__))
;
4405
4406 CXXRecordDecl *ThisContext = nullptr;
4407 Qualifiers ThisTypeQuals;
4408 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
4409 ThisContext = cast<CXXRecordDecl>(Owner);
4410 ThisTypeQuals = Method->getMethodQualifiers();
4411 }
4412
4413 TypeSourceInfo *NewTInfo = SemaRef.SubstFunctionDeclType(
4414 OldTInfo, TemplateArgs, D->getTypeSpecStartLoc(), D->getDeclName(),
4415 ThisContext, ThisTypeQuals, EvaluateConstraints);
4416 if (!NewTInfo)
4417 return nullptr;
4418
4419 TypeLoc OldTL = OldTInfo->getTypeLoc().IgnoreParens();
4420 if (FunctionProtoTypeLoc OldProtoLoc = OldTL.getAs<FunctionProtoTypeLoc>()) {
4421 if (NewTInfo != OldTInfo) {
4422 // Get parameters from the new type info.
4423 TypeLoc NewTL = NewTInfo->getTypeLoc().IgnoreParens();
4424 FunctionProtoTypeLoc NewProtoLoc = NewTL.castAs<FunctionProtoTypeLoc>();
4425 unsigned NewIdx = 0;
4426 for (unsigned OldIdx = 0, NumOldParams = OldProtoLoc.getNumParams();
4427 OldIdx != NumOldParams; ++OldIdx) {
4428 ParmVarDecl *OldParam = OldProtoLoc.getParam(OldIdx);
4429 if (!OldParam)
4430 return nullptr;
4431
4432 LocalInstantiationScope *Scope = SemaRef.CurrentInstantiationScope;
4433
4434 std::optional<unsigned> NumArgumentsInExpansion;
4435 if (OldParam->isParameterPack())
4436 NumArgumentsInExpansion =
4437 SemaRef.getNumArgumentsInExpansion(OldParam->getType(),
4438 TemplateArgs);
4439 if (!NumArgumentsInExpansion) {
4440 // Simple case: normal parameter, or a parameter pack that's
4441 // instantiated to a (still-dependent) parameter pack.
4442 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4443 Params.push_back(NewParam);
4444 Scope->InstantiatedLocal(OldParam, NewParam);
4445 } else {
4446 // Parameter pack expansion: make the instantiation an argument pack.
4447 Scope->MakeInstantiatedLocalArgPack(OldParam);
4448 for (unsigned I = 0; I != *NumArgumentsInExpansion; ++I) {
4449 ParmVarDecl *NewParam = NewProtoLoc.getParam(NewIdx++);
4450 Params.push_back(NewParam);
4451 Scope->InstantiatedLocalPackArg(OldParam, NewParam);
4452 }
4453 }
4454 }
4455 } else {
4456 // The function type itself was not dependent and therefore no
4457 // substitution occurred. However, we still need to instantiate
4458 // the function parameters themselves.
4459 const FunctionProtoType *OldProto =
4460 cast<FunctionProtoType>(OldProtoLoc.getType());
4461 for (unsigned i = 0, i_end = OldProtoLoc.getNumParams(); i != i_end;
4462 ++i) {
4463 ParmVarDecl *OldParam = OldProtoLoc.getParam(i);
4464 if (!OldParam) {
4465 Params.push_back(SemaRef.BuildParmVarDeclForTypedef(
4466 D, D->getLocation(), OldProto->getParamType(i)));
4467 continue;
4468 }
4469
4470 ParmVarDecl *Parm =
4471 cast_or_null<ParmVarDecl>(VisitParmVarDecl(OldParam));
4472 if (!Parm)
4473 return nullptr;
4474 Params.push_back(Parm);
4475 }
4476 }
4477 } else {
4478 // If the type of this function, after ignoring parentheses, is not
4479 // *directly* a function type, then we're instantiating a function that
4480 // was declared via a typedef or with attributes, e.g.,
4481 //
4482 // typedef int functype(int, int);
4483 // functype func;
4484 // int __cdecl meth(int, int);
4485 //
4486 // In this case, we'll just go instantiate the ParmVarDecls that we
4487 // synthesized in the method declaration.
4488 SmallVector<QualType, 4> ParamTypes;
4489 Sema::ExtParameterInfoBuilder ExtParamInfos;
4490 if (SemaRef.SubstParmTypes(D->getLocation(), D->parameters(), nullptr,
4491 TemplateArgs, ParamTypes, &Params,
4492 ExtParamInfos))
4493 return nullptr;
4494 }
4495
4496 return NewTInfo;
4497}
4498
4499/// Introduce the instantiated function parameters into the local
4500/// instantiation scope, and set the parameter names to those used
4501/// in the template.
4502bool Sema::addInstantiatedParametersToScope(
4503 FunctionDecl *Function, const FunctionDecl *PatternDecl,
4504 LocalInstantiationScope &Scope,
4505 const MultiLevelTemplateArgumentList &TemplateArgs) {
4506 unsigned FParamIdx = 0;
4507 for (unsigned I = 0, N = PatternDecl->getNumParams(); I != N; ++I) {
4508 const ParmVarDecl *PatternParam = PatternDecl->getParamDecl(I);
4509 if (!PatternParam->isParameterPack()) {
4510 // Simple case: not a parameter pack.
4511 assert(FParamIdx < Function->getNumParams())(static_cast <bool> (FParamIdx < Function->getNumParams
()) ? void (0) : __assert_fail ("FParamIdx < Function->getNumParams()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4511, __extension__
__PRETTY_FUNCTION__))
;
4512 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4513 FunctionParam->setDeclName(PatternParam->getDeclName());
4514 // If the parameter's type is not dependent, update it to match the type
4515 // in the pattern. They can differ in top-level cv-qualifiers, and we want
4516 // the pattern's type here. If the type is dependent, they can't differ,
4517 // per core issue 1668. Substitute into the type from the pattern, in case
4518 // it's instantiation-dependent.
4519 // FIXME: Updating the type to work around this is at best fragile.
4520 if (!PatternDecl->getType()->isDependentType()) {
4521 QualType T = SubstType(PatternParam->getType(), TemplateArgs,
4522 FunctionParam->getLocation(),
4523 FunctionParam->getDeclName());
4524 if (T.isNull())
4525 return true;
4526 FunctionParam->setType(T);
4527 }
4528
4529 Scope.InstantiatedLocal(PatternParam, FunctionParam);
4530 ++FParamIdx;
4531 continue;
4532 }
4533
4534 // Expand the parameter pack.
4535 Scope.MakeInstantiatedLocalArgPack(PatternParam);
4536 std::optional<unsigned> NumArgumentsInExpansion =
4537 getNumArgumentsInExpansion(PatternParam->getType(), TemplateArgs);
4538 if (NumArgumentsInExpansion) {
4539 QualType PatternType =
4540 PatternParam->getType()->castAs<PackExpansionType>()->getPattern();
4541 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg) {
4542 ParmVarDecl *FunctionParam = Function->getParamDecl(FParamIdx);
4543 FunctionParam->setDeclName(PatternParam->getDeclName());
4544 if (!PatternDecl->getType()->isDependentType()) {
4545 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, Arg);
4546 QualType T =
4547 SubstType(PatternType, TemplateArgs, FunctionParam->getLocation(),
4548 FunctionParam->getDeclName());
4549 if (T.isNull())
4550 return true;
4551 FunctionParam->setType(T);
4552 }
4553
4554 Scope.InstantiatedLocalPackArg(PatternParam, FunctionParam);
4555 ++FParamIdx;
4556 }
4557 }
4558 }
4559
4560 return false;
4561}
4562
4563bool Sema::InstantiateDefaultArgument(SourceLocation CallLoc, FunctionDecl *FD,
4564 ParmVarDecl *Param) {
4565 assert(Param->hasUninstantiatedDefaultArg())(static_cast <bool> (Param->hasUninstantiatedDefaultArg
()) ? void (0) : __assert_fail ("Param->hasUninstantiatedDefaultArg()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4565, __extension__
__PRETTY_FUNCTION__))
;
4566
4567 // Instantiate the expression.
4568 //
4569 // FIXME: Pass in a correct Pattern argument, otherwise
4570 // getTemplateInstantiationArgs uses the lexical context of FD, e.g.
4571 //
4572 // template<typename T>
4573 // struct A {
4574 // static int FooImpl();
4575 //
4576 // template<typename Tp>
4577 // // bug: default argument A<T>::FooImpl() is evaluated with 2-level
4578 // // template argument list [[T], [Tp]], should be [[Tp]].
4579 // friend A<Tp> Foo(int a);
4580 // };
4581 //
4582 // template<typename T>
4583 // A<T> Foo(int a = A<T>::FooImpl());
4584 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4585 FD, /*Final=*/false, nullptr, /*RelativeToPrimary=*/true);
4586
4587 if (SubstDefaultArgument(CallLoc, Param, TemplateArgs, /*ForCallExpr*/ true))
4588 return true;
4589
4590 if (ASTMutationListener *L = getASTMutationListener())
4591 L->DefaultArgumentInstantiated(Param);
4592
4593 return false;
4594}
4595
4596void Sema::InstantiateExceptionSpec(SourceLocation PointOfInstantiation,
4597 FunctionDecl *Decl) {
4598 const FunctionProtoType *Proto = Decl->getType()->castAs<FunctionProtoType>();
4599 if (Proto->getExceptionSpecType() != EST_Uninstantiated)
4600 return;
4601
4602 InstantiatingTemplate Inst(*this, PointOfInstantiation, Decl,
4603 InstantiatingTemplate::ExceptionSpecification());
4604 if (Inst.isInvalid()) {
4605 // We hit the instantiation depth limit. Clear the exception specification
4606 // so that our callers don't have to cope with EST_Uninstantiated.
4607 UpdateExceptionSpec(Decl, EST_None);
4608 return;
4609 }
4610 if (Inst.isAlreadyInstantiating()) {
4611 // This exception specification indirectly depends on itself. Reject.
4612 // FIXME: Corresponding rule in the standard?
4613 Diag(PointOfInstantiation, diag::err_exception_spec_cycle) << Decl;
4614 UpdateExceptionSpec(Decl, EST_None);
4615 return;
4616 }
4617
4618 // Enter the scope of this instantiation. We don't use
4619 // PushDeclContext because we don't have a scope.
4620 Sema::ContextRAII savedContext(*this, Decl);
4621 LocalInstantiationScope Scope(*this);
4622
4623 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
4624 Decl, /*Final=*/false, nullptr, /*RelativeToPrimary*/ true);
4625
4626 // FIXME: We can't use getTemplateInstantiationPattern(false) in general
4627 // here, because for a non-defining friend declaration in a class template,
4628 // we don't store enough information to map back to the friend declaration in
4629 // the template.
4630 FunctionDecl *Template = Proto->getExceptionSpecTemplate();
4631 if (addInstantiatedParametersToScope(Decl, Template, Scope, TemplateArgs)) {
4632 UpdateExceptionSpec(Decl, EST_None);
4633 return;
4634 }
4635
4636 SubstExceptionSpec(Decl, Template->getType()->castAs<FunctionProtoType>(),
4637 TemplateArgs);
4638}
4639
4640/// Initializes the common fields of an instantiation function
4641/// declaration (New) from the corresponding fields of its template (Tmpl).
4642///
4643/// \returns true if there was an error
4644bool
4645TemplateDeclInstantiator::InitFunctionInstantiation(FunctionDecl *New,
4646 FunctionDecl *Tmpl) {
4647 New->setImplicit(Tmpl->isImplicit());
4648
4649 // Forward the mangling number from the template to the instantiated decl.
4650 SemaRef.Context.setManglingNumber(New,
4651 SemaRef.Context.getManglingNumber(Tmpl));
4652
4653 // If we are performing substituting explicitly-specified template arguments
4654 // or deduced template arguments into a function template and we reach this
4655 // point, we are now past the point where SFINAE applies and have committed
4656 // to keeping the new function template specialization. We therefore
4657 // convert the active template instantiation for the function template
4658 // into a template instantiation for this specific function template
4659 // specialization, which is not a SFINAE context, so that we diagnose any
4660 // further errors in the declaration itself.
4661 //
4662 // FIXME: This is a hack.
4663 typedef Sema::CodeSynthesisContext ActiveInstType;
4664 ActiveInstType &ActiveInst = SemaRef.CodeSynthesisContexts.back();
4665 if (ActiveInst.Kind == ActiveInstType::ExplicitTemplateArgumentSubstitution ||
4666 ActiveInst.Kind == ActiveInstType::DeducedTemplateArgumentSubstitution) {
4667 if (isa<FunctionTemplateDecl>(ActiveInst.Entity)) {
4668 SemaRef.InstantiatingSpecializations.erase(
4669 {ActiveInst.Entity->getCanonicalDecl(), ActiveInst.Kind});
4670 atTemplateEnd(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4671 ActiveInst.Kind = ActiveInstType::TemplateInstantiation;
4672 ActiveInst.Entity = New;
4673 atTemplateBegin(SemaRef.TemplateInstCallbacks, SemaRef, ActiveInst);
4674 }
4675 }
4676
4677 const FunctionProtoType *Proto = Tmpl->getType()->getAs<FunctionProtoType>();
4678 assert(Proto && "Function template without prototype?")(static_cast <bool> (Proto && "Function template without prototype?"
) ? void (0) : __assert_fail ("Proto && \"Function template without prototype?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4678, __extension__
__PRETTY_FUNCTION__))
;
4679
4680 if (Proto->hasExceptionSpec() || Proto->getNoReturnAttr()) {
4681 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
4682
4683 // DR1330: In C++11, defer instantiation of a non-trivial
4684 // exception specification.
4685 // DR1484: Local classes and their members are instantiated along with the
4686 // containing function.
4687 if (SemaRef.getLangOpts().CPlusPlus11 &&
4688 EPI.ExceptionSpec.Type != EST_None &&
4689 EPI.ExceptionSpec.Type != EST_DynamicNone &&
4690 EPI.ExceptionSpec.Type != EST_BasicNoexcept &&
4691 !Tmpl->isInLocalScopeForInstantiation()) {
4692 FunctionDecl *ExceptionSpecTemplate = Tmpl;
4693 if (EPI.ExceptionSpec.Type == EST_Uninstantiated)
4694 ExceptionSpecTemplate = EPI.ExceptionSpec.SourceTemplate;
4695 ExceptionSpecificationType NewEST = EST_Uninstantiated;
4696 if (EPI.ExceptionSpec.Type == EST_Unevaluated)
4697 NewEST = EST_Unevaluated;
4698
4699 // Mark the function has having an uninstantiated exception specification.
4700 const FunctionProtoType *NewProto
4701 = New->getType()->getAs<FunctionProtoType>();
4702 assert(NewProto && "Template instantiation without function prototype?")(static_cast <bool> (NewProto && "Template instantiation without function prototype?"
) ? void (0) : __assert_fail ("NewProto && \"Template instantiation without function prototype?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4702, __extension__
__PRETTY_FUNCTION__))
;
4703 EPI = NewProto->getExtProtoInfo();
4704 EPI.ExceptionSpec.Type = NewEST;
4705 EPI.ExceptionSpec.SourceDecl = New;
4706 EPI.ExceptionSpec.SourceTemplate = ExceptionSpecTemplate;
4707 New->setType(SemaRef.Context.getFunctionType(
4708 NewProto->getReturnType(), NewProto->getParamTypes(), EPI));
4709 } else {
4710 Sema::ContextRAII SwitchContext(SemaRef, New);
4711 SemaRef.SubstExceptionSpec(New, Proto, TemplateArgs);
4712 }
4713 }
4714
4715 // Get the definition. Leaves the variable unchanged if undefined.
4716 const FunctionDecl *Definition = Tmpl;
4717 Tmpl->isDefined(Definition);
4718
4719 SemaRef.InstantiateAttrs(TemplateArgs, Definition, New,
4720 LateAttrs, StartingScope);
4721
4722 return false;
4723}
4724
4725/// Initializes common fields of an instantiated method
4726/// declaration (New) from the corresponding fields of its template
4727/// (Tmpl).
4728///
4729/// \returns true if there was an error
4730bool
4731TemplateDeclInstantiator::InitMethodInstantiation(CXXMethodDecl *New,
4732 CXXMethodDecl *Tmpl) {
4733 if (InitFunctionInstantiation(New, Tmpl))
4734 return true;
4735
4736 if (isa<CXXDestructorDecl>(New) && SemaRef.getLangOpts().CPlusPlus11)
4737 SemaRef.AdjustDestructorExceptionSpec(cast<CXXDestructorDecl>(New));
4738
4739 New->setAccess(Tmpl->getAccess());
4740 if (Tmpl->isVirtualAsWritten())
4741 New->setVirtualAsWritten(true);
4742
4743 // FIXME: New needs a pointer to Tmpl
4744 return false;
4745}
4746
4747bool TemplateDeclInstantiator::SubstDefaultedFunction(FunctionDecl *New,
4748 FunctionDecl *Tmpl) {
4749 // Transfer across any unqualified lookups.
4750 if (auto *DFI = Tmpl->getDefaultedFunctionInfo()) {
4751 SmallVector<DeclAccessPair, 32> Lookups;
4752 Lookups.reserve(DFI->getUnqualifiedLookups().size());
4753 bool AnyChanged = false;
4754 for (DeclAccessPair DA : DFI->getUnqualifiedLookups()) {
4755 NamedDecl *D = SemaRef.FindInstantiatedDecl(New->getLocation(),
4756 DA.getDecl(), TemplateArgs);
4757 if (!D)
4758 return true;
4759 AnyChanged |= (D != DA.getDecl());
4760 Lookups.push_back(DeclAccessPair::make(D, DA.getAccess()));
4761 }
4762
4763 // It's unlikely that substitution will change any declarations. Don't
4764 // store an unnecessary copy in that case.
4765 New->setDefaultedFunctionInfo(
4766 AnyChanged ? FunctionDecl::DefaultedFunctionInfo::Create(
4767 SemaRef.Context, Lookups)
4768 : DFI);
4769 }
4770
4771 SemaRef.SetDeclDefaulted(New, Tmpl->getLocation());
4772 return false;
4773}
4774
4775/// Instantiate (or find existing instantiation of) a function template with a
4776/// given set of template arguments.
4777///
4778/// Usually this should not be used, and template argument deduction should be
4779/// used in its place.
4780FunctionDecl *
4781Sema::InstantiateFunctionDeclaration(FunctionTemplateDecl *FTD,
4782 const TemplateArgumentList *Args,
4783 SourceLocation Loc) {
4784 FunctionDecl *FD = FTD->getTemplatedDecl();
4785
4786 sema::TemplateDeductionInfo Info(Loc);
4787 InstantiatingTemplate Inst(
4788 *this, Loc, FTD, Args->asArray(),
4789 CodeSynthesisContext::ExplicitTemplateArgumentSubstitution, Info);
4790 if (Inst.isInvalid())
4791 return nullptr;
4792
4793 ContextRAII SavedContext(*this, FD);
4794 MultiLevelTemplateArgumentList MArgs(FTD, Args->asArray(),
4795 /*Final=*/false);
4796
4797 return cast_or_null<FunctionDecl>(SubstDecl(FD, FD->getParent(), MArgs));
4798}
4799
4800/// Instantiate the definition of the given function from its
4801/// template.
4802///
4803/// \param PointOfInstantiation the point at which the instantiation was
4804/// required. Note that this is not precisely a "point of instantiation"
4805/// for the function, but it's close.
4806///
4807/// \param Function the already-instantiated declaration of a
4808/// function template specialization or member function of a class template
4809/// specialization.
4810///
4811/// \param Recursive if true, recursively instantiates any functions that
4812/// are required by this instantiation.
4813///
4814/// \param DefinitionRequired if true, then we are performing an explicit
4815/// instantiation where the body of the function is required. Complain if
4816/// there is no such body.
4817void Sema::InstantiateFunctionDefinition(SourceLocation PointOfInstantiation,
4818 FunctionDecl *Function,
4819 bool Recursive,
4820 bool DefinitionRequired,
4821 bool AtEndOfTU) {
4822 if (Function->isInvalidDecl() || isa<CXXDeductionGuideDecl>(Function))
4823 return;
4824
4825 // Never instantiate an explicit specialization except if it is a class scope
4826 // explicit specialization.
4827 TemplateSpecializationKind TSK =
4828 Function->getTemplateSpecializationKindForInstantiation();
4829 if (TSK == TSK_ExplicitSpecialization)
4830 return;
4831
4832 // Never implicitly instantiate a builtin; we don't actually need a function
4833 // body.
4834 if (Function->getBuiltinID() && TSK == TSK_ImplicitInstantiation &&
4835 !DefinitionRequired)
4836 return;
4837
4838 // Don't instantiate a definition if we already have one.
4839 const FunctionDecl *ExistingDefn = nullptr;
4840 if (Function->isDefined(ExistingDefn,
4841 /*CheckForPendingFriendDefinition=*/true)) {
4842 if (ExistingDefn->isThisDeclarationADefinition())
4843 return;
4844
4845 // If we're asked to instantiate a function whose body comes from an
4846 // instantiated friend declaration, attach the instantiated body to the
4847 // corresponding declaration of the function.
4848 assert(ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition())(static_cast <bool> (ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition
()) ? void (0) : __assert_fail ("ExistingDefn->isThisDeclarationInstantiatedFromAFriendDefinition()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4848, __extension__
__PRETTY_FUNCTION__))
;
4849 Function = const_cast<FunctionDecl*>(ExistingDefn);
4850 }
4851
4852 // Find the function body that we'll be substituting.
4853 const FunctionDecl *PatternDecl = Function->getTemplateInstantiationPattern();
4854 assert(PatternDecl && "instantiating a non-template")(static_cast <bool> (PatternDecl && "instantiating a non-template"
) ? void (0) : __assert_fail ("PatternDecl && \"instantiating a non-template\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4854, __extension__
__PRETTY_FUNCTION__))
;
4855
4856 const FunctionDecl *PatternDef = PatternDecl->getDefinition();
4857 Stmt *Pattern = nullptr;
4858 if (PatternDef) {
4859 Pattern = PatternDef->getBody(PatternDef);
4860 PatternDecl = PatternDef;
4861 if (PatternDef->willHaveBody())
4862 PatternDef = nullptr;
4863 }
4864
4865 // FIXME: We need to track the instantiation stack in order to know which
4866 // definitions should be visible within this instantiation.
4867 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Function,
4868 Function->getInstantiatedFromMemberFunction(),
4869 PatternDecl, PatternDef, TSK,
4870 /*Complain*/DefinitionRequired)) {
4871 if (DefinitionRequired)
4872 Function->setInvalidDecl();
4873 else if (TSK == TSK_ExplicitInstantiationDefinition ||
4874 (Function->isConstexpr() && !Recursive)) {
4875 // Try again at the end of the translation unit (at which point a
4876 // definition will be required).
4877 assert(!Recursive)(static_cast <bool> (!Recursive) ? void (0) : __assert_fail
("!Recursive", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 4877, __extension__ __PRETTY_FUNCTION__))
;
4878 Function->setInstantiationIsPending(true);
4879 PendingInstantiations.push_back(
4880 std::make_pair(Function, PointOfInstantiation));
4881 } else if (TSK == TSK_ImplicitInstantiation) {
4882 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
4883 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
4884 Diag(PointOfInstantiation, diag::warn_func_template_missing)
4885 << Function;
4886 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
4887 if (getLangOpts().CPlusPlus11)
4888 Diag(PointOfInstantiation, diag::note_inst_declaration_hint)
4889 << Function;
4890 }
4891 }
4892
4893 return;
4894 }
4895
4896 // Postpone late parsed template instantiations.
4897 if (PatternDecl->isLateTemplateParsed() &&
4898 !LateTemplateParser) {
4899 Function->setInstantiationIsPending(true);
4900 LateParsedInstantiations.push_back(
4901 std::make_pair(Function, PointOfInstantiation));
4902 return;
4903 }
4904
4905 llvm::TimeTraceScope TimeScope("InstantiateFunction", [&]() {
4906 std::string Name;
4907 llvm::raw_string_ostream OS(Name);
4908 Function->getNameForDiagnostic(OS, getPrintingPolicy(),
4909 /*Qualified=*/true);
4910 return Name;
4911 });
4912
4913 // If we're performing recursive template instantiation, create our own
4914 // queue of pending implicit instantiations that we will instantiate later,
4915 // while we're still within our own instantiation context.
4916 // This has to happen before LateTemplateParser below is called, so that
4917 // it marks vtables used in late parsed templates as used.
4918 GlobalEagerInstantiationScope GlobalInstantiations(*this,
4919 /*Enabled=*/Recursive);
4920 LocalEagerInstantiationScope LocalInstantiations(*this);
4921
4922 // Call the LateTemplateParser callback if there is a need to late parse
4923 // a templated function definition.
4924 if (!Pattern && PatternDecl->isLateTemplateParsed() &&
4925 LateTemplateParser) {
4926 // FIXME: Optimize to allow individual templates to be deserialized.
4927 if (PatternDecl->isFromASTFile())
4928 ExternalSource->ReadLateParsedTemplates(LateParsedTemplateMap);
4929
4930 auto LPTIter = LateParsedTemplateMap.find(PatternDecl);
4931 assert(LPTIter != LateParsedTemplateMap.end() &&(static_cast <bool> (LPTIter != LateParsedTemplateMap.end
() && "missing LateParsedTemplate") ? void (0) : __assert_fail
("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4932, __extension__
__PRETTY_FUNCTION__))
4932 "missing LateParsedTemplate")(static_cast <bool> (LPTIter != LateParsedTemplateMap.end
() && "missing LateParsedTemplate") ? void (0) : __assert_fail
("LPTIter != LateParsedTemplateMap.end() && \"missing LateParsedTemplate\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4932, __extension__
__PRETTY_FUNCTION__))
;
4933 LateTemplateParser(OpaqueParser, *LPTIter->second);
4934 Pattern = PatternDecl->getBody(PatternDecl);
4935 updateAttrsForLateParsedTemplate(PatternDecl, Function);
4936 }
4937
4938 // Note, we should never try to instantiate a deleted function template.
4939 assert((Pattern || PatternDecl->isDefaulted() ||(static_cast <bool> ((Pattern || PatternDecl->isDefaulted
() || PatternDecl->hasSkippedBody()) && "unexpected kind of function template definition"
) ? void (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4941, __extension__
__PRETTY_FUNCTION__))
4940 PatternDecl->hasSkippedBody()) &&(static_cast <bool> ((Pattern || PatternDecl->isDefaulted
() || PatternDecl->hasSkippedBody()) && "unexpected kind of function template definition"
) ? void (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4941, __extension__
__PRETTY_FUNCTION__))
4941 "unexpected kind of function template definition")(static_cast <bool> ((Pattern || PatternDecl->isDefaulted
() || PatternDecl->hasSkippedBody()) && "unexpected kind of function template definition"
) ? void (0) : __assert_fail ("(Pattern || PatternDecl->isDefaulted() || PatternDecl->hasSkippedBody()) && \"unexpected kind of function template definition\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4941, __extension__
__PRETTY_FUNCTION__))
;
4942
4943 // C++1y [temp.explicit]p10:
4944 // Except for inline functions, declarations with types deduced from their
4945 // initializer or return value, and class template specializations, other
4946 // explicit instantiation declarations have the effect of suppressing the
4947 // implicit instantiation of the entity to which they refer.
4948 if (TSK == TSK_ExplicitInstantiationDeclaration &&
4949 !PatternDecl->isInlined() &&
4950 !PatternDecl->getReturnType()->getContainedAutoType())
4951 return;
4952
4953 if (PatternDecl->isInlined()) {
4954 // Function, and all later redeclarations of it (from imported modules,
4955 // for instance), are now implicitly inline.
4956 for (auto *D = Function->getMostRecentDecl(); /**/;
4957 D = D->getPreviousDecl()) {
4958 D->setImplicitlyInline();
4959 if (D == Function)
4960 break;
4961 }
4962 }
4963
4964 InstantiatingTemplate Inst(*this, PointOfInstantiation, Function);
4965 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
4966 return;
4967 PrettyDeclStackTraceEntry CrashInfo(Context, Function, SourceLocation(),
4968 "instantiating function definition");
4969
4970 // The instantiation is visible here, even if it was first declared in an
4971 // unimported module.
4972 Function->setVisibleDespiteOwningModule();
4973
4974 // Copy the inner loc start from the pattern.
4975 Function->setInnerLocStart(PatternDecl->getInnerLocStart());
4976
4977 EnterExpressionEvaluationContext EvalContext(
4978 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
4979
4980 // Introduce a new scope where local variable instantiations will be
4981 // recorded, unless we're actually a member function within a local
4982 // class, in which case we need to merge our results with the parent
4983 // scope (of the enclosing function). The exception is instantiating
4984 // a function template specialization, since the template to be
4985 // instantiated already has references to locals properly substituted.
4986 bool MergeWithParentScope = false;
4987 if (CXXRecordDecl *Rec = dyn_cast<CXXRecordDecl>(Function->getDeclContext()))
4988 MergeWithParentScope =
4989 Rec->isLocalClass() && !Function->isFunctionTemplateSpecialization();
4990
4991 LocalInstantiationScope Scope(*this, MergeWithParentScope);
4992 auto RebuildTypeSourceInfoForDefaultSpecialMembers = [&]() {
4993 // Special members might get their TypeSourceInfo set up w.r.t the
4994 // PatternDecl context, in which case parameters could still be pointing
4995 // back to the original class, make sure arguments are bound to the
4996 // instantiated record instead.
4997 assert(PatternDecl->isDefaulted() &&(static_cast <bool> (PatternDecl->isDefaulted() &&
"Special member needs to be defaulted") ? void (0) : __assert_fail
("PatternDecl->isDefaulted() && \"Special member needs to be defaulted\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4998, __extension__
__PRETTY_FUNCTION__))
1
Assuming the condition is true
2
'?' condition is true
4998 "Special member needs to be defaulted")(static_cast <bool> (PatternDecl->isDefaulted() &&
"Special member needs to be defaulted") ? void (0) : __assert_fail
("PatternDecl->isDefaulted() && \"Special member needs to be defaulted\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 4998, __extension__
__PRETTY_FUNCTION__))
;
4999 auto PatternSM = getDefaultedFunctionKind(PatternDecl).asSpecialMember();
5000 if (!(PatternSM == Sema::CXXCopyConstructor ||
3
Assuming 'PatternSM' is not equal to CXXCopyConstructor
6
Taking false branch
5001 PatternSM == Sema::CXXCopyAssignment ||
4
Assuming 'PatternSM' is not equal to CXXCopyAssignment
5002 PatternSM == Sema::CXXMoveConstructor ||
5
Assuming 'PatternSM' is equal to CXXMoveConstructor
5003 PatternSM == Sema::CXXMoveAssignment))
5004 return;
5005
5006 auto *NewRec = dyn_cast<CXXRecordDecl>(Function->getDeclContext());
7
Assuming the object is a 'CastReturnType'
5007 const auto *PatternRec =
5008 dyn_cast<CXXRecordDecl>(PatternDecl->getDeclContext());
8
Assuming the object is a 'CastReturnType'
5009 if (!NewRec
8.1
'NewRec' is non-null
8.1
'NewRec' is non-null
8.1
'NewRec' is non-null
|| !PatternRec
8.2
'PatternRec' is non-null
8.2
'PatternRec' is non-null
8.2
'PatternRec' is non-null
)
9
Taking false branch
5010 return;
5011 if (!PatternRec->isLambda())
10
Assuming the condition is false
11
Taking false branch
5012 return;
5013
5014 struct SpecialMemberTypeInfoRebuilder
5015 : TreeTransform<SpecialMemberTypeInfoRebuilder> {
5016 using Base = TreeTransform<SpecialMemberTypeInfoRebuilder>;
5017 const CXXRecordDecl *OldDecl;
5018 CXXRecordDecl *NewDecl;
5019
5020 SpecialMemberTypeInfoRebuilder(Sema &SemaRef, const CXXRecordDecl *O,
5021 CXXRecordDecl *N)
5022 : TreeTransform(SemaRef), OldDecl(O), NewDecl(N) {}
5023
5024 bool TransformExceptionSpec(SourceLocation Loc,
5025 FunctionProtoType::ExceptionSpecInfo &ESI,
5026 SmallVectorImpl<QualType> &Exceptions,
5027 bool &Changed) {
5028 return false;
5029 }
5030
5031 QualType TransformRecordType(TypeLocBuilder &TLB, RecordTypeLoc TL) {
5032 const RecordType *T = TL.getTypePtr();
5033 RecordDecl *Record = cast_or_null<RecordDecl>(
5034 getDerived().TransformDecl(TL.getNameLoc(), T->getDecl()));
5035 if (Record != OldDecl)
5036 return Base::TransformRecordType(TLB, TL);
5037
5038 QualType Result = getDerived().RebuildRecordType(NewDecl);
5039 if (Result.isNull())
5040 return QualType();
5041
5042 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
5043 NewTL.setNameLoc(TL.getNameLoc());
5044 return Result;
5045 }
5046 } IR{*this, PatternRec, NewRec};
5047
5048 TypeSourceInfo *NewSI = IR.TransformType(Function->getTypeSourceInfo());
12
Calling 'TreeTransform::TransformType'
5049 Function->setType(NewSI->getType());
5050 Function->setTypeSourceInfo(NewSI);
5051
5052 ParmVarDecl *Parm = Function->getParamDecl(0);
5053 TypeSourceInfo *NewParmSI = IR.TransformType(Parm->getTypeSourceInfo());
5054 Parm->setType(NewParmSI->getType());
5055 Parm->setTypeSourceInfo(NewParmSI);
5056 };
5057
5058 if (PatternDecl->isDefaulted()) {
5059 RebuildTypeSourceInfoForDefaultSpecialMembers();
5060 SetDeclDefaulted(Function, PatternDecl->getLocation());
5061 } else {
5062 MultiLevelTemplateArgumentList TemplateArgs = getTemplateInstantiationArgs(
5063 Function, /*Final=*/false, nullptr, false, PatternDecl);
5064
5065 // Substitute into the qualifier; we can get a substitution failure here
5066 // through evil use of alias templates.
5067 // FIXME: Is CurContext correct for this? Should we go to the (instantiation
5068 // of the) lexical context of the pattern?
5069 SubstQualifier(*this, PatternDecl, Function, TemplateArgs);
5070
5071 ActOnStartOfFunctionDef(nullptr, Function);
5072
5073 // Enter the scope of this instantiation. We don't use
5074 // PushDeclContext because we don't have a scope.
5075 Sema::ContextRAII savedContext(*this, Function);
5076
5077 if (addInstantiatedParametersToScope(Function, PatternDecl, Scope,
5078 TemplateArgs))
5079 return;
5080
5081 StmtResult Body;
5082 if (PatternDecl->hasSkippedBody()) {
5083 ActOnSkippedFunctionBody(Function);
5084 Body = nullptr;
5085 } else {
5086 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Function)) {
5087 // If this is a constructor, instantiate the member initializers.
5088 InstantiateMemInitializers(Ctor, cast<CXXConstructorDecl>(PatternDecl),
5089 TemplateArgs);
5090
5091 // If this is an MS ABI dllexport default constructor, instantiate any
5092 // default arguments.
5093 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5094 Ctor->isDefaultConstructor()) {
5095 InstantiateDefaultCtorDefaultArgs(Ctor);
5096 }
5097 }
5098
5099 // Instantiate the function body.
5100 Body = SubstStmt(Pattern, TemplateArgs);
5101
5102 if (Body.isInvalid())
5103 Function->setInvalidDecl();
5104 }
5105 // FIXME: finishing the function body while in an expression evaluation
5106 // context seems wrong. Investigate more.
5107 ActOnFinishFunctionBody(Function, Body.get(), /*IsInstantiation=*/true);
5108
5109 PerformDependentDiagnostics(PatternDecl, TemplateArgs);
5110
5111 if (auto *Listener = getASTMutationListener())
5112 Listener->FunctionDefinitionInstantiated(Function);
5113
5114 savedContext.pop();
5115 }
5116
5117 DeclGroupRef DG(Function);
5118 Consumer.HandleTopLevelDecl(DG);
5119
5120 // This class may have local implicit instantiations that need to be
5121 // instantiation within this scope.
5122 LocalInstantiations.perform();
5123 Scope.Exit();
5124 GlobalInstantiations.perform();
5125}
5126
5127VarTemplateSpecializationDecl *Sema::BuildVarTemplateInstantiation(
5128 VarTemplateDecl *VarTemplate, VarDecl *FromVar,
5129 const TemplateArgumentList &TemplateArgList,
5130 const TemplateArgumentListInfo &TemplateArgsInfo,
5131 SmallVectorImpl<TemplateArgument> &Converted,
5132 SourceLocation PointOfInstantiation, LateInstantiatedAttrVec *LateAttrs,
5133 LocalInstantiationScope *StartingScope) {
5134 if (FromVar->isInvalidDecl())
5135 return nullptr;
5136
5137 InstantiatingTemplate Inst(*this, PointOfInstantiation, FromVar);
5138 if (Inst.isInvalid())
5139 return nullptr;
5140
5141 // Instantiate the first declaration of the variable template: for a partial
5142 // specialization of a static data member template, the first declaration may
5143 // or may not be the declaration in the class; if it's in the class, we want
5144 // to instantiate a member in the class (a declaration), and if it's outside,
5145 // we want to instantiate a definition.
5146 //
5147 // If we're instantiating an explicitly-specialized member template or member
5148 // partial specialization, don't do this. The member specialization completely
5149 // replaces the original declaration in this case.
5150 bool IsMemberSpec = false;
5151 MultiLevelTemplateArgumentList MultiLevelList;
5152 if (auto *PartialSpec =
5153 dyn_cast<VarTemplatePartialSpecializationDecl>(FromVar)) {
5154 IsMemberSpec = PartialSpec->isMemberSpecialization();
5155 MultiLevelList.addOuterTemplateArguments(
5156 PartialSpec, TemplateArgList.asArray(), /*Final=*/false);
5157 } else {
5158 assert(VarTemplate == FromVar->getDescribedVarTemplate())(static_cast <bool> (VarTemplate == FromVar->getDescribedVarTemplate
()) ? void (0) : __assert_fail ("VarTemplate == FromVar->getDescribedVarTemplate()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5158, __extension__
__PRETTY_FUNCTION__))
;
5159 IsMemberSpec = VarTemplate->isMemberSpecialization();
5160 MultiLevelList.addOuterTemplateArguments(
5161 VarTemplate, TemplateArgList.asArray(), /*Final=*/false);
5162 }
5163 if (!IsMemberSpec)
5164 FromVar = FromVar->getFirstDecl();
5165
5166 TemplateDeclInstantiator Instantiator(*this, FromVar->getDeclContext(),
5167 MultiLevelList);
5168
5169 // TODO: Set LateAttrs and StartingScope ...
5170
5171 return cast_or_null<VarTemplateSpecializationDecl>(
5172 Instantiator.VisitVarTemplateSpecializationDecl(
5173 VarTemplate, FromVar, TemplateArgsInfo, Converted));
5174}
5175
5176/// Instantiates a variable template specialization by completing it
5177/// with appropriate type information and initializer.
5178VarTemplateSpecializationDecl *Sema::CompleteVarTemplateSpecializationDecl(
5179 VarTemplateSpecializationDecl *VarSpec, VarDecl *PatternDecl,
5180 const MultiLevelTemplateArgumentList &TemplateArgs) {
5181 assert(PatternDecl->isThisDeclarationADefinition() &&(static_cast <bool> (PatternDecl->isThisDeclarationADefinition
() && "don't have a definition to instantiate from") ?
void (0) : __assert_fail ("PatternDecl->isThisDeclarationADefinition() && \"don't have a definition to instantiate from\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5182, __extension__
__PRETTY_FUNCTION__))
5182 "don't have a definition to instantiate from")(static_cast <bool> (PatternDecl->isThisDeclarationADefinition
() && "don't have a definition to instantiate from") ?
void (0) : __assert_fail ("PatternDecl->isThisDeclarationADefinition() && \"don't have a definition to instantiate from\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5182, __extension__
__PRETTY_FUNCTION__))
;
5183
5184 // Do substitution on the type of the declaration
5185 TypeSourceInfo *DI =
5186 SubstType(PatternDecl->getTypeSourceInfo(), TemplateArgs,
5187 PatternDecl->getTypeSpecStartLoc(), PatternDecl->getDeclName());
5188 if (!DI)
5189 return nullptr;
5190
5191 // Update the type of this variable template specialization.
5192 VarSpec->setType(DI->getType());
5193
5194 // Convert the declaration into a definition now.
5195 VarSpec->setCompleteDefinition();
5196
5197 // Instantiate the initializer.
5198 InstantiateVariableInitializer(VarSpec, PatternDecl, TemplateArgs);
5199
5200 if (getLangOpts().OpenCL)
5201 deduceOpenCLAddressSpace(VarSpec);
5202
5203 return VarSpec;
5204}
5205
5206/// BuildVariableInstantiation - Used after a new variable has been created.
5207/// Sets basic variable data and decides whether to postpone the
5208/// variable instantiation.
5209void Sema::BuildVariableInstantiation(
5210 VarDecl *NewVar, VarDecl *OldVar,
5211 const MultiLevelTemplateArgumentList &TemplateArgs,
5212 LateInstantiatedAttrVec *LateAttrs, DeclContext *Owner,
5213 LocalInstantiationScope *StartingScope,
5214 bool InstantiatingVarTemplate,
5215 VarTemplateSpecializationDecl *PrevDeclForVarTemplateSpecialization) {
5216 // Instantiating a partial specialization to produce a partial
5217 // specialization.
5218 bool InstantiatingVarTemplatePartialSpec =
5219 isa<VarTemplatePartialSpecializationDecl>(OldVar) &&
5220 isa<VarTemplatePartialSpecializationDecl>(NewVar);
5221 // Instantiating from a variable template (or partial specialization) to
5222 // produce a variable template specialization.
5223 bool InstantiatingSpecFromTemplate =
5224 isa<VarTemplateSpecializationDecl>(NewVar) &&
5225 (OldVar->getDescribedVarTemplate() ||
5226 isa<VarTemplatePartialSpecializationDecl>(OldVar));
5227
5228 // If we are instantiating a local extern declaration, the
5229 // instantiation belongs lexically to the containing function.
5230 // If we are instantiating a static data member defined
5231 // out-of-line, the instantiation will have the same lexical
5232 // context (which will be a namespace scope) as the template.
5233 if (OldVar->isLocalExternDecl()) {
5234 NewVar->setLocalExternDecl();
5235 NewVar->setLexicalDeclContext(Owner);
5236 } else if (OldVar->isOutOfLine())
5237 NewVar->setLexicalDeclContext(OldVar->getLexicalDeclContext());
5238 NewVar->setTSCSpec(OldVar->getTSCSpec());
5239 NewVar->setInitStyle(OldVar->getInitStyle());
5240 NewVar->setCXXForRangeDecl(OldVar->isCXXForRangeDecl());
5241 NewVar->setObjCForDecl(OldVar->isObjCForDecl());
5242 NewVar->setConstexpr(OldVar->isConstexpr());
5243 NewVar->setInitCapture(OldVar->isInitCapture());
5244 NewVar->setPreviousDeclInSameBlockScope(
5245 OldVar->isPreviousDeclInSameBlockScope());
5246 NewVar->setAccess(OldVar->getAccess());
5247
5248 if (!OldVar->isStaticDataMember()) {
5249 if (OldVar->isUsed(false))
5250 NewVar->setIsUsed();
5251 NewVar->setReferenced(OldVar->isReferenced());
5252 }
5253
5254 InstantiateAttrs(TemplateArgs, OldVar, NewVar, LateAttrs, StartingScope);
5255
5256 LookupResult Previous(
5257 *this, NewVar->getDeclName(), NewVar->getLocation(),
5258 NewVar->isLocalExternDecl() ? Sema::LookupRedeclarationWithLinkage
5259 : Sema::LookupOrdinaryName,
5260 NewVar->isLocalExternDecl() ? Sema::ForExternalRedeclaration
5261 : forRedeclarationInCurContext());
5262
5263 if (NewVar->isLocalExternDecl() && OldVar->getPreviousDecl() &&
5264 (!OldVar->getPreviousDecl()->getDeclContext()->isDependentContext() ||
5265 OldVar->getPreviousDecl()->getDeclContext()==OldVar->getDeclContext())) {
5266 // We have a previous declaration. Use that one, so we merge with the
5267 // right type.
5268 if (NamedDecl *NewPrev = FindInstantiatedDecl(
5269 NewVar->getLocation(), OldVar->getPreviousDecl(), TemplateArgs))
5270 Previous.addDecl(NewPrev);
5271 } else if (!isa<VarTemplateSpecializationDecl>(NewVar) &&
5272 OldVar->hasLinkage()) {
5273 LookupQualifiedName(Previous, NewVar->getDeclContext(), false);
5274 } else if (PrevDeclForVarTemplateSpecialization) {
5275 Previous.addDecl(PrevDeclForVarTemplateSpecialization);
5276 }
5277 CheckVariableDeclaration(NewVar, Previous);
5278
5279 if (!InstantiatingVarTemplate) {
5280 NewVar->getLexicalDeclContext()->addHiddenDecl(NewVar);
5281 if (!NewVar->isLocalExternDecl() || !NewVar->getPreviousDecl())
5282 NewVar->getDeclContext()->makeDeclVisibleInContext(NewVar);
5283 }
5284
5285 if (!OldVar->isOutOfLine()) {
5286 if (NewVar->getDeclContext()->isFunctionOrMethod())
5287 CurrentInstantiationScope->InstantiatedLocal(OldVar, NewVar);
5288 }
5289
5290 // Link instantiations of static data members back to the template from
5291 // which they were instantiated.
5292 //
5293 // Don't do this when instantiating a template (we link the template itself
5294 // back in that case) nor when instantiating a static data member template
5295 // (that's not a member specialization).
5296 if (NewVar->isStaticDataMember() && !InstantiatingVarTemplate &&
5297 !InstantiatingSpecFromTemplate)
5298 NewVar->setInstantiationOfStaticDataMember(OldVar,
5299 TSK_ImplicitInstantiation);
5300
5301 // If the pattern is an (in-class) explicit specialization, then the result
5302 // is also an explicit specialization.
5303 if (VarTemplateSpecializationDecl *OldVTSD =
5304 dyn_cast<VarTemplateSpecializationDecl>(OldVar)) {
5305 if (OldVTSD->getSpecializationKind() == TSK_ExplicitSpecialization &&
5306 !isa<VarTemplatePartialSpecializationDecl>(OldVTSD))
5307 cast<VarTemplateSpecializationDecl>(NewVar)->setSpecializationKind(
5308 TSK_ExplicitSpecialization);
5309 }
5310
5311 // Forward the mangling number from the template to the instantiated decl.
5312 Context.setManglingNumber(NewVar, Context.getManglingNumber(OldVar));
5313 Context.setStaticLocalNumber(NewVar, Context.getStaticLocalNumber(OldVar));
5314
5315 // Figure out whether to eagerly instantiate the initializer.
5316 if (InstantiatingVarTemplate || InstantiatingVarTemplatePartialSpec) {
5317 // We're producing a template. Don't instantiate the initializer yet.
5318 } else if (NewVar->getType()->isUndeducedType()) {
5319 // We need the type to complete the declaration of the variable.
5320 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5321 } else if (InstantiatingSpecFromTemplate ||
5322 (OldVar->isInline() && OldVar->isThisDeclarationADefinition() &&
5323 !NewVar->isThisDeclarationADefinition())) {
5324 // Delay instantiation of the initializer for variable template
5325 // specializations or inline static data members until a definition of the
5326 // variable is needed.
5327 } else {
5328 InstantiateVariableInitializer(NewVar, OldVar, TemplateArgs);
5329 }
5330
5331 // Diagnose unused local variables with dependent types, where the diagnostic
5332 // will have been deferred.
5333 if (!NewVar->isInvalidDecl() &&
5334 NewVar->getDeclContext()->isFunctionOrMethod() &&
5335 OldVar->getType()->isDependentType())
5336 DiagnoseUnusedDecl(NewVar);
5337}
5338
5339/// Instantiate the initializer of a variable.
5340void Sema::InstantiateVariableInitializer(
5341 VarDecl *Var, VarDecl *OldVar,
5342 const MultiLevelTemplateArgumentList &TemplateArgs) {
5343 if (ASTMutationListener *L = getASTContext().getASTMutationListener())
5344 L->VariableDefinitionInstantiated(Var);
5345
5346 // We propagate the 'inline' flag with the initializer, because it
5347 // would otherwise imply that the variable is a definition for a
5348 // non-static data member.
5349 if (OldVar->isInlineSpecified())
5350 Var->setInlineSpecified();
5351 else if (OldVar->isInline())
5352 Var->setImplicitlyInline();
5353
5354 if (OldVar->getInit()) {
5355 EnterExpressionEvaluationContext Evaluated(
5356 *this, Sema::ExpressionEvaluationContext::PotentiallyEvaluated, Var);
5357
5358 // Instantiate the initializer.
5359 ExprResult Init;
5360
5361 {
5362 ContextRAII SwitchContext(*this, Var->getDeclContext());
5363 Init = SubstInitializer(OldVar->getInit(), TemplateArgs,
5364 OldVar->getInitStyle() == VarDecl::CallInit);
5365 }
5366
5367 if (!Init.isInvalid()) {
5368 Expr *InitExpr = Init.get();
5369
5370 if (Var->hasAttr<DLLImportAttr>() &&
5371 (!InitExpr ||
5372 !InitExpr->isConstantInitializer(getASTContext(), false))) {
5373 // Do not dynamically initialize dllimport variables.
5374 } else if (InitExpr) {
5375 bool DirectInit = OldVar->isDirectInit();
5376 AddInitializerToDecl(Var, InitExpr, DirectInit);
5377 } else
5378 ActOnUninitializedDecl(Var);
5379 } else {
5380 // FIXME: Not too happy about invalidating the declaration
5381 // because of a bogus initializer.
5382 Var->setInvalidDecl();
5383 }
5384 } else {
5385 // `inline` variables are a definition and declaration all in one; we won't
5386 // pick up an initializer from anywhere else.
5387 if (Var->isStaticDataMember() && !Var->isInline()) {
5388 if (!Var->isOutOfLine())
5389 return;
5390
5391 // If the declaration inside the class had an initializer, don't add
5392 // another one to the out-of-line definition.
5393 if (OldVar->getFirstDecl()->hasInit())
5394 return;
5395 }
5396
5397 // We'll add an initializer to a for-range declaration later.
5398 if (Var->isCXXForRangeDecl() || Var->isObjCForDecl())
5399 return;
5400
5401 ActOnUninitializedDecl(Var);
5402 }
5403
5404 if (getLangOpts().CUDA)
5405 checkAllowedCUDAInitializer(Var);
5406}
5407
5408/// Instantiate the definition of the given variable from its
5409/// template.
5410///
5411/// \param PointOfInstantiation the point at which the instantiation was
5412/// required. Note that this is not precisely a "point of instantiation"
5413/// for the variable, but it's close.
5414///
5415/// \param Var the already-instantiated declaration of a templated variable.
5416///
5417/// \param Recursive if true, recursively instantiates any functions that
5418/// are required by this instantiation.
5419///
5420/// \param DefinitionRequired if true, then we are performing an explicit
5421/// instantiation where a definition of the variable is required. Complain
5422/// if there is no such definition.
5423void Sema::InstantiateVariableDefinition(SourceLocation PointOfInstantiation,
5424 VarDecl *Var, bool Recursive,
5425 bool DefinitionRequired, bool AtEndOfTU) {
5426 if (Var->isInvalidDecl())
5427 return;
5428
5429 // Never instantiate an explicitly-specialized entity.
5430 TemplateSpecializationKind TSK =
5431 Var->getTemplateSpecializationKindForInstantiation();
5432 if (TSK == TSK_ExplicitSpecialization)
5433 return;
5434
5435 // Find the pattern and the arguments to substitute into it.
5436 VarDecl *PatternDecl = Var->getTemplateInstantiationPattern();
5437 assert(PatternDecl && "no pattern for templated variable")(static_cast <bool> (PatternDecl && "no pattern for templated variable"
) ? void (0) : __assert_fail ("PatternDecl && \"no pattern for templated variable\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5437, __extension__
__PRETTY_FUNCTION__))
;
5438 MultiLevelTemplateArgumentList TemplateArgs =
5439 getTemplateInstantiationArgs(Var);
5440
5441 VarTemplateSpecializationDecl *VarSpec =
5442 dyn_cast<VarTemplateSpecializationDecl>(Var);
5443 if (VarSpec) {
5444 // If this is a static data member template, there might be an
5445 // uninstantiated initializer on the declaration. If so, instantiate
5446 // it now.
5447 //
5448 // FIXME: This largely duplicates what we would do below. The difference
5449 // is that along this path we may instantiate an initializer from an
5450 // in-class declaration of the template and instantiate the definition
5451 // from a separate out-of-class definition.
5452 if (PatternDecl->isStaticDataMember() &&
5453 (PatternDecl = PatternDecl->getFirstDecl())->hasInit() &&
5454 !Var->hasInit()) {
5455 // FIXME: Factor out the duplicated instantiation context setup/tear down
5456 // code here.
5457 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5458 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5459 return;
5460 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5461 "instantiating variable initializer");
5462
5463 // The instantiation is visible here, even if it was first declared in an
5464 // unimported module.
5465 Var->setVisibleDespiteOwningModule();
5466
5467 // If we're performing recursive template instantiation, create our own
5468 // queue of pending implicit instantiations that we will instantiate
5469 // later, while we're still within our own instantiation context.
5470 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5471 /*Enabled=*/Recursive);
5472 LocalInstantiationScope Local(*this);
5473 LocalEagerInstantiationScope LocalInstantiations(*this);
5474
5475 // Enter the scope of this instantiation. We don't use
5476 // PushDeclContext because we don't have a scope.
5477 ContextRAII PreviousContext(*this, Var->getDeclContext());
5478 InstantiateVariableInitializer(Var, PatternDecl, TemplateArgs);
5479 PreviousContext.pop();
5480
5481 // This variable may have local implicit instantiations that need to be
5482 // instantiated within this scope.
5483 LocalInstantiations.perform();
5484 Local.Exit();
5485 GlobalInstantiations.perform();
5486 }
5487 } else {
5488 assert(Var->isStaticDataMember() && PatternDecl->isStaticDataMember() &&(static_cast <bool> (Var->isStaticDataMember() &&
PatternDecl->isStaticDataMember() && "not a static data member?"
) ? void (0) : __assert_fail ("Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && \"not a static data member?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5489, __extension__
__PRETTY_FUNCTION__))
5489 "not a static data member?")(static_cast <bool> (Var->isStaticDataMember() &&
PatternDecl->isStaticDataMember() && "not a static data member?"
) ? void (0) : __assert_fail ("Var->isStaticDataMember() && PatternDecl->isStaticDataMember() && \"not a static data member?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5489, __extension__
__PRETTY_FUNCTION__))
;
5490 }
5491
5492 VarDecl *Def = PatternDecl->getDefinition(getASTContext());
5493
5494 // If we don't have a definition of the variable template, we won't perform
5495 // any instantiation. Rather, we rely on the user to instantiate this
5496 // definition (or provide a specialization for it) in another translation
5497 // unit.
5498 if (!Def && !DefinitionRequired) {
5499 if (TSK == TSK_ExplicitInstantiationDefinition) {
5500 PendingInstantiations.push_back(
5501 std::make_pair(Var, PointOfInstantiation));
5502 } else if (TSK == TSK_ImplicitInstantiation) {
5503 // Warn about missing definition at the end of translation unit.
5504 if (AtEndOfTU && !getDiagnostics().hasErrorOccurred() &&
5505 !getSourceManager().isInSystemHeader(PatternDecl->getBeginLoc())) {
5506 Diag(PointOfInstantiation, diag::warn_var_template_missing)
5507 << Var;
5508 Diag(PatternDecl->getLocation(), diag::note_forward_template_decl);
5509 if (getLangOpts().CPlusPlus11)
5510 Diag(PointOfInstantiation, diag::note_inst_declaration_hint) << Var;
5511 }
5512 return;
5513 }
5514 }
5515
5516 // FIXME: We need to track the instantiation stack in order to know which
5517 // definitions should be visible within this instantiation.
5518 // FIXME: Produce diagnostics when Var->getInstantiatedFromStaticDataMember().
5519 if (DiagnoseUninstantiableTemplate(PointOfInstantiation, Var,
5520 /*InstantiatedFromMember*/false,
5521 PatternDecl, Def, TSK,
5522 /*Complain*/DefinitionRequired))
5523 return;
5524
5525 // C++11 [temp.explicit]p10:
5526 // Except for inline functions, const variables of literal types, variables
5527 // of reference types, [...] explicit instantiation declarations
5528 // have the effect of suppressing the implicit instantiation of the entity
5529 // to which they refer.
5530 //
5531 // FIXME: That's not exactly the same as "might be usable in constant
5532 // expressions", which only allows constexpr variables and const integral
5533 // types, not arbitrary const literal types.
5534 if (TSK == TSK_ExplicitInstantiationDeclaration &&
5535 !Var->mightBeUsableInConstantExpressions(getASTContext()))
5536 return;
5537
5538 // Make sure to pass the instantiated variable to the consumer at the end.
5539 struct PassToConsumerRAII {
5540 ASTConsumer &Consumer;
5541 VarDecl *Var;
5542
5543 PassToConsumerRAII(ASTConsumer &Consumer, VarDecl *Var)
5544 : Consumer(Consumer), Var(Var) { }
5545
5546 ~PassToConsumerRAII() {
5547 Consumer.HandleCXXStaticMemberVarInstantiation(Var);
5548 }
5549 } PassToConsumerRAII(Consumer, Var);
5550
5551 // If we already have a definition, we're done.
5552 if (VarDecl *Def = Var->getDefinition()) {
5553 // We may be explicitly instantiating something we've already implicitly
5554 // instantiated.
5555 Def->setTemplateSpecializationKind(Var->getTemplateSpecializationKind(),
5556 PointOfInstantiation);
5557 return;
5558 }
5559
5560 InstantiatingTemplate Inst(*this, PointOfInstantiation, Var);
5561 if (Inst.isInvalid() || Inst.isAlreadyInstantiating())
5562 return;
5563 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
5564 "instantiating variable definition");
5565
5566 // If we're performing recursive template instantiation, create our own
5567 // queue of pending implicit instantiations that we will instantiate later,
5568 // while we're still within our own instantiation context.
5569 GlobalEagerInstantiationScope GlobalInstantiations(*this,
5570 /*Enabled=*/Recursive);
5571
5572 // Enter the scope of this instantiation. We don't use
5573 // PushDeclContext because we don't have a scope.
5574 ContextRAII PreviousContext(*this, Var->getDeclContext());
5575 LocalInstantiationScope Local(*this);
5576
5577 LocalEagerInstantiationScope LocalInstantiations(*this);
5578
5579 VarDecl *OldVar = Var;
5580 if (Def->isStaticDataMember() && !Def->isOutOfLine()) {
5581 // We're instantiating an inline static data member whose definition was
5582 // provided inside the class.
5583 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5584 } else if (!VarSpec) {
5585 Var = cast_or_null<VarDecl>(SubstDecl(Def, Var->getDeclContext(),
5586 TemplateArgs));
5587 } else if (Var->isStaticDataMember() &&
5588 Var->getLexicalDeclContext()->isRecord()) {
5589 // We need to instantiate the definition of a static data member template,
5590 // and all we have is the in-class declaration of it. Instantiate a separate
5591 // declaration of the definition.
5592 TemplateDeclInstantiator Instantiator(*this, Var->getDeclContext(),
5593 TemplateArgs);
5594
5595 TemplateArgumentListInfo TemplateArgInfo;
5596 if (const ASTTemplateArgumentListInfo *ArgInfo =
5597 VarSpec->getTemplateArgsInfo()) {
5598 TemplateArgInfo.setLAngleLoc(ArgInfo->getLAngleLoc());
5599 TemplateArgInfo.setRAngleLoc(ArgInfo->getRAngleLoc());
5600 for (const TemplateArgumentLoc &Arg : ArgInfo->arguments())
5601 TemplateArgInfo.addArgument(Arg);
5602 }
5603
5604 Var = cast_or_null<VarDecl>(Instantiator.VisitVarTemplateSpecializationDecl(
5605 VarSpec->getSpecializedTemplate(), Def, TemplateArgInfo,
5606 VarSpec->getTemplateArgs().asArray(), VarSpec));
5607 if (Var) {
5608 llvm::PointerUnion<VarTemplateDecl *,
5609 VarTemplatePartialSpecializationDecl *> PatternPtr =
5610 VarSpec->getSpecializedTemplateOrPartial();
5611 if (VarTemplatePartialSpecializationDecl *Partial =
5612 PatternPtr.dyn_cast<VarTemplatePartialSpecializationDecl *>())
5613 cast<VarTemplateSpecializationDecl>(Var)->setInstantiationOf(
5614 Partial, &VarSpec->getTemplateInstantiationArgs());
5615
5616 // Attach the initializer.
5617 InstantiateVariableInitializer(Var, Def, TemplateArgs);
5618 }
5619 } else
5620 // Complete the existing variable's definition with an appropriately
5621 // substituted type and initializer.
5622 Var = CompleteVarTemplateSpecializationDecl(VarSpec, Def, TemplateArgs);
5623
5624 PreviousContext.pop();
5625
5626 if (Var) {
5627 PassToConsumerRAII.Var = Var;
5628 Var->setTemplateSpecializationKind(OldVar->getTemplateSpecializationKind(),
5629 OldVar->getPointOfInstantiation());
5630 }
5631
5632 // This variable may have local implicit instantiations that need to be
5633 // instantiated within this scope.
5634 LocalInstantiations.perform();
5635 Local.Exit();
5636 GlobalInstantiations.perform();
5637}
5638
5639void
5640Sema::InstantiateMemInitializers(CXXConstructorDecl *New,
5641 const CXXConstructorDecl *Tmpl,
5642 const MultiLevelTemplateArgumentList &TemplateArgs) {
5643
5644 SmallVector<CXXCtorInitializer*, 4> NewInits;
5645 bool AnyErrors = Tmpl->isInvalidDecl();
5646
5647 // Instantiate all the initializers.
5648 for (const auto *Init : Tmpl->inits()) {
5649 // Only instantiate written initializers, let Sema re-construct implicit
5650 // ones.
5651 if (!Init->isWritten())
5652 continue;
5653
5654 SourceLocation EllipsisLoc;
5655
5656 if (Init->isPackExpansion()) {
5657 // This is a pack expansion. We should expand it now.
5658 TypeLoc BaseTL = Init->getTypeSourceInfo()->getTypeLoc();
5659 SmallVector<UnexpandedParameterPack, 4> Unexpanded;
5660 collectUnexpandedParameterPacks(BaseTL, Unexpanded);
5661 collectUnexpandedParameterPacks(Init->getInit(), Unexpanded);
5662 bool ShouldExpand = false;
5663 bool RetainExpansion = false;
5664 std::optional<unsigned> NumExpansions;
5665 if (CheckParameterPacksForExpansion(Init->getEllipsisLoc(),
5666 BaseTL.getSourceRange(),
5667 Unexpanded,
5668 TemplateArgs, ShouldExpand,
5669 RetainExpansion,
5670 NumExpansions)) {
5671 AnyErrors = true;
5672 New->setInvalidDecl();
5673 continue;
5674 }
5675 assert(ShouldExpand && "Partial instantiation of base initializer?")(static_cast <bool> (ShouldExpand && "Partial instantiation of base initializer?"
) ? void (0) : __assert_fail ("ShouldExpand && \"Partial instantiation of base initializer?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5675, __extension__
__PRETTY_FUNCTION__))
;
5676
5677 // Loop over all of the arguments in the argument pack(s),
5678 for (unsigned I = 0; I != *NumExpansions; ++I) {
5679 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(*this, I);
5680
5681 // Instantiate the initializer.
5682 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5683 /*CXXDirectInit=*/true);
5684 if (TempInit.isInvalid()) {
5685 AnyErrors = true;
5686 break;
5687 }
5688
5689 // Instantiate the base type.
5690 TypeSourceInfo *BaseTInfo = SubstType(Init->getTypeSourceInfo(),
5691 TemplateArgs,
5692 Init->getSourceLocation(),
5693 New->getDeclName());
5694 if (!BaseTInfo) {
5695 AnyErrors = true;
5696 break;
5697 }
5698
5699 // Build the initializer.
5700 MemInitResult NewInit = BuildBaseInitializer(BaseTInfo->getType(),
5701 BaseTInfo, TempInit.get(),
5702 New->getParent(),
5703 SourceLocation());
5704 if (NewInit.isInvalid()) {
5705 AnyErrors = true;
5706 break;
5707 }
5708
5709 NewInits.push_back(NewInit.get());
5710 }
5711
5712 continue;
5713 }
5714
5715 // Instantiate the initializer.
5716 ExprResult TempInit = SubstInitializer(Init->getInit(), TemplateArgs,
5717 /*CXXDirectInit=*/true);
5718 if (TempInit.isInvalid()) {
5719 AnyErrors = true;
5720 continue;
5721 }
5722
5723 MemInitResult NewInit;
5724 if (Init->isDelegatingInitializer() || Init->isBaseInitializer()) {
5725 TypeSourceInfo *TInfo = SubstType(Init->getTypeSourceInfo(),
5726 TemplateArgs,
5727 Init->getSourceLocation(),
5728 New->getDeclName());
5729 if (!TInfo) {
5730 AnyErrors = true;
5731 New->setInvalidDecl();
5732 continue;
5733 }
5734
5735 if (Init->isBaseInitializer())
5736 NewInit = BuildBaseInitializer(TInfo->getType(), TInfo, TempInit.get(),
5737 New->getParent(), EllipsisLoc);
5738 else
5739 NewInit = BuildDelegatingInitializer(TInfo, TempInit.get(),
5740 cast<CXXRecordDecl>(CurContext->getParent()));
5741 } else if (Init->isMemberInitializer()) {
5742 FieldDecl *Member = cast_or_null<FieldDecl>(FindInstantiatedDecl(
5743 Init->getMemberLocation(),
5744 Init->getMember(),
5745 TemplateArgs));
5746 if (!Member) {
5747 AnyErrors = true;
5748 New->setInvalidDecl();
5749 continue;
5750 }
5751
5752 NewInit = BuildMemberInitializer(Member, TempInit.get(),
5753 Init->getSourceLocation());
5754 } else if (Init->isIndirectMemberInitializer()) {
5755 IndirectFieldDecl *IndirectMember =
5756 cast_or_null<IndirectFieldDecl>(FindInstantiatedDecl(
5757 Init->getMemberLocation(),
5758 Init->getIndirectMember(), TemplateArgs));
5759
5760 if (!IndirectMember) {
5761 AnyErrors = true;
5762 New->setInvalidDecl();
5763 continue;
5764 }
5765
5766 NewInit = BuildMemberInitializer(IndirectMember, TempInit.get(),
5767 Init->getSourceLocation());
5768 }
5769
5770 if (NewInit.isInvalid()) {
5771 AnyErrors = true;
5772 New->setInvalidDecl();
5773 } else {
5774 NewInits.push_back(NewInit.get());
5775 }
5776 }
5777
5778 // Assign all the initializers to the new constructor.
5779 ActOnMemInitializers(New,
5780 /*FIXME: ColonLoc */
5781 SourceLocation(),
5782 NewInits,
5783 AnyErrors);
5784}
5785
5786// TODO: this could be templated if the various decl types used the
5787// same method name.
5788static bool isInstantiationOf(ClassTemplateDecl *Pattern,
5789 ClassTemplateDecl *Instance) {
5790 Pattern = Pattern->getCanonicalDecl();
5791
5792 do {
5793 Instance = Instance->getCanonicalDecl();
5794 if (Pattern == Instance) return true;
5795 Instance = Instance->getInstantiatedFromMemberTemplate();
5796 } while (Instance);
5797
5798 return false;
5799}
5800
5801static bool isInstantiationOf(FunctionTemplateDecl *Pattern,
5802 FunctionTemplateDecl *Instance) {
5803 Pattern = Pattern->getCanonicalDecl();
5804
5805 do {
5806 Instance = Instance->getCanonicalDecl();
5807 if (Pattern == Instance) return true;
5808 Instance = Instance->getInstantiatedFromMemberTemplate();
5809 } while (Instance);
5810
5811 return false;
5812}
5813
5814static bool
5815isInstantiationOf(ClassTemplatePartialSpecializationDecl *Pattern,
5816 ClassTemplatePartialSpecializationDecl *Instance) {
5817 Pattern
5818 = cast<ClassTemplatePartialSpecializationDecl>(Pattern->getCanonicalDecl());
5819 do {
5820 Instance = cast<ClassTemplatePartialSpecializationDecl>(
5821 Instance->getCanonicalDecl());
5822 if (Pattern == Instance)
5823 return true;
5824 Instance = Instance->getInstantiatedFromMember();
5825 } while (Instance);
5826
5827 return false;
5828}
5829
5830static bool isInstantiationOf(CXXRecordDecl *Pattern,
5831 CXXRecordDecl *Instance) {
5832 Pattern = Pattern->getCanonicalDecl();
5833
5834 do {
5835 Instance = Instance->getCanonicalDecl();
5836 if (Pattern == Instance) return true;
5837 Instance = Instance->getInstantiatedFromMemberClass();
5838 } while (Instance);
5839
5840 return false;
5841}
5842
5843static bool isInstantiationOf(FunctionDecl *Pattern,
5844 FunctionDecl *Instance) {
5845 Pattern = Pattern->getCanonicalDecl();
5846
5847 do {
5848 Instance = Instance->getCanonicalDecl();
5849 if (Pattern == Instance) return true;
5850 Instance = Instance->getInstantiatedFromMemberFunction();
5851 } while (Instance);
5852
5853 return false;
5854}
5855
5856static bool isInstantiationOf(EnumDecl *Pattern,
5857 EnumDecl *Instance) {
5858 Pattern = Pattern->getCanonicalDecl();
5859
5860 do {
5861 Instance = Instance->getCanonicalDecl();
5862 if (Pattern == Instance) return true;
5863 Instance = Instance->getInstantiatedFromMemberEnum();
5864 } while (Instance);
5865
5866 return false;
5867}
5868
5869static bool isInstantiationOf(UsingShadowDecl *Pattern,
5870 UsingShadowDecl *Instance,
5871 ASTContext &C) {
5872 return declaresSameEntity(C.getInstantiatedFromUsingShadowDecl(Instance),
5873 Pattern);
5874}
5875
5876static bool isInstantiationOf(UsingDecl *Pattern, UsingDecl *Instance,
5877 ASTContext &C) {
5878 return declaresSameEntity(C.getInstantiatedFromUsingDecl(Instance), Pattern);
5879}
5880
5881template<typename T>
5882static bool isInstantiationOfUnresolvedUsingDecl(T *Pattern, Decl *Other,
5883 ASTContext &Ctx) {
5884 // An unresolved using declaration can instantiate to an unresolved using
5885 // declaration, or to a using declaration or a using declaration pack.
5886 //
5887 // Multiple declarations can claim to be instantiated from an unresolved
5888 // using declaration if it's a pack expansion. We want the UsingPackDecl
5889 // in that case, not the individual UsingDecls within the pack.
5890 bool OtherIsPackExpansion;
5891 NamedDecl *OtherFrom;
5892 if (auto *OtherUUD = dyn_cast<T>(Other)) {
5893 OtherIsPackExpansion = OtherUUD->isPackExpansion();
5894 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUUD);
5895 } else if (auto *OtherUPD = dyn_cast<UsingPackDecl>(Other)) {
5896 OtherIsPackExpansion = true;
5897 OtherFrom = OtherUPD->getInstantiatedFromUsingDecl();
5898 } else if (auto *OtherUD = dyn_cast<UsingDecl>(Other)) {
5899 OtherIsPackExpansion = false;
5900 OtherFrom = Ctx.getInstantiatedFromUsingDecl(OtherUD);
5901 } else {
5902 return false;
5903 }
5904 return Pattern->isPackExpansion() == OtherIsPackExpansion &&
5905 declaresSameEntity(OtherFrom, Pattern);
5906}
5907
5908static bool isInstantiationOfStaticDataMember(VarDecl *Pattern,
5909 VarDecl *Instance) {
5910 assert(Instance->isStaticDataMember())(static_cast <bool> (Instance->isStaticDataMember())
? void (0) : __assert_fail ("Instance->isStaticDataMember()"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 5910, __extension__
__PRETTY_FUNCTION__))
;
5911
5912 Pattern = Pattern->getCanonicalDecl();
5913
5914 do {
5915 Instance = Instance->getCanonicalDecl();
5916 if (Pattern == Instance) return true;
5917 Instance = Instance->getInstantiatedFromStaticDataMember();
5918 } while (Instance);
5919
5920 return false;
5921}
5922
5923// Other is the prospective instantiation
5924// D is the prospective pattern
5925static bool isInstantiationOf(ASTContext &Ctx, NamedDecl *D, Decl *Other) {
5926 if (auto *UUD = dyn_cast<UnresolvedUsingTypenameDecl>(D))
5927 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5928
5929 if (auto *UUD = dyn_cast<UnresolvedUsingValueDecl>(D))
5930 return isInstantiationOfUnresolvedUsingDecl(UUD, Other, Ctx);
5931
5932 if (D->getKind() != Other->getKind())
5933 return false;
5934
5935 if (auto *Record = dyn_cast<CXXRecordDecl>(Other))
5936 return isInstantiationOf(cast<CXXRecordDecl>(D), Record);
5937
5938 if (auto *Function = dyn_cast<FunctionDecl>(Other))
5939 return isInstantiationOf(cast<FunctionDecl>(D), Function);
5940
5941 if (auto *Enum = dyn_cast<EnumDecl>(Other))
5942 return isInstantiationOf(cast<EnumDecl>(D), Enum);
5943
5944 if (auto *Var = dyn_cast<VarDecl>(Other))
5945 if (Var->isStaticDataMember())
5946 return isInstantiationOfStaticDataMember(cast<VarDecl>(D), Var);
5947
5948 if (auto *Temp = dyn_cast<ClassTemplateDecl>(Other))
5949 return isInstantiationOf(cast<ClassTemplateDecl>(D), Temp);
5950
5951 if (auto *Temp = dyn_cast<FunctionTemplateDecl>(Other))
5952 return isInstantiationOf(cast<FunctionTemplateDecl>(D), Temp);
5953
5954 if (auto *PartialSpec =
5955 dyn_cast<ClassTemplatePartialSpecializationDecl>(Other))
5956 return isInstantiationOf(cast<ClassTemplatePartialSpecializationDecl>(D),
5957 PartialSpec);
5958
5959 if (auto *Field = dyn_cast<FieldDecl>(Other)) {
5960 if (!Field->getDeclName()) {
5961 // This is an unnamed field.
5962 return declaresSameEntity(Ctx.getInstantiatedFromUnnamedFieldDecl(Field),
5963 cast<FieldDecl>(D));
5964 }
5965 }
5966
5967 if (auto *Using = dyn_cast<UsingDecl>(Other))
5968 return isInstantiationOf(cast<UsingDecl>(D), Using, Ctx);
5969
5970 if (auto *Shadow = dyn_cast<UsingShadowDecl>(Other))
5971 return isInstantiationOf(cast<UsingShadowDecl>(D), Shadow, Ctx);
5972
5973 return D->getDeclName() &&
5974 D->getDeclName() == cast<NamedDecl>(Other)->getDeclName();
5975}
5976
5977template<typename ForwardIterator>
5978static NamedDecl *findInstantiationOf(ASTContext &Ctx,
5979 NamedDecl *D,
5980 ForwardIterator first,
5981 ForwardIterator last) {
5982 for (; first != last; ++first)
5983 if (isInstantiationOf(Ctx, D, *first))
5984 return cast<NamedDecl>(*first);
5985
5986 return nullptr;
5987}
5988
5989/// Finds the instantiation of the given declaration context
5990/// within the current instantiation.
5991///
5992/// \returns NULL if there was an error
5993DeclContext *Sema::FindInstantiatedContext(SourceLocation Loc, DeclContext* DC,
5994 const MultiLevelTemplateArgumentList &TemplateArgs) {
5995 if (NamedDecl *D = dyn_cast<NamedDecl>(DC)) {
5996 Decl* ID = FindInstantiatedDecl(Loc, D, TemplateArgs, true);
5997 return cast_or_null<DeclContext>(ID);
5998 } else return DC;
5999}
6000
6001/// Determine whether the given context is dependent on template parameters at
6002/// level \p Level or below.
6003///
6004/// Sometimes we only substitute an inner set of template arguments and leave
6005/// the outer templates alone. In such cases, contexts dependent only on the
6006/// outer levels are not effectively dependent.
6007static bool isDependentContextAtLevel(DeclContext *DC, unsigned Level) {
6008 if (!DC->isDependentContext())
6009 return false;
6010 if (!Level)
6011 return true;
6012 return cast<Decl>(DC)->getTemplateDepth() > Level;
6013}
6014
6015/// Find the instantiation of the given declaration within the
6016/// current instantiation.
6017///
6018/// This routine is intended to be used when \p D is a declaration
6019/// referenced from within a template, that needs to mapped into the
6020/// corresponding declaration within an instantiation. For example,
6021/// given:
6022///
6023/// \code
6024/// template<typename T>
6025/// struct X {
6026/// enum Kind {
6027/// KnownValue = sizeof(T)
6028/// };
6029///
6030/// bool getKind() const { return KnownValue; }
6031/// };
6032///
6033/// template struct X<int>;
6034/// \endcode
6035///
6036/// In the instantiation of X<int>::getKind(), we need to map the \p
6037/// EnumConstantDecl for \p KnownValue (which refers to
6038/// X<T>::<Kind>::KnownValue) to its instantiation (X<int>::<Kind>::KnownValue).
6039/// \p FindInstantiatedDecl performs this mapping from within the instantiation
6040/// of X<int>.
6041NamedDecl *Sema::FindInstantiatedDecl(SourceLocation Loc, NamedDecl *D,
6042 const MultiLevelTemplateArgumentList &TemplateArgs,
6043 bool FindingInstantiatedContext) {
6044 DeclContext *ParentDC = D->getDeclContext();
6045 // Determine whether our parent context depends on any of the template
6046 // arguments we're currently substituting.
6047 bool ParentDependsOnArgs = isDependentContextAtLevel(
6048 ParentDC, TemplateArgs.getNumRetainedOuterLevels());
6049 // FIXME: Parameters of pointer to functions (y below) that are themselves
6050 // parameters (p below) can have their ParentDC set to the translation-unit
6051 // - thus we can not consistently check if the ParentDC of such a parameter
6052 // is Dependent or/and a FunctionOrMethod.
6053 // For e.g. this code, during Template argument deduction tries to
6054 // find an instantiated decl for (T y) when the ParentDC for y is
6055 // the translation unit.
6056 // e.g. template <class T> void Foo(auto (*p)(T y) -> decltype(y())) {}
6057 // float baz(float(*)()) { return 0.0; }
6058 // Foo(baz);
6059 // The better fix here is perhaps to ensure that a ParmVarDecl, by the time
6060 // it gets here, always has a FunctionOrMethod as its ParentDC??
6061 // For now:
6062 // - as long as we have a ParmVarDecl whose parent is non-dependent and
6063 // whose type is not instantiation dependent, do nothing to the decl
6064 // - otherwise find its instantiated decl.
6065 if (isa<ParmVarDecl>(D) && !ParentDependsOnArgs &&
6066 !cast<ParmVarDecl>(D)->getType()->isInstantiationDependentType())
6067 return D;
6068 if (isa<ParmVarDecl>(D) || isa<NonTypeTemplateParmDecl>(D) ||
6069 isa<TemplateTypeParmDecl>(D) || isa<TemplateTemplateParmDecl>(D) ||
6070 (ParentDependsOnArgs && (ParentDC->isFunctionOrMethod() ||
6071 isa<OMPDeclareReductionDecl>(ParentDC) ||
6072 isa<OMPDeclareMapperDecl>(ParentDC))) ||
6073 (isa<CXXRecordDecl>(D) && cast<CXXRecordDecl>(D)->isLambda() &&
6074 cast<CXXRecordDecl>(D)->getTemplateDepth() >
6075 TemplateArgs.getNumRetainedOuterLevels())) {
6076 // D is a local of some kind. Look into the map of local
6077 // declarations to their instantiations.
6078 if (CurrentInstantiationScope) {
6079 if (auto Found = CurrentInstantiationScope->findInstantiationOf(D)) {
6080 if (Decl *FD = Found->dyn_cast<Decl *>())
6081 return cast<NamedDecl>(FD);
6082
6083 int PackIdx = ArgumentPackSubstitutionIndex;
6084 assert(PackIdx != -1 &&(static_cast <bool> (PackIdx != -1 && "found declaration pack but not pack expanding"
) ? void (0) : __assert_fail ("PackIdx != -1 && \"found declaration pack but not pack expanding\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6085, __extension__
__PRETTY_FUNCTION__))
6085 "found declaration pack but not pack expanding")(static_cast <bool> (PackIdx != -1 && "found declaration pack but not pack expanding"
) ? void (0) : __assert_fail ("PackIdx != -1 && \"found declaration pack but not pack expanding\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6085, __extension__
__PRETTY_FUNCTION__))
;
6086 typedef LocalInstantiationScope::DeclArgumentPack DeclArgumentPack;
6087 return cast<NamedDecl>((*Found->get<DeclArgumentPack *>())[PackIdx]);
6088 }
6089 }
6090
6091 // If we're performing a partial substitution during template argument
6092 // deduction, we may not have values for template parameters yet. They
6093 // just map to themselves.
6094 if (isa<NonTypeTemplateParmDecl>(D) || isa<TemplateTypeParmDecl>(D) ||
6095 isa<TemplateTemplateParmDecl>(D))
6096 return D;
6097
6098 if (D->isInvalidDecl())
6099 return nullptr;
6100
6101 // Normally this function only searches for already instantiated declaration
6102 // however we have to make an exclusion for local types used before
6103 // definition as in the code:
6104 //
6105 // template<typename T> void f1() {
6106 // void g1(struct x1);
6107 // struct x1 {};
6108 // }
6109 //
6110 // In this case instantiation of the type of 'g1' requires definition of
6111 // 'x1', which is defined later. Error recovery may produce an enum used
6112 // before definition. In these cases we need to instantiate relevant
6113 // declarations here.
6114 bool NeedInstantiate = false;
6115 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D))
6116 NeedInstantiate = RD->isLocalClass();
6117 else if (isa<TypedefNameDecl>(D) &&
6118 isa<CXXDeductionGuideDecl>(D->getDeclContext()))
6119 NeedInstantiate = true;
6120 else
6121 NeedInstantiate = isa<EnumDecl>(D);
6122 if (NeedInstantiate) {
6123 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6124 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6125 return cast<TypeDecl>(Inst);
6126 }
6127
6128 // If we didn't find the decl, then we must have a label decl that hasn't
6129 // been found yet. Lazily instantiate it and return it now.
6130 assert(isa<LabelDecl>(D))(static_cast <bool> (isa<LabelDecl>(D)) ? void (0
) : __assert_fail ("isa<LabelDecl>(D)", "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp"
, 6130, __extension__ __PRETTY_FUNCTION__))
;
6131
6132 Decl *Inst = SubstDecl(D, CurContext, TemplateArgs);
6133 assert(Inst && "Failed to instantiate label??")(static_cast <bool> (Inst && "Failed to instantiate label??"
) ? void (0) : __assert_fail ("Inst && \"Failed to instantiate label??\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6133, __extension__
__PRETTY_FUNCTION__))
;
6134
6135 CurrentInstantiationScope->InstantiatedLocal(D, Inst);
6136 return cast<LabelDecl>(Inst);
6137 }
6138
6139 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(D)) {
6140 if (!Record->isDependentContext())
6141 return D;
6142
6143 // Determine whether this record is the "templated" declaration describing
6144 // a class template or class template partial specialization.
6145 ClassTemplateDecl *ClassTemplate = Record->getDescribedClassTemplate();
6146 if (ClassTemplate)
6147 ClassTemplate = ClassTemplate->getCanonicalDecl();
6148 else if (ClassTemplatePartialSpecializationDecl *PartialSpec
6149 = dyn_cast<ClassTemplatePartialSpecializationDecl>(Record))
6150 ClassTemplate = PartialSpec->getSpecializedTemplate()->getCanonicalDecl();
6151
6152 // Walk the current context to find either the record or an instantiation of
6153 // it.
6154 DeclContext *DC = CurContext;
6155 while (!DC->isFileContext()) {
6156 // If we're performing substitution while we're inside the template
6157 // definition, we'll find our own context. We're done.
6158 if (DC->Equals(Record))
6159 return Record;
6160
6161 if (CXXRecordDecl *InstRecord = dyn_cast<CXXRecordDecl>(DC)) {
6162 // Check whether we're in the process of instantiating a class template
6163 // specialization of the template we're mapping.
6164 if (ClassTemplateSpecializationDecl *InstSpec
6165 = dyn_cast<ClassTemplateSpecializationDecl>(InstRecord)){
6166 ClassTemplateDecl *SpecTemplate = InstSpec->getSpecializedTemplate();
6167 if (ClassTemplate && isInstantiationOf(ClassTemplate, SpecTemplate))
6168 return InstRecord;
6169 }
6170
6171 // Check whether we're in the process of instantiating a member class.
6172 if (isInstantiationOf(Record, InstRecord))
6173 return InstRecord;
6174 }
6175
6176 // Move to the outer template scope.
6177 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) {
6178 if (FD->getFriendObjectKind() &&
6179 FD->getNonTransparentDeclContext()->isFileContext()) {
6180 DC = FD->getLexicalDeclContext();
6181 continue;
6182 }
6183 // An implicit deduction guide acts as if it's within the class template
6184 // specialization described by its name and first N template params.
6185 auto *Guide = dyn_cast<CXXDeductionGuideDecl>(FD);
6186 if (Guide && Guide->isImplicit()) {
6187 TemplateDecl *TD = Guide->getDeducedTemplate();
6188 // Convert the arguments to an "as-written" list.
6189 TemplateArgumentListInfo Args(Loc, Loc);
6190 for (TemplateArgument Arg : TemplateArgs.getInnermost().take_front(
6191 TD->getTemplateParameters()->size())) {
6192 ArrayRef<TemplateArgument> Unpacked(Arg);
6193 if (Arg.getKind() == TemplateArgument::Pack)
6194 Unpacked = Arg.pack_elements();
6195 for (TemplateArgument UnpackedArg : Unpacked)
6196 Args.addArgument(
6197 getTrivialTemplateArgumentLoc(UnpackedArg, QualType(), Loc));
6198 }
6199 QualType T = CheckTemplateIdType(TemplateName(TD), Loc, Args);
6200 if (T.isNull())
6201 return nullptr;
6202 auto *SubstRecord = T->getAsCXXRecordDecl();
6203 assert(SubstRecord && "class template id not a class type?")(static_cast <bool> (SubstRecord && "class template id not a class type?"
) ? void (0) : __assert_fail ("SubstRecord && \"class template id not a class type?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6203, __extension__
__PRETTY_FUNCTION__))
;
6204 // Check that this template-id names the primary template and not a
6205 // partial or explicit specialization. (In the latter cases, it's
6206 // meaningless to attempt to find an instantiation of D within the
6207 // specialization.)
6208 // FIXME: The standard doesn't say what should happen here.
6209 if (FindingInstantiatedContext &&
6210 usesPartialOrExplicitSpecialization(
6211 Loc, cast<ClassTemplateSpecializationDecl>(SubstRecord))) {
6212 Diag(Loc, diag::err_specialization_not_primary_template)
6213 << T << (SubstRecord->getTemplateSpecializationKind() ==
6214 TSK_ExplicitSpecialization);
6215 return nullptr;
6216 }
6217 DC = SubstRecord;
6218 continue;
6219 }
6220 }
6221
6222 DC = DC->getParent();
6223 }
6224
6225 // Fall through to deal with other dependent record types (e.g.,
6226 // anonymous unions in class templates).
6227 }
6228
6229 if (!ParentDependsOnArgs)
6230 return D;
6231
6232 ParentDC = FindInstantiatedContext(Loc, ParentDC, TemplateArgs);
6233 if (!ParentDC)
6234 return nullptr;
6235
6236 if (ParentDC != D->getDeclContext()) {
6237 // We performed some kind of instantiation in the parent context,
6238 // so now we need to look into the instantiated parent context to
6239 // find the instantiation of the declaration D.
6240
6241 // If our context used to be dependent, we may need to instantiate
6242 // it before performing lookup into that context.
6243 bool IsBeingInstantiated = false;
6244 if (CXXRecordDecl *Spec = dyn_cast<CXXRecordDecl>(ParentDC)) {
6245 if (!Spec->isDependentContext()) {
6246 QualType T = Context.getTypeDeclType(Spec);
6247 const RecordType *Tag = T->getAs<RecordType>();
6248 assert(Tag && "type of non-dependent record is not a RecordType")(static_cast <bool> (Tag && "type of non-dependent record is not a RecordType"
) ? void (0) : __assert_fail ("Tag && \"type of non-dependent record is not a RecordType\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6248, __extension__
__PRETTY_FUNCTION__))
;
6249 if (Tag->isBeingDefined())
6250 IsBeingInstantiated = true;
6251 if (!Tag->isBeingDefined() &&
6252 RequireCompleteType(Loc, T, diag::err_incomplete_type))
6253 return nullptr;
6254
6255 ParentDC = Tag->getDecl();
6256 }
6257 }
6258
6259 NamedDecl *Result = nullptr;
6260 // FIXME: If the name is a dependent name, this lookup won't necessarily
6261 // find it. Does that ever matter?
6262 if (auto Name = D->getDeclName()) {
6263 DeclarationNameInfo NameInfo(Name, D->getLocation());
6264 DeclarationNameInfo NewNameInfo =
6265 SubstDeclarationNameInfo(NameInfo, TemplateArgs);
6266 Name = NewNameInfo.getName();
6267 if (!Name)
6268 return nullptr;
6269 DeclContext::lookup_result Found = ParentDC->lookup(Name);
6270
6271 Result = findInstantiationOf(Context, D, Found.begin(), Found.end());
6272 } else {
6273 // Since we don't have a name for the entity we're looking for,
6274 // our only option is to walk through all of the declarations to
6275 // find that name. This will occur in a few cases:
6276 //
6277 // - anonymous struct/union within a template
6278 // - unnamed class/struct/union/enum within a template
6279 //
6280 // FIXME: Find a better way to find these instantiations!
6281 Result = findInstantiationOf(Context, D,
6282 ParentDC->decls_begin(),
6283 ParentDC->decls_end());
6284 }
6285
6286 if (!Result) {
6287 if (isa<UsingShadowDecl>(D)) {
6288 // UsingShadowDecls can instantiate to nothing because of using hiding.
6289 } else if (hasUncompilableErrorOccurred()) {
6290 // We've already complained about some ill-formed code, so most likely
6291 // this declaration failed to instantiate. There's no point in
6292 // complaining further, since this is normal in invalid code.
6293 // FIXME: Use more fine-grained 'invalid' tracking for this.
6294 } else if (IsBeingInstantiated) {
6295 // The class in which this member exists is currently being
6296 // instantiated, and we haven't gotten around to instantiating this
6297 // member yet. This can happen when the code uses forward declarations
6298 // of member classes, and introduces ordering dependencies via
6299 // template instantiation.
6300 Diag(Loc, diag::err_member_not_yet_instantiated)
6301 << D->getDeclName()
6302 << Context.getTypeDeclType(cast<CXXRecordDecl>(ParentDC));
6303 Diag(D->getLocation(), diag::note_non_instantiated_member_here);
6304 } else if (EnumConstantDecl *ED = dyn_cast<EnumConstantDecl>(D)) {
6305 // This enumeration constant was found when the template was defined,
6306 // but can't be found in the instantiation. This can happen if an
6307 // unscoped enumeration member is explicitly specialized.
6308 EnumDecl *Enum = cast<EnumDecl>(ED->getLexicalDeclContext());
6309 EnumDecl *Spec = cast<EnumDecl>(FindInstantiatedDecl(Loc, Enum,
6310 TemplateArgs));
6311 assert(Spec->getTemplateSpecializationKind() ==(static_cast <bool> (Spec->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization) ? void (0) : __assert_fail (
"Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6312, __extension__
__PRETTY_FUNCTION__))
6312 TSK_ExplicitSpecialization)(static_cast <bool> (Spec->getTemplateSpecializationKind
() == TSK_ExplicitSpecialization) ? void (0) : __assert_fail (
"Spec->getTemplateSpecializationKind() == TSK_ExplicitSpecialization"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6312, __extension__
__PRETTY_FUNCTION__))
;
6313 Diag(Loc, diag::err_enumerator_does_not_exist)
6314 << D->getDeclName()
6315 << Context.getTypeDeclType(cast<TypeDecl>(Spec->getDeclContext()));
6316 Diag(Spec->getLocation(), diag::note_enum_specialized_here)
6317 << Context.getTypeDeclType(Spec);
6318 } else {
6319 // We should have found something, but didn't.
6320 llvm_unreachable("Unable to find instantiation of declaration!")::llvm::llvm_unreachable_internal("Unable to find instantiation of declaration!"
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6320)
;
6321 }
6322 }
6323
6324 D = Result;
6325 }
6326
6327 return D;
6328}
6329
6330/// Performs template instantiation for all implicit template
6331/// instantiations we have seen until this point.
6332void Sema::PerformPendingInstantiations(bool LocalOnly) {
6333 std::deque<PendingImplicitInstantiation> delayedPCHInstantiations;
6334 while (!PendingLocalImplicitInstantiations.empty() ||
6335 (!LocalOnly && !PendingInstantiations.empty())) {
6336 PendingImplicitInstantiation Inst;
6337
6338 if (PendingLocalImplicitInstantiations.empty()) {
6339 Inst = PendingInstantiations.front();
6340 PendingInstantiations.pop_front();
6341 } else {
6342 Inst = PendingLocalImplicitInstantiations.front();
6343 PendingLocalImplicitInstantiations.pop_front();
6344 }
6345
6346 // Instantiate function definitions
6347 if (FunctionDecl *Function = dyn_cast<FunctionDecl>(Inst.first)) {
6348 bool DefinitionRequired = Function->getTemplateSpecializationKind() ==
6349 TSK_ExplicitInstantiationDefinition;
6350 if (Function->isMultiVersion()) {
6351 getASTContext().forEachMultiversionedFunctionVersion(
6352 Function, [this, Inst, DefinitionRequired](FunctionDecl *CurFD) {
6353 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, CurFD, true,
6354 DefinitionRequired, true);
6355 if (CurFD->isDefined())
6356 CurFD->setInstantiationIsPending(false);
6357 });
6358 } else {
6359 InstantiateFunctionDefinition(/*FIXME:*/ Inst.second, Function, true,
6360 DefinitionRequired, true);
6361 if (Function->isDefined())
6362 Function->setInstantiationIsPending(false);
6363 }
6364 // Definition of a PCH-ed template declaration may be available only in the TU.
6365 if (!LocalOnly && LangOpts.PCHInstantiateTemplates &&
6366 TUKind == TU_Prefix && Function->instantiationIsPending())
6367 delayedPCHInstantiations.push_back(Inst);
6368 continue;
6369 }
6370
6371 // Instantiate variable definitions
6372 VarDecl *Var = cast<VarDecl>(Inst.first);
6373
6374 assert((Var->isStaticDataMember() ||(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
6375 isa<VarTemplateSpecializationDecl>(Var)) &&(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
6376 "Not a static data member, nor a variable template"(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
6377 " specialization?")(static_cast <bool> ((Var->isStaticDataMember() || isa
<VarTemplateSpecializationDecl>(Var)) && "Not a static data member, nor a variable template"
" specialization?") ? void (0) : __assert_fail ("(Var->isStaticDataMember() || isa<VarTemplateSpecializationDecl>(Var)) && \"Not a static data member, nor a variable template\" \" specialization?\""
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6377, __extension__
__PRETTY_FUNCTION__))
;
6378
6379 // Don't try to instantiate declarations if the most recent redeclaration
6380 // is invalid.
6381 if (Var->getMostRecentDecl()->isInvalidDecl())
6382 continue;
6383
6384 // Check if the most recent declaration has changed the specialization kind
6385 // and removed the need for implicit instantiation.
6386 switch (Var->getMostRecentDecl()
6387 ->getTemplateSpecializationKindForInstantiation()) {
6388 case TSK_Undeclared:
6389 llvm_unreachable("Cannot instantitiate an undeclared specialization.")::llvm::llvm_unreachable_internal("Cannot instantitiate an undeclared specialization."
, "clang/lib/Sema/SemaTemplateInstantiateDecl.cpp", 6389)
;
6390 case TSK_ExplicitInstantiationDeclaration:
6391 case TSK_ExplicitSpecialization:
6392 continue; // No longer need to instantiate this type.
6393 case TSK_ExplicitInstantiationDefinition:
6394 // We only need an instantiation if the pending instantiation *is* the
6395 // explicit instantiation.
6396 if (Var != Var->getMostRecentDecl())
6397 continue;
6398 break;
6399 case TSK_ImplicitInstantiation:
6400 break;
6401 }
6402
6403 PrettyDeclStackTraceEntry CrashInfo(Context, Var, SourceLocation(),
6404 "instantiating variable definition");
6405 bool DefinitionRequired = Var->getTemplateSpecializationKind() ==
6406 TSK_ExplicitInstantiationDefinition;
6407
6408 // Instantiate static data member definitions or variable template
6409 // specializations.
6410 InstantiateVariableDefinition(/*FIXME:*/ Inst.second, Var, true,
6411 DefinitionRequired, true);
6412 }
6413
6414 if (!LocalOnly && LangOpts.PCHInstantiateTemplates)
6415 PendingInstantiations.swap(delayedPCHInstantiations);
6416}
6417
6418void Sema::PerformDependentDiagnostics(const DeclContext *Pattern,
6419 const MultiLevelTemplateArgumentList &TemplateArgs) {
6420 for (auto *DD : Pattern->ddiags()) {
6421 switch (DD->getKind()) {
6422 case DependentDiagnostic::Access:
6423 HandleDependentAccessCheck(*DD, TemplateArgs);
6424 break;
6425 }
6426 }
6427}

/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,
1500 SourceLocation RParenLoc) {
1501 return getSema().ActOnGCCAsmStmt(AsmLoc, IsSimple, IsVolatile, NumOutputs,
1502 NumInputs, Names, Constraints, Exprs,
1503 AsmString, Clobbers, NumLabels, RParenLoc);
1504 }
1505
1506 /// Build a new MS style inline asm statement.
1507 ///
1508 /// By default, performs semantic analysis to build the new statement.
1509 /// Subclasses may override this routine to provide different behavior.
1510 StmtResult RebuildMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1511 ArrayRef<Token> AsmToks,
1512 StringRef AsmString,
1513 unsigned NumOutputs, unsigned NumInputs,
1514 ArrayRef<StringRef> Constraints,
1515 ArrayRef<StringRef> Clobbers,
1516 ArrayRef<Expr*> Exprs,
1517 SourceLocation EndLoc) {
1518 return getSema().ActOnMSAsmStmt(AsmLoc, LBraceLoc, AsmToks, AsmString,
1519 NumOutputs, NumInputs,
1520 Constraints, Clobbers, Exprs, EndLoc);
1521 }
1522
1523 /// Build a new co_return statement.
1524 ///
1525 /// By default, performs semantic analysis to build the new statement.
1526 /// Subclasses may override this routine to provide different behavior.
1527 StmtResult RebuildCoreturnStmt(SourceLocation CoreturnLoc, Expr *Result,
1528 bool IsImplicit) {
1529 return getSema().BuildCoreturnStmt(CoreturnLoc, Result, IsImplicit);
1530 }
1531
1532 /// Build a new co_await expression.
1533 ///
1534 /// By default, performs semantic analysis to build the new expression.
1535 /// Subclasses may override this routine to provide different behavior.
1536 ExprResult RebuildCoawaitExpr(SourceLocation CoawaitLoc, Expr *Operand,
1537 UnresolvedLookupExpr *OpCoawaitLookup,
1538 bool IsImplicit) {
1539 // This function rebuilds a coawait-expr given its operator.
1540 // For an explicit coawait-expr, the rebuild involves the full set
1541 // of transformations performed by BuildUnresolvedCoawaitExpr(),
1542 // including calling await_transform().
1543 // For an implicit coawait-expr, we need to rebuild the "operator
1544 // coawait" but not await_transform(), so use BuildResolvedCoawaitExpr().
1545 // This mirrors how the implicit CoawaitExpr is originally created
1546 // in Sema::ActOnCoroutineBodyStart().
1547 if (IsImplicit) {
1548 ExprResult Suspend = getSema().BuildOperatorCoawaitCall(
1549 CoawaitLoc, Operand, OpCoawaitLookup);
1550 if (Suspend.isInvalid())
1551 return ExprError();
1552 return getSema().BuildResolvedCoawaitExpr(CoawaitLoc, Operand,
1553 Suspend.get(), true);
1554 }
1555
1556 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Operand,
1557 OpCoawaitLookup);
1558 }
1559
1560 /// Build a new co_await expression.
1561 ///
1562 /// By default, performs semantic analysis to build the new expression.
1563 /// Subclasses may override this routine to provide different behavior.
1564 ExprResult RebuildDependentCoawaitExpr(SourceLocation CoawaitLoc,
1565 Expr *Result,
1566 UnresolvedLookupExpr *Lookup) {
1567 return getSema().BuildUnresolvedCoawaitExpr(CoawaitLoc, Result, Lookup);
1568 }
1569
1570 /// Build a new co_yield expression.
1571 ///
1572 /// By default, performs semantic analysis to build the new expression.
1573 /// Subclasses may override this routine to provide different behavior.
1574 ExprResult RebuildCoyieldExpr(SourceLocation CoyieldLoc, Expr *Result) {
1575 return getSema().BuildCoyieldExpr(CoyieldLoc, Result);
1576 }
1577
1578 StmtResult RebuildCoroutineBodyStmt(CoroutineBodyStmt::CtorArgs Args) {
1579 return getSema().BuildCoroutineBodyStmt(Args);
1580 }
1581
1582 /// Build a new Objective-C \@try statement.
1583 ///
1584 /// By default, performs semantic analysis to build the new statement.
1585 /// Subclasses may override this routine to provide different behavior.
1586 StmtResult RebuildObjCAtTryStmt(SourceLocation AtLoc,
1587 Stmt *TryBody,
1588 MultiStmtArg CatchStmts,
1589 Stmt *Finally) {
1590 return getSema().ActOnObjCAtTryStmt(AtLoc, TryBody, CatchStmts,
1591 Finally);
1592 }
1593
1594 /// Rebuild an Objective-C exception declaration.
1595 ///
1596 /// By default, performs semantic analysis to build the new declaration.
1597 /// Subclasses may override this routine to provide different behavior.
1598 VarDecl *RebuildObjCExceptionDecl(VarDecl *ExceptionDecl,
1599 TypeSourceInfo *TInfo, QualType T) {
1600 return getSema().BuildObjCExceptionDecl(TInfo, T,
1601 ExceptionDecl->getInnerLocStart(),
1602 ExceptionDecl->getLocation(),
1603 ExceptionDecl->getIdentifier());
1604 }
1605
1606 /// Build a new Objective-C \@catch statement.
1607 ///
1608 /// By default, performs semantic analysis to build the new statement.
1609 /// Subclasses may override this routine to provide different behavior.
1610 StmtResult RebuildObjCAtCatchStmt(SourceLocation AtLoc,
1611 SourceLocation RParenLoc,
1612 VarDecl *Var,
1613 Stmt *Body) {
1614 return getSema().ActOnObjCAtCatchStmt(AtLoc, RParenLoc,
1615 Var, Body);
1616 }
1617
1618 /// Build a new Objective-C \@finally statement.
1619 ///
1620 /// By default, performs semantic analysis to build the new statement.
1621 /// Subclasses may override this routine to provide different behavior.
1622 StmtResult RebuildObjCAtFinallyStmt(SourceLocation AtLoc,
1623 Stmt *Body) {
1624 return getSema().ActOnObjCAtFinallyStmt(AtLoc, Body);
1625 }
1626
1627 /// Build a new Objective-C \@throw statement.
1628 ///
1629 /// By default, performs semantic analysis to build the new statement.
1630 /// Subclasses may override this routine to provide different behavior.
1631 StmtResult RebuildObjCAtThrowStmt(SourceLocation AtLoc,
1632 Expr *Operand) {
1633 return getSema().BuildObjCAtThrowStmt(AtLoc, Operand);
1634 }
1635
1636 /// Build a new OpenMP Canonical loop.
1637 ///
1638 /// Ensures that the outermost loop in @p LoopStmt is wrapped by a
1639 /// OMPCanonicalLoop.
1640 StmtResult RebuildOMPCanonicalLoop(Stmt *LoopStmt) {
1641 return getSema().ActOnOpenMPCanonicalLoop(LoopStmt);
1642 }
1643
1644 /// Build a new OpenMP executable directive.
1645 ///
1646 /// By default, performs semantic analysis to build the new statement.
1647 /// Subclasses may override this routine to provide different behavior.
1648 StmtResult RebuildOMPExecutableDirective(OpenMPDirectiveKind Kind,
1649 DeclarationNameInfo DirName,
1650 OpenMPDirectiveKind CancelRegion,
1651 ArrayRef<OMPClause *> Clauses,
1652 Stmt *AStmt, SourceLocation StartLoc,
1653 SourceLocation EndLoc) {
1654 return getSema().ActOnOpenMPExecutableDirective(
1655 Kind, DirName, CancelRegion, Clauses, AStmt, StartLoc, EndLoc);
1656 }
1657
1658 /// Build a new OpenMP 'if' clause.
1659 ///
1660 /// By default, performs semantic analysis to build the new OpenMP clause.
1661 /// Subclasses may override this routine to provide different behavior.
1662 OMPClause *RebuildOMPIfClause(OpenMPDirectiveKind NameModifier,
1663 Expr *Condition, SourceLocation StartLoc,
1664 SourceLocation LParenLoc,
1665 SourceLocation NameModifierLoc,
1666 SourceLocation ColonLoc,
1667 SourceLocation EndLoc) {
1668 return getSema().ActOnOpenMPIfClause(NameModifier, Condition, StartLoc,
1669 LParenLoc, NameModifierLoc, ColonLoc,
1670 EndLoc);
1671 }
1672
1673 /// Build a new OpenMP 'final' clause.
1674 ///
1675 /// By default, performs semantic analysis to build the new OpenMP clause.
1676 /// Subclasses may override this routine to provide different behavior.
1677 OMPClause *RebuildOMPFinalClause(Expr *Condition, SourceLocation StartLoc,
1678 SourceLocation LParenLoc,
1679 SourceLocation EndLoc) {
1680 return getSema().ActOnOpenMPFinalClause(Condition, StartLoc, LParenLoc,
1681 EndLoc);
1682 }
1683
1684 /// Build a new OpenMP 'num_threads' clause.
1685 ///
1686 /// By default, performs semantic analysis to build the new OpenMP clause.
1687 /// Subclasses may override this routine to provide different behavior.
1688 OMPClause *RebuildOMPNumThreadsClause(Expr *NumThreads,
1689 SourceLocation StartLoc,
1690 SourceLocation LParenLoc,
1691 SourceLocation EndLoc) {
1692 return getSema().ActOnOpenMPNumThreadsClause(NumThreads, StartLoc,
1693 LParenLoc, EndLoc);
1694 }
1695
1696 /// Build a new OpenMP 'safelen' clause.
1697 ///
1698 /// By default, performs semantic analysis to build the new OpenMP clause.
1699 /// Subclasses may override this routine to provide different behavior.
1700 OMPClause *RebuildOMPSafelenClause(Expr *Len, SourceLocation StartLoc,
1701 SourceLocation LParenLoc,
1702 SourceLocation EndLoc) {
1703 return getSema().ActOnOpenMPSafelenClause(Len, StartLoc, LParenLoc, EndLoc);
1704 }
1705
1706 /// Build a new OpenMP 'simdlen' clause.
1707 ///
1708 /// By default, performs semantic analysis to build the new OpenMP clause.
1709 /// Subclasses may override this routine to provide different behavior.
1710 OMPClause *RebuildOMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
1711 SourceLocation LParenLoc,
1712 SourceLocation EndLoc) {
1713 return getSema().ActOnOpenMPSimdlenClause(Len, StartLoc, LParenLoc, EndLoc);
1714 }
1715
1716 OMPClause *RebuildOMPSizesClause(ArrayRef<Expr *> Sizes,
1717 SourceLocation StartLoc,
1718 SourceLocation LParenLoc,
1719 SourceLocation EndLoc) {
1720 return getSema().ActOnOpenMPSizesClause(Sizes, StartLoc, LParenLoc, EndLoc);
1721 }
1722
1723 /// Build a new OpenMP 'full' clause.
1724 OMPClause *RebuildOMPFullClause(SourceLocation StartLoc,
1725 SourceLocation EndLoc) {
1726 return getSema().ActOnOpenMPFullClause(StartLoc, EndLoc);
1727 }
1728
1729 /// Build a new OpenMP 'partial' clause.
1730 OMPClause *RebuildOMPPartialClause(Expr *Factor, SourceLocation StartLoc,
1731 SourceLocation LParenLoc,
1732 SourceLocation EndLoc) {
1733 return getSema().ActOnOpenMPPartialClause(Factor, StartLoc, LParenLoc,
1734 EndLoc);
1735 }
1736
1737 /// Build a new OpenMP 'allocator' clause.
1738 ///
1739 /// By default, performs semantic analysis to build the new OpenMP clause.
1740 /// Subclasses may override this routine to provide different behavior.
1741 OMPClause *RebuildOMPAllocatorClause(Expr *A, SourceLocation StartLoc,
1742 SourceLocation LParenLoc,
1743 SourceLocation EndLoc) {
1744 return getSema().ActOnOpenMPAllocatorClause(A, StartLoc, LParenLoc, EndLoc);
1745 }
1746
1747 /// Build a new OpenMP 'collapse' clause.
1748 ///
1749 /// By default, performs semantic analysis to build the new OpenMP clause.
1750 /// Subclasses may override this routine to provide different behavior.
1751 OMPClause *RebuildOMPCollapseClause(Expr *Num, SourceLocation StartLoc,
1752 SourceLocation LParenLoc,
1753 SourceLocation EndLoc) {
1754 return getSema().ActOnOpenMPCollapseClause(Num, StartLoc, LParenLoc,
1755 EndLoc);
1756 }
1757
1758 /// Build a new OpenMP 'default' clause.
1759 ///
1760 /// By default, performs semantic analysis to build the new OpenMP clause.
1761 /// Subclasses may override this routine to provide different behavior.
1762 OMPClause *RebuildOMPDefaultClause(DefaultKind Kind, SourceLocation KindKwLoc,
1763 SourceLocation StartLoc,
1764 SourceLocation LParenLoc,
1765 SourceLocation EndLoc) {
1766 return getSema().ActOnOpenMPDefaultClause(Kind, KindKwLoc,
1767 StartLoc, LParenLoc, EndLoc);
1768 }
1769
1770 /// Build a new OpenMP 'proc_bind' clause.
1771 ///
1772 /// By default, performs semantic analysis to build the new OpenMP clause.
1773 /// Subclasses may override this routine to provide different behavior.
1774 OMPClause *RebuildOMPProcBindClause(ProcBindKind Kind,
1775 SourceLocation KindKwLoc,
1776 SourceLocation StartLoc,
1777 SourceLocation LParenLoc,
1778 SourceLocation EndLoc) {
1779 return getSema().ActOnOpenMPProcBindClause(Kind, KindKwLoc,
1780 StartLoc, LParenLoc, EndLoc);
1781 }
1782
1783 /// Build a new OpenMP 'schedule' clause.
1784 ///
1785 /// By default, performs semantic analysis to build the new OpenMP clause.
1786 /// Subclasses may override this routine to provide different behavior.
1787 OMPClause *RebuildOMPScheduleClause(
1788 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
1789 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
1790 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
1791 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
1792 return getSema().ActOnOpenMPScheduleClause(
1793 M1, M2, Kind, ChunkSize, StartLoc, LParenLoc, M1Loc, M2Loc, KindLoc,
1794 CommaLoc, EndLoc);
1795 }
1796
1797 /// Build a new OpenMP 'ordered' clause.
1798 ///
1799 /// By default, performs semantic analysis to build the new OpenMP clause.
1800 /// Subclasses may override this routine to provide different behavior.
1801 OMPClause *RebuildOMPOrderedClause(SourceLocation StartLoc,
1802 SourceLocation EndLoc,
1803 SourceLocation LParenLoc, Expr *Num) {
1804 return getSema().ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Num);
1805 }
1806
1807 /// Build a new OpenMP 'private' clause.
1808 ///
1809 /// By default, performs semantic analysis to build the new OpenMP clause.
1810 /// Subclasses may override this routine to provide different behavior.
1811 OMPClause *RebuildOMPPrivateClause(ArrayRef<Expr *> VarList,
1812 SourceLocation StartLoc,
1813 SourceLocation LParenLoc,
1814 SourceLocation EndLoc) {
1815 return getSema().ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc,
1816 EndLoc);
1817 }
1818
1819 /// Build a new OpenMP 'firstprivate' clause.
1820 ///
1821 /// By default, performs semantic analysis to build the new OpenMP clause.
1822 /// Subclasses may override this routine to provide different behavior.
1823 OMPClause *RebuildOMPFirstprivateClause(ArrayRef<Expr *> VarList,
1824 SourceLocation StartLoc,
1825 SourceLocation LParenLoc,
1826 SourceLocation EndLoc) {
1827 return getSema().ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc,
1828 EndLoc);
1829 }
1830
1831 /// Build a new OpenMP 'lastprivate' clause.
1832 ///
1833 /// By default, performs semantic analysis to build the new OpenMP clause.
1834 /// Subclasses may override this routine to provide different behavior.
1835 OMPClause *RebuildOMPLastprivateClause(ArrayRef<Expr *> VarList,
1836 OpenMPLastprivateModifier LPKind,
1837 SourceLocation LPKindLoc,
1838 SourceLocation ColonLoc,
1839 SourceLocation StartLoc,
1840 SourceLocation LParenLoc,
1841 SourceLocation EndLoc) {
1842 return getSema().ActOnOpenMPLastprivateClause(
1843 VarList, LPKind, LPKindLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
1844 }
1845
1846 /// Build a new OpenMP 'shared' clause.
1847 ///
1848 /// By default, performs semantic analysis to build the new OpenMP clause.
1849 /// Subclasses may override this routine to provide different behavior.
1850 OMPClause *RebuildOMPSharedClause(ArrayRef<Expr *> VarList,
1851 SourceLocation StartLoc,
1852 SourceLocation LParenLoc,
1853 SourceLocation EndLoc) {
1854 return getSema().ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc,
1855 EndLoc);
1856 }
1857
1858 /// Build a new OpenMP 'reduction' clause.
1859 ///
1860 /// By default, performs semantic analysis to build the new statement.
1861 /// Subclasses may override this routine to provide different behavior.
1862 OMPClause *RebuildOMPReductionClause(
1863 ArrayRef<Expr *> VarList, OpenMPReductionClauseModifier Modifier,
1864 SourceLocation StartLoc, SourceLocation LParenLoc,
1865 SourceLocation ModifierLoc, SourceLocation ColonLoc,
1866 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
1867 const DeclarationNameInfo &ReductionId,
1868 ArrayRef<Expr *> UnresolvedReductions) {
1869 return getSema().ActOnOpenMPReductionClause(
1870 VarList, Modifier, StartLoc, LParenLoc, ModifierLoc, ColonLoc, EndLoc,
1871 ReductionIdScopeSpec, ReductionId, UnresolvedReductions);
1872 }
1873
1874 /// Build a new OpenMP 'task_reduction' clause.
1875 ///
1876 /// By default, performs semantic analysis to build the new statement.
1877 /// Subclasses may override this routine to provide different behavior.
1878 OMPClause *RebuildOMPTaskReductionClause(
1879 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1880 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc,
1881 CXXScopeSpec &ReductionIdScopeSpec,
1882 const DeclarationNameInfo &ReductionId,
1883 ArrayRef<Expr *> UnresolvedReductions) {
1884 return getSema().ActOnOpenMPTaskReductionClause(
1885 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1886 ReductionId, UnresolvedReductions);
1887 }
1888
1889 /// Build a new OpenMP 'in_reduction' clause.
1890 ///
1891 /// By default, performs semantic analysis to build the new statement.
1892 /// Subclasses may override this routine to provide different behavior.
1893 OMPClause *
1894 RebuildOMPInReductionClause(ArrayRef<Expr *> VarList, SourceLocation StartLoc,
1895 SourceLocation LParenLoc, SourceLocation ColonLoc,
1896 SourceLocation EndLoc,
1897 CXXScopeSpec &ReductionIdScopeSpec,
1898 const DeclarationNameInfo &ReductionId,
1899 ArrayRef<Expr *> UnresolvedReductions) {
1900 return getSema().ActOnOpenMPInReductionClause(
1901 VarList, StartLoc, LParenLoc, ColonLoc, EndLoc, ReductionIdScopeSpec,
1902 ReductionId, UnresolvedReductions);
1903 }
1904
1905 /// Build a new OpenMP 'linear' clause.
1906 ///
1907 /// By default, performs semantic analysis to build the new OpenMP clause.
1908 /// Subclasses may override this routine to provide different behavior.
1909 OMPClause *RebuildOMPLinearClause(ArrayRef<Expr *> VarList, Expr *Step,
1910 SourceLocation StartLoc,
1911 SourceLocation LParenLoc,
1912 OpenMPLinearClauseKind Modifier,
1913 SourceLocation ModifierLoc,
1914 SourceLocation ColonLoc,
1915 SourceLocation EndLoc) {
1916 return getSema().ActOnOpenMPLinearClause(VarList, Step, StartLoc, LParenLoc,
1917 Modifier, ModifierLoc, ColonLoc,
1918 EndLoc);
1919 }
1920
1921 /// Build a new OpenMP 'aligned' clause.
1922 ///
1923 /// By default, performs semantic analysis to build the new OpenMP clause.
1924 /// Subclasses may override this routine to provide different behavior.
1925 OMPClause *RebuildOMPAlignedClause(ArrayRef<Expr *> VarList, Expr *Alignment,
1926 SourceLocation StartLoc,
1927 SourceLocation LParenLoc,
1928 SourceLocation ColonLoc,
1929 SourceLocation EndLoc) {
1930 return getSema().ActOnOpenMPAlignedClause(VarList, Alignment, StartLoc,
1931 LParenLoc, ColonLoc, EndLoc);
1932 }
1933
1934 /// Build a new OpenMP 'copyin' clause.
1935 ///
1936 /// By default, performs semantic analysis to build the new OpenMP clause.
1937 /// Subclasses may override this routine to provide different behavior.
1938 OMPClause *RebuildOMPCopyinClause(ArrayRef<Expr *> VarList,
1939 SourceLocation StartLoc,
1940 SourceLocation LParenLoc,
1941 SourceLocation EndLoc) {
1942 return getSema().ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc,
1943 EndLoc);
1944 }
1945
1946 /// Build a new OpenMP 'copyprivate' clause.
1947 ///
1948 /// By default, performs semantic analysis to build the new OpenMP clause.
1949 /// Subclasses may override this routine to provide different behavior.
1950 OMPClause *RebuildOMPCopyprivateClause(ArrayRef<Expr *> VarList,
1951 SourceLocation StartLoc,
1952 SourceLocation LParenLoc,
1953 SourceLocation EndLoc) {
1954 return getSema().ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc,
1955 EndLoc);
1956 }
1957
1958 /// Build a new OpenMP 'flush' pseudo clause.
1959 ///
1960 /// By default, performs semantic analysis to build the new OpenMP clause.
1961 /// Subclasses may override this routine to provide different behavior.
1962 OMPClause *RebuildOMPFlushClause(ArrayRef<Expr *> VarList,
1963 SourceLocation StartLoc,
1964 SourceLocation LParenLoc,
1965 SourceLocation EndLoc) {
1966 return getSema().ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc,
1967 EndLoc);
1968 }
1969
1970 /// Build a new OpenMP 'depobj' pseudo clause.
1971 ///
1972 /// By default, performs semantic analysis to build the new OpenMP clause.
1973 /// Subclasses may override this routine to provide different behavior.
1974 OMPClause *RebuildOMPDepobjClause(Expr *Depobj, SourceLocation StartLoc,
1975 SourceLocation LParenLoc,
1976 SourceLocation EndLoc) {
1977 return getSema().ActOnOpenMPDepobjClause(Depobj, StartLoc, LParenLoc,
1978 EndLoc);
1979 }
1980
1981 /// Build a new OpenMP 'depend' pseudo clause.
1982 ///
1983 /// By default, performs semantic analysis to build the new OpenMP clause.
1984 /// Subclasses may override this routine to provide different behavior.
1985 OMPClause *RebuildOMPDependClause(OMPDependClause::DependDataTy Data,
1986 Expr *DepModifier, ArrayRef<Expr *> VarList,
1987 SourceLocation StartLoc,
1988 SourceLocation LParenLoc,
1989 SourceLocation EndLoc) {
1990 return getSema().ActOnOpenMPDependClause(Data, DepModifier, VarList,
1991 StartLoc, LParenLoc, EndLoc);
1992 }
1993
1994 /// Build a new OpenMP 'device' clause.
1995 ///
1996 /// By default, performs semantic analysis to build the new statement.
1997 /// Subclasses may override this routine to provide different behavior.
1998 OMPClause *RebuildOMPDeviceClause(OpenMPDeviceClauseModifier Modifier,
1999 Expr *Device, SourceLocation StartLoc,
2000 SourceLocation LParenLoc,
2001 SourceLocation ModifierLoc,
2002 SourceLocation EndLoc) {
2003 return getSema().ActOnOpenMPDeviceClause(Modifier, Device, StartLoc,
2004 LParenLoc, ModifierLoc, EndLoc);
2005 }
2006
2007 /// Build a new OpenMP 'map' clause.
2008 ///
2009 /// By default, performs semantic analysis to build the new OpenMP clause.
2010 /// Subclasses may override this routine to provide different behavior.
2011 OMPClause *RebuildOMPMapClause(
2012 Expr *IteratorModifier, ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
2013 ArrayRef<SourceLocation> MapTypeModifiersLoc,
2014 CXXScopeSpec MapperIdScopeSpec, DeclarationNameInfo MapperId,
2015 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
2016 SourceLocation MapLoc, SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
2017 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
2018 return getSema().ActOnOpenMPMapClause(
2019 IteratorModifier, MapTypeModifiers, MapTypeModifiersLoc,
2020 MapperIdScopeSpec, MapperId, MapType, IsMapTypeImplicit, MapLoc,
2021 ColonLoc, VarList, Locs,
2022 /*NoDiagnose=*/false, UnresolvedMappers);
2023 }
2024
2025 /// Build a new OpenMP 'allocate' clause.
2026 ///
2027 /// By default, performs semantic analysis to build the new OpenMP clause.
2028 /// Subclasses may override this routine to provide different behavior.
2029 OMPClause *RebuildOMPAllocateClause(Expr *Allocate, ArrayRef<Expr *> VarList,
2030 SourceLocation StartLoc,
2031 SourceLocation LParenLoc,
2032 SourceLocation ColonLoc,
2033 SourceLocation EndLoc) {
2034 return getSema().ActOnOpenMPAllocateClause(Allocate, VarList, StartLoc,
2035 LParenLoc, ColonLoc, EndLoc);
2036 }
2037
2038 /// Build a new OpenMP 'num_teams' clause.
2039 ///
2040 /// By default, performs semantic analysis to build the new statement.
2041 /// Subclasses may override this routine to provide different behavior.
2042 OMPClause *RebuildOMPNumTeamsClause(Expr *NumTeams, SourceLocation StartLoc,
2043 SourceLocation LParenLoc,
2044 SourceLocation EndLoc) {
2045 return getSema().ActOnOpenMPNumTeamsClause(NumTeams, StartLoc, LParenLoc,
2046 EndLoc);
2047 }
2048
2049 /// Build a new OpenMP 'thread_limit' clause.
2050 ///
2051 /// By default, performs semantic analysis to build the new statement.
2052 /// Subclasses may override this routine to provide different behavior.
2053 OMPClause *RebuildOMPThreadLimitClause(Expr *ThreadLimit,
2054 SourceLocation StartLoc,
2055 SourceLocation LParenLoc,
2056 SourceLocation EndLoc) {
2057 return getSema().ActOnOpenMPThreadLimitClause(ThreadLimit, StartLoc,
2058 LParenLoc, EndLoc);
2059 }
2060
2061 /// Build a new OpenMP 'priority' clause.
2062 ///
2063 /// By default, performs semantic analysis to build the new statement.
2064 /// Subclasses may override this routine to provide different behavior.
2065 OMPClause *RebuildOMPPriorityClause(Expr *Priority, SourceLocation StartLoc,
2066 SourceLocation LParenLoc,
2067 SourceLocation EndLoc) {
2068 return getSema().ActOnOpenMPPriorityClause(Priority, StartLoc, LParenLoc,
2069 EndLoc);
2070 }
2071
2072 /// Build a new OpenMP 'grainsize' clause.
2073 ///
2074 /// By default, performs semantic analysis to build the new statement.
2075 /// Subclasses may override this routine to provide different behavior.
2076 OMPClause *RebuildOMPGrainsizeClause(OpenMPGrainsizeClauseModifier Modifier,
2077 Expr *Device, SourceLocation StartLoc,
2078 SourceLocation LParenLoc,
2079 SourceLocation ModifierLoc,
2080 SourceLocation EndLoc) {
2081 return getSema().ActOnOpenMPGrainsizeClause(Modifier, Device, StartLoc,
2082 LParenLoc, ModifierLoc, EndLoc);
2083 }
2084
2085 /// Build a new OpenMP 'num_tasks' clause.
2086 ///
2087 /// By default, performs semantic analysis to build the new statement.
2088 /// Subclasses may override this routine to provide different behavior.
2089 OMPClause *RebuildOMPNumTasksClause(OpenMPNumTasksClauseModifier Modifier,
2090 Expr *NumTasks, SourceLocation StartLoc,
2091 SourceLocation LParenLoc,
2092 SourceLocation ModifierLoc,
2093 SourceLocation EndLoc) {
2094 return getSema().ActOnOpenMPNumTasksClause(Modifier, NumTasks, StartLoc,
2095 LParenLoc, ModifierLoc, EndLoc);
2096 }
2097
2098 /// Build a new OpenMP 'hint' clause.
2099 ///
2100 /// By default, performs semantic analysis to build the new statement.
2101 /// Subclasses may override this routine to provide different behavior.
2102 OMPClause *RebuildOMPHintClause(Expr *Hint, SourceLocation StartLoc,
2103 SourceLocation LParenLoc,
2104 SourceLocation EndLoc) {
2105 return getSema().ActOnOpenMPHintClause(Hint, StartLoc, LParenLoc, EndLoc);
2106 }
2107
2108 /// Build a new OpenMP 'detach' clause.
2109 ///
2110 /// By default, performs semantic analysis to build the new statement.
2111 /// Subclasses may override this routine to provide different behavior.
2112 OMPClause *RebuildOMPDetachClause(Expr *Evt, SourceLocation StartLoc,
2113 SourceLocation LParenLoc,
2114 SourceLocation EndLoc) {
2115 return getSema().ActOnOpenMPDetachClause(Evt, StartLoc, LParenLoc, EndLoc);
2116 }
2117
2118 /// Build a new OpenMP 'dist_schedule' clause.
2119 ///
2120 /// By default, performs semantic analysis to build the new OpenMP clause.
2121 /// Subclasses may override this routine to provide different behavior.
2122 OMPClause *
2123 RebuildOMPDistScheduleClause(OpenMPDistScheduleClauseKind Kind,
2124 Expr *ChunkSize, SourceLocation StartLoc,
2125 SourceLocation LParenLoc, SourceLocation KindLoc,
2126 SourceLocation CommaLoc, SourceLocation EndLoc) {
2127 return getSema().ActOnOpenMPDistScheduleClause(
2128 Kind, ChunkSize, StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc);
2129 }
2130
2131 /// Build a new OpenMP 'to' clause.
2132 ///
2133 /// By default, performs semantic analysis to build the new statement.
2134 /// Subclasses may override this routine to provide different behavior.
2135 OMPClause *
2136 RebuildOMPToClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2137 ArrayRef<SourceLocation> MotionModifiersLoc,
2138 CXXScopeSpec &MapperIdScopeSpec,
2139 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2140 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2141 ArrayRef<Expr *> UnresolvedMappers) {
2142 return getSema().ActOnOpenMPToClause(MotionModifiers, MotionModifiersLoc,
2143 MapperIdScopeSpec, MapperId, ColonLoc,
2144 VarList, Locs, UnresolvedMappers);
2145 }
2146
2147 /// Build a new OpenMP 'from' clause.
2148 ///
2149 /// By default, performs semantic analysis to build the new statement.
2150 /// Subclasses may override this routine to provide different behavior.
2151 OMPClause *
2152 RebuildOMPFromClause(ArrayRef<OpenMPMotionModifierKind> MotionModifiers,
2153 ArrayRef<SourceLocation> MotionModifiersLoc,
2154 CXXScopeSpec &MapperIdScopeSpec,
2155 DeclarationNameInfo &MapperId, SourceLocation ColonLoc,
2156 ArrayRef<Expr *> VarList, const OMPVarListLocTy &Locs,
2157 ArrayRef<Expr *> UnresolvedMappers) {
2158 return getSema().ActOnOpenMPFromClause(
2159 MotionModifiers, MotionModifiersLoc, MapperIdScopeSpec, MapperId,
2160 ColonLoc, VarList, Locs, UnresolvedMappers);
2161 }
2162
2163 /// Build a new OpenMP 'use_device_ptr' clause.
2164 ///
2165 /// By default, performs semantic analysis to build the new OpenMP clause.
2166 /// Subclasses may override this routine to provide different behavior.
2167 OMPClause *RebuildOMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
2168 const OMPVarListLocTy &Locs) {
2169 return getSema().ActOnOpenMPUseDevicePtrClause(VarList, Locs);
2170 }
2171
2172 /// Build a new OpenMP 'use_device_addr' clause.
2173 ///
2174 /// By default, performs semantic analysis to build the new OpenMP clause.
2175 /// Subclasses may override this routine to provide different behavior.
2176 OMPClause *RebuildOMPUseDeviceAddrClause(ArrayRef<Expr *> VarList,
2177 const OMPVarListLocTy &Locs) {
2178 return getSema().ActOnOpenMPUseDeviceAddrClause(VarList, Locs);
2179 }
2180
2181 /// Build a new OpenMP 'is_device_ptr' clause.
2182 ///
2183 /// By default, performs semantic analysis to build the new OpenMP clause.
2184 /// Subclasses may override this routine to provide different behavior.
2185 OMPClause *RebuildOMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
2186 const OMPVarListLocTy &Locs) {
2187 return getSema().ActOnOpenMPIsDevicePtrClause(VarList, Locs);
2188 }
2189
2190 /// Build a new OpenMP 'has_device_addr' clause.
2191 ///
2192 /// By default, performs semantic analysis to build the new OpenMP clause.
2193 /// Subclasses may override this routine to provide different behavior.
2194 OMPClause *RebuildOMPHasDeviceAddrClause(ArrayRef<Expr *> VarList,
2195 const OMPVarListLocTy &Locs) {
2196 return getSema().ActOnOpenMPHasDeviceAddrClause(VarList, Locs);
2197 }
2198
2199 /// Build a new OpenMP 'defaultmap' clause.
2200 ///
2201 /// By default, performs semantic analysis to build the new OpenMP clause.
2202 /// Subclasses may override this routine to provide different behavior.
2203 OMPClause *RebuildOMPDefaultmapClause(OpenMPDefaultmapClauseModifier M,
2204 OpenMPDefaultmapClauseKind Kind,
2205 SourceLocation StartLoc,
2206 SourceLocation LParenLoc,
2207 SourceLocation MLoc,
2208 SourceLocation KindLoc,
2209 SourceLocation EndLoc) {
2210 return getSema().ActOnOpenMPDefaultmapClause(M, Kind, StartLoc, LParenLoc,
2211 MLoc, KindLoc, EndLoc);
2212 }
2213
2214 /// Build a new OpenMP 'nontemporal' clause.
2215 ///
2216 /// By default, performs semantic analysis to build the new OpenMP clause.
2217 /// Subclasses may override this routine to provide different behavior.
2218 OMPClause *RebuildOMPNontemporalClause(ArrayRef<Expr *> VarList,
2219 SourceLocation StartLoc,
2220 SourceLocation LParenLoc,
2221 SourceLocation EndLoc) {
2222 return getSema().ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc,
2223 EndLoc);
2224 }
2225
2226 /// Build a new OpenMP 'inclusive' clause.
2227 ///
2228 /// By default, performs semantic analysis to build the new OpenMP clause.
2229 /// Subclasses may override this routine to provide different behavior.
2230 OMPClause *RebuildOMPInclusiveClause(ArrayRef<Expr *> VarList,
2231 SourceLocation StartLoc,
2232 SourceLocation LParenLoc,
2233 SourceLocation EndLoc) {
2234 return getSema().ActOnOpenMPInclusiveClause(VarList, StartLoc, LParenLoc,
2235 EndLoc);
2236 }
2237
2238 /// Build a new OpenMP 'exclusive' clause.
2239 ///
2240 /// By default, performs semantic analysis to build the new OpenMP clause.
2241 /// Subclasses may override this routine to provide different behavior.
2242 OMPClause *RebuildOMPExclusiveClause(ArrayRef<Expr *> VarList,
2243 SourceLocation StartLoc,
2244 SourceLocation LParenLoc,
2245 SourceLocation EndLoc) {
2246 return getSema().ActOnOpenMPExclusiveClause(VarList, StartLoc, LParenLoc,
2247 EndLoc);
2248 }
2249
2250 /// Build a new OpenMP 'uses_allocators' clause.
2251 ///
2252 /// By default, performs semantic analysis to build the new OpenMP clause.
2253 /// Subclasses may override this routine to provide different behavior.
2254 OMPClause *RebuildOMPUsesAllocatorsClause(
2255 ArrayRef<Sema::UsesAllocatorsData> Data, SourceLocation StartLoc,
2256 SourceLocation LParenLoc, SourceLocation EndLoc) {
2257 return getSema().ActOnOpenMPUsesAllocatorClause(StartLoc, LParenLoc, EndLoc,
2258 Data);
2259 }
2260
2261 /// Build a new OpenMP 'affinity' clause.
2262 ///
2263 /// By default, performs semantic analysis to build the new OpenMP clause.
2264 /// Subclasses may override this routine to provide different behavior.
2265 OMPClause *RebuildOMPAffinityClause(SourceLocation StartLoc,
2266 SourceLocation LParenLoc,
2267 SourceLocation ColonLoc,
2268 SourceLocation EndLoc, Expr *Modifier,
2269 ArrayRef<Expr *> Locators) {
2270 return getSema().ActOnOpenMPAffinityClause(StartLoc, LParenLoc, ColonLoc,
2271 EndLoc, Modifier, Locators);
2272 }
2273
2274 /// Build a new OpenMP 'order' clause.
2275 ///
2276 /// By default, performs semantic analysis to build the new OpenMP clause.
2277 /// Subclasses may override this routine to provide different behavior.
2278 OMPClause *RebuildOMPOrderClause(
2279 OpenMPOrderClauseKind Kind, SourceLocation KindKwLoc,
2280 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc,
2281 OpenMPOrderClauseModifier Modifier, SourceLocation ModifierKwLoc) {
2282 return getSema().ActOnOpenMPOrderClause(Modifier, Kind, StartLoc, LParenLoc,
2283 ModifierKwLoc, KindKwLoc, EndLoc);
2284 }
2285
2286 /// Build a new OpenMP 'init' clause.
2287 ///
2288 /// By default, performs semantic analysis to build the new OpenMP clause.
2289 /// Subclasses may override this routine to provide different behavior.
2290 OMPClause *RebuildOMPInitClause(Expr *InteropVar, OMPInteropInfo &InteropInfo,
2291 SourceLocation StartLoc,
2292 SourceLocation LParenLoc,
2293 SourceLocation VarLoc,
2294 SourceLocation EndLoc) {
2295 return getSema().ActOnOpenMPInitClause(InteropVar, InteropInfo, StartLoc,
2296 LParenLoc, VarLoc, EndLoc);
2297 }
2298
2299 /// Build a new OpenMP 'use' clause.
2300 ///
2301 /// By default, performs semantic analysis to build the new OpenMP clause.
2302 /// Subclasses may override this routine to provide different behavior.
2303 OMPClause *RebuildOMPUseClause(Expr *InteropVar, SourceLocation StartLoc,
2304 SourceLocation LParenLoc,
2305 SourceLocation VarLoc, SourceLocation EndLoc) {
2306 return getSema().ActOnOpenMPUseClause(InteropVar, StartLoc, LParenLoc,
2307 VarLoc, EndLoc);
2308 }
2309
2310 /// Build a new OpenMP 'destroy' clause.
2311 ///
2312 /// By default, performs semantic analysis to build the new OpenMP clause.
2313 /// Subclasses may override this routine to provide different behavior.
2314 OMPClause *RebuildOMPDestroyClause(Expr *InteropVar, SourceLocation StartLoc,
2315 SourceLocation LParenLoc,
2316 SourceLocation VarLoc,
2317 SourceLocation EndLoc) {
2318 return getSema().ActOnOpenMPDestroyClause(InteropVar, StartLoc, LParenLoc,
2319 VarLoc, EndLoc);
2320 }
2321
2322 /// Build a new OpenMP 'novariants' clause.
2323 ///
2324 /// By default, performs semantic analysis to build the new OpenMP clause.
2325 /// Subclasses may override this routine to provide different behavior.
2326 OMPClause *RebuildOMPNovariantsClause(Expr *Condition,
2327 SourceLocation StartLoc,
2328 SourceLocation LParenLoc,
2329 SourceLocation EndLoc) {
2330 return getSema().ActOnOpenMPNovariantsClause(Condition, StartLoc, LParenLoc,
2331 EndLoc);
2332 }
2333
2334 /// Build a new OpenMP 'nocontext' clause.
2335 ///
2336 /// By default, performs semantic analysis to build the new OpenMP clause.
2337 /// Subclasses may override this routine to provide different behavior.
2338 OMPClause *RebuildOMPNocontextClause(Expr *Condition, SourceLocation StartLoc,
2339 SourceLocation LParenLoc,
2340 SourceLocation EndLoc) {
2341 return getSema().ActOnOpenMPNocontextClause(Condition, StartLoc, LParenLoc,
2342 EndLoc);
2343 }
2344
2345 /// Build a new OpenMP 'filter' clause.
2346 ///
2347 /// By default, performs semantic analysis to build the new OpenMP clause.
2348 /// Subclasses may override this routine to provide different behavior.
2349 OMPClause *RebuildOMPFilterClause(Expr *ThreadID, SourceLocation StartLoc,
2350 SourceLocation LParenLoc,
2351 SourceLocation EndLoc) {
2352 return getSema().ActOnOpenMPFilterClause(ThreadID, StartLoc, LParenLoc,
2353 EndLoc);
2354 }
2355
2356 /// Build a new OpenMP 'bind' clause.
2357 ///
2358 /// By default, performs semantic analysis to build the new OpenMP clause.
2359 /// Subclasses may override this routine to provide different behavior.
2360 OMPClause *RebuildOMPBindClause(OpenMPBindClauseKind Kind,
2361 SourceLocation KindLoc,
2362 SourceLocation StartLoc,
2363 SourceLocation LParenLoc,
2364 SourceLocation EndLoc) {
2365 return getSema().ActOnOpenMPBindClause(Kind, KindLoc, StartLoc, LParenLoc,
2366 EndLoc);
2367 }
2368
2369 /// Build a new OpenMP 'ompx_dyn_cgroup_mem' clause.
2370 ///
2371 /// By default, performs semantic analysis to build the new OpenMP clause.
2372 /// Subclasses may override this routine to provide different behavior.
2373 OMPClause *RebuildOMPXDynCGroupMemClause(Expr *Size, SourceLocation StartLoc,
2374 SourceLocation LParenLoc,
2375 SourceLocation EndLoc) {
2376 return getSema().ActOnOpenMPXDynCGroupMemClause(Size, StartLoc, LParenLoc,
2377 EndLoc);
2378 }
2379
2380 /// Build a new OpenMP 'align' clause.
2381 ///
2382 /// By default, performs semantic analysis to build the new OpenMP clause.
2383 /// Subclasses may override this routine to provide different behavior.
2384 OMPClause *RebuildOMPAlignClause(Expr *A, SourceLocation StartLoc,
2385 SourceLocation LParenLoc,
2386 SourceLocation EndLoc) {
2387 return getSema().ActOnOpenMPAlignClause(A, StartLoc, LParenLoc, EndLoc);
2388 }
2389
2390 /// Build a new OpenMP 'at' clause.
2391 ///
2392 /// By default, performs semantic analysis to build the new OpenMP clause.
2393 /// Subclasses may override this routine to provide different behavior.
2394 OMPClause *RebuildOMPAtClause(OpenMPAtClauseKind Kind, SourceLocation KwLoc,
2395 SourceLocation StartLoc,
2396 SourceLocation LParenLoc,
2397 SourceLocation EndLoc) {
2398 return getSema().ActOnOpenMPAtClause(Kind, KwLoc, StartLoc, LParenLoc,
2399 EndLoc);
2400 }
2401
2402 /// Build a new OpenMP 'severity' clause.
2403 ///
2404 /// By default, performs semantic analysis to build the new OpenMP clause.
2405 /// Subclasses may override this routine to provide different behavior.
2406 OMPClause *RebuildOMPSeverityClause(OpenMPSeverityClauseKind Kind,
2407 SourceLocation KwLoc,
2408 SourceLocation StartLoc,
2409 SourceLocation LParenLoc,
2410 SourceLocation EndLoc) {
2411 return getSema().ActOnOpenMPSeverityClause(Kind, KwLoc, StartLoc, LParenLoc,
2412 EndLoc);
2413 }
2414
2415 /// Build a new OpenMP 'message' clause.
2416 ///
2417 /// By default, performs semantic analysis to build the new OpenMP clause.
2418 /// Subclasses may override this routine to provide different behavior.
2419 OMPClause *RebuildOMPMessageClause(Expr *MS, SourceLocation StartLoc,
2420 SourceLocation LParenLoc,
2421 SourceLocation EndLoc) {
2422 return getSema().ActOnOpenMPMessageClause(MS, StartLoc, LParenLoc, EndLoc);
2423 }
2424
2425 /// Rebuild the operand to an Objective-C \@synchronized statement.
2426 ///
2427 /// By default, performs semantic analysis to build the new statement.
2428 /// Subclasses may override this routine to provide different behavior.
2429 ExprResult RebuildObjCAtSynchronizedOperand(SourceLocation atLoc,
2430 Expr *object) {
2431 return getSema().ActOnObjCAtSynchronizedOperand(atLoc, object);
2432 }
2433
2434 /// Build a new Objective-C \@synchronized statement.
2435 ///
2436 /// By default, performs semantic analysis to build the new statement.
2437 /// Subclasses may override this routine to provide different behavior.
2438 StmtResult RebuildObjCAtSynchronizedStmt(SourceLocation AtLoc,
2439 Expr *Object, Stmt *Body) {
2440 return getSema().ActOnObjCAtSynchronizedStmt(AtLoc, Object, Body);
2441 }
2442
2443 /// Build a new Objective-C \@autoreleasepool statement.
2444 ///
2445 /// By default, performs semantic analysis to build the new statement.
2446 /// Subclasses may override this routine to provide different behavior.
2447 StmtResult RebuildObjCAutoreleasePoolStmt(SourceLocation AtLoc,
2448 Stmt *Body) {
2449 return getSema().ActOnObjCAutoreleasePoolStmt(AtLoc, Body);
2450 }
2451
2452 /// Build a new Objective-C fast enumeration statement.
2453 ///
2454 /// By default, performs semantic analysis to build the new statement.
2455 /// Subclasses may override this routine to provide different behavior.
2456 StmtResult RebuildObjCForCollectionStmt(SourceLocation ForLoc,
2457 Stmt *Element,
2458 Expr *Collection,
2459 SourceLocation RParenLoc,
2460 Stmt *Body) {
2461 StmtResult ForEachStmt = getSema().ActOnObjCForCollectionStmt(ForLoc,
2462 Element,
2463 Collection,
2464 RParenLoc);
2465 if (ForEachStmt.isInvalid())
2466 return StmtError();
2467
2468 return getSema().FinishObjCForCollectionStmt(ForEachStmt.get(), Body);
2469 }
2470
2471 /// Build a new C++ exception declaration.
2472 ///
2473 /// By default, performs semantic analysis to build the new decaration.
2474 /// Subclasses may override this routine to provide different behavior.
2475 VarDecl *RebuildExceptionDecl(VarDecl *ExceptionDecl,
2476 TypeSourceInfo *Declarator,
2477 SourceLocation StartLoc,
2478 SourceLocation IdLoc,
2479 IdentifierInfo *Id) {
2480 VarDecl *Var = getSema().BuildExceptionDeclaration(nullptr, Declarator,
2481 StartLoc, IdLoc, Id);
2482 if (Var)
2483 getSema().CurContext->addDecl(Var);
2484 return Var;
2485 }
2486
2487 /// Build a new C++ catch statement.
2488 ///
2489 /// By default, performs semantic analysis to build the new statement.
2490 /// Subclasses may override this routine to provide different behavior.
2491 StmtResult RebuildCXXCatchStmt(SourceLocation CatchLoc,
2492 VarDecl *ExceptionDecl,
2493 Stmt *Handler) {
2494 return Owned(new (getSema().Context) CXXCatchStmt(CatchLoc, ExceptionDecl,
2495 Handler));
2496 }
2497
2498 /// Build a new C++ try statement.
2499 ///
2500 /// By default, performs semantic analysis to build the new statement.
2501 /// Subclasses may override this routine to provide different behavior.
2502 StmtResult RebuildCXXTryStmt(SourceLocation TryLoc, Stmt *TryBlock,
2503 ArrayRef<Stmt *> Handlers) {
2504 return getSema().ActOnCXXTryBlock(TryLoc, TryBlock, Handlers);
2505 }
2506
2507 /// Build a new C++0x range-based for statement.
2508 ///
2509 /// By default, performs semantic analysis to build the new statement.
2510 /// Subclasses may override this routine to provide different behavior.
2511 StmtResult RebuildCXXForRangeStmt(SourceLocation ForLoc,
2512 SourceLocation CoawaitLoc, Stmt *Init,
2513 SourceLocation ColonLoc, Stmt *Range,
2514 Stmt *Begin, Stmt *End, Expr *Cond,
2515 Expr *Inc, Stmt *LoopVar,
2516 SourceLocation RParenLoc) {
2517 // If we've just learned that the range is actually an Objective-C
2518 // collection, treat this as an Objective-C fast enumeration loop.
2519 if (DeclStmt *RangeStmt = dyn_cast<DeclStmt>(Range)) {
2520 if (RangeStmt->isSingleDecl()) {
2521 if (VarDecl *RangeVar = dyn_cast<VarDecl>(RangeStmt->getSingleDecl())) {
2522 if (RangeVar->isInvalidDecl())
2523 return StmtError();
2524
2525 Expr *RangeExpr = RangeVar->getInit();
2526 if (!RangeExpr->isTypeDependent() &&
2527 RangeExpr->getType()->isObjCObjectPointerType()) {
2528 // FIXME: Support init-statements in Objective-C++20 ranged for
2529 // statement.
2530 if (Init) {
2531 return SemaRef.Diag(Init->getBeginLoc(),
2532 diag::err_objc_for_range_init_stmt)
2533 << Init->getSourceRange();
2534 }
2535 return getSema().ActOnObjCForCollectionStmt(ForLoc, LoopVar,
2536 RangeExpr, RParenLoc);
2537 }
2538 }
2539 }
2540 }
2541
2542 return getSema().BuildCXXForRangeStmt(ForLoc, CoawaitLoc, Init, ColonLoc,
2543 Range, Begin, End, Cond, Inc, LoopVar,
2544 RParenLoc, Sema::BFRK_Rebuild);
2545 }
2546
2547 /// Build a new C++0x range-based for statement.
2548 ///
2549 /// By default, performs semantic analysis to build the new statement.
2550 /// Subclasses may override this routine to provide different behavior.
2551 StmtResult RebuildMSDependentExistsStmt(SourceLocation KeywordLoc,
2552 bool IsIfExists,
2553 NestedNameSpecifierLoc QualifierLoc,
2554 DeclarationNameInfo NameInfo,
2555 Stmt *Nested) {
2556 return getSema().BuildMSDependentExistsStmt(KeywordLoc, IsIfExists,
2557 QualifierLoc, NameInfo, Nested);
2558 }
2559
2560 /// Attach body to a C++0x range-based for statement.
2561 ///
2562 /// By default, performs semantic analysis to finish the new statement.
2563 /// Subclasses may override this routine to provide different behavior.
2564 StmtResult FinishCXXForRangeStmt(Stmt *ForRange, Stmt *Body) {
2565 return getSema().FinishCXXForRangeStmt(ForRange, Body);
2566 }
2567
2568 StmtResult RebuildSEHTryStmt(bool IsCXXTry, SourceLocation TryLoc,
2569 Stmt *TryBlock, Stmt *Handler) {
2570 return getSema().ActOnSEHTryBlock(IsCXXTry, TryLoc, TryBlock, Handler);
2571 }
2572
2573 StmtResult RebuildSEHExceptStmt(SourceLocation Loc, Expr *FilterExpr,
2574 Stmt *Block) {
2575 return getSema().ActOnSEHExceptBlock(Loc, FilterExpr, Block);
2576 }
2577
2578 StmtResult RebuildSEHFinallyStmt(SourceLocation Loc, Stmt *Block) {
2579 return SEHFinallyStmt::Create(getSema().getASTContext(), Loc, Block);
2580 }
2581
2582 ExprResult RebuildSYCLUniqueStableNameExpr(SourceLocation OpLoc,
2583 SourceLocation LParen,
2584 SourceLocation RParen,
2585 TypeSourceInfo *TSI) {
2586 return getSema().BuildSYCLUniqueStableNameExpr(OpLoc, LParen, RParen, TSI);
2587 }
2588
2589 /// Build a new predefined expression.
2590 ///
2591 /// By default, performs semantic analysis to build the new expression.
2592 /// Subclasses may override this routine to provide different behavior.
2593 ExprResult RebuildPredefinedExpr(SourceLocation Loc,
2594 PredefinedExpr::IdentKind IK) {
2595 return getSema().BuildPredefinedExpr(Loc, IK);
2596 }
2597
2598 /// Build a new expression that references a declaration.
2599 ///
2600 /// By default, performs semantic analysis to build the new expression.
2601 /// Subclasses may override this routine to provide different behavior.
2602 ExprResult RebuildDeclarationNameExpr(const CXXScopeSpec &SS,
2603 LookupResult &R,
2604 bool RequiresADL) {
2605 return getSema().BuildDeclarationNameExpr(SS, R, RequiresADL);
2606 }
2607
2608
2609 /// Build a new expression that references a declaration.
2610 ///
2611 /// By default, performs semantic analysis to build the new expression.
2612 /// Subclasses may override this routine to provide different behavior.
2613 ExprResult RebuildDeclRefExpr(NestedNameSpecifierLoc QualifierLoc,
2614 ValueDecl *VD,
2615 const DeclarationNameInfo &NameInfo,
2616 NamedDecl *Found,
2617 TemplateArgumentListInfo *TemplateArgs) {
2618 CXXScopeSpec SS;
2619 SS.Adopt(QualifierLoc);
2620 return getSema().BuildDeclarationNameExpr(SS, NameInfo, VD, Found,
2621 TemplateArgs);
2622 }
2623
2624 /// Build a new expression in parentheses.
2625 ///
2626 /// By default, performs semantic analysis to build the new expression.
2627 /// Subclasses may override this routine to provide different behavior.
2628 ExprResult RebuildParenExpr(Expr *SubExpr, SourceLocation LParen,
2629 SourceLocation RParen) {
2630 return getSema().ActOnParenExpr(LParen, RParen, SubExpr);
2631 }
2632
2633 /// Build a new pseudo-destructor expression.
2634 ///
2635 /// By default, performs semantic analysis to build the new expression.
2636 /// Subclasses may override this routine to provide different behavior.
2637 ExprResult RebuildCXXPseudoDestructorExpr(Expr *Base,
2638 SourceLocation OperatorLoc,
2639 bool isArrow,
2640 CXXScopeSpec &SS,
2641 TypeSourceInfo *ScopeType,
2642 SourceLocation CCLoc,
2643 SourceLocation TildeLoc,
2644 PseudoDestructorTypeStorage Destroyed);
2645
2646 /// Build a new unary operator expression.
2647 ///
2648 /// By default, performs semantic analysis to build the new expression.
2649 /// Subclasses may override this routine to provide different behavior.
2650 ExprResult RebuildUnaryOperator(SourceLocation OpLoc,
2651 UnaryOperatorKind Opc,
2652 Expr *SubExpr) {
2653 return getSema().BuildUnaryOp(/*Scope=*/nullptr, OpLoc, Opc, SubExpr);
2654 }
2655
2656 /// Build a new builtin offsetof expression.
2657 ///
2658 /// By default, performs semantic analysis to build the new expression.
2659 /// Subclasses may override this routine to provide different behavior.
2660 ExprResult RebuildOffsetOfExpr(SourceLocation OperatorLoc,
2661 TypeSourceInfo *Type,
2662 ArrayRef<Sema::OffsetOfComponent> Components,
2663 SourceLocation RParenLoc) {
2664 return getSema().BuildBuiltinOffsetOf(OperatorLoc, Type, Components,
2665 RParenLoc);
2666 }
2667
2668 /// Build a new sizeof, alignof or vec_step expression with a
2669 /// type argument.
2670 ///
2671 /// By default, performs semantic analysis to build the new expression.
2672 /// Subclasses may override this routine to provide different behavior.
2673 ExprResult RebuildUnaryExprOrTypeTrait(TypeSourceInfo *TInfo,
2674 SourceLocation OpLoc,
2675 UnaryExprOrTypeTrait ExprKind,
2676 SourceRange R) {
2677 return getSema().CreateUnaryExprOrTypeTraitExpr(TInfo, OpLoc, ExprKind, R);
2678 }
2679
2680 /// Build a new sizeof, alignof or vec step expression with an
2681 /// expression argument.
2682 ///
2683 /// By default, performs semantic analysis to build the new expression.
2684 /// Subclasses may override this routine to provide different behavior.
2685 ExprResult RebuildUnaryExprOrTypeTrait(Expr *SubExpr, SourceLocation OpLoc,
2686 UnaryExprOrTypeTrait ExprKind,
2687 SourceRange R) {
2688 ExprResult Result
2689 = getSema().CreateUnaryExprOrTypeTraitExpr(SubExpr, OpLoc, ExprKind);
2690 if (Result.isInvalid())
2691 return ExprError();
2692
2693 return Result;
2694 }
2695
2696 /// Build a new array subscript expression.
2697 ///
2698 /// By default, performs semantic analysis to build the new expression.
2699 /// Subclasses may override this routine to provide different behavior.
2700 ExprResult RebuildArraySubscriptExpr(Expr *LHS,
2701 SourceLocation LBracketLoc,
2702 Expr *RHS,
2703 SourceLocation RBracketLoc) {
2704 return getSema().ActOnArraySubscriptExpr(/*Scope=*/nullptr, LHS,
2705 LBracketLoc, RHS,
2706 RBracketLoc);
2707 }
2708
2709 /// Build a new matrix subscript expression.
2710 ///
2711 /// By default, performs semantic analysis to build the new expression.
2712 /// Subclasses may override this routine to provide different behavior.
2713 ExprResult RebuildMatrixSubscriptExpr(Expr *Base, Expr *RowIdx,
2714 Expr *ColumnIdx,
2715 SourceLocation RBracketLoc) {
2716 return getSema().CreateBuiltinMatrixSubscriptExpr(Base, RowIdx, ColumnIdx,
2717 RBracketLoc);
2718 }
2719
2720 /// Build a new array section expression.
2721 ///
2722 /// By default, performs semantic analysis to build the new expression.
2723 /// Subclasses may override this routine to provide different behavior.
2724 ExprResult RebuildOMPArraySectionExpr(Expr *Base, SourceLocation LBracketLoc,
2725 Expr *LowerBound,
2726 SourceLocation ColonLocFirst,
2727 SourceLocation ColonLocSecond,
2728 Expr *Length, Expr *Stride,
2729 SourceLocation RBracketLoc) {
2730 return getSema().ActOnOMPArraySectionExpr(Base, LBracketLoc, LowerBound,
2731 ColonLocFirst, ColonLocSecond,
2732 Length, Stride, RBracketLoc);
2733 }
2734
2735 /// Build a new array shaping expression.
2736 ///
2737 /// By default, performs semantic analysis to build the new expression.
2738 /// Subclasses may override this routine to provide different behavior.
2739 ExprResult RebuildOMPArrayShapingExpr(Expr *Base, SourceLocation LParenLoc,
2740 SourceLocation RParenLoc,
2741 ArrayRef<Expr *> Dims,
2742 ArrayRef<SourceRange> BracketsRanges) {
2743 return getSema().ActOnOMPArrayShapingExpr(Base, LParenLoc, RParenLoc, Dims,
2744 BracketsRanges);
2745 }
2746
2747 /// Build a new iterator expression.
2748 ///
2749 /// By default, performs semantic analysis to build the new expression.
2750 /// Subclasses may override this routine to provide different behavior.
2751 ExprResult RebuildOMPIteratorExpr(
2752 SourceLocation IteratorKwLoc, SourceLocation LLoc, SourceLocation RLoc,
2753 ArrayRef<Sema::OMPIteratorData> Data) {
2754 return getSema().ActOnOMPIteratorExpr(/*Scope=*/nullptr, IteratorKwLoc,
2755 LLoc, RLoc, Data);
2756 }
2757
2758 /// Build a new call expression.
2759 ///
2760 /// By default, performs semantic analysis to build the new expression.
2761 /// Subclasses may override this routine to provide different behavior.
2762 ExprResult RebuildCallExpr(Expr *Callee, SourceLocation LParenLoc,
2763 MultiExprArg Args,
2764 SourceLocation RParenLoc,
2765 Expr *ExecConfig = nullptr) {
2766 return getSema().ActOnCallExpr(
2767 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc, ExecConfig);
2768 }
2769
2770 ExprResult RebuildCxxSubscriptExpr(Expr *Callee, SourceLocation LParenLoc,
2771 MultiExprArg Args,
2772 SourceLocation RParenLoc) {
2773 return getSema().ActOnArraySubscriptExpr(
2774 /*Scope=*/nullptr, Callee, LParenLoc, Args, RParenLoc);
2775 }
2776
2777 /// Build a new member access expression.
2778 ///
2779 /// By default, performs semantic analysis to build the new expression.
2780 /// Subclasses may override this routine to provide different behavior.
2781 ExprResult RebuildMemberExpr(Expr *Base, SourceLocation OpLoc,
2782 bool isArrow,
2783 NestedNameSpecifierLoc QualifierLoc,
2784 SourceLocation TemplateKWLoc,
2785 const DeclarationNameInfo &MemberNameInfo,
2786 ValueDecl *Member,
2787 NamedDecl *FoundDecl,
2788 const TemplateArgumentListInfo *ExplicitTemplateArgs,
2789 NamedDecl *FirstQualifierInScope) {
2790 ExprResult BaseResult = getSema().PerformMemberExprBaseConversion(Base,
2791 isArrow);
2792 if (!Member->getDeclName()) {
2793 // We have a reference to an unnamed field. This is always the
2794 // base of an anonymous struct/union member access, i.e. the
2795 // field is always of record type.
2796 assert(Member->getType()->isRecordType() &&(static_cast <bool> (Member->getType()->isRecordType
() && "unnamed member not of record type?") ? void (0
) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "clang/lib/Sema/TreeTransform.h", 2797, __extension__ __PRETTY_FUNCTION__
))
2797 "unnamed member not of record type?")(static_cast <bool> (Member->getType()->isRecordType
() && "unnamed member not of record type?") ? void (0
) : __assert_fail ("Member->getType()->isRecordType() && \"unnamed member not of record type?\""
, "clang/lib/Sema/TreeTransform.h", 2797, __extension__ __PRETTY_FUNCTION__
))
;
2798
2799 BaseResult =
2800 getSema().PerformObjectMemberConversion(BaseResult.get(),
2801 QualifierLoc.getNestedNameSpecifier(),
2802 FoundDecl, Member);
2803 if (BaseResult.isInvalid())
2804 return ExprError();
2805 Base = BaseResult.get();
2806
2807 CXXScopeSpec EmptySS;
2808 return getSema().BuildFieldReferenceExpr(
2809 Base, isArrow, OpLoc, EmptySS, cast<FieldDecl>(Member),
2810 DeclAccessPair::make(FoundDecl, FoundDecl->getAccess()), MemberNameInfo);
2811 }
2812
2813 CXXScopeSpec SS;
2814 SS.Adopt(QualifierLoc);
2815
2816 Base = BaseResult.get();
2817 QualType BaseType = Base->getType();
2818
2819 if (isArrow && !BaseType->isPointerType())
2820 return ExprError();
2821
2822 // FIXME: this involves duplicating earlier analysis in a lot of
2823 // cases; we should avoid this when possible.
2824 LookupResult R(getSema(), MemberNameInfo, Sema::LookupMemberName);
2825 R.addDecl(FoundDecl);
2826 R.resolveKind();
2827
2828 if (getSema().isUnevaluatedContext() && Base->isImplicitCXXThis() &&
2829 isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(Member)) {
2830 if (auto *ThisClass = cast<CXXThisExpr>(Base)
2831 ->getType()
2832 ->getPointeeType()
2833 ->getAsCXXRecordDecl()) {
2834 auto *Class = cast<CXXRecordDecl>(Member->getDeclContext());
2835 // In unevaluated contexts, an expression supposed to be a member access
2836 // might reference a member in an unrelated class.
2837 if (!ThisClass->Equals(Class) && !ThisClass->isDerivedFrom(Class))
2838 return getSema().BuildDeclRefExpr(Member, Member->getType(),
2839 VK_LValue, Member->getLocation());
2840 }
2841 }
2842
2843 return getSema().BuildMemberReferenceExpr(Base, BaseType, OpLoc, isArrow,
2844 SS, TemplateKWLoc,
2845 FirstQualifierInScope,
2846 R, ExplicitTemplateArgs,
2847 /*S*/nullptr);
2848 }
2849
2850 /// Build a new binary operator expression.
2851 ///
2852 /// By default, performs semantic analysis to build the new expression.
2853 /// Subclasses may override this routine to provide different behavior.
2854 ExprResult RebuildBinaryOperator(SourceLocation OpLoc,
2855 BinaryOperatorKind Opc,
2856 Expr *LHS, Expr *RHS) {
2857 return getSema().BuildBinOp(/*Scope=*/nullptr, OpLoc, Opc, LHS, RHS);
2858 }
2859
2860 /// Build a new rewritten operator expression.
2861 ///
2862 /// By default, performs semantic analysis to build the new expression.
2863 /// Subclasses may override this routine to provide different behavior.
2864 ExprResult RebuildCXXRewrittenBinaryOperator(
2865 SourceLocation OpLoc, BinaryOperatorKind Opcode,
2866 const UnresolvedSetImpl &UnqualLookups, Expr *LHS, Expr *RHS) {
2867 return getSema().CreateOverloadedBinOp(OpLoc, Opcode, UnqualLookups, LHS,
2868 RHS, /*RequiresADL*/false);
2869 }
2870
2871 /// Build a new conditional operator expression.
2872 ///
2873 /// By default, performs semantic analysis to build the new expression.
2874 /// Subclasses may override this routine to provide different behavior.
2875 ExprResult RebuildConditionalOperator(Expr *Cond,
2876 SourceLocation QuestionLoc,
2877 Expr *LHS,
2878 SourceLocation ColonLoc,
2879 Expr *RHS) {
2880 return getSema().ActOnConditionalOp(QuestionLoc, ColonLoc, Cond,
2881 LHS, RHS);
2882 }
2883
2884 /// Build a new C-style cast expression.
2885 ///
2886 /// By default, performs semantic analysis to build the new expression.
2887 /// Subclasses may override this routine to provide different behavior.
2888 ExprResult RebuildCStyleCastExpr(SourceLocation LParenLoc,
2889 TypeSourceInfo *TInfo,
2890 SourceLocation RParenLoc,
2891 Expr *SubExpr) {
2892 return getSema().BuildCStyleCastExpr(LParenLoc, TInfo, RParenLoc,
2893 SubExpr);
2894 }
2895
2896 /// Build a new compound literal expression.
2897 ///
2898 /// By default, performs semantic analysis to build the new expression.
2899 /// Subclasses may override this routine to provide different behavior.
2900 ExprResult RebuildCompoundLiteralExpr(SourceLocation LParenLoc,
2901 TypeSourceInfo *TInfo,
2902 SourceLocation RParenLoc,
2903 Expr *Init) {
2904 return getSema().BuildCompoundLiteralExpr(LParenLoc, TInfo, RParenLoc,
2905 Init);
2906 }
2907
2908 /// Build a new extended vector element access expression.
2909 ///
2910 /// By default, performs semantic analysis to build the new expression.
2911 /// Subclasses may override this routine to provide different behavior.
2912 ExprResult RebuildExtVectorElementExpr(Expr *Base, SourceLocation OpLoc,
2913 bool IsArrow,
2914 SourceLocation AccessorLoc,
2915 IdentifierInfo &Accessor) {
2916
2917 CXXScopeSpec SS;
2918 DeclarationNameInfo NameInfo(&Accessor, AccessorLoc);
2919 return getSema().BuildMemberReferenceExpr(
2920 Base, Base->getType(), OpLoc, IsArrow, SS, SourceLocation(),
2921 /*FirstQualifierInScope*/ nullptr, NameInfo,
2922 /* TemplateArgs */ nullptr,
2923 /*S*/ nullptr);
2924 }
2925
2926 /// Build a new initializer list expression.
2927 ///
2928 /// By default, performs semantic analysis to build the new expression.
2929 /// Subclasses may override this routine to provide different behavior.
2930 ExprResult RebuildInitList(SourceLocation LBraceLoc,
2931 MultiExprArg Inits,
2932 SourceLocation RBraceLoc) {
2933 return SemaRef.BuildInitList(LBraceLoc, Inits, RBraceLoc);
2934 }
2935
2936 /// Build a new designated initializer expression.
2937 ///
2938 /// By default, performs semantic analysis to build the new expression.
2939 /// Subclasses may override this routine to provide different behavior.
2940 ExprResult RebuildDesignatedInitExpr(Designation &Desig,
2941 MultiExprArg ArrayExprs,
2942 SourceLocation EqualOrColonLoc,
2943 bool GNUSyntax,
2944 Expr *Init) {
2945 ExprResult Result
2946 = SemaRef.ActOnDesignatedInitializer(Desig, EqualOrColonLoc, GNUSyntax,
2947 Init);
2948 if (Result.isInvalid())
2949 return ExprError();
2950
2951 return Result;
2952 }
2953
2954 /// Build a new value-initialized expression.
2955 ///
2956 /// By default, builds the implicit value initialization without performing
2957 /// any semantic analysis. Subclasses may override this routine to provide
2958 /// different behavior.
2959 ExprResult RebuildImplicitValueInitExpr(QualType T) {
2960 return new (SemaRef.Context) ImplicitValueInitExpr(T);
2961 }
2962
2963 /// Build a new \c va_arg expression.
2964 ///
2965 /// By default, performs semantic analysis to build the new expression.
2966 /// Subclasses may override this routine to provide different behavior.
2967 ExprResult RebuildVAArgExpr(SourceLocation BuiltinLoc,
2968 Expr *SubExpr, TypeSourceInfo *TInfo,
2969 SourceLocation RParenLoc) {
2970 return getSema().BuildVAArgExpr(BuiltinLoc,
2971 SubExpr, TInfo,
2972 RParenLoc);
2973 }
2974
2975 /// Build a new expression list in parentheses.
2976 ///
2977 /// By default, performs semantic analysis to build the new expression.
2978 /// Subclasses may override this routine to provide different behavior.
2979 ExprResult RebuildParenListExpr(SourceLocation LParenLoc,
2980 MultiExprArg SubExprs,
2981 SourceLocation RParenLoc) {
2982 return getSema().ActOnParenListExpr(LParenLoc, RParenLoc, SubExprs);
2983 }
2984
2985 /// Build a new address-of-label expression.
2986 ///
2987 /// By default, performs semantic analysis, using the name of the label
2988 /// rather than attempting to map the label statement itself.
2989 /// Subclasses may override this routine to provide different behavior.
2990 ExprResult RebuildAddrLabelExpr(SourceLocation AmpAmpLoc,
2991 SourceLocation LabelLoc, LabelDecl *Label) {
2992 return getSema().ActOnAddrLabel(AmpAmpLoc, LabelLoc, Label);
2993 }
2994
2995 /// Build a new GNU statement expression.
2996 ///
2997 /// By default, performs semantic analysis to build the new expression.
2998 /// Subclasses may override this routine to provide different behavior.
2999 ExprResult RebuildStmtExpr(SourceLocation LParenLoc, Stmt *SubStmt,
3000 SourceLocation RParenLoc, unsigned TemplateDepth) {
3001 return getSema().BuildStmtExpr(LParenLoc, SubStmt, RParenLoc,
3002 TemplateDepth);
3003 }
3004
3005 /// Build a new __builtin_choose_expr expression.
3006 ///
3007 /// By default, performs semantic analysis to build the new expression.
3008 /// Subclasses may override this routine to provide different behavior.
3009 ExprResult RebuildChooseExpr(SourceLocation BuiltinLoc,
3010 Expr *Cond, Expr *LHS, Expr *RHS,
3011 SourceLocation RParenLoc) {
3012 return SemaRef.ActOnChooseExpr(BuiltinLoc,
3013 Cond, LHS, RHS,
3014 RParenLoc);
3015 }
3016
3017 /// Build a new generic selection expression.
3018 ///
3019 /// By default, performs semantic analysis to build the new expression.
3020 /// Subclasses may override this routine to provide different behavior.
3021 ExprResult RebuildGenericSelectionExpr(SourceLocation KeyLoc,
3022 SourceLocation DefaultLoc,
3023 SourceLocation RParenLoc,
3024 Expr *ControllingExpr,
3025 ArrayRef<TypeSourceInfo *> Types,
3026 ArrayRef<Expr *> Exprs) {
3027 return getSema().CreateGenericSelectionExpr(KeyLoc, DefaultLoc, RParenLoc,
3028 ControllingExpr, Types, Exprs);
3029 }
3030
3031 /// Build a new overloaded operator call expression.
3032 ///
3033 /// By default, performs semantic analysis to build the new expression.
3034 /// The semantic analysis provides the behavior of template instantiation,
3035 /// copying with transformations that turn what looks like an overloaded
3036 /// operator call into a use of a builtin operator, performing
3037 /// argument-dependent lookup, etc. Subclasses may override this routine to
3038 /// provide different behavior.
3039 ExprResult RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
3040 SourceLocation OpLoc,
3041 Expr *Callee,
3042 Expr *First,
3043 Expr *Second);
3044
3045 /// Build a new C++ "named" cast expression, such as static_cast or
3046 /// reinterpret_cast.
3047 ///
3048 /// By default, this routine dispatches to one of the more-specific routines
3049 /// for a particular named case, e.g., RebuildCXXStaticCastExpr().
3050 /// Subclasses may override this routine to provide different behavior.
3051 ExprResult RebuildCXXNamedCastExpr(SourceLocation OpLoc,
3052 Stmt::StmtClass Class,
3053 SourceLocation LAngleLoc,
3054 TypeSourceInfo *TInfo,
3055 SourceLocation RAngleLoc,
3056 SourceLocation LParenLoc,
3057 Expr *SubExpr,
3058 SourceLocation RParenLoc) {
3059 switch (Class) {
3060 case Stmt::CXXStaticCastExprClass:
3061 return getDerived().RebuildCXXStaticCastExpr(OpLoc, LAngleLoc, TInfo,
3062 RAngleLoc, LParenLoc,
3063 SubExpr, RParenLoc);
3064
3065 case Stmt::CXXDynamicCastExprClass:
3066 return getDerived().RebuildCXXDynamicCastExpr(OpLoc, LAngleLoc, TInfo,
3067 RAngleLoc, LParenLoc,
3068 SubExpr, RParenLoc);
3069
3070 case Stmt::CXXReinterpretCastExprClass:
3071 return getDerived().RebuildCXXReinterpretCastExpr(OpLoc, LAngleLoc, TInfo,
3072 RAngleLoc, LParenLoc,
3073 SubExpr,
3074 RParenLoc);
3075
3076 case Stmt::CXXConstCastExprClass:
3077 return getDerived().RebuildCXXConstCastExpr(OpLoc, LAngleLoc, TInfo,
3078 RAngleLoc, LParenLoc,
3079 SubExpr, RParenLoc);
3080
3081 case Stmt::CXXAddrspaceCastExprClass:
3082 return getDerived().RebuildCXXAddrspaceCastExpr(
3083 OpLoc, LAngleLoc, TInfo, RAngleLoc, LParenLoc, SubExpr, RParenLoc);
3084
3085 default:
3086 llvm_unreachable("Invalid C++ named cast")::llvm::llvm_unreachable_internal("Invalid C++ named cast", "clang/lib/Sema/TreeTransform.h"
, 3086)
;
3087 }
3088 }
3089
3090 /// Build a new C++ static_cast expression.
3091 ///
3092 /// By default, performs semantic analysis to build the new expression.
3093 /// Subclasses may override this routine to provide different behavior.
3094 ExprResult RebuildCXXStaticCastExpr(SourceLocation OpLoc,
3095 SourceLocation LAngleLoc,
3096 TypeSourceInfo *TInfo,
3097 SourceLocation RAngleLoc,
3098 SourceLocation LParenLoc,
3099 Expr *SubExpr,
3100 SourceLocation RParenLoc) {
3101 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_static_cast,
3102 TInfo, SubExpr,
3103 SourceRange(LAngleLoc, RAngleLoc),
3104 SourceRange(LParenLoc, RParenLoc));
3105 }
3106
3107 /// Build a new C++ dynamic_cast expression.
3108 ///
3109 /// By default, performs semantic analysis to build the new expression.
3110 /// Subclasses may override this routine to provide different behavior.
3111 ExprResult RebuildCXXDynamicCastExpr(SourceLocation OpLoc,
3112 SourceLocation LAngleLoc,
3113 TypeSourceInfo *TInfo,
3114 SourceLocation RAngleLoc,
3115 SourceLocation LParenLoc,
3116 Expr *SubExpr,
3117 SourceLocation RParenLoc) {
3118 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_dynamic_cast,
3119 TInfo, SubExpr,
3120 SourceRange(LAngleLoc, RAngleLoc),
3121 SourceRange(LParenLoc, RParenLoc));
3122 }
3123
3124 /// Build a new C++ reinterpret_cast expression.
3125 ///
3126 /// By default, performs semantic analysis to build the new expression.
3127 /// Subclasses may override this routine to provide different behavior.
3128 ExprResult RebuildCXXReinterpretCastExpr(SourceLocation OpLoc,
3129 SourceLocation LAngleLoc,
3130 TypeSourceInfo *TInfo,
3131 SourceLocation RAngleLoc,
3132 SourceLocation LParenLoc,
3133 Expr *SubExpr,
3134 SourceLocation RParenLoc) {
3135 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_reinterpret_cast,
3136 TInfo, SubExpr,
3137 SourceRange(LAngleLoc, RAngleLoc),
3138 SourceRange(LParenLoc, RParenLoc));
3139 }
3140
3141 /// Build a new C++ const_cast expression.
3142 ///
3143 /// By default, performs semantic analysis to build the new expression.
3144 /// Subclasses may override this routine to provide different behavior.
3145 ExprResult RebuildCXXConstCastExpr(SourceLocation OpLoc,
3146 SourceLocation LAngleLoc,
3147 TypeSourceInfo *TInfo,
3148 SourceLocation RAngleLoc,
3149 SourceLocation LParenLoc,
3150 Expr *SubExpr,
3151 SourceLocation RParenLoc) {
3152 return getSema().BuildCXXNamedCast(OpLoc, tok::kw_const_cast,
3153 TInfo, SubExpr,
3154 SourceRange(LAngleLoc, RAngleLoc),
3155 SourceRange(LParenLoc, RParenLoc));
3156 }
3157
3158 ExprResult
3159 RebuildCXXAddrspaceCastExpr(SourceLocation OpLoc, SourceLocation LAngleLoc,
3160 TypeSourceInfo *TInfo, SourceLocation RAngleLoc,
3161 SourceLocation LParenLoc, Expr *SubExpr,
3162 SourceLocation RParenLoc) {
3163 return getSema().BuildCXXNamedCast(
3164 OpLoc, tok::kw_addrspace_cast, TInfo, SubExpr,
3165 SourceRange(LAngleLoc, RAngleLoc), SourceRange(LParenLoc, RParenLoc));
3166 }
3167
3168 /// Build a new C++ functional-style cast expression.
3169 ///
3170 /// By default, performs semantic analysis to build the new expression.
3171 /// Subclasses may override this routine to provide different behavior.
3172 ExprResult RebuildCXXFunctionalCastExpr(TypeSourceInfo *TInfo,
3173 SourceLocation LParenLoc,
3174 Expr *Sub,
3175 SourceLocation RParenLoc,
3176 bool ListInitialization) {
3177 // If Sub is a ParenListExpr, then Sub is the syntatic form of a
3178 // CXXParenListInitExpr. Pass its expanded arguments so that the
3179 // CXXParenListInitExpr can be rebuilt.
3180 if (auto *PLE = dyn_cast<ParenListExpr>(Sub))
3181 return getSema().BuildCXXTypeConstructExpr(
3182 TInfo, LParenLoc, MultiExprArg(PLE->getExprs(), PLE->getNumExprs()),
3183 RParenLoc, ListInitialization);
3184 return getSema().BuildCXXTypeConstructExpr(TInfo, LParenLoc,
3185 MultiExprArg(&Sub, 1), RParenLoc,
3186 ListInitialization);
3187 }
3188
3189 /// Build a new C++ __builtin_bit_cast expression.
3190 ///
3191 /// By default, performs semantic analysis to build the new expression.
3192 /// Subclasses may override this routine to provide different behavior.
3193 ExprResult RebuildBuiltinBitCastExpr(SourceLocation KWLoc,
3194 TypeSourceInfo *TSI, Expr *Sub,
3195 SourceLocation RParenLoc) {
3196 return getSema().BuildBuiltinBitCastExpr(KWLoc, TSI, Sub, RParenLoc);
3197 }
3198
3199 /// Build a new C++ typeid(type) expression.
3200 ///
3201 /// By default, performs semantic analysis to build the new expression.
3202 /// Subclasses may override this routine to provide different behavior.
3203 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3204 SourceLocation TypeidLoc,
3205 TypeSourceInfo *Operand,
3206 SourceLocation RParenLoc) {
3207 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3208 RParenLoc);
3209 }
3210
3211
3212 /// Build a new C++ typeid(expr) expression.
3213 ///
3214 /// By default, performs semantic analysis to build the new expression.
3215 /// Subclasses may override this routine to provide different behavior.
3216 ExprResult RebuildCXXTypeidExpr(QualType TypeInfoType,
3217 SourceLocation TypeidLoc,
3218 Expr *Operand,
3219 SourceLocation RParenLoc) {
3220 return getSema().BuildCXXTypeId(TypeInfoType, TypeidLoc, Operand,
3221 RParenLoc);
3222 }
3223
3224 /// Build a new C++ __uuidof(type) expression.
3225 ///
3226 /// By default, performs semantic analysis to build the new expression.
3227 /// Subclasses may override this routine to provide different behavior.
3228 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3229 TypeSourceInfo *Operand,
3230 SourceLocation RParenLoc) {
3231 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3232 }
3233
3234 /// Build a new C++ __uuidof(expr) expression.
3235 ///
3236 /// By default, performs semantic analysis to build the new expression.
3237 /// Subclasses may override this routine to provide different behavior.
3238 ExprResult RebuildCXXUuidofExpr(QualType Type, SourceLocation TypeidLoc,
3239 Expr *Operand, SourceLocation RParenLoc) {
3240 return getSema().BuildCXXUuidof(Type, TypeidLoc, Operand, RParenLoc);
3241 }
3242
3243 /// Build a new C++ "this" expression.
3244 ///
3245 /// By default, builds a new "this" expression without performing any
3246 /// semantic analysis. Subclasses may override this routine to provide
3247 /// different behavior.
3248 ExprResult RebuildCXXThisExpr(SourceLocation ThisLoc,
3249 QualType ThisType,
3250 bool isImplicit) {
3251 return getSema().BuildCXXThisExpr(ThisLoc, ThisType, isImplicit);
3252 }
3253
3254 /// Build a new C++ throw expression.
3255 ///
3256 /// By default, performs semantic analysis to build the new expression.
3257 /// Subclasses may override this routine to provide different behavior.
3258 ExprResult RebuildCXXThrowExpr(SourceLocation ThrowLoc, Expr *Sub,
3259 bool IsThrownVariableInScope) {
3260 return getSema().BuildCXXThrow(ThrowLoc, Sub, IsThrownVariableInScope);
3261 }
3262
3263 /// Build a new C++ default-argument expression.
3264 ///
3265 /// By default, builds a new default-argument expression, which does not
3266 /// require any semantic analysis. Subclasses may override this routine to
3267 /// provide different behavior.
3268 ExprResult RebuildCXXDefaultArgExpr(SourceLocation Loc, ParmVarDecl *Param,
3269 Expr *RewrittenExpr) {
3270 return CXXDefaultArgExpr::Create(getSema().Context, Loc, Param,
3271 RewrittenExpr, getSema().CurContext);
3272 }
3273
3274 /// Build a new C++11 default-initialization expression.
3275 ///
3276 /// By default, builds a new default field initialization expression, which
3277 /// does not require any semantic analysis. Subclasses may override this
3278 /// routine to provide different behavior.
3279 ExprResult RebuildCXXDefaultInitExpr(SourceLocation Loc,
3280 FieldDecl *Field) {
3281 return getSema().BuildCXXDefaultInitExpr(Loc, Field);
3282 }
3283
3284 /// Build a new C++ zero-initialization expression.
3285 ///
3286 /// By default, performs semantic analysis to build the new expression.
3287 /// Subclasses may override this routine to provide different behavior.
3288 ExprResult RebuildCXXScalarValueInitExpr(TypeSourceInfo *TSInfo,
3289 SourceLocation LParenLoc,
3290 SourceLocation RParenLoc) {
3291 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, std::nullopt,
3292 RParenLoc,
3293 /*ListInitialization=*/false);
3294 }
3295
3296 /// Build a new C++ "new" expression.
3297 ///
3298 /// By default, performs semantic analysis to build the new expression.
3299 /// Subclasses may override this routine to provide different behavior.
3300 ExprResult RebuildCXXNewExpr(SourceLocation StartLoc, bool UseGlobal,
3301 SourceLocation PlacementLParen,
3302 MultiExprArg PlacementArgs,
3303 SourceLocation PlacementRParen,
3304 SourceRange TypeIdParens, QualType AllocatedType,
3305 TypeSourceInfo *AllocatedTypeInfo,
3306 std::optional<Expr *> ArraySize,
3307 SourceRange DirectInitRange, Expr *Initializer) {
3308 return getSema().BuildCXXNew(StartLoc, UseGlobal,
3309 PlacementLParen,
3310 PlacementArgs,
3311 PlacementRParen,
3312 TypeIdParens,
3313 AllocatedType,
3314 AllocatedTypeInfo,
3315 ArraySize,
3316 DirectInitRange,
3317 Initializer);
3318 }
3319
3320 /// Build a new C++ "delete" expression.
3321 ///
3322 /// By default, performs semantic analysis to build the new expression.
3323 /// Subclasses may override this routine to provide different behavior.
3324 ExprResult RebuildCXXDeleteExpr(SourceLocation StartLoc,
3325 bool IsGlobalDelete,
3326 bool IsArrayForm,
3327 Expr *Operand) {
3328 return getSema().ActOnCXXDelete(StartLoc, IsGlobalDelete, IsArrayForm,
3329 Operand);
3330 }
3331
3332 /// Build a new type trait expression.
3333 ///
3334 /// By default, performs semantic analysis to build the new expression.
3335 /// Subclasses may override this routine to provide different behavior.
3336 ExprResult RebuildTypeTrait(TypeTrait Trait,
3337 SourceLocation StartLoc,
3338 ArrayRef<TypeSourceInfo *> Args,
3339 SourceLocation RParenLoc) {
3340 return getSema().BuildTypeTrait(Trait, StartLoc, Args, RParenLoc);
3341 }
3342
3343 /// Build a new array type trait expression.
3344 ///
3345 /// By default, performs semantic analysis to build the new expression.
3346 /// Subclasses may override this routine to provide different behavior.
3347 ExprResult RebuildArrayTypeTrait(ArrayTypeTrait Trait,
3348 SourceLocation StartLoc,
3349 TypeSourceInfo *TSInfo,
3350 Expr *DimExpr,
3351 SourceLocation RParenLoc) {
3352 return getSema().BuildArrayTypeTrait(Trait, StartLoc, TSInfo, DimExpr, RParenLoc);
3353 }
3354
3355 /// Build a new expression trait expression.
3356 ///
3357 /// By default, performs semantic analysis to build the new expression.
3358 /// Subclasses may override this routine to provide different behavior.
3359 ExprResult RebuildExpressionTrait(ExpressionTrait Trait,
3360 SourceLocation StartLoc,
3361 Expr *Queried,
3362 SourceLocation RParenLoc) {
3363 return getSema().BuildExpressionTrait(Trait, StartLoc, Queried, RParenLoc);
3364 }
3365
3366 /// Build a new (previously unresolved) declaration reference
3367 /// expression.
3368 ///
3369 /// By default, performs semantic analysis to build the new expression.
3370 /// Subclasses may override this routine to provide different behavior.
3371 ExprResult RebuildDependentScopeDeclRefExpr(
3372 NestedNameSpecifierLoc QualifierLoc,
3373 SourceLocation TemplateKWLoc,
3374 const DeclarationNameInfo &NameInfo,
3375 const TemplateArgumentListInfo *TemplateArgs,
3376 bool IsAddressOfOperand,
3377 TypeSourceInfo **RecoveryTSI) {
3378 CXXScopeSpec SS;
3379 SS.Adopt(QualifierLoc);
3380
3381 if (TemplateArgs || TemplateKWLoc.isValid())
3382 return getSema().BuildQualifiedTemplateIdExpr(SS, TemplateKWLoc, NameInfo,
3383 TemplateArgs);
3384
3385 return getSema().BuildQualifiedDeclarationNameExpr(
3386 SS, NameInfo, IsAddressOfOperand, /*S*/nullptr, RecoveryTSI);
3387 }
3388
3389 /// Build a new template-id expression.
3390 ///
3391 /// By default, performs semantic analysis to build the new expression.
3392 /// Subclasses may override this routine to provide different behavior.
3393 ExprResult RebuildTemplateIdExpr(const CXXScopeSpec &SS,
3394 SourceLocation TemplateKWLoc,
3395 LookupResult &R,
3396 bool RequiresADL,
3397 const TemplateArgumentListInfo *TemplateArgs) {
3398 return getSema().BuildTemplateIdExpr(SS, TemplateKWLoc, R, RequiresADL,
3399 TemplateArgs);
3400 }
3401
3402 /// Build a new object-construction expression.
3403 ///
3404 /// By default, performs semantic analysis to build the new expression.
3405 /// Subclasses may override this routine to provide different behavior.
3406 ExprResult RebuildCXXConstructExpr(QualType T,
3407 SourceLocation Loc,
3408 CXXConstructorDecl *Constructor,
3409 bool IsElidable,
3410 MultiExprArg Args,
3411 bool HadMultipleCandidates,
3412 bool ListInitialization,
3413 bool StdInitListInitialization,
3414 bool RequiresZeroInit,
3415 CXXConstructExpr::ConstructionKind ConstructKind,
3416 SourceRange ParenRange) {
3417 // Reconstruct the constructor we originally found, which might be
3418 // different if this is a call to an inherited constructor.
3419 CXXConstructorDecl *FoundCtor = Constructor;
3420 if (Constructor->isInheritingConstructor())
3421 FoundCtor = Constructor->getInheritedConstructor().getConstructor();
3422
3423 SmallVector<Expr *, 8> ConvertedArgs;
3424 if (getSema().CompleteConstructorCall(FoundCtor, T, Args, Loc,
3425 ConvertedArgs))
3426 return ExprError();
3427
3428 return getSema().BuildCXXConstructExpr(Loc, T, Constructor,
3429 IsElidable,
3430 ConvertedArgs,
3431 HadMultipleCandidates,
3432 ListInitialization,
3433 StdInitListInitialization,
3434 RequiresZeroInit, ConstructKind,
3435 ParenRange);
3436 }
3437
3438 /// Build a new implicit construction via inherited constructor
3439 /// expression.
3440 ExprResult RebuildCXXInheritedCtorInitExpr(QualType T, SourceLocation Loc,
3441 CXXConstructorDecl *Constructor,
3442 bool ConstructsVBase,
3443 bool InheritedFromVBase) {
3444 return new (getSema().Context) CXXInheritedCtorInitExpr(
3445 Loc, T, Constructor, ConstructsVBase, InheritedFromVBase);
3446 }
3447
3448 /// Build a new object-construction expression.
3449 ///
3450 /// By default, performs semantic analysis to build the new expression.
3451 /// Subclasses may override this routine to provide different behavior.
3452 ExprResult RebuildCXXTemporaryObjectExpr(TypeSourceInfo *TSInfo,
3453 SourceLocation LParenOrBraceLoc,
3454 MultiExprArg Args,
3455 SourceLocation RParenOrBraceLoc,
3456 bool ListInitialization) {
3457 return getSema().BuildCXXTypeConstructExpr(
3458 TSInfo, LParenOrBraceLoc, Args, RParenOrBraceLoc, ListInitialization);
3459 }
3460
3461 /// Build a new object-construction expression.
3462 ///
3463 /// By default, performs semantic analysis to build the new expression.
3464 /// Subclasses may override this routine to provide different behavior.
3465 ExprResult RebuildCXXUnresolvedConstructExpr(TypeSourceInfo *TSInfo,
3466 SourceLocation LParenLoc,
3467 MultiExprArg Args,
3468 SourceLocation RParenLoc,
3469 bool ListInitialization) {
3470 return getSema().BuildCXXTypeConstructExpr(TSInfo, LParenLoc, Args,
3471 RParenLoc, ListInitialization);
3472 }
3473
3474 /// Build a new member reference expression.
3475 ///
3476 /// By default, performs semantic analysis to build the new expression.
3477 /// Subclasses may override this routine to provide different behavior.
3478 ExprResult RebuildCXXDependentScopeMemberExpr(Expr *BaseE,
3479 QualType BaseType,
3480 bool IsArrow,
3481 SourceLocation OperatorLoc,
3482 NestedNameSpecifierLoc QualifierLoc,
3483 SourceLocation TemplateKWLoc,
3484 NamedDecl *FirstQualifierInScope,
3485 const DeclarationNameInfo &MemberNameInfo,
3486 const TemplateArgumentListInfo *TemplateArgs) {
3487 CXXScopeSpec SS;
3488 SS.Adopt(QualifierLoc);
3489
3490 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3491 OperatorLoc, IsArrow,
3492 SS, TemplateKWLoc,
3493 FirstQualifierInScope,
3494 MemberNameInfo,
3495 TemplateArgs, /*S*/nullptr);
3496 }
3497
3498 /// Build a new member reference expression.
3499 ///
3500 /// By default, performs semantic analysis to build the new expression.
3501 /// Subclasses may override this routine to provide different behavior.
3502 ExprResult RebuildUnresolvedMemberExpr(Expr *BaseE, QualType BaseType,
3503 SourceLocation OperatorLoc,
3504 bool IsArrow,
3505 NestedNameSpecifierLoc QualifierLoc,
3506 SourceLocation TemplateKWLoc,
3507 NamedDecl *FirstQualifierInScope,
3508 LookupResult &R,
3509 const TemplateArgumentListInfo *TemplateArgs) {
3510 CXXScopeSpec SS;
3511 SS.Adopt(QualifierLoc);
3512
3513 return SemaRef.BuildMemberReferenceExpr(BaseE, BaseType,
3514 OperatorLoc, IsArrow,
3515 SS, TemplateKWLoc,
3516 FirstQualifierInScope,
3517 R, TemplateArgs, /*S*/nullptr);
3518 }
3519
3520 /// Build a new noexcept expression.
3521 ///
3522 /// By default, performs semantic analysis to build the new expression.
3523 /// Subclasses may override this routine to provide different behavior.
3524 ExprResult RebuildCXXNoexceptExpr(SourceRange Range, Expr *Arg) {
3525 return SemaRef.BuildCXXNoexceptExpr(Range.getBegin(), Arg, Range.getEnd());
3526 }
3527
3528 /// Build a new expression to compute the length of a parameter pack.
3529 ExprResult RebuildSizeOfPackExpr(SourceLocation OperatorLoc, NamedDecl *Pack,
3530 SourceLocation PackLoc,
3531 SourceLocation RParenLoc,
3532 std::optional<unsigned> Length,
3533 ArrayRef<TemplateArgument> PartialArgs) {
3534 return SizeOfPackExpr::Create(SemaRef.Context, OperatorLoc, Pack, PackLoc,
3535 RParenLoc, Length, PartialArgs);
3536 }
3537
3538 /// Build a new expression representing a call to a source location
3539 /// builtin.
3540 ///
3541 /// By default, performs semantic analysis to build the new expression.
3542 /// Subclasses may override this routine to provide different behavior.
3543 ExprResult RebuildSourceLocExpr(SourceLocExpr::IdentKind Kind,
3544 QualType ResultTy, SourceLocation BuiltinLoc,
3545 SourceLocation RPLoc,
3546 DeclContext *ParentContext) {
3547 return getSema().BuildSourceLocExpr(Kind, ResultTy, BuiltinLoc, RPLoc,
3548 ParentContext);
3549 }
3550
3551 /// Build a new Objective-C boxed expression.
3552 ///
3553 /// By default, performs semantic analysis to build the new expression.
3554 /// Subclasses may override this routine to provide different behavior.
3555 ExprResult RebuildConceptSpecializationExpr(NestedNameSpecifierLoc NNS,
3556 SourceLocation TemplateKWLoc, DeclarationNameInfo ConceptNameInfo,
3557 NamedDecl *FoundDecl, ConceptDecl *NamedConcept,
3558 TemplateArgumentListInfo *TALI) {
3559 CXXScopeSpec SS;
3560 SS.Adopt(NNS);
3561 ExprResult Result = getSema().CheckConceptTemplateId(SS, TemplateKWLoc,
3562 ConceptNameInfo,
3563 FoundDecl,
3564 NamedConcept, TALI);
3565 if (Result.isInvalid())
3566 return ExprError();
3567 return Result;
3568 }
3569
3570 /// \brief Build a new requires expression.
3571 ///
3572 /// By default, performs semantic analysis to build the new expression.
3573 /// Subclasses may override this routine to provide different behavior.
3574 ExprResult RebuildRequiresExpr(SourceLocation RequiresKWLoc,
3575 RequiresExprBodyDecl *Body,
3576 ArrayRef<ParmVarDecl *> LocalParameters,
3577 ArrayRef<concepts::Requirement *> Requirements,
3578 SourceLocation ClosingBraceLoc) {
3579 return RequiresExpr::Create(SemaRef.Context, RequiresKWLoc, Body,
3580 LocalParameters, Requirements, ClosingBraceLoc);
3581 }
3582
3583 concepts::TypeRequirement *
3584 RebuildTypeRequirement(
3585 concepts::Requirement::SubstitutionDiagnostic *SubstDiag) {
3586 return SemaRef.BuildTypeRequirement(SubstDiag);
3587 }
3588
3589 concepts::TypeRequirement *RebuildTypeRequirement(TypeSourceInfo *T) {
3590 return SemaRef.BuildTypeRequirement(T);
3591 }
3592
3593 concepts::ExprRequirement *
3594 RebuildExprRequirement(
3595 concepts::Requirement::SubstitutionDiagnostic *SubstDiag, bool IsSimple,
3596 SourceLocation NoexceptLoc,
3597 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3598 return SemaRef.BuildExprRequirement(SubstDiag, IsSimple, NoexceptLoc,
3599 std::move(Ret));
3600 }
3601
3602 concepts::ExprRequirement *
3603 RebuildExprRequirement(Expr *E, bool IsSimple, SourceLocation NoexceptLoc,
3604 concepts::ExprRequirement::ReturnTypeRequirement Ret) {
3605 return SemaRef.BuildExprRequirement(E, IsSimple, NoexceptLoc,
3606 std::move(Ret));
3607 }
3608
3609 concepts::NestedRequirement *
3610 RebuildNestedRequirement(StringRef InvalidConstraintEntity,
3611 const ASTConstraintSatisfaction &Satisfaction) {
3612 return SemaRef.BuildNestedRequirement(InvalidConstraintEntity,
3613 Satisfaction);
3614 }
3615
3616 concepts::NestedRequirement *RebuildNestedRequirement(Expr *Constraint) {
3617 return SemaRef.BuildNestedRequirement(Constraint);
3618 }
3619
3620 /// \brief Build a new Objective-C boxed expression.
3621 ///
3622 /// By default, performs semantic analysis to build the new expression.
3623 /// Subclasses may override this routine to provide different behavior.
3624 ExprResult RebuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) {
3625 return getSema().BuildObjCBoxedExpr(SR, ValueExpr);
3626 }
3627
3628 /// Build a new Objective-C array literal.
3629 ///
3630 /// By default, performs semantic analysis to build the new expression.
3631 /// Subclasses may override this routine to provide different behavior.
3632 ExprResult RebuildObjCArrayLiteral(SourceRange Range,
3633 Expr **Elements, unsigned NumElements) {
3634 return getSema().BuildObjCArrayLiteral(Range,
3635 MultiExprArg(Elements, NumElements));
3636 }
3637
3638 ExprResult RebuildObjCSubscriptRefExpr(SourceLocation RB,
3639 Expr *Base, Expr *Key,
3640 ObjCMethodDecl *getterMethod,
3641 ObjCMethodDecl *setterMethod) {
3642 return getSema().BuildObjCSubscriptExpression(RB, Base, Key,
3643 getterMethod, setterMethod);
3644 }
3645
3646 /// Build a new Objective-C dictionary literal.
3647 ///
3648 /// By default, performs semantic analysis to build the new expression.
3649 /// Subclasses may override this routine to provide different behavior.
3650 ExprResult RebuildObjCDictionaryLiteral(SourceRange Range,
3651 MutableArrayRef<ObjCDictionaryElement> Elements) {
3652 return getSema().BuildObjCDictionaryLiteral(Range, Elements);
3653 }
3654
3655 /// Build a new Objective-C \@encode expression.
3656 ///
3657 /// By default, performs semantic analysis to build the new expression.
3658 /// Subclasses may override this routine to provide different behavior.
3659 ExprResult RebuildObjCEncodeExpr(SourceLocation AtLoc,
3660 TypeSourceInfo *EncodeTypeInfo,
3661 SourceLocation RParenLoc) {
3662 return SemaRef.BuildObjCEncodeExpression(AtLoc, EncodeTypeInfo, RParenLoc);
3663 }
3664
3665 /// Build a new Objective-C class message.
3666 ExprResult RebuildObjCMessageExpr(TypeSourceInfo *ReceiverTypeInfo,
3667 Selector Sel,
3668 ArrayRef<SourceLocation> SelectorLocs,
3669 ObjCMethodDecl *Method,
3670 SourceLocation LBracLoc,
3671 MultiExprArg Args,
3672 SourceLocation RBracLoc) {
3673 return SemaRef.BuildClassMessage(ReceiverTypeInfo,
3674 ReceiverTypeInfo->getType(),
3675 /*SuperLoc=*/SourceLocation(),
3676 Sel, Method, LBracLoc, SelectorLocs,
3677 RBracLoc, Args);
3678 }
3679
3680 /// Build a new Objective-C instance message.
3681 ExprResult RebuildObjCMessageExpr(Expr *Receiver,
3682 Selector Sel,
3683 ArrayRef<SourceLocation> SelectorLocs,
3684 ObjCMethodDecl *Method,
3685 SourceLocation LBracLoc,
3686 MultiExprArg Args,
3687 SourceLocation RBracLoc) {
3688 return SemaRef.BuildInstanceMessage(Receiver,
3689 Receiver->getType(),
3690 /*SuperLoc=*/SourceLocation(),
3691 Sel, Method, LBracLoc, SelectorLocs,
3692 RBracLoc, Args);
3693 }
3694
3695 /// Build a new Objective-C instance/class message to 'super'.
3696 ExprResult RebuildObjCMessageExpr(SourceLocation SuperLoc,
3697 Selector Sel,
3698 ArrayRef<SourceLocation> SelectorLocs,
3699 QualType SuperType,
3700 ObjCMethodDecl *Method,
3701 SourceLocation LBracLoc,
3702 MultiExprArg Args,
3703 SourceLocation RBracLoc) {
3704 return Method->isInstanceMethod() ? SemaRef.BuildInstanceMessage(nullptr,
3705 SuperType,
3706 SuperLoc,
3707 Sel, Method, LBracLoc, SelectorLocs,
3708 RBracLoc, Args)
3709 : SemaRef.BuildClassMessage(nullptr,
3710 SuperType,
3711 SuperLoc,
3712 Sel, Method, LBracLoc, SelectorLocs,
3713 RBracLoc, Args);
3714
3715
3716 }
3717
3718 /// Build a new Objective-C ivar reference expression.
3719 ///
3720 /// By default, performs semantic analysis to build the new expression.
3721 /// Subclasses may override this routine to provide different behavior.
3722 ExprResult RebuildObjCIvarRefExpr(Expr *BaseArg, ObjCIvarDecl *Ivar,
3723 SourceLocation IvarLoc,
3724 bool IsArrow, bool IsFreeIvar) {
3725 CXXScopeSpec SS;
3726 DeclarationNameInfo NameInfo(Ivar->getDeclName(), IvarLoc);
3727 ExprResult Result = getSema().BuildMemberReferenceExpr(
3728 BaseArg, BaseArg->getType(),
3729 /*FIXME:*/ IvarLoc, IsArrow, SS, SourceLocation(),
3730 /*FirstQualifierInScope=*/nullptr, NameInfo,
3731 /*TemplateArgs=*/nullptr,
3732 /*S=*/nullptr);
3733 if (IsFreeIvar && Result.isUsable())
3734 cast<ObjCIvarRefExpr>(Result.get())->setIsFreeIvar(IsFreeIvar);
3735 return Result;
3736 }
3737
3738 /// Build a new Objective-C property reference expression.
3739 ///
3740 /// By default, performs semantic analysis to build the new expression.
3741 /// Subclasses may override this routine to provide different behavior.
3742 ExprResult RebuildObjCPropertyRefExpr(Expr *BaseArg,
3743 ObjCPropertyDecl *Property,
3744 SourceLocation PropertyLoc) {
3745 CXXScopeSpec SS;
3746 DeclarationNameInfo NameInfo(Property->getDeclName(), PropertyLoc);
3747 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3748 /*FIXME:*/PropertyLoc,
3749 /*IsArrow=*/false,
3750 SS, SourceLocation(),
3751 /*FirstQualifierInScope=*/nullptr,
3752 NameInfo,
3753 /*TemplateArgs=*/nullptr,
3754 /*S=*/nullptr);
3755 }
3756
3757 /// Build a new Objective-C property reference expression.
3758 ///
3759 /// By default, performs semantic analysis to build the new expression.
3760 /// Subclasses may override this routine to provide different behavior.
3761 ExprResult RebuildObjCPropertyRefExpr(Expr *Base, QualType T,
3762 ObjCMethodDecl *Getter,
3763 ObjCMethodDecl *Setter,
3764 SourceLocation PropertyLoc) {
3765 // Since these expressions can only be value-dependent, we do not
3766 // need to perform semantic analysis again.
3767 return Owned(
3768 new (getSema().Context) ObjCPropertyRefExpr(Getter, Setter, T,
3769 VK_LValue, OK_ObjCProperty,
3770 PropertyLoc, Base));
3771 }
3772
3773 /// Build a new Objective-C "isa" expression.
3774 ///
3775 /// By default, performs semantic analysis to build the new expression.
3776 /// Subclasses may override this routine to provide different behavior.
3777 ExprResult RebuildObjCIsaExpr(Expr *BaseArg, SourceLocation IsaLoc,
3778 SourceLocation OpLoc, bool IsArrow) {
3779 CXXScopeSpec SS;
3780 DeclarationNameInfo NameInfo(&getSema().Context.Idents.get("isa"), IsaLoc);
3781 return getSema().BuildMemberReferenceExpr(BaseArg, BaseArg->getType(),
3782 OpLoc, IsArrow,
3783 SS, SourceLocation(),
3784 /*FirstQualifierInScope=*/nullptr,
3785 NameInfo,
3786 /*TemplateArgs=*/nullptr,
3787 /*S=*/nullptr);
3788 }
3789
3790 /// Build a new shuffle vector expression.
3791 ///
3792 /// By default, performs semantic analysis to build the new expression.
3793 /// Subclasses may override this routine to provide different behavior.
3794 ExprResult RebuildShuffleVectorExpr(SourceLocation BuiltinLoc,
3795 MultiExprArg SubExprs,
3796 SourceLocation RParenLoc) {
3797 // Find the declaration for __builtin_shufflevector
3798 const IdentifierInfo &Name
3799 = SemaRef.Context.Idents.get("__builtin_shufflevector");
3800 TranslationUnitDecl *TUDecl = SemaRef.Context.getTranslationUnitDecl();
3801 DeclContext::lookup_result Lookup = TUDecl->lookup(DeclarationName(&Name));
3802 assert(!Lookup.empty() && "No __builtin_shufflevector?")(static_cast <bool> (!Lookup.empty() && "No __builtin_shufflevector?"
) ? void (0) : __assert_fail ("!Lookup.empty() && \"No __builtin_shufflevector?\""
, "clang/lib/Sema/TreeTransform.h", 3802, __extension__ __PRETTY_FUNCTION__
))
;
3803
3804 // Build a reference to the __builtin_shufflevector builtin
3805 FunctionDecl *Builtin = cast<FunctionDecl>(Lookup.front());
3806 Expr *Callee = new (SemaRef.Context)
3807 DeclRefExpr(SemaRef.Context, Builtin, false,
3808 SemaRef.Context.BuiltinFnTy, VK_PRValue, BuiltinLoc);
3809 QualType CalleePtrTy = SemaRef.Context.getPointerType(Builtin->getType());
3810 Callee = SemaRef.ImpCastExprToType(Callee, CalleePtrTy,
3811 CK_BuiltinFnToFnPtr).get();
3812
3813 // Build the CallExpr
3814 ExprResult TheCall = CallExpr::Create(
3815 SemaRef.Context, Callee, SubExprs, Builtin->getCallResultType(),
3816 Expr::getValueKindForType(Builtin->getReturnType()), RParenLoc,
3817 FPOptionsOverride());
3818
3819 // Type-check the __builtin_shufflevector expression.
3820 return SemaRef.SemaBuiltinShuffleVector(cast<CallExpr>(TheCall.get()));
3821 }
3822
3823 /// Build a new convert vector expression.
3824 ExprResult RebuildConvertVectorExpr(SourceLocation BuiltinLoc,
3825 Expr *SrcExpr, TypeSourceInfo *DstTInfo,
3826 SourceLocation RParenLoc) {
3827 return SemaRef.SemaConvertVectorExpr(SrcExpr, DstTInfo,
3828 BuiltinLoc, RParenLoc);
3829 }
3830
3831 /// Build a new template argument pack expansion.
3832 ///
3833 /// By default, performs semantic analysis to build a new pack expansion
3834 /// for a template argument. Subclasses may override this routine to provide
3835 /// different behavior.
3836 TemplateArgumentLoc
3837 RebuildPackExpansion(TemplateArgumentLoc Pattern, SourceLocation EllipsisLoc,
3838 std::optional<unsigned> NumExpansions) {
3839 switch (Pattern.getArgument().getKind()) {
3840 case TemplateArgument::Expression: {
3841 ExprResult Result
3842 = getSema().CheckPackExpansion(Pattern.getSourceExpression(),
3843 EllipsisLoc, NumExpansions);
3844 if (Result.isInvalid())
3845 return TemplateArgumentLoc();
3846
3847 return TemplateArgumentLoc(Result.get(), Result.get());
3848 }
3849
3850 case TemplateArgument::Template:
3851 return TemplateArgumentLoc(
3852 SemaRef.Context,
3853 TemplateArgument(Pattern.getArgument().getAsTemplate(),
3854 NumExpansions),
3855 Pattern.getTemplateQualifierLoc(), Pattern.getTemplateNameLoc(),
3856 EllipsisLoc);
3857
3858 case TemplateArgument::Null:
3859 case TemplateArgument::Integral:
3860 case TemplateArgument::Declaration:
3861 case TemplateArgument::Pack:
3862 case TemplateArgument::TemplateExpansion:
3863 case TemplateArgument::NullPtr:
3864 llvm_unreachable("Pack expansion pattern has no parameter packs")::llvm::llvm_unreachable_internal("Pack expansion pattern has no parameter packs"
, "clang/lib/Sema/TreeTransform.h", 3864)
;
3865
3866 case TemplateArgument::Type:
3867 if (TypeSourceInfo *Expansion
3868 = getSema().CheckPackExpansion(Pattern.getTypeSourceInfo(),
3869 EllipsisLoc,
3870 NumExpansions))
3871 return TemplateArgumentLoc(TemplateArgument(Expansion->getType()),
3872 Expansion);
3873 break;
3874 }
3875
3876 return TemplateArgumentLoc();
3877 }
3878
3879 /// Build a new expression pack expansion.
3880 ///
3881 /// By default, performs semantic analysis to build a new pack expansion
3882 /// for an expression. Subclasses may override this routine to provide
3883 /// different behavior.
3884 ExprResult RebuildPackExpansion(Expr *Pattern, SourceLocation EllipsisLoc,
3885 std::optional<unsigned> NumExpansions) {
3886 return getSema().CheckPackExpansion(Pattern, EllipsisLoc, NumExpansions);
3887 }
3888
3889 /// Build a new C++1z fold-expression.
3890 ///
3891 /// By default, performs semantic analysis in order to build a new fold
3892 /// expression.
3893 ExprResult RebuildCXXFoldExpr(UnresolvedLookupExpr *ULE,
3894 SourceLocation LParenLoc, Expr *LHS,
3895 BinaryOperatorKind Operator,
3896 SourceLocation EllipsisLoc, Expr *RHS,
3897 SourceLocation RParenLoc,
3898 std::optional<unsigned> NumExpansions) {
3899 return getSema().BuildCXXFoldExpr(ULE, LParenLoc, LHS, Operator,
3900 EllipsisLoc, RHS, RParenLoc,
3901 NumExpansions);
3902 }
3903
3904 /// Build an empty C++1z fold-expression with the given operator.
3905 ///
3906 /// By default, produces the fallback value for the fold-expression, or
3907 /// produce an error if there is no fallback value.
3908 ExprResult RebuildEmptyCXXFoldExpr(SourceLocation EllipsisLoc,
3909 BinaryOperatorKind Operator) {
3910 return getSema().BuildEmptyCXXFoldExpr(EllipsisLoc, Operator);
3911 }
3912
3913 /// Build a new atomic operation expression.
3914 ///
3915 /// By default, performs semantic analysis to build the new expression.
3916 /// Subclasses may override this routine to provide different behavior.
3917 ExprResult RebuildAtomicExpr(SourceLocation BuiltinLoc, MultiExprArg SubExprs,
3918 AtomicExpr::AtomicOp Op,
3919 SourceLocation RParenLoc) {
3920 // Use this for all of the locations, since we don't know the difference
3921 // between the call and the expr at this point.
3922 SourceRange Range{BuiltinLoc, RParenLoc};
3923 return getSema().BuildAtomicExpr(Range, Range, RParenLoc, SubExprs, Op,
3924 Sema::AtomicArgumentOrder::AST);
3925 }
3926
3927 ExprResult RebuildRecoveryExpr(SourceLocation BeginLoc, SourceLocation EndLoc,
3928 ArrayRef<Expr *> SubExprs, QualType Type) {
3929 return getSema().CreateRecoveryExpr(BeginLoc, EndLoc, SubExprs, Type);
3930 }
3931
3932private:
3933 TypeLoc TransformTypeInObjectScope(TypeLoc TL,
3934 QualType ObjectType,
3935 NamedDecl *FirstQualifierInScope,
3936 CXXScopeSpec &SS);
3937
3938 TypeSourceInfo *TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
3939 QualType ObjectType,
3940 NamedDecl *FirstQualifierInScope,
3941 CXXScopeSpec &SS);
3942
3943 TypeSourceInfo *TransformTSIInObjectScope(TypeLoc TL, QualType ObjectType,
3944 NamedDecl *FirstQualifierInScope,
3945 CXXScopeSpec &SS);
3946
3947 QualType TransformDependentNameType(TypeLocBuilder &TLB,
3948 DependentNameTypeLoc TL,
3949 bool DeducibleTSTContext);
3950};
3951
3952template <typename Derived>
3953StmtResult TreeTransform<Derived>::TransformStmt(Stmt *S, StmtDiscardKind SDK) {
3954 if (!S)
3955 return S;
3956
3957 switch (S->getStmtClass()) {
3958 case Stmt::NoStmtClass: break;
3959
3960 // Transform individual statement nodes
3961 // Pass SDK into statements that can produce a value
3962#define STMT(Node, Parent) \
3963 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(S));
3964#define VALUESTMT(Node, Parent) \
3965 case Stmt::Node##Class: \
3966 return getDerived().Transform##Node(cast<Node>(S), SDK);
3967#define ABSTRACT_STMT(Node)
3968#define EXPR(Node, Parent)
3969#include "clang/AST/StmtNodes.inc"
3970
3971 // Transform expressions by calling TransformExpr.
3972#define STMT(Node, Parent)
3973#define ABSTRACT_STMT(Stmt)
3974#define EXPR(Node, Parent) case Stmt::Node##Class:
3975#include "clang/AST/StmtNodes.inc"
3976 {
3977 ExprResult E = getDerived().TransformExpr(cast<Expr>(S));
3978
3979 if (SDK == SDK_StmtExprResult)
3980 E = getSema().ActOnStmtExprResult(E);
3981 return getSema().ActOnExprStmt(E, SDK == SDK_Discarded);
3982 }
3983 }
3984
3985 return S;
3986}
3987
3988template<typename Derived>
3989OMPClause *TreeTransform<Derived>::TransformOMPClause(OMPClause *S) {
3990 if (!S)
3991 return S;
3992
3993 switch (S->getClauseKind()) {
3994 default: break;
3995 // Transform individual clause nodes
3996#define GEN_CLANG_CLAUSE_CLASS
3997#define CLAUSE_CLASS(Enum, Str, Class) \
3998 case Enum: \
3999 return getDerived().Transform##Class(cast<Class>(S));
4000#include "llvm/Frontend/OpenMP/OMP.inc"
4001 }
4002
4003 return S;
4004}
4005
4006
4007template<typename Derived>
4008ExprResult TreeTransform<Derived>::TransformExpr(Expr *E) {
4009 if (!E)
4010 return E;
4011
4012 switch (E->getStmtClass()) {
4013 case Stmt::NoStmtClass: break;
4014#define STMT(Node, Parent) case Stmt::Node##Class: break;
4015#define ABSTRACT_STMT(Stmt)
4016#define EXPR(Node, Parent) \
4017 case Stmt::Node##Class: return getDerived().Transform##Node(cast<Node>(E));
4018#include "clang/AST/StmtNodes.inc"
4019 }
4020
4021 return E;
4022}
4023
4024template<typename Derived>
4025ExprResult TreeTransform<Derived>::TransformInitializer(Expr *Init,
4026 bool NotCopyInit) {
4027 // Initializers are instantiated like expressions, except that various outer
4028 // layers are stripped.
4029 if (!Init)
4030 return Init;
4031
4032 if (auto *FE = dyn_cast<FullExpr>(Init))
4033 Init = FE->getSubExpr();
4034
4035 if (auto *AIL = dyn_cast<ArrayInitLoopExpr>(Init)) {
4036 OpaqueValueExpr *OVE = AIL->getCommonExpr();
4037 Init = OVE->getSourceExpr();
4038 }
4039
4040 if (MaterializeTemporaryExpr *MTE = dyn_cast<MaterializeTemporaryExpr>(Init))
4041 Init = MTE->getSubExpr();
4042
4043 while (CXXBindTemporaryExpr *Binder = dyn_cast<CXXBindTemporaryExpr>(Init))
4044 Init = Binder->getSubExpr();
4045
4046 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Init))
4047 Init = ICE->getSubExprAsWritten();
4048
4049 if (CXXStdInitializerListExpr *ILE =
4050 dyn_cast<CXXStdInitializerListExpr>(Init))
4051 return TransformInitializer(ILE->getSubExpr(), NotCopyInit);
4052
4053 // If this is copy-initialization, we only need to reconstruct
4054 // InitListExprs. Other forms of copy-initialization will be a no-op if
4055 // the initializer is already the right type.
4056 CXXConstructExpr *Construct = dyn_cast<CXXConstructExpr>(Init);
4057 if (!NotCopyInit && !(Construct && Construct->isListInitialization()))
4058 return getDerived().TransformExpr(Init);
4059
4060 // Revert value-initialization back to empty parens.
4061 if (CXXScalarValueInitExpr *VIE = dyn_cast<CXXScalarValueInitExpr>(Init)) {
4062 SourceRange Parens = VIE->getSourceRange();
4063 return getDerived().RebuildParenListExpr(Parens.getBegin(), std::nullopt,
4064 Parens.getEnd());
4065 }
4066
4067 // FIXME: We shouldn't build ImplicitValueInitExprs for direct-initialization.
4068 if (isa<ImplicitValueInitExpr>(Init))
4069 return getDerived().RebuildParenListExpr(SourceLocation(), std::nullopt,
4070 SourceLocation());
4071
4072 // Revert initialization by constructor back to a parenthesized or braced list
4073 // of expressions. Any other form of initializer can just be reused directly.
4074 if (!Construct || isa<CXXTemporaryObjectExpr>(Construct))
4075 return getDerived().TransformExpr(Init);
4076
4077 // If the initialization implicitly converted an initializer list to a
4078 // std::initializer_list object, unwrap the std::initializer_list too.
4079 if (Construct && Construct->isStdInitListInitialization())
4080 return TransformInitializer(Construct->getArg(0), NotCopyInit);
4081
4082 // Enter a list-init context if this was list initialization.
4083 EnterExpressionEvaluationContext Context(
4084 getSema(), EnterExpressionEvaluationContext::InitList,
4085 Construct->isListInitialization());
4086
4087 SmallVector<Expr*, 8> NewArgs;
4088 bool ArgChanged = false;
4089 if (getDerived().TransformExprs(Construct->getArgs(), Construct->getNumArgs(),
4090 /*IsCall*/true, NewArgs, &ArgChanged))
4091 return ExprError();
4092
4093 // If this was list initialization, revert to syntactic list form.
4094 if (Construct->isListInitialization())
4095 return getDerived().RebuildInitList(Construct->getBeginLoc(), NewArgs,
4096 Construct->getEndLoc());
4097
4098 // Build a ParenListExpr to represent anything else.
4099 SourceRange Parens = Construct->getParenOrBraceRange();
4100 if (Parens.isInvalid()) {
4101 // This was a variable declaration's initialization for which no initializer
4102 // was specified.
4103 assert(NewArgs.empty() &&(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "clang/lib/Sema/TreeTransform.h", 4104, __extension__ __PRETTY_FUNCTION__
))
4104 "no parens or braces but have direct init with arguments?")(static_cast <bool> (NewArgs.empty() && "no parens or braces but have direct init with arguments?"
) ? void (0) : __assert_fail ("NewArgs.empty() && \"no parens or braces but have direct init with arguments?\""
, "clang/lib/Sema/TreeTransform.h", 4104, __extension__ __PRETTY_FUNCTION__
))
;
4105 return ExprEmpty();
4106 }
4107 return getDerived().RebuildParenListExpr(Parens.getBegin(), NewArgs,
4108 Parens.getEnd());
4109}
4110
4111template<typename Derived>
4112bool TreeTransform<Derived>::TransformExprs(Expr *const *Inputs,
4113 unsigned NumInputs,
4114 bool IsCall,
4115 SmallVectorImpl<Expr *> &Outputs,
4116 bool *ArgChanged) {
4117 for (unsigned I = 0; I != NumInputs; ++I) {
4118 // If requested, drop call arguments that need to be dropped.
4119 if (IsCall && getDerived().DropCallArgument(Inputs[I])) {
4120 if (ArgChanged)
4121 *ArgChanged = true;
4122
4123 break;
4124 }
4125
4126 if (PackExpansionExpr *Expansion = dyn_cast<PackExpansionExpr>(Inputs[I])) {
4127 Expr *Pattern = Expansion->getPattern();
4128
4129 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4130 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4131 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 4131, __extension__ __PRETTY_FUNCTION__
))
;
4132
4133 // Determine whether the set of unexpanded parameter packs can and should
4134 // be expanded.
4135 bool Expand = true;
4136 bool RetainExpansion = false;
4137 std::optional<unsigned> OrigNumExpansions = Expansion->getNumExpansions();
4138 std::optional<unsigned> NumExpansions = OrigNumExpansions;
4139 if (getDerived().TryExpandParameterPacks(Expansion->getEllipsisLoc(),
4140 Pattern->getSourceRange(),
4141 Unexpanded,
4142 Expand, RetainExpansion,
4143 NumExpansions))
4144 return true;
4145
4146 if (!Expand) {
4147 // The transform has determined that we should perform a simple
4148 // transformation on the pack expansion, producing another pack
4149 // expansion.
4150 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4151 ExprResult OutPattern = getDerived().TransformExpr(Pattern);
4152 if (OutPattern.isInvalid())
4153 return true;
4154
4155 ExprResult Out = getDerived().RebuildPackExpansion(OutPattern.get(),
4156 Expansion->getEllipsisLoc(),
4157 NumExpansions);
4158 if (Out.isInvalid())
4159 return true;
4160
4161 if (ArgChanged)
4162 *ArgChanged = true;
4163 Outputs.push_back(Out.get());
4164 continue;
4165 }
4166
4167 // Record right away that the argument was changed. This needs
4168 // to happen even if the array expands to nothing.
4169 if (ArgChanged) *ArgChanged = true;
4170
4171 // The transform has determined that we should perform an elementwise
4172 // expansion of the pattern. Do so.
4173 for (unsigned I = 0; I != *NumExpansions; ++I) {
4174 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4175 ExprResult Out = getDerived().TransformExpr(Pattern);
4176 if (Out.isInvalid())
4177 return true;
4178
4179 if (Out.get()->containsUnexpandedParameterPack()) {
4180 Out = getDerived().RebuildPackExpansion(
4181 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4182 if (Out.isInvalid())
4183 return true;
4184 }
4185
4186 Outputs.push_back(Out.get());
4187 }
4188
4189 // If we're supposed to retain a pack expansion, do so by temporarily
4190 // forgetting the partially-substituted parameter pack.
4191 if (RetainExpansion) {
4192 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4193
4194 ExprResult Out = getDerived().TransformExpr(Pattern);
4195 if (Out.isInvalid())
4196 return true;
4197
4198 Out = getDerived().RebuildPackExpansion(
4199 Out.get(), Expansion->getEllipsisLoc(), OrigNumExpansions);
4200 if (Out.isInvalid())
4201 return true;
4202
4203 Outputs.push_back(Out.get());
4204 }
4205
4206 continue;
4207 }
4208
4209 ExprResult Result =
4210 IsCall ? getDerived().TransformInitializer(Inputs[I], /*DirectInit*/false)
4211 : getDerived().TransformExpr(Inputs[I]);
4212 if (Result.isInvalid())
4213 return true;
4214
4215 if (Result.get() != Inputs[I] && ArgChanged)
4216 *ArgChanged = true;
4217
4218 Outputs.push_back(Result.get());
4219 }
4220
4221 return false;
4222}
4223
4224template <typename Derived>
4225Sema::ConditionResult TreeTransform<Derived>::TransformCondition(
4226 SourceLocation Loc, VarDecl *Var, Expr *Expr, Sema::ConditionKind Kind) {
4227 if (Var) {
4228 VarDecl *ConditionVar = cast_or_null<VarDecl>(
4229 getDerived().TransformDefinition(Var->getLocation(), Var));
4230
4231 if (!ConditionVar)
4232 return Sema::ConditionError();
4233
4234 return getSema().ActOnConditionVariable(ConditionVar, Loc, Kind);
4235 }
4236
4237 if (Expr) {
4238 ExprResult CondExpr = getDerived().TransformExpr(Expr);
4239
4240 if (CondExpr.isInvalid())
4241 return Sema::ConditionError();
4242
4243 return getSema().ActOnCondition(nullptr, Loc, CondExpr.get(), Kind,
4244 /*MissingOK=*/true);
4245 }
4246
4247 return Sema::ConditionResult();
4248}
4249
4250template <typename Derived>
4251NestedNameSpecifierLoc TreeTransform<Derived>::TransformNestedNameSpecifierLoc(
4252 NestedNameSpecifierLoc NNS, QualType ObjectType,
4253 NamedDecl *FirstQualifierInScope) {
4254 SmallVector<NestedNameSpecifierLoc, 4> Qualifiers;
4255
4256 auto insertNNS = [&Qualifiers](NestedNameSpecifierLoc NNS) {
4257 for (NestedNameSpecifierLoc Qualifier = NNS; Qualifier;
4258 Qualifier = Qualifier.getPrefix())
4259 Qualifiers.push_back(Qualifier);
4260 };
4261 insertNNS(NNS);
4262
4263 CXXScopeSpec SS;
4264 while (!Qualifiers.empty()) {
4265 NestedNameSpecifierLoc Q = Qualifiers.pop_back_val();
4266 NestedNameSpecifier *QNNS = Q.getNestedNameSpecifier();
4267
4268 switch (QNNS->getKind()) {
4269 case NestedNameSpecifier::Identifier: {
4270 Sema::NestedNameSpecInfo IdInfo(QNNS->getAsIdentifier(),
4271 Q.getLocalBeginLoc(), Q.getLocalEndLoc(),
4272 ObjectType);
4273 if (SemaRef.BuildCXXNestedNameSpecifier(/*Scope=*/nullptr, IdInfo, false,
4274 SS, FirstQualifierInScope, false))
4275 return NestedNameSpecifierLoc();
4276 break;
4277 }
4278
4279 case NestedNameSpecifier::Namespace: {
4280 NamespaceDecl *NS =
4281 cast_or_null<NamespaceDecl>(getDerived().TransformDecl(
4282 Q.getLocalBeginLoc(), QNNS->getAsNamespace()));
4283 SS.Extend(SemaRef.Context, NS, Q.getLocalBeginLoc(), Q.getLocalEndLoc());
4284 break;
4285 }
4286
4287 case NestedNameSpecifier::NamespaceAlias: {
4288 NamespaceAliasDecl *Alias =
4289 cast_or_null<NamespaceAliasDecl>(getDerived().TransformDecl(
4290 Q.getLocalBeginLoc(), QNNS->getAsNamespaceAlias()));
4291 SS.Extend(SemaRef.Context, Alias, Q.getLocalBeginLoc(),
4292 Q.getLocalEndLoc());
4293 break;
4294 }
4295
4296 case NestedNameSpecifier::Global:
4297 // There is no meaningful transformation that one could perform on the
4298 // global scope.
4299 SS.MakeGlobal(SemaRef.Context, Q.getBeginLoc());
4300 break;
4301
4302 case NestedNameSpecifier::Super: {
4303 CXXRecordDecl *RD =
4304 cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
4305 SourceLocation(), QNNS->getAsRecordDecl()));
4306 SS.MakeSuper(SemaRef.Context, RD, Q.getBeginLoc(), Q.getEndLoc());
4307 break;
4308 }
4309
4310 case NestedNameSpecifier::TypeSpecWithTemplate:
4311 case NestedNameSpecifier::TypeSpec: {
4312 TypeLoc TL = TransformTypeInObjectScope(Q.getTypeLoc(), ObjectType,
4313 FirstQualifierInScope, SS);
4314
4315 if (!TL)
4316 return NestedNameSpecifierLoc();
4317
4318 QualType T = TL.getType();
4319 if (T->isDependentType() || T->isRecordType() ||
4320 (SemaRef.getLangOpts().CPlusPlus11 && T->isEnumeralType())) {
4321 if (T->isEnumeralType())
4322 SemaRef.Diag(TL.getBeginLoc(),
4323 diag::warn_cxx98_compat_enum_nested_name_spec);
4324
4325 if (const auto ETL = TL.getAs<ElaboratedTypeLoc>()) {
4326 SS.Adopt(ETL.getQualifierLoc());
4327 TL = ETL.getNamedTypeLoc();
4328 }
4329 SS.Extend(SemaRef.Context, /*FIXME:*/ SourceLocation(), TL,
4330 Q.getLocalEndLoc());
4331 break;
4332 }
4333 // If the nested-name-specifier is an invalid type def, don't emit an
4334 // error because a previous error should have already been emitted.
4335 TypedefTypeLoc TTL = TL.getAsAdjusted<TypedefTypeLoc>();
4336 if (!TTL || !TTL.getTypedefNameDecl()->isInvalidDecl()) {
4337 SemaRef.Diag(TL.getBeginLoc(), diag::err_nested_name_spec_non_tag)
4338 << T << SS.getRange();
4339 }
4340 return NestedNameSpecifierLoc();
4341 }
4342 }
4343
4344 // The qualifier-in-scope and object type only apply to the leftmost entity.
4345 FirstQualifierInScope = nullptr;
4346 ObjectType = QualType();
4347 }
4348
4349 // Don't rebuild the nested-name-specifier if we don't have to.
4350 if (SS.getScopeRep() == NNS.getNestedNameSpecifier() &&
4351 !getDerived().AlwaysRebuild())
4352 return NNS;
4353
4354 // If we can re-use the source-location data from the original
4355 // nested-name-specifier, do so.
4356 if (SS.location_size() == NNS.getDataLength() &&
4357 memcmp(SS.location_data(), NNS.getOpaqueData(), SS.location_size()) == 0)
4358 return NestedNameSpecifierLoc(SS.getScopeRep(), NNS.getOpaqueData());
4359
4360 // Allocate new nested-name-specifier location information.
4361 return SS.getWithLocInContext(SemaRef.Context);
4362}
4363
4364template<typename Derived>
4365DeclarationNameInfo
4366TreeTransform<Derived>
4367::TransformDeclarationNameInfo(const DeclarationNameInfo &NameInfo) {
4368 DeclarationName Name = NameInfo.getName();
4369 if (!Name)
4370 return DeclarationNameInfo();
4371
4372 switch (Name.getNameKind()) {
4373 case DeclarationName::Identifier:
4374 case DeclarationName::ObjCZeroArgSelector:
4375 case DeclarationName::ObjCOneArgSelector:
4376 case DeclarationName::ObjCMultiArgSelector:
4377 case DeclarationName::CXXOperatorName:
4378 case DeclarationName::CXXLiteralOperatorName:
4379 case DeclarationName::CXXUsingDirective:
4380 return NameInfo;
4381
4382 case DeclarationName::CXXDeductionGuideName: {
4383 TemplateDecl *OldTemplate = Name.getCXXDeductionGuideTemplate();
4384 TemplateDecl *NewTemplate = cast_or_null<TemplateDecl>(
4385 getDerived().TransformDecl(NameInfo.getLoc(), OldTemplate));
4386 if (!NewTemplate)
4387 return DeclarationNameInfo();
4388
4389 DeclarationNameInfo NewNameInfo(NameInfo);
4390 NewNameInfo.setName(
4391 SemaRef.Context.DeclarationNames.getCXXDeductionGuideName(NewTemplate));
4392 return NewNameInfo;
4393 }
4394
4395 case DeclarationName::CXXConstructorName:
4396 case DeclarationName::CXXDestructorName:
4397 case DeclarationName::CXXConversionFunctionName: {
4398 TypeSourceInfo *NewTInfo;
4399 CanQualType NewCanTy;
4400 if (TypeSourceInfo *OldTInfo = NameInfo.getNamedTypeInfo()) {
4401 NewTInfo = getDerived().TransformType(OldTInfo);
4402 if (!NewTInfo)
4403 return DeclarationNameInfo();
4404 NewCanTy = SemaRef.Context.getCanonicalType(NewTInfo->getType());
4405 }
4406 else {
4407 NewTInfo = nullptr;
4408 TemporaryBase Rebase(*this, NameInfo.getLoc(), Name);
4409 QualType NewT = getDerived().TransformType(Name.getCXXNameType());
4410 if (NewT.isNull())
4411 return DeclarationNameInfo();
4412 NewCanTy = SemaRef.Context.getCanonicalType(NewT);
4413 }
4414
4415 DeclarationName NewName
4416 = SemaRef.Context.DeclarationNames.getCXXSpecialName(Name.getNameKind(),
4417 NewCanTy);
4418 DeclarationNameInfo NewNameInfo(NameInfo);
4419 NewNameInfo.setName(NewName);
4420 NewNameInfo.setNamedTypeInfo(NewTInfo);
4421 return NewNameInfo;
4422 }
4423 }
4424
4425 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "clang/lib/Sema/TreeTransform.h"
, 4425)
;
4426}
4427
4428template<typename Derived>
4429TemplateName
4430TreeTransform<Derived>::TransformTemplateName(CXXScopeSpec &SS,
4431 TemplateName Name,
4432 SourceLocation NameLoc,
4433 QualType ObjectType,
4434 NamedDecl *FirstQualifierInScope,
4435 bool AllowInjectedClassName) {
4436 if (QualifiedTemplateName *QTN = Name.getAsQualifiedTemplateName()) {
4437 TemplateDecl *Template = QTN->getUnderlyingTemplate().getAsTemplateDecl();
4438 assert(Template && "qualified template name must refer to a template")(static_cast <bool> (Template && "qualified template name must refer to a template"
) ? void (0) : __assert_fail ("Template && \"qualified template name must refer to a template\""
, "clang/lib/Sema/TreeTransform.h", 4438, __extension__ __PRETTY_FUNCTION__
))
;
4439
4440 TemplateDecl *TransTemplate
4441 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4442 Template));
4443 if (!TransTemplate)
4444 return TemplateName();
4445
4446 if (!getDerived().AlwaysRebuild() &&
4447 SS.getScopeRep() == QTN->getQualifier() &&
4448 TransTemplate == Template)
4449 return Name;
4450
4451 return getDerived().RebuildTemplateName(SS, QTN->hasTemplateKeyword(),
4452 TransTemplate);
4453 }
4454
4455 if (DependentTemplateName *DTN = Name.getAsDependentTemplateName()) {
4456 if (SS.getScopeRep()) {
4457 // These apply to the scope specifier, not the template.
4458 ObjectType = QualType();
4459 FirstQualifierInScope = nullptr;
4460 }
4461
4462 if (!getDerived().AlwaysRebuild() &&
4463 SS.getScopeRep() == DTN->getQualifier() &&
4464 ObjectType.isNull())
4465 return Name;
4466
4467 // FIXME: Preserve the location of the "template" keyword.
4468 SourceLocation TemplateKWLoc = NameLoc;
4469
4470 if (DTN->isIdentifier()) {
4471 return getDerived().RebuildTemplateName(SS,
4472 TemplateKWLoc,
4473 *DTN->getIdentifier(),
4474 NameLoc,
4475 ObjectType,
4476 FirstQualifierInScope,
4477 AllowInjectedClassName);
4478 }
4479
4480 return getDerived().RebuildTemplateName(SS, TemplateKWLoc,
4481 DTN->getOperator(), NameLoc,
4482 ObjectType, AllowInjectedClassName);
4483 }
4484
4485 if (TemplateDecl *Template = Name.getAsTemplateDecl()) {
4486 TemplateDecl *TransTemplate
4487 = cast_or_null<TemplateDecl>(getDerived().TransformDecl(NameLoc,
4488 Template));
4489 if (!TransTemplate)
4490 return TemplateName();
4491
4492 if (!getDerived().AlwaysRebuild() &&
4493 TransTemplate == Template)
4494 return Name;
4495
4496 return TemplateName(TransTemplate);
4497 }
4498
4499 if (SubstTemplateTemplateParmPackStorage *SubstPack
4500 = Name.getAsSubstTemplateTemplateParmPack()) {
4501 return getDerived().RebuildTemplateName(
4502 SubstPack->getArgumentPack(), SubstPack->getAssociatedDecl(),
4503 SubstPack->getIndex(), SubstPack->getFinal());
4504 }
4505
4506 // These should be getting filtered out before they reach the AST.
4507 llvm_unreachable("overloaded function decl survived to here")::llvm::llvm_unreachable_internal("overloaded function decl survived to here"
, "clang/lib/Sema/TreeTransform.h", 4507)
;
4508}
4509
4510template<typename Derived>
4511void TreeTransform<Derived>::InventTemplateArgumentLoc(
4512 const TemplateArgument &Arg,
4513 TemplateArgumentLoc &Output) {
4514 Output = getSema().getTrivialTemplateArgumentLoc(
4515 Arg, QualType(), getDerived().getBaseLocation());
4516}
4517
4518template <typename Derived>
4519bool TreeTransform<Derived>::TransformTemplateArgument(
4520 const TemplateArgumentLoc &Input, TemplateArgumentLoc &Output,
4521 bool Uneval) {
4522 const TemplateArgument &Arg = Input.getArgument();
4523 switch (Arg.getKind()) {
4524 case TemplateArgument::Null:
4525 case TemplateArgument::Pack:
4526 llvm_unreachable("Unexpected TemplateArgument")::llvm::llvm_unreachable_internal("Unexpected TemplateArgument"
, "clang/lib/Sema/TreeTransform.h", 4526)
;
4527
4528 case TemplateArgument::Integral:
4529 case TemplateArgument::NullPtr:
4530 case TemplateArgument::Declaration: {
4531 // Transform a resolved template argument straight to a resolved template
4532 // argument. We get here when substituting into an already-substituted
4533 // template type argument during concept satisfaction checking.
4534 QualType T = Arg.getNonTypeTemplateArgumentType();
4535 QualType NewT = getDerived().TransformType(T);
4536 if (NewT.isNull())
4537 return true;
4538
4539 ValueDecl *D = Arg.getKind() == TemplateArgument::Declaration
4540 ? Arg.getAsDecl()
4541 : nullptr;
4542 ValueDecl *NewD = D ? cast_or_null<ValueDecl>(getDerived().TransformDecl(
4543 getDerived().getBaseLocation(), D))
4544 : nullptr;
4545 if (D && !NewD)
4546 return true;
4547
4548 if (NewT == T && D == NewD)
4549 Output = Input;
4550 else if (Arg.getKind() == TemplateArgument::Integral)
4551 Output = TemplateArgumentLoc(
4552 TemplateArgument(getSema().Context, Arg.getAsIntegral(), NewT),
4553 TemplateArgumentLocInfo());
4554 else if (Arg.getKind() == TemplateArgument::NullPtr)
4555 Output = TemplateArgumentLoc(TemplateArgument(NewT, /*IsNullPtr=*/true),
4556 TemplateArgumentLocInfo());
4557 else
4558 Output = TemplateArgumentLoc(TemplateArgument(NewD, NewT),
4559 TemplateArgumentLocInfo());
4560
4561 return false;
4562 }
4563
4564 case TemplateArgument::Type: {
4565 TypeSourceInfo *DI = Input.getTypeSourceInfo();
4566 if (!DI)
4567 DI = InventTypeSourceInfo(Input.getArgument().getAsType());
4568
4569 DI = getDerived().TransformType(DI);
4570 if (!DI)
4571 return true;
4572
4573 Output = TemplateArgumentLoc(TemplateArgument(DI->getType()), DI);
4574 return false;
4575 }
4576
4577 case TemplateArgument::Template: {
4578 NestedNameSpecifierLoc QualifierLoc = Input.getTemplateQualifierLoc();
4579 if (QualifierLoc) {
4580 QualifierLoc = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc);
4581 if (!QualifierLoc)
4582 return true;
4583 }
4584
4585 CXXScopeSpec SS;
4586 SS.Adopt(QualifierLoc);
4587 TemplateName Template = getDerived().TransformTemplateName(
4588 SS, Arg.getAsTemplate(), Input.getTemplateNameLoc());
4589 if (Template.isNull())
4590 return true;
4591
4592 Output = TemplateArgumentLoc(SemaRef.Context, TemplateArgument(Template),
4593 QualifierLoc, Input.getTemplateNameLoc());
4594 return false;
4595 }
4596
4597 case TemplateArgument::TemplateExpansion:
4598 llvm_unreachable("Caller should expand pack expansions")::llvm::llvm_unreachable_internal("Caller should expand pack expansions"
, "clang/lib/Sema/TreeTransform.h", 4598)
;
4599
4600 case TemplateArgument::Expression: {
4601 // Template argument expressions are constant expressions.
4602 EnterExpressionEvaluationContext Unevaluated(
4603 getSema(),
4604 Uneval ? Sema::ExpressionEvaluationContext::Unevaluated
4605 : Sema::ExpressionEvaluationContext::ConstantEvaluated,
4606 Sema::ReuseLambdaContextDecl, /*ExprContext=*/
4607 Sema::ExpressionEvaluationContextRecord::EK_TemplateArgument);
4608
4609 Expr *InputExpr = Input.getSourceExpression();
4610 if (!InputExpr)
4611 InputExpr = Input.getArgument().getAsExpr();
4612
4613 ExprResult E = getDerived().TransformExpr(InputExpr);
4614 E = SemaRef.ActOnConstantExpression(E);
4615 if (E.isInvalid())
4616 return true;
4617 Output = TemplateArgumentLoc(TemplateArgument(E.get()), E.get());
4618 return false;
4619 }
4620 }
4621
4622 // Work around bogus GCC warning
4623 return true;
4624}
4625
4626/// Iterator adaptor that invents template argument location information
4627/// for each of the template arguments in its underlying iterator.
4628template<typename Derived, typename InputIterator>
4629class TemplateArgumentLocInventIterator {
4630 TreeTransform<Derived> &Self;
4631 InputIterator Iter;
4632
4633public:
4634 typedef TemplateArgumentLoc value_type;
4635 typedef TemplateArgumentLoc reference;
4636 typedef typename std::iterator_traits<InputIterator>::difference_type
4637 difference_type;
4638 typedef std::input_iterator_tag iterator_category;
4639
4640 class pointer {
4641 TemplateArgumentLoc Arg;
4642
4643 public:
4644 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
4645
4646 const TemplateArgumentLoc *operator->() const { return &Arg; }
4647 };
4648
4649 TemplateArgumentLocInventIterator() { }
4650
4651 explicit TemplateArgumentLocInventIterator(TreeTransform<Derived> &Self,
4652 InputIterator Iter)
4653 : Self(Self), Iter(Iter) { }
4654
4655 TemplateArgumentLocInventIterator &operator++() {
4656 ++Iter;
4657 return *this;
4658 }
4659
4660 TemplateArgumentLocInventIterator operator++(int) {
4661 TemplateArgumentLocInventIterator Old(*this);
4662 ++(*this);
4663 return Old;
4664 }
4665
4666 reference operator*() const {
4667 TemplateArgumentLoc Result;
4668 Self.InventTemplateArgumentLoc(*Iter, Result);
4669 return Result;
4670 }
4671
4672 pointer operator->() const { return pointer(**this); }
4673
4674 friend bool operator==(const TemplateArgumentLocInventIterator &X,
4675 const TemplateArgumentLocInventIterator &Y) {
4676 return X.Iter == Y.Iter;
4677 }
4678
4679 friend bool operator!=(const TemplateArgumentLocInventIterator &X,
4680 const TemplateArgumentLocInventIterator &Y) {
4681 return X.Iter != Y.Iter;
4682 }
4683};
4684
4685template<typename Derived>
4686template<typename InputIterator>
4687bool TreeTransform<Derived>::TransformTemplateArguments(
4688 InputIterator First, InputIterator Last, TemplateArgumentListInfo &Outputs,
4689 bool Uneval) {
4690 for (; First != Last; ++First) {
4691 TemplateArgumentLoc Out;
4692 TemplateArgumentLoc In = *First;
4693
4694 if (In.getArgument().getKind() == TemplateArgument::Pack) {
4695 // Unpack argument packs, which we translate them into separate
4696 // arguments.
4697 // FIXME: We could do much better if we could guarantee that the
4698 // TemplateArgumentLocInfo for the pack expansion would be usable for
4699 // all of the template arguments in the argument pack.
4700 typedef TemplateArgumentLocInventIterator<Derived,
4701 TemplateArgument::pack_iterator>
4702 PackLocIterator;
4703 if (TransformTemplateArguments(PackLocIterator(*this,
4704 In.getArgument().pack_begin()),
4705 PackLocIterator(*this,
4706 In.getArgument().pack_end()),
4707 Outputs, Uneval))
4708 return true;
4709
4710 continue;
4711 }
4712
4713 if (In.getArgument().isPackExpansion()) {
4714 // We have a pack expansion, for which we will be substituting into
4715 // the pattern.
4716 SourceLocation Ellipsis;
4717 std::optional<unsigned> OrigNumExpansions;
4718 TemplateArgumentLoc Pattern
4719 = getSema().getTemplateArgumentPackExpansionPattern(
4720 In, Ellipsis, OrigNumExpansions);
4721
4722 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
4723 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
4724 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 4724, __extension__ __PRETTY_FUNCTION__
))
;
4725
4726 // Determine whether the set of unexpanded parameter packs can and should
4727 // be expanded.
4728 bool Expand = true;
4729 bool RetainExpansion = false;
4730 std::optional<unsigned> NumExpansions = OrigNumExpansions;
4731 if (getDerived().TryExpandParameterPacks(Ellipsis,
4732 Pattern.getSourceRange(),
4733 Unexpanded,
4734 Expand,
4735 RetainExpansion,
4736 NumExpansions))
4737 return true;
4738
4739 if (!Expand) {
4740 // The transform has determined that we should perform a simple
4741 // transformation on the pack expansion, producing another pack
4742 // expansion.
4743 TemplateArgumentLoc OutPattern;
4744 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
4745 if (getDerived().TransformTemplateArgument(Pattern, OutPattern, Uneval))
4746 return true;
4747
4748 Out = getDerived().RebuildPackExpansion(OutPattern, Ellipsis,
4749 NumExpansions);
4750 if (Out.getArgument().isNull())
4751 return true;
4752
4753 Outputs.addArgument(Out);
4754 continue;
4755 }
4756
4757 // The transform has determined that we should perform an elementwise
4758 // expansion of the pattern. Do so.
4759 for (unsigned I = 0; I != *NumExpansions; ++I) {
4760 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
4761
4762 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4763 return true;
4764
4765 if (Out.getArgument().containsUnexpandedParameterPack()) {
4766 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4767 OrigNumExpansions);
4768 if (Out.getArgument().isNull())
4769 return true;
4770 }
4771
4772 Outputs.addArgument(Out);
4773 }
4774
4775 // If we're supposed to retain a pack expansion, do so by temporarily
4776 // forgetting the partially-substituted parameter pack.
4777 if (RetainExpansion) {
4778 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
4779
4780 if (getDerived().TransformTemplateArgument(Pattern, Out, Uneval))
4781 return true;
4782
4783 Out = getDerived().RebuildPackExpansion(Out, Ellipsis,
4784 OrigNumExpansions);
4785 if (Out.getArgument().isNull())
4786 return true;
4787
4788 Outputs.addArgument(Out);
4789 }
4790
4791 continue;
4792 }
4793
4794 // The simple case:
4795 if (getDerived().TransformTemplateArgument(In, Out, Uneval))
4796 return true;
4797
4798 Outputs.addArgument(Out);
4799 }
4800
4801 return false;
4802
4803}
4804
4805//===----------------------------------------------------------------------===//
4806// Type transformation
4807//===----------------------------------------------------------------------===//
4808
4809template<typename Derived>
4810QualType TreeTransform<Derived>::TransformType(QualType T) {
4811 if (getDerived().AlreadyTransformed(T))
4812 return T;
4813
4814 // Temporary workaround. All of these transformations should
4815 // eventually turn into transformations on TypeLocs.
4816 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4817 getDerived().getBaseLocation());
4818
4819 TypeSourceInfo *NewDI = getDerived().TransformType(DI);
4820
4821 if (!NewDI)
4822 return QualType();
4823
4824 return NewDI->getType();
4825}
4826
4827template<typename Derived>
4828TypeSourceInfo *TreeTransform<Derived>::TransformType(TypeSourceInfo *DI) {
4829 // Refine the base location to the type's location.
4830 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4831 getDerived().getBaseEntity());
4832 if (getDerived().AlreadyTransformed(DI->getType()))
13
Taking false branch
4833 return DI;
4834
4835 TypeLocBuilder TLB;
4836
4837 TypeLoc TL = DI->getTypeLoc();
4838 TLB.reserve(TL.getFullDataSize());
4839
4840 QualType Result = getDerived().TransformType(TLB, TL);
14
Calling 'TreeTransform::TransformType'
4841 if (Result.isNull())
4842 return nullptr;
4843
4844 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4845}
4846
4847template<typename Derived>
4848QualType
4849TreeTransform<Derived>::TransformType(TypeLocBuilder &TLB, TypeLoc T) {
4850 switch (T.getTypeLocClass()) {
15
Control jumps to 'case TypeOfExpr:' at line 73
4851#define ABSTRACT_TYPELOC(CLASS, PARENT)
4852#define TYPELOC(CLASS, PARENT) \
4853 case TypeLoc::CLASS: \
4854 return getDerived().Transform##CLASS##Type(TLB, \
4855 T.castAs<CLASS##TypeLoc>());
4856#include "clang/AST/TypeLocNodes.def"
4857 }
4858
4859 llvm_unreachable("unhandled type loc!")::llvm::llvm_unreachable_internal("unhandled type loc!", "clang/lib/Sema/TreeTransform.h"
, 4859)
;
4860}
4861
4862template<typename Derived>
4863QualType TreeTransform<Derived>::TransformTypeWithDeducedTST(QualType T) {
4864 if (!isa<DependentNameType>(T))
4865 return TransformType(T);
4866
4867 if (getDerived().AlreadyTransformed(T))
4868 return T;
4869 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(T,
4870 getDerived().getBaseLocation());
4871 TypeSourceInfo *NewDI = getDerived().TransformTypeWithDeducedTST(DI);
4872 return NewDI ? NewDI->getType() : QualType();
4873}
4874
4875template<typename Derived>
4876TypeSourceInfo *
4877TreeTransform<Derived>::TransformTypeWithDeducedTST(TypeSourceInfo *DI) {
4878 if (!isa<DependentNameType>(DI->getType()))
4879 return TransformType(DI);
4880
4881 // Refine the base location to the type's location.
4882 TemporaryBase Rebase(*this, DI->getTypeLoc().getBeginLoc(),
4883 getDerived().getBaseEntity());
4884 if (getDerived().AlreadyTransformed(DI->getType()))
4885 return DI;
4886
4887 TypeLocBuilder TLB;
4888
4889 TypeLoc TL = DI->getTypeLoc();
4890 TLB.reserve(TL.getFullDataSize());
4891
4892 auto QTL = TL.getAs<QualifiedTypeLoc>();
4893 if (QTL)
4894 TL = QTL.getUnqualifiedLoc();
4895
4896 auto DNTL = TL.castAs<DependentNameTypeLoc>();
4897
4898 QualType Result = getDerived().TransformDependentNameType(
4899 TLB, DNTL, /*DeducedTSTContext*/true);
4900 if (Result.isNull())
4901 return nullptr;
4902
4903 if (QTL) {
4904 Result = getDerived().RebuildQualifiedType(Result, QTL);
4905 if (Result.isNull())
4906 return nullptr;
4907 TLB.TypeWasModifiedSafely(Result);
4908 }
4909
4910 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
4911}
4912
4913template<typename Derived>
4914QualType
4915TreeTransform<Derived>::TransformQualifiedType(TypeLocBuilder &TLB,
4916 QualifiedTypeLoc T) {
4917 QualType Result;
4918 TypeLoc UnqualTL = T.getUnqualifiedLoc();
4919 auto SuppressObjCLifetime =
4920 T.getType().getLocalQualifiers().hasObjCLifetime();
4921 if (auto TTP = UnqualTL.getAs<TemplateTypeParmTypeLoc>()) {
4922 Result = getDerived().TransformTemplateTypeParmType(TLB, TTP,
4923 SuppressObjCLifetime);
4924 } else if (auto STTP = UnqualTL.getAs<SubstTemplateTypeParmPackTypeLoc>()) {
4925 Result = getDerived().TransformSubstTemplateTypeParmPackType(
4926 TLB, STTP, SuppressObjCLifetime);
4927 } else {
4928 Result = getDerived().TransformType(TLB, UnqualTL);
4929 }
4930
4931 if (Result.isNull())
4932 return QualType();
4933
4934 Result = getDerived().RebuildQualifiedType(Result, T);
4935
4936 if (Result.isNull())
4937 return QualType();
4938
4939 // RebuildQualifiedType might have updated the type, but not in a way
4940 // that invalidates the TypeLoc. (There's no location information for
4941 // qualifiers.)
4942 TLB.TypeWasModifiedSafely(Result);
4943
4944 return Result;
4945}
4946
4947template <typename Derived>
4948QualType TreeTransform<Derived>::RebuildQualifiedType(QualType T,
4949 QualifiedTypeLoc TL) {
4950
4951 SourceLocation Loc = TL.getBeginLoc();
4952 Qualifiers Quals = TL.getType().getLocalQualifiers();
4953
4954 if ((T.getAddressSpace() != LangAS::Default &&
4955 Quals.getAddressSpace() != LangAS::Default) &&
4956 T.getAddressSpace() != Quals.getAddressSpace()) {
4957 SemaRef.Diag(Loc, diag::err_address_space_mismatch_templ_inst)
4958 << TL.getType() << T;
4959 return QualType();
4960 }
4961
4962 // C++ [dcl.fct]p7:
4963 // [When] adding cv-qualifications on top of the function type [...] the
4964 // cv-qualifiers are ignored.
4965 if (T->isFunctionType()) {
4966 T = SemaRef.getASTContext().getAddrSpaceQualType(T,
4967 Quals.getAddressSpace());
4968 return T;
4969 }
4970
4971 // C++ [dcl.ref]p1:
4972 // when the cv-qualifiers are introduced through the use of a typedef-name
4973 // or decltype-specifier [...] the cv-qualifiers are ignored.
4974 // Note that [dcl.ref]p1 lists all cases in which cv-qualifiers can be
4975 // applied to a reference type.
4976 if (T->isReferenceType()) {
4977 // The only qualifier that applies to a reference type is restrict.
4978 if (!Quals.hasRestrict())
4979 return T;
4980 Quals = Qualifiers::fromCVRMask(Qualifiers::Restrict);
4981 }
4982
4983 // Suppress Objective-C lifetime qualifiers if they don't make sense for the
4984 // resulting type.
4985 if (Quals.hasObjCLifetime()) {
4986 if (!T->isObjCLifetimeType() && !T->isDependentType())
4987 Quals.removeObjCLifetime();
4988 else if (T.getObjCLifetime()) {
4989 // Objective-C ARC:
4990 // A lifetime qualifier applied to a substituted template parameter
4991 // overrides the lifetime qualifier from the template argument.
4992 const AutoType *AutoTy;
4993 if ((AutoTy = dyn_cast<AutoType>(T)) && AutoTy->isDeduced()) {
4994 // 'auto' types behave the same way as template parameters.
4995 QualType Deduced = AutoTy->getDeducedType();
4996 Qualifiers Qs = Deduced.getQualifiers();
4997 Qs.removeObjCLifetime();
4998 Deduced =
4999 SemaRef.Context.getQualifiedType(Deduced.getUnqualifiedType(), Qs);
5000 T = SemaRef.Context.getAutoType(Deduced, AutoTy->getKeyword(),
5001 AutoTy->isDependentType(),
5002 /*isPack=*/false,
5003 AutoTy->getTypeConstraintConcept(),
5004 AutoTy->getTypeConstraintArguments());
5005 } else {
5006 // Otherwise, complain about the addition of a qualifier to an
5007 // already-qualified type.
5008 // FIXME: Why is this check not in Sema::BuildQualifiedType?
5009 SemaRef.Diag(Loc, diag::err_attr_objc_ownership_redundant) << T;
5010 Quals.removeObjCLifetime();
5011 }
5012 }
5013 }
5014
5015 return SemaRef.BuildQualifiedType(T, Loc, Quals);
5016}
5017
5018template<typename Derived>
5019TypeLoc
5020TreeTransform<Derived>::TransformTypeInObjectScope(TypeLoc TL,
5021 QualType ObjectType,
5022 NamedDecl *UnqualLookup,
5023 CXXScopeSpec &SS) {
5024 if (getDerived().AlreadyTransformed(TL.getType()))
5025 return TL;
5026
5027 TypeSourceInfo *TSI =
5028 TransformTSIInObjectScope(TL, ObjectType, UnqualLookup, SS);
5029 if (TSI)
5030 return TSI->getTypeLoc();
5031 return TypeLoc();
5032}
5033
5034template<typename Derived>
5035TypeSourceInfo *
5036TreeTransform<Derived>::TransformTypeInObjectScope(TypeSourceInfo *TSInfo,
5037 QualType ObjectType,
5038 NamedDecl *UnqualLookup,
5039 CXXScopeSpec &SS) {
5040 if (getDerived().AlreadyTransformed(TSInfo->getType()))
5041 return TSInfo;
5042
5043 return TransformTSIInObjectScope(TSInfo->getTypeLoc(), ObjectType,
5044 UnqualLookup, SS);
5045}
5046
5047template <typename Derived>
5048TypeSourceInfo *TreeTransform<Derived>::TransformTSIInObjectScope(
5049 TypeLoc TL, QualType ObjectType, NamedDecl *UnqualLookup,
5050 CXXScopeSpec &SS) {
5051 QualType T = TL.getType();
5052 assert(!getDerived().AlreadyTransformed(T))(static_cast <bool> (!getDerived().AlreadyTransformed(T
)) ? void (0) : __assert_fail ("!getDerived().AlreadyTransformed(T)"
, "clang/lib/Sema/TreeTransform.h", 5052, __extension__ __PRETTY_FUNCTION__
))
;
5053
5054 TypeLocBuilder TLB;
5055 QualType Result;
5056
5057 if (isa<TemplateSpecializationType>(T)) {
5058 TemplateSpecializationTypeLoc SpecTL =
5059 TL.castAs<TemplateSpecializationTypeLoc>();
5060
5061 TemplateName Template = getDerived().TransformTemplateName(
5062 SS, SpecTL.getTypePtr()->getTemplateName(), SpecTL.getTemplateNameLoc(),
5063 ObjectType, UnqualLookup, /*AllowInjectedClassName*/true);
5064 if (Template.isNull())
5065 return nullptr;
5066
5067 Result = getDerived().TransformTemplateSpecializationType(TLB, SpecTL,
5068 Template);
5069 } else if (isa<DependentTemplateSpecializationType>(T)) {
5070 DependentTemplateSpecializationTypeLoc SpecTL =
5071 TL.castAs<DependentTemplateSpecializationTypeLoc>();
5072
5073 TemplateName Template
5074 = getDerived().RebuildTemplateName(SS,
5075 SpecTL.getTemplateKeywordLoc(),
5076 *SpecTL.getTypePtr()->getIdentifier(),
5077 SpecTL.getTemplateNameLoc(),
5078 ObjectType, UnqualLookup,
5079 /*AllowInjectedClassName*/true);
5080 if (Template.isNull())
5081 return nullptr;
5082
5083 Result = getDerived().TransformDependentTemplateSpecializationType(TLB,
5084 SpecTL,
5085 Template,
5086 SS);
5087 } else {
5088 // Nothing special needs to be done for these.
5089 Result = getDerived().TransformType(TLB, TL);
5090 }
5091
5092 if (Result.isNull())
5093 return nullptr;
5094
5095 return TLB.getTypeSourceInfo(SemaRef.Context, Result);
5096}
5097
5098template <class TyLoc> static inline
5099QualType TransformTypeSpecType(TypeLocBuilder &TLB, TyLoc T) {
5100 TyLoc NewT = TLB.push<TyLoc>(T.getType());
5101 NewT.setNameLoc(T.getNameLoc());
5102 return T.getType();
5103}
5104
5105template<typename Derived>
5106QualType TreeTransform<Derived>::TransformBuiltinType(TypeLocBuilder &TLB,
5107 BuiltinTypeLoc T) {
5108 BuiltinTypeLoc NewT = TLB.push<BuiltinTypeLoc>(T.getType());
5109 NewT.setBuiltinLoc(T.getBuiltinLoc());
5110 if (T.needsExtraLocalData())
5111 NewT.getWrittenBuiltinSpecs() = T.getWrittenBuiltinSpecs();
5112 return T.getType();
5113}
5114
5115template<typename Derived>
5116QualType TreeTransform<Derived>::TransformComplexType(TypeLocBuilder &TLB,
5117 ComplexTypeLoc T) {
5118 // FIXME: recurse?
5119 return TransformTypeSpecType(TLB, T);
5120}
5121
5122template <typename Derived>
5123QualType TreeTransform<Derived>::TransformAdjustedType(TypeLocBuilder &TLB,
5124 AdjustedTypeLoc TL) {
5125 // Adjustments applied during transformation are handled elsewhere.
5126 return getDerived().TransformType(TLB, TL.getOriginalLoc());
5127}
5128
5129template<typename Derived>
5130QualType TreeTransform<Derived>::TransformDecayedType(TypeLocBuilder &TLB,
5131 DecayedTypeLoc TL) {
5132 QualType OriginalType = getDerived().TransformType(TLB, TL.getOriginalLoc());
5133 if (OriginalType.isNull())
5134 return QualType();
5135
5136 QualType Result = TL.getType();
5137 if (getDerived().AlwaysRebuild() ||
5138 OriginalType != TL.getOriginalLoc().getType())
5139 Result = SemaRef.Context.getDecayedType(OriginalType);
5140 TLB.push<DecayedTypeLoc>(Result);
5141 // Nothing to set for DecayedTypeLoc.
5142 return Result;
5143}
5144
5145template<typename Derived>
5146QualType TreeTransform<Derived>::TransformPointerType(TypeLocBuilder &TLB,
5147 PointerTypeLoc TL) {
5148 QualType PointeeType
5149 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5150 if (PointeeType.isNull())
5151 return QualType();
5152
5153 QualType Result = TL.getType();
5154 if (PointeeType->getAs<ObjCObjectType>()) {
5155 // A dependent pointer type 'T *' has is being transformed such
5156 // that an Objective-C class type is being replaced for 'T'. The
5157 // resulting pointer type is an ObjCObjectPointerType, not a
5158 // PointerType.
5159 Result = SemaRef.Context.getObjCObjectPointerType(PointeeType);
5160
5161 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
5162 NewT.setStarLoc(TL.getStarLoc());
5163 return Result;
5164 }
5165
5166 if (getDerived().AlwaysRebuild() ||
5167 PointeeType != TL.getPointeeLoc().getType()) {
5168 Result = getDerived().RebuildPointerType(PointeeType, TL.getSigilLoc());
5169 if (Result.isNull())
5170 return QualType();
5171 }
5172
5173 // Objective-C ARC can add lifetime qualifiers to the type that we're
5174 // pointing to.
5175 TLB.TypeWasModifiedSafely(Result->getPointeeType());
5176
5177 PointerTypeLoc NewT = TLB.push<PointerTypeLoc>(Result);
5178 NewT.setSigilLoc(TL.getSigilLoc());
5179 return Result;
5180}
5181
5182template<typename Derived>
5183QualType
5184TreeTransform<Derived>::TransformBlockPointerType(TypeLocBuilder &TLB,
5185 BlockPointerTypeLoc TL) {
5186 QualType PointeeType
5187 = getDerived().TransformType(TLB, TL.getPointeeLoc());
5188 if (PointeeType.isNull())
5189 return QualType();
5190
5191 QualType Result = TL.getType();
5192 if (getDerived().AlwaysRebuild() ||
5193 PointeeType != TL.getPointeeLoc().getType()) {
5194 Result = getDerived().RebuildBlockPointerType(PointeeType,
5195 TL.getSigilLoc());
5196 if (Result.isNull())
5197 return QualType();
5198 }
5199
5200 BlockPointerTypeLoc NewT = TLB.push<BlockPointerTypeLoc>(Result);
5201 NewT.setSigilLoc(TL.getSigilLoc());
5202 return Result;
5203}
5204
5205/// Transforms a reference type. Note that somewhat paradoxically we
5206/// don't care whether the type itself is an l-value type or an r-value
5207/// type; we only care if the type was *written* as an l-value type
5208/// or an r-value type.
5209template<typename Derived>
5210QualType
5211TreeTransform<Derived>::TransformReferenceType(TypeLocBuilder &TLB,
5212 ReferenceTypeLoc TL) {
5213 const ReferenceType *T = TL.getTypePtr();
5214
5215 // Note that this works with the pointee-as-written.
5216 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5217 if (PointeeType.isNull())
5218 return QualType();
5219
5220 QualType Result = TL.getType();
5221 if (getDerived().AlwaysRebuild() ||
5222 PointeeType != T->getPointeeTypeAsWritten()) {
5223 Result = getDerived().RebuildReferenceType(PointeeType,
5224 T->isSpelledAsLValue(),
5225 TL.getSigilLoc());
5226 if (Result.isNull())
5227 return QualType();
5228 }
5229
5230 // Objective-C ARC can add lifetime qualifiers to the type that we're
5231 // referring to.
5232 TLB.TypeWasModifiedSafely(
5233 Result->castAs<ReferenceType>()->getPointeeTypeAsWritten());
5234
5235 // r-value references can be rebuilt as l-value references.
5236 ReferenceTypeLoc NewTL;
5237 if (isa<LValueReferenceType>(Result))
5238 NewTL = TLB.push<LValueReferenceTypeLoc>(Result);
5239 else
5240 NewTL = TLB.push<RValueReferenceTypeLoc>(Result);
5241 NewTL.setSigilLoc(TL.getSigilLoc());
5242
5243 return Result;
5244}
5245
5246template<typename Derived>
5247QualType
5248TreeTransform<Derived>::TransformLValueReferenceType(TypeLocBuilder &TLB,
5249 LValueReferenceTypeLoc TL) {
5250 return TransformReferenceType(TLB, TL);
5251}
5252
5253template<typename Derived>
5254QualType
5255TreeTransform<Derived>::TransformRValueReferenceType(TypeLocBuilder &TLB,
5256 RValueReferenceTypeLoc TL) {
5257 return TransformReferenceType(TLB, TL);
5258}
5259
5260template<typename Derived>
5261QualType
5262TreeTransform<Derived>::TransformMemberPointerType(TypeLocBuilder &TLB,
5263 MemberPointerTypeLoc TL) {
5264 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
5265 if (PointeeType.isNull())
5266 return QualType();
5267
5268 TypeSourceInfo* OldClsTInfo = TL.getClassTInfo();
5269 TypeSourceInfo *NewClsTInfo = nullptr;
5270 if (OldClsTInfo) {
5271 NewClsTInfo = getDerived().TransformType(OldClsTInfo);
5272 if (!NewClsTInfo)
5273 return QualType();
5274 }
5275
5276 const MemberPointerType *T = TL.getTypePtr();
5277 QualType OldClsType = QualType(T->getClass(), 0);
5278 QualType NewClsType;
5279 if (NewClsTInfo)
5280 NewClsType = NewClsTInfo->getType();
5281 else {
5282 NewClsType = getDerived().TransformType(OldClsType);
5283 if (NewClsType.isNull())
5284 return QualType();
5285 }
5286
5287 QualType Result = TL.getType();
5288 if (getDerived().AlwaysRebuild() ||
5289 PointeeType != T->getPointeeType() ||
5290 NewClsType != OldClsType) {
5291 Result = getDerived().RebuildMemberPointerType(PointeeType, NewClsType,
5292 TL.getStarLoc());
5293 if (Result.isNull())
5294 return QualType();
5295 }
5296
5297 // If we had to adjust the pointee type when building a member pointer, make
5298 // sure to push TypeLoc info for it.
5299 const MemberPointerType *MPT = Result->getAs<MemberPointerType>();
5300 if (MPT && PointeeType != MPT->getPointeeType()) {
5301 assert(isa<AdjustedType>(MPT->getPointeeType()))(static_cast <bool> (isa<AdjustedType>(MPT->getPointeeType
())) ? void (0) : __assert_fail ("isa<AdjustedType>(MPT->getPointeeType())"
, "clang/lib/Sema/TreeTransform.h", 5301, __extension__ __PRETTY_FUNCTION__
))
;
5302 TLB.push<AdjustedTypeLoc>(MPT->getPointeeType());
5303 }
5304
5305 MemberPointerTypeLoc NewTL = TLB.push<MemberPointerTypeLoc>(Result);
5306 NewTL.setSigilLoc(TL.getSigilLoc());
5307 NewTL.setClassTInfo(NewClsTInfo);
5308
5309 return Result;
5310}
5311
5312template<typename Derived>
5313QualType
5314TreeTransform<Derived>::TransformConstantArrayType(TypeLocBuilder &TLB,
5315 ConstantArrayTypeLoc TL) {
5316 const ConstantArrayType *T = TL.getTypePtr();
5317 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5318 if (ElementType.isNull())
5319 return QualType();
5320
5321 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5322 Expr *OldSize = TL.getSizeExpr();
5323 if (!OldSize)
5324 OldSize = const_cast<Expr*>(T->getSizeExpr());
5325 Expr *NewSize = nullptr;
5326 if (OldSize) {
5327 EnterExpressionEvaluationContext Unevaluated(
5328 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5329 NewSize = getDerived().TransformExpr(OldSize).template getAs<Expr>();
5330 NewSize = SemaRef.ActOnConstantExpression(NewSize).get();
5331 }
5332
5333 QualType Result = TL.getType();
5334 if (getDerived().AlwaysRebuild() ||
5335 ElementType != T->getElementType() ||
5336 (T->getSizeExpr() && NewSize != OldSize)) {
5337 Result = getDerived().RebuildConstantArrayType(ElementType,
5338 T->getSizeModifier(),
5339 T->getSize(), NewSize,
5340 T->getIndexTypeCVRQualifiers(),
5341 TL.getBracketsRange());
5342 if (Result.isNull())
5343 return QualType();
5344 }
5345
5346 // We might have either a ConstantArrayType or a VariableArrayType now:
5347 // a ConstantArrayType is allowed to have an element type which is a
5348 // VariableArrayType if the type is dependent. Fortunately, all array
5349 // types have the same location layout.
5350 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5351 NewTL.setLBracketLoc(TL.getLBracketLoc());
5352 NewTL.setRBracketLoc(TL.getRBracketLoc());
5353 NewTL.setSizeExpr(NewSize);
5354
5355 return Result;
5356}
5357
5358template<typename Derived>
5359QualType TreeTransform<Derived>::TransformIncompleteArrayType(
5360 TypeLocBuilder &TLB,
5361 IncompleteArrayTypeLoc TL) {
5362 const IncompleteArrayType *T = TL.getTypePtr();
5363 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5364 if (ElementType.isNull())
5365 return QualType();
5366
5367 QualType Result = TL.getType();
5368 if (getDerived().AlwaysRebuild() ||
5369 ElementType != T->getElementType()) {
5370 Result = getDerived().RebuildIncompleteArrayType(ElementType,
5371 T->getSizeModifier(),
5372 T->getIndexTypeCVRQualifiers(),
5373 TL.getBracketsRange());
5374 if (Result.isNull())
5375 return QualType();
5376 }
5377
5378 IncompleteArrayTypeLoc NewTL = TLB.push<IncompleteArrayTypeLoc>(Result);
5379 NewTL.setLBracketLoc(TL.getLBracketLoc());
5380 NewTL.setRBracketLoc(TL.getRBracketLoc());
5381 NewTL.setSizeExpr(nullptr);
5382
5383 return Result;
5384}
5385
5386template<typename Derived>
5387QualType
5388TreeTransform<Derived>::TransformVariableArrayType(TypeLocBuilder &TLB,
5389 VariableArrayTypeLoc TL) {
5390 const VariableArrayType *T = TL.getTypePtr();
5391 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5392 if (ElementType.isNull())
5393 return QualType();
5394
5395 ExprResult SizeResult;
5396 {
5397 EnterExpressionEvaluationContext Context(
5398 SemaRef, Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
5399 SizeResult = getDerived().TransformExpr(T->getSizeExpr());
5400 }
5401 if (SizeResult.isInvalid())
5402 return QualType();
5403 SizeResult =
5404 SemaRef.ActOnFinishFullExpr(SizeResult.get(), /*DiscardedValue*/ false);
5405 if (SizeResult.isInvalid())
5406 return QualType();
5407
5408 Expr *Size = SizeResult.get();
5409
5410 QualType Result = TL.getType();
5411 if (getDerived().AlwaysRebuild() ||
5412 ElementType != T->getElementType() ||
5413 Size != T->getSizeExpr()) {
5414 Result = getDerived().RebuildVariableArrayType(ElementType,
5415 T->getSizeModifier(),
5416 Size,
5417 T->getIndexTypeCVRQualifiers(),
5418 TL.getBracketsRange());
5419 if (Result.isNull())
5420 return QualType();
5421 }
5422
5423 // We might have constant size array now, but fortunately it has the same
5424 // location layout.
5425 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5426 NewTL.setLBracketLoc(TL.getLBracketLoc());
5427 NewTL.setRBracketLoc(TL.getRBracketLoc());
5428 NewTL.setSizeExpr(Size);
5429
5430 return Result;
5431}
5432
5433template<typename Derived>
5434QualType
5435TreeTransform<Derived>::TransformDependentSizedArrayType(TypeLocBuilder &TLB,
5436 DependentSizedArrayTypeLoc TL) {
5437 const DependentSizedArrayType *T = TL.getTypePtr();
5438 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5439 if (ElementType.isNull())
5440 return QualType();
5441
5442 // Array bounds are constant expressions.
5443 EnterExpressionEvaluationContext Unevaluated(
5444 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5445
5446 // Prefer the expression from the TypeLoc; the other may have been uniqued.
5447 Expr *origSize = TL.getSizeExpr();
5448 if (!origSize) origSize = T->getSizeExpr();
5449
5450 ExprResult sizeResult
5451 = getDerived().TransformExpr(origSize);
5452 sizeResult = SemaRef.ActOnConstantExpression(sizeResult);
5453 if (sizeResult.isInvalid())
5454 return QualType();
5455
5456 Expr *size = sizeResult.get();
5457
5458 QualType Result = TL.getType();
5459 if (getDerived().AlwaysRebuild() ||
5460 ElementType != T->getElementType() ||
5461 size != origSize) {
5462 Result = getDerived().RebuildDependentSizedArrayType(ElementType,
5463 T->getSizeModifier(),
5464 size,
5465 T->getIndexTypeCVRQualifiers(),
5466 TL.getBracketsRange());
5467 if (Result.isNull())
5468 return QualType();
5469 }
5470
5471 // We might have any sort of array type now, but fortunately they
5472 // all have the same location layout.
5473 ArrayTypeLoc NewTL = TLB.push<ArrayTypeLoc>(Result);
5474 NewTL.setLBracketLoc(TL.getLBracketLoc());
5475 NewTL.setRBracketLoc(TL.getRBracketLoc());
5476 NewTL.setSizeExpr(size);
5477
5478 return Result;
5479}
5480
5481template <typename Derived>
5482QualType TreeTransform<Derived>::TransformDependentVectorType(
5483 TypeLocBuilder &TLB, DependentVectorTypeLoc TL) {
5484 const DependentVectorType *T = TL.getTypePtr();
5485 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5486 if (ElementType.isNull())
5487 return QualType();
5488
5489 EnterExpressionEvaluationContext Unevaluated(
5490 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5491
5492 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5493 Size = SemaRef.ActOnConstantExpression(Size);
5494 if (Size.isInvalid())
5495 return QualType();
5496
5497 QualType Result = TL.getType();
5498 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5499 Size.get() != T->getSizeExpr()) {
5500 Result = getDerived().RebuildDependentVectorType(
5501 ElementType, Size.get(), T->getAttributeLoc(), T->getVectorKind());
5502 if (Result.isNull())
5503 return QualType();
5504 }
5505
5506 // Result might be dependent or not.
5507 if (isa<DependentVectorType>(Result)) {
5508 DependentVectorTypeLoc NewTL =
5509 TLB.push<DependentVectorTypeLoc>(Result);
5510 NewTL.setNameLoc(TL.getNameLoc());
5511 } else {
5512 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5513 NewTL.setNameLoc(TL.getNameLoc());
5514 }
5515
5516 return Result;
5517}
5518
5519template<typename Derived>
5520QualType TreeTransform<Derived>::TransformDependentSizedExtVectorType(
5521 TypeLocBuilder &TLB,
5522 DependentSizedExtVectorTypeLoc TL) {
5523 const DependentSizedExtVectorType *T = TL.getTypePtr();
5524
5525 // FIXME: ext vector locs should be nested
5526 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5527 if (ElementType.isNull())
5528 return QualType();
5529
5530 // Vector sizes are constant expressions.
5531 EnterExpressionEvaluationContext Unevaluated(
5532 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5533
5534 ExprResult Size = getDerived().TransformExpr(T->getSizeExpr());
5535 Size = SemaRef.ActOnConstantExpression(Size);
5536 if (Size.isInvalid())
5537 return QualType();
5538
5539 QualType Result = TL.getType();
5540 if (getDerived().AlwaysRebuild() ||
5541 ElementType != T->getElementType() ||
5542 Size.get() != T->getSizeExpr()) {
5543 Result = getDerived().RebuildDependentSizedExtVectorType(ElementType,
5544 Size.get(),
5545 T->getAttributeLoc());
5546 if (Result.isNull())
5547 return QualType();
5548 }
5549
5550 // Result might be dependent or not.
5551 if (isa<DependentSizedExtVectorType>(Result)) {
5552 DependentSizedExtVectorTypeLoc NewTL
5553 = TLB.push<DependentSizedExtVectorTypeLoc>(Result);
5554 NewTL.setNameLoc(TL.getNameLoc());
5555 } else {
5556 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5557 NewTL.setNameLoc(TL.getNameLoc());
5558 }
5559
5560 return Result;
5561}
5562
5563template <typename Derived>
5564QualType
5565TreeTransform<Derived>::TransformConstantMatrixType(TypeLocBuilder &TLB,
5566 ConstantMatrixTypeLoc TL) {
5567 const ConstantMatrixType *T = TL.getTypePtr();
5568 QualType ElementType = getDerived().TransformType(T->getElementType());
5569 if (ElementType.isNull())
5570 return QualType();
5571
5572 QualType Result = TL.getType();
5573 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType()) {
5574 Result = getDerived().RebuildConstantMatrixType(
5575 ElementType, T->getNumRows(), T->getNumColumns());
5576 if (Result.isNull())
5577 return QualType();
5578 }
5579
5580 ConstantMatrixTypeLoc NewTL = TLB.push<ConstantMatrixTypeLoc>(Result);
5581 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5582 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5583 NewTL.setAttrRowOperand(TL.getAttrRowOperand());
5584 NewTL.setAttrColumnOperand(TL.getAttrColumnOperand());
5585
5586 return Result;
5587}
5588
5589template <typename Derived>
5590QualType TreeTransform<Derived>::TransformDependentSizedMatrixType(
5591 TypeLocBuilder &TLB, DependentSizedMatrixTypeLoc TL) {
5592 const DependentSizedMatrixType *T = TL.getTypePtr();
5593
5594 QualType ElementType = getDerived().TransformType(T->getElementType());
5595 if (ElementType.isNull()) {
5596 return QualType();
5597 }
5598
5599 // Matrix dimensions are constant expressions.
5600 EnterExpressionEvaluationContext Unevaluated(
5601 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5602
5603 Expr *origRows = TL.getAttrRowOperand();
5604 if (!origRows)
5605 origRows = T->getRowExpr();
5606 Expr *origColumns = TL.getAttrColumnOperand();
5607 if (!origColumns)
5608 origColumns = T->getColumnExpr();
5609
5610 ExprResult rowResult = getDerived().TransformExpr(origRows);
5611 rowResult = SemaRef.ActOnConstantExpression(rowResult);
5612 if (rowResult.isInvalid())
5613 return QualType();
5614
5615 ExprResult columnResult = getDerived().TransformExpr(origColumns);
5616 columnResult = SemaRef.ActOnConstantExpression(columnResult);
5617 if (columnResult.isInvalid())
5618 return QualType();
5619
5620 Expr *rows = rowResult.get();
5621 Expr *columns = columnResult.get();
5622
5623 QualType Result = TL.getType();
5624 if (getDerived().AlwaysRebuild() || ElementType != T->getElementType() ||
5625 rows != origRows || columns != origColumns) {
5626 Result = getDerived().RebuildDependentSizedMatrixType(
5627 ElementType, rows, columns, T->getAttributeLoc());
5628
5629 if (Result.isNull())
5630 return QualType();
5631 }
5632
5633 // We might have any sort of matrix type now, but fortunately they
5634 // all have the same location layout.
5635 MatrixTypeLoc NewTL = TLB.push<MatrixTypeLoc>(Result);
5636 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5637 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5638 NewTL.setAttrRowOperand(rows);
5639 NewTL.setAttrColumnOperand(columns);
5640 return Result;
5641}
5642
5643template <typename Derived>
5644QualType TreeTransform<Derived>::TransformDependentAddressSpaceType(
5645 TypeLocBuilder &TLB, DependentAddressSpaceTypeLoc TL) {
5646 const DependentAddressSpaceType *T = TL.getTypePtr();
5647
5648 QualType pointeeType = getDerived().TransformType(T->getPointeeType());
5649
5650 if (pointeeType.isNull())
5651 return QualType();
5652
5653 // Address spaces are constant expressions.
5654 EnterExpressionEvaluationContext Unevaluated(
5655 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
5656
5657 ExprResult AddrSpace = getDerived().TransformExpr(T->getAddrSpaceExpr());
5658 AddrSpace = SemaRef.ActOnConstantExpression(AddrSpace);
5659 if (AddrSpace.isInvalid())
5660 return QualType();
5661
5662 QualType Result = TL.getType();
5663 if (getDerived().AlwaysRebuild() || pointeeType != T->getPointeeType() ||
5664 AddrSpace.get() != T->getAddrSpaceExpr()) {
5665 Result = getDerived().RebuildDependentAddressSpaceType(
5666 pointeeType, AddrSpace.get(), T->getAttributeLoc());
5667 if (Result.isNull())
5668 return QualType();
5669 }
5670
5671 // Result might be dependent or not.
5672 if (isa<DependentAddressSpaceType>(Result)) {
5673 DependentAddressSpaceTypeLoc NewTL =
5674 TLB.push<DependentAddressSpaceTypeLoc>(Result);
5675
5676 NewTL.setAttrOperandParensRange(TL.getAttrOperandParensRange());
5677 NewTL.setAttrExprOperand(TL.getAttrExprOperand());
5678 NewTL.setAttrNameLoc(TL.getAttrNameLoc());
5679
5680 } else {
5681 TypeSourceInfo *DI = getSema().Context.getTrivialTypeSourceInfo(
5682 Result, getDerived().getBaseLocation());
5683 TransformType(TLB, DI->getTypeLoc());
5684 }
5685
5686 return Result;
5687}
5688
5689template <typename Derived>
5690QualType TreeTransform<Derived>::TransformVectorType(TypeLocBuilder &TLB,
5691 VectorTypeLoc TL) {
5692 const VectorType *T = TL.getTypePtr();
5693 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5694 if (ElementType.isNull())
5695 return QualType();
5696
5697 QualType Result = TL.getType();
5698 if (getDerived().AlwaysRebuild() ||
5699 ElementType != T->getElementType()) {
5700 Result = getDerived().RebuildVectorType(ElementType, T->getNumElements(),
5701 T->getVectorKind());
5702 if (Result.isNull())
5703 return QualType();
5704 }
5705
5706 VectorTypeLoc NewTL = TLB.push<VectorTypeLoc>(Result);
5707 NewTL.setNameLoc(TL.getNameLoc());
5708
5709 return Result;
5710}
5711
5712template<typename Derived>
5713QualType TreeTransform<Derived>::TransformExtVectorType(TypeLocBuilder &TLB,
5714 ExtVectorTypeLoc TL) {
5715 const VectorType *T = TL.getTypePtr();
5716 QualType ElementType = getDerived().TransformType(TLB, TL.getElementLoc());
5717 if (ElementType.isNull())
5718 return QualType();
5719
5720 QualType Result = TL.getType();
5721 if (getDerived().AlwaysRebuild() ||
5722 ElementType != T->getElementType()) {
5723 Result = getDerived().RebuildExtVectorType(ElementType,
5724 T->getNumElements(),
5725 /*FIXME*/ SourceLocation());
5726 if (Result.isNull())
5727 return QualType();
5728 }
5729
5730 ExtVectorTypeLoc NewTL = TLB.push<ExtVectorTypeLoc>(Result);
5731 NewTL.setNameLoc(TL.getNameLoc());
5732
5733 return Result;
5734}
5735
5736template <typename Derived>
5737ParmVarDecl *TreeTransform<Derived>::TransformFunctionTypeParam(
5738 ParmVarDecl *OldParm, int indexAdjustment,
5739 std::optional<unsigned> NumExpansions, bool ExpectParameterPack) {
5740 TypeSourceInfo *OldDI = OldParm->getTypeSourceInfo();
5741 TypeSourceInfo *NewDI = nullptr;
5742
5743 if (NumExpansions && isa<PackExpansionType>(OldDI->getType())) {
5744 // If we're substituting into a pack expansion type and we know the
5745 // length we want to expand to, just substitute for the pattern.
5746 TypeLoc OldTL = OldDI->getTypeLoc();
5747 PackExpansionTypeLoc OldExpansionTL = OldTL.castAs<PackExpansionTypeLoc>();
5748
5749 TypeLocBuilder TLB;
5750 TypeLoc NewTL = OldDI->getTypeLoc();
5751 TLB.reserve(NewTL.getFullDataSize());
5752
5753 QualType Result = getDerived().TransformType(TLB,
5754 OldExpansionTL.getPatternLoc());
5755 if (Result.isNull())
5756 return nullptr;
5757
5758 Result = RebuildPackExpansionType(Result,
5759 OldExpansionTL.getPatternLoc().getSourceRange(),
5760 OldExpansionTL.getEllipsisLoc(),
5761 NumExpansions);
5762 if (Result.isNull())
5763 return nullptr;
5764
5765 PackExpansionTypeLoc NewExpansionTL
5766 = TLB.push<PackExpansionTypeLoc>(Result);
5767 NewExpansionTL.setEllipsisLoc(OldExpansionTL.getEllipsisLoc());
5768 NewDI = TLB.getTypeSourceInfo(SemaRef.Context, Result);
5769 } else
5770 NewDI = getDerived().TransformType(OldDI);
5771 if (!NewDI)
5772 return nullptr;
5773
5774 if (NewDI == OldDI && indexAdjustment == 0)
5775 return OldParm;
5776
5777 ParmVarDecl *newParm = ParmVarDecl::Create(SemaRef.Context,
5778 OldParm->getDeclContext(),
5779 OldParm->getInnerLocStart(),
5780 OldParm->getLocation(),
5781 OldParm->getIdentifier(),
5782 NewDI->getType(),
5783 NewDI,
5784 OldParm->getStorageClass(),
5785 /* DefArg */ nullptr);
5786 newParm->setScopeInfo(OldParm->getFunctionScopeDepth(),
5787 OldParm->getFunctionScopeIndex() + indexAdjustment);
5788 transformedLocalDecl(OldParm, {newParm});
5789 return newParm;
5790}
5791
5792template <typename Derived>
5793bool TreeTransform<Derived>::TransformFunctionTypeParams(
5794 SourceLocation Loc, ArrayRef<ParmVarDecl *> Params,
5795 const QualType *ParamTypes,
5796 const FunctionProtoType::ExtParameterInfo *ParamInfos,
5797 SmallVectorImpl<QualType> &OutParamTypes,
5798 SmallVectorImpl<ParmVarDecl *> *PVars,
5799 Sema::ExtParameterInfoBuilder &PInfos,
5800 unsigned *LastParamTransformed) {
5801 int indexAdjustment = 0;
5802
5803 unsigned NumParams = Params.size();
5804 for (unsigned i = 0; i != NumParams; ++i) {
5805 if (LastParamTransformed)
5806 *LastParamTransformed = i;
5807 if (ParmVarDecl *OldParm = Params[i]) {
5808 assert(OldParm->getFunctionScopeIndex() == i)(static_cast <bool> (OldParm->getFunctionScopeIndex(
) == i) ? void (0) : __assert_fail ("OldParm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 5808, __extension__ __PRETTY_FUNCTION__
))
;
5809
5810 std::optional<unsigned> NumExpansions;
5811 ParmVarDecl *NewParm = nullptr;
5812 if (OldParm->isParameterPack()) {
5813 // We have a function parameter pack that may need to be expanded.
5814 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5815
5816 // Find the parameter packs that could be expanded.
5817 TypeLoc TL = OldParm->getTypeSourceInfo()->getTypeLoc();
5818 PackExpansionTypeLoc ExpansionTL = TL.castAs<PackExpansionTypeLoc>();
5819 TypeLoc Pattern = ExpansionTL.getPatternLoc();
5820 SemaRef.collectUnexpandedParameterPacks(Pattern, Unexpanded);
5821
5822 // Determine whether we should expand the parameter packs.
5823 bool ShouldExpand = false;
5824 bool RetainExpansion = false;
5825 std::optional<unsigned> OrigNumExpansions;
5826 if (Unexpanded.size() > 0) {
5827 OrigNumExpansions = ExpansionTL.getTypePtr()->getNumExpansions();
5828 NumExpansions = OrigNumExpansions;
5829 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
5830 Pattern.getSourceRange(),
5831 Unexpanded,
5832 ShouldExpand,
5833 RetainExpansion,
5834 NumExpansions)) {
5835 return true;
5836 }
5837 } else {
5838#ifndef NDEBUG
5839 const AutoType *AT =
5840 Pattern.getType().getTypePtr()->getContainedAutoType();
5841 assert((AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) &&(static_cast <bool> ((AT && (!AT->isDeduced(
) || AT->getDeducedType().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? void (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "clang/lib/Sema/TreeTransform.h", 5842, __extension__ __PRETTY_FUNCTION__
))
5842 "Could not find parameter packs or undeduced auto type!")(static_cast <bool> ((AT && (!AT->isDeduced(
) || AT->getDeducedType().isNull())) && "Could not find parameter packs or undeduced auto type!"
) ? void (0) : __assert_fail ("(AT && (!AT->isDeduced() || AT->getDeducedType().isNull())) && \"Could not find parameter packs or undeduced auto type!\""
, "clang/lib/Sema/TreeTransform.h", 5842, __extension__ __PRETTY_FUNCTION__
))
;
5843#endif
5844 }
5845
5846 if (ShouldExpand) {
5847 // Expand the function parameter pack into multiple, separate
5848 // parameters.
5849 getDerived().ExpandingFunctionParameterPack(OldParm);
5850 for (unsigned I = 0; I != *NumExpansions; ++I) {
5851 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5852 ParmVarDecl *NewParm
5853 = getDerived().TransformFunctionTypeParam(OldParm,
5854 indexAdjustment++,
5855 OrigNumExpansions,
5856 /*ExpectParameterPack=*/false);
5857 if (!NewParm)
5858 return true;
5859
5860 if (ParamInfos)
5861 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5862 OutParamTypes.push_back(NewParm->getType());
5863 if (PVars)
5864 PVars->push_back(NewParm);
5865 }
5866
5867 // If we're supposed to retain a pack expansion, do so by temporarily
5868 // forgetting the partially-substituted parameter pack.
5869 if (RetainExpansion) {
5870 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5871 ParmVarDecl *NewParm
5872 = getDerived().TransformFunctionTypeParam(OldParm,
5873 indexAdjustment++,
5874 OrigNumExpansions,
5875 /*ExpectParameterPack=*/false);
5876 if (!NewParm)
5877 return true;
5878
5879 if (ParamInfos)
5880 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5881 OutParamTypes.push_back(NewParm->getType());
5882 if (PVars)
5883 PVars->push_back(NewParm);
5884 }
5885
5886 // The next parameter should have the same adjustment as the
5887 // last thing we pushed, but we post-incremented indexAdjustment
5888 // on every push. Also, if we push nothing, the adjustment should
5889 // go down by one.
5890 indexAdjustment--;
5891
5892 // We're done with the pack expansion.
5893 continue;
5894 }
5895
5896 // We'll substitute the parameter now without expanding the pack
5897 // expansion.
5898 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5899 NewParm = getDerived().TransformFunctionTypeParam(OldParm,
5900 indexAdjustment,
5901 NumExpansions,
5902 /*ExpectParameterPack=*/true);
5903 assert(NewParm->isParameterPack() &&(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
5904 "Parameter pack no longer a parameter pack after "(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
5905 "transformation.")(static_cast <bool> (NewParm->isParameterPack() &&
"Parameter pack no longer a parameter pack after " "transformation."
) ? void (0) : __assert_fail ("NewParm->isParameterPack() && \"Parameter pack no longer a parameter pack after \" \"transformation.\""
, "clang/lib/Sema/TreeTransform.h", 5905, __extension__ __PRETTY_FUNCTION__
))
;
5906 } else {
5907 NewParm = getDerived().TransformFunctionTypeParam(
5908 OldParm, indexAdjustment, std::nullopt,
5909 /*ExpectParameterPack=*/false);
5910 }
5911
5912 if (!NewParm)
5913 return true;
5914
5915 if (ParamInfos)
5916 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5917 OutParamTypes.push_back(NewParm->getType());
5918 if (PVars)
5919 PVars->push_back(NewParm);
5920 continue;
5921 }
5922
5923 // Deal with the possibility that we don't have a parameter
5924 // declaration for this parameter.
5925 assert(ParamTypes)(static_cast <bool> (ParamTypes) ? void (0) : __assert_fail
("ParamTypes", "clang/lib/Sema/TreeTransform.h", 5925, __extension__
__PRETTY_FUNCTION__))
;
5926 QualType OldType = ParamTypes[i];
5927 bool IsPackExpansion = false;
5928 std::optional<unsigned> NumExpansions;
5929 QualType NewType;
5930 if (const PackExpansionType *Expansion
5931 = dyn_cast<PackExpansionType>(OldType)) {
5932 // We have a function parameter pack that may need to be expanded.
5933 QualType Pattern = Expansion->getPattern();
5934 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
5935 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
5936
5937 // Determine whether we should expand the parameter packs.
5938 bool ShouldExpand = false;
5939 bool RetainExpansion = false;
5940 if (getDerived().TryExpandParameterPacks(Loc, SourceRange(),
5941 Unexpanded,
5942 ShouldExpand,
5943 RetainExpansion,
5944 NumExpansions)) {
5945 return true;
5946 }
5947
5948 if (ShouldExpand) {
5949 // Expand the function parameter pack into multiple, separate
5950 // parameters.
5951 for (unsigned I = 0; I != *NumExpansions; ++I) {
5952 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
5953 QualType NewType = getDerived().TransformType(Pattern);
5954 if (NewType.isNull())
5955 return true;
5956
5957 if (NewType->containsUnexpandedParameterPack()) {
5958 NewType = getSema().getASTContext().getPackExpansionType(
5959 NewType, std::nullopt);
5960
5961 if (NewType.isNull())
5962 return true;
5963 }
5964
5965 if (ParamInfos)
5966 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5967 OutParamTypes.push_back(NewType);
5968 if (PVars)
5969 PVars->push_back(nullptr);
5970 }
5971
5972 // We're done with the pack expansion.
5973 continue;
5974 }
5975
5976 // If we're supposed to retain a pack expansion, do so by temporarily
5977 // forgetting the partially-substituted parameter pack.
5978 if (RetainExpansion) {
5979 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
5980 QualType NewType = getDerived().TransformType(Pattern);
5981 if (NewType.isNull())
5982 return true;
5983
5984 if (ParamInfos)
5985 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
5986 OutParamTypes.push_back(NewType);
5987 if (PVars)
5988 PVars->push_back(nullptr);
5989 }
5990
5991 // We'll substitute the parameter now without expanding the pack
5992 // expansion.
5993 OldType = Expansion->getPattern();
5994 IsPackExpansion = true;
5995 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
5996 NewType = getDerived().TransformType(OldType);
5997 } else {
5998 NewType = getDerived().TransformType(OldType);
5999 }
6000
6001 if (NewType.isNull())
6002 return true;
6003
6004 if (IsPackExpansion)
6005 NewType = getSema().Context.getPackExpansionType(NewType,
6006 NumExpansions);
6007
6008 if (ParamInfos)
6009 PInfos.set(OutParamTypes.size(), ParamInfos[i]);
6010 OutParamTypes.push_back(NewType);
6011 if (PVars)
6012 PVars->push_back(nullptr);
6013 }
6014
6015#ifndef NDEBUG
6016 if (PVars) {
6017 for (unsigned i = 0, e = PVars->size(); i != e; ++i)
6018 if (ParmVarDecl *parm = (*PVars)[i])
6019 assert(parm->getFunctionScopeIndex() == i)(static_cast <bool> (parm->getFunctionScopeIndex() ==
i) ? void (0) : __assert_fail ("parm->getFunctionScopeIndex() == i"
, "clang/lib/Sema/TreeTransform.h", 6019, __extension__ __PRETTY_FUNCTION__
))
;
6020 }
6021#endif
6022
6023 return false;
6024}
6025
6026template<typename Derived>
6027QualType
6028TreeTransform<Derived>::TransformFunctionProtoType(TypeLocBuilder &TLB,
6029 FunctionProtoTypeLoc TL) {
6030 SmallVector<QualType, 4> ExceptionStorage;
6031 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
6032 return getDerived().TransformFunctionProtoType(
6033 TLB, TL, nullptr, Qualifiers(),
6034 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
6035 return This->getDerived().TransformExceptionSpec(
6036 TL.getBeginLoc(), ESI, ExceptionStorage, Changed);
6037 });
6038}
6039
6040template<typename Derived> template<typename Fn>
6041QualType TreeTransform<Derived>::TransformFunctionProtoType(
6042 TypeLocBuilder &TLB, FunctionProtoTypeLoc TL, CXXRecordDecl *ThisContext,
6043 Qualifiers ThisTypeQuals, Fn TransformExceptionSpec) {
6044
6045 // Transform the parameters and return type.
6046 //
6047 // We are required to instantiate the params and return type in source order.
6048 // When the function has a trailing return type, we instantiate the
6049 // parameters before the return type, since the return type can then refer
6050 // to the parameters themselves (via decltype, sizeof, etc.).
6051 //
6052 SmallVector<QualType, 4> ParamTypes;
6053 SmallVector<ParmVarDecl*, 4> ParamDecls;
6054 Sema::ExtParameterInfoBuilder ExtParamInfos;
6055 const FunctionProtoType *T = TL.getTypePtr();
6056
6057 QualType ResultType;
6058
6059 if (T->hasTrailingReturn()) {
6060 if (getDerived().TransformFunctionTypeParams(
6061 TL.getBeginLoc(), TL.getParams(),
6062 TL.getTypePtr()->param_type_begin(),
6063 T->getExtParameterInfosOrNull(),
6064 ParamTypes, &ParamDecls, ExtParamInfos))
6065 return QualType();
6066
6067 {
6068 // C++11 [expr.prim.general]p3:
6069 // If a declaration declares a member function or member function
6070 // template of a class X, the expression this is a prvalue of type
6071 // "pointer to cv-qualifier-seq X" between the optional cv-qualifer-seq
6072 // and the end of the function-definition, member-declarator, or
6073 // declarator.
6074 Sema::CXXThisScopeRAII ThisScope(SemaRef, ThisContext, ThisTypeQuals);
6075
6076 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6077 if (ResultType.isNull())
6078 return QualType();
6079 }
6080 }
6081 else {
6082 ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6083 if (ResultType.isNull())
6084 return QualType();
6085
6086 if (getDerived().TransformFunctionTypeParams(
6087 TL.getBeginLoc(), TL.getParams(),
6088 TL.getTypePtr()->param_type_begin(),
6089 T->getExtParameterInfosOrNull(),
6090 ParamTypes, &ParamDecls, ExtParamInfos))
6091 return QualType();
6092 }
6093
6094 FunctionProtoType::ExtProtoInfo EPI = T->getExtProtoInfo();
6095
6096 bool EPIChanged = false;
6097 if (TransformExceptionSpec(EPI.ExceptionSpec, EPIChanged))
6098 return QualType();
6099
6100 // Handle extended parameter information.
6101 if (auto NewExtParamInfos =
6102 ExtParamInfos.getPointerOrNull(ParamTypes.size())) {
6103 if (!EPI.ExtParameterInfos ||
6104 llvm::ArrayRef(EPI.ExtParameterInfos, TL.getNumParams()) !=
6105 llvm::ArrayRef(NewExtParamInfos, ParamTypes.size())) {
6106 EPIChanged = true;
6107 }
6108 EPI.ExtParameterInfos = NewExtParamInfos;
6109 } else if (EPI.ExtParameterInfos) {
6110 EPIChanged = true;
6111 EPI.ExtParameterInfos = nullptr;
6112 }
6113
6114 QualType Result = TL.getType();
6115 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType() ||
6116 T->getParamTypes() != llvm::ArrayRef(ParamTypes) || EPIChanged) {
6117 Result = getDerived().RebuildFunctionProtoType(ResultType, ParamTypes, EPI);
6118 if (Result.isNull())
6119 return QualType();
6120 }
6121
6122 FunctionProtoTypeLoc NewTL = TLB.push<FunctionProtoTypeLoc>(Result);
6123 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6124 NewTL.setLParenLoc(TL.getLParenLoc());
6125 NewTL.setRParenLoc(TL.getRParenLoc());
6126 NewTL.setExceptionSpecRange(TL.getExceptionSpecRange());
6127 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6128 for (unsigned i = 0, e = NewTL.getNumParams(); i != e; ++i)
6129 NewTL.setParam(i, ParamDecls[i]);
6130
6131 return Result;
6132}
6133
6134template<typename Derived>
6135bool TreeTransform<Derived>::TransformExceptionSpec(
6136 SourceLocation Loc, FunctionProtoType::ExceptionSpecInfo &ESI,
6137 SmallVectorImpl<QualType> &Exceptions, bool &Changed) {
6138 assert(ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated)(static_cast <bool> (ESI.Type != EST_Uninstantiated &&
ESI.Type != EST_Unevaluated) ? void (0) : __assert_fail ("ESI.Type != EST_Uninstantiated && ESI.Type != EST_Unevaluated"
, "clang/lib/Sema/TreeTransform.h", 6138, __extension__ __PRETTY_FUNCTION__
))
;
6139
6140 // Instantiate a dynamic noexcept expression, if any.
6141 if (isComputedNoexcept(ESI.Type)) {
6142 EnterExpressionEvaluationContext Unevaluated(
6143 getSema(), Sema::ExpressionEvaluationContext::ConstantEvaluated);
6144 ExprResult NoexceptExpr = getDerived().TransformExpr(ESI.NoexceptExpr);
6145 if (NoexceptExpr.isInvalid())
6146 return true;
6147
6148 ExceptionSpecificationType EST = ESI.Type;
6149 NoexceptExpr =
6150 getSema().ActOnNoexceptSpec(NoexceptExpr.get(), EST);
6151 if (NoexceptExpr.isInvalid())
6152 return true;
6153
6154 if (ESI.NoexceptExpr != NoexceptExpr.get() || EST != ESI.Type)
6155 Changed = true;
6156 ESI.NoexceptExpr = NoexceptExpr.get();
6157 ESI.Type = EST;
6158 }
6159
6160 if (ESI.Type != EST_Dynamic)
6161 return false;
6162
6163 // Instantiate a dynamic exception specification's type.
6164 for (QualType T : ESI.Exceptions) {
6165 if (const PackExpansionType *PackExpansion =
6166 T->getAs<PackExpansionType>()) {
6167 Changed = true;
6168
6169 // We have a pack expansion. Instantiate it.
6170 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
6171 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
6172 Unexpanded);
6173 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 6173, __extension__ __PRETTY_FUNCTION__
))
;
6174
6175 // Determine whether the set of unexpanded parameter packs can and
6176 // should
6177 // be expanded.
6178 bool Expand = false;
6179 bool RetainExpansion = false;
6180 std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
6181 // FIXME: Track the location of the ellipsis (and track source location
6182 // information for the types in the exception specification in general).
6183 if (getDerived().TryExpandParameterPacks(
6184 Loc, SourceRange(), Unexpanded, Expand,
6185 RetainExpansion, NumExpansions))
6186 return true;
6187
6188 if (!Expand) {
6189 // We can't expand this pack expansion into separate arguments yet;
6190 // just substitute into the pattern and create a new pack expansion
6191 // type.
6192 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
6193 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6194 if (U.isNull())
6195 return true;
6196
6197 U = SemaRef.Context.getPackExpansionType(U, NumExpansions);
6198 Exceptions.push_back(U);
6199 continue;
6200 }
6201
6202 // Substitute into the pack expansion pattern for each slice of the
6203 // pack.
6204 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
6205 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
6206
6207 QualType U = getDerived().TransformType(PackExpansion->getPattern());
6208 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6209 return true;
6210
6211 Exceptions.push_back(U);
6212 }
6213 } else {
6214 QualType U = getDerived().TransformType(T);
6215 if (U.isNull() || SemaRef.CheckSpecifiedExceptionType(U, Loc))
6216 return true;
6217 if (T != U)
6218 Changed = true;
6219
6220 Exceptions.push_back(U);
6221 }
6222 }
6223
6224 ESI.Exceptions = Exceptions;
6225 if (ESI.Exceptions.empty())
6226 ESI.Type = EST_DynamicNone;
6227 return false;
6228}
6229
6230template<typename Derived>
6231QualType TreeTransform<Derived>::TransformFunctionNoProtoType(
6232 TypeLocBuilder &TLB,
6233 FunctionNoProtoTypeLoc TL) {
6234 const FunctionNoProtoType *T = TL.getTypePtr();
6235 QualType ResultType = getDerived().TransformType(TLB, TL.getReturnLoc());
6236 if (ResultType.isNull())
6237 return QualType();
6238
6239 QualType Result = TL.getType();
6240 if (getDerived().AlwaysRebuild() || ResultType != T->getReturnType())
6241 Result = getDerived().RebuildFunctionNoProtoType(ResultType);
6242
6243 FunctionNoProtoTypeLoc NewTL = TLB.push<FunctionNoProtoTypeLoc>(Result);
6244 NewTL.setLocalRangeBegin(TL.getLocalRangeBegin());
6245 NewTL.setLParenLoc(TL.getLParenLoc());
6246 NewTL.setRParenLoc(TL.getRParenLoc());
6247 NewTL.setLocalRangeEnd(TL.getLocalRangeEnd());
6248
6249 return Result;
6250}
6251
6252template <typename Derived>
6253QualType TreeTransform<Derived>::TransformUnresolvedUsingType(
6254 TypeLocBuilder &TLB, UnresolvedUsingTypeLoc TL) {
6255 const UnresolvedUsingType *T = TL.getTypePtr();
6256 Decl *D = getDerived().TransformDecl(TL.getNameLoc(), T->getDecl());
6257 if (!D)
6258 return QualType();
6259
6260 QualType Result = TL.getType();
6261 if (getDerived().AlwaysRebuild() || D != T->getDecl()) {
6262 Result = getDerived().RebuildUnresolvedUsingType(TL.getNameLoc(), D);
6263 if (Result.isNull())
6264 return QualType();
6265 }
6266
6267 // We might get an arbitrary type spec type back. We should at
6268 // least always get a type spec type, though.
6269 TypeSpecTypeLoc NewTL = TLB.pushTypeSpec(Result);
6270 NewTL.setNameLoc(TL.getNameLoc());
6271
6272 return Result;
6273}
6274
6275template <typename Derived>
6276QualType TreeTransform<Derived>::TransformUsingType(TypeLocBuilder &TLB,
6277 UsingTypeLoc TL) {
6278 const UsingType *T = TL.getTypePtr();
6279
6280 auto *Found = cast_or_null<UsingShadowDecl>(getDerived().TransformDecl(
6281 TL.getLocalSourceRange().getBegin(), T->getFoundDecl()));
6282 if (!Found)
6283 return QualType();
6284
6285 QualType Underlying = getDerived().TransformType(T->desugar());
6286 if (Underlying.isNull())
6287 return QualType();
6288
6289 QualType Result = TL.getType();
6290 if (getDerived().AlwaysRebuild() || Found != T->getFoundDecl() ||
6291 Underlying != T->getUnderlyingType()) {
6292 Result = getDerived().RebuildUsingType(Found, Underlying);
6293 if (Result.isNull())
6294 return QualType();
6295 }
6296
6297 TLB.pushTypeSpec(Result).setNameLoc(TL.getNameLoc());
6298 return Result;
6299}
6300
6301template<typename Derived>
6302QualType TreeTransform<Derived>::TransformTypedefType(TypeLocBuilder &TLB,
6303 TypedefTypeLoc TL) {
6304 const TypedefType *T = TL.getTypePtr();
6305 TypedefNameDecl *Typedef
6306 = cast_or_null<TypedefNameDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6307 T->getDecl()));
6308 if (!Typedef)
6309 return QualType();
6310
6311 QualType Result = TL.getType();
6312 if (getDerived().AlwaysRebuild() ||
6313 Typedef != T->getDecl()) {
6314 Result = getDerived().RebuildTypedefType(Typedef);
6315 if (Result.isNull())
6316 return QualType();
6317 }
6318
6319 TypedefTypeLoc NewTL = TLB.push<TypedefTypeLoc>(Result);
6320 NewTL.setNameLoc(TL.getNameLoc());
6321
6322 return Result;
6323}
6324
6325template<typename Derived>
6326QualType TreeTransform<Derived>::TransformTypeOfExprType(TypeLocBuilder &TLB,
6327 TypeOfExprTypeLoc TL) {
6328 // typeof expressions are not potentially evaluated contexts
6329 EnterExpressionEvaluationContext Unevaluated(
6330 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
6331 Sema::ReuseLambdaContextDecl);
6332
6333 ExprResult E = getDerived().TransformExpr(TL.getUnderlyingExpr());
6334 if (E.isInvalid())
17
Assuming the condition is false
18
Taking false branch
6335 return QualType();
6336
6337 E = SemaRef.HandleExprEvaluationContextForTypeof(E.get());
6338 if (E.isInvalid())
19
Assuming the condition is false
20
Taking false branch
6339 return QualType();
6340
6341 QualType Result = TL.getType();
6342 TypeOfKind Kind = Result->getAs<TypeOfExprType>()->getKind();
21
Assuming the object is not a 'const class clang::TypeOfExprType *'
22
Called C++ object pointer is null
6343 if (getDerived().AlwaysRebuild() || E.get() != TL.getUnderlyingExpr()) {
6344 Result =
6345 getDerived().RebuildTypeOfExprType(E.get(), TL.getTypeofLoc(), Kind);
6346 if (Result.isNull())
6347 return QualType();
6348 }
6349
6350 TypeOfExprTypeLoc NewTL = TLB.push<TypeOfExprTypeLoc>(Result);
6351 NewTL.setTypeofLoc(TL.getTypeofLoc());
6352 NewTL.setLParenLoc(TL.getLParenLoc());
6353 NewTL.setRParenLoc(TL.getRParenLoc());
6354
6355 return Result;
6356}
6357
6358template<typename Derived>
6359QualType TreeTransform<Derived>::TransformTypeOfType(TypeLocBuilder &TLB,
6360 TypeOfTypeLoc TL) {
6361 TypeSourceInfo* Old_Under_TI = TL.getUnmodifiedTInfo();
6362 TypeSourceInfo* New_Under_TI = getDerived().TransformType(Old_Under_TI);
6363 if (!New_Under_TI)
6364 return QualType();
6365
6366 QualType Result = TL.getType();
6367 TypeOfKind Kind = Result->getAs<TypeOfType>()->getKind();
6368 if (getDerived().AlwaysRebuild() || New_Under_TI != Old_Under_TI) {
6369 Result = getDerived().RebuildTypeOfType(New_Under_TI->getType(), Kind);
6370 if (Result.isNull())
6371 return QualType();
6372 }
6373
6374 TypeOfTypeLoc NewTL = TLB.push<TypeOfTypeLoc>(Result);
6375 NewTL.setTypeofLoc(TL.getTypeofLoc());
6376 NewTL.setLParenLoc(TL.getLParenLoc());
6377 NewTL.setRParenLoc(TL.getRParenLoc());
6378 NewTL.setUnmodifiedTInfo(New_Under_TI);
6379
6380 return Result;
6381}
6382
6383template<typename Derived>
6384QualType TreeTransform<Derived>::TransformDecltypeType(TypeLocBuilder &TLB,
6385 DecltypeTypeLoc TL) {
6386 const DecltypeType *T = TL.getTypePtr();
6387
6388 // decltype expressions are not potentially evaluated contexts
6389 EnterExpressionEvaluationContext Unevaluated(
6390 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated, nullptr,
6391 Sema::ExpressionEvaluationContextRecord::EK_Decltype);
6392
6393 ExprResult E = getDerived().TransformExpr(T->getUnderlyingExpr());
6394 if (E.isInvalid())
6395 return QualType();
6396
6397 E = getSema().ActOnDecltypeExpression(E.get());
6398 if (E.isInvalid())
6399 return QualType();
6400
6401 QualType Result = TL.getType();
6402 if (getDerived().AlwaysRebuild() ||
6403 E.get() != T->getUnderlyingExpr()) {
6404 Result = getDerived().RebuildDecltypeType(E.get(), TL.getDecltypeLoc());
6405 if (Result.isNull())
6406 return QualType();
6407 }
6408 else E.get();
6409
6410 DecltypeTypeLoc NewTL = TLB.push<DecltypeTypeLoc>(Result);
6411 NewTL.setDecltypeLoc(TL.getDecltypeLoc());
6412 NewTL.setRParenLoc(TL.getRParenLoc());
6413 return Result;
6414}
6415
6416template<typename Derived>
6417QualType TreeTransform<Derived>::TransformUnaryTransformType(
6418 TypeLocBuilder &TLB,
6419 UnaryTransformTypeLoc TL) {
6420 QualType Result = TL.getType();
6421 if (Result->isDependentType()) {
6422 const UnaryTransformType *T = TL.getTypePtr();
6423 QualType NewBase =
6424 getDerived().TransformType(TL.getUnderlyingTInfo())->getType();
6425 Result = getDerived().RebuildUnaryTransformType(NewBase,
6426 T->getUTTKind(),
6427 TL.getKWLoc());
6428 if (Result.isNull())
6429 return QualType();
6430 }
6431
6432 UnaryTransformTypeLoc NewTL = TLB.push<UnaryTransformTypeLoc>(Result);
6433 NewTL.setKWLoc(TL.getKWLoc());
6434 NewTL.setParensRange(TL.getParensRange());
6435 NewTL.setUnderlyingTInfo(TL.getUnderlyingTInfo());
6436 return Result;
6437}
6438
6439template<typename Derived>
6440QualType TreeTransform<Derived>::TransformDeducedTemplateSpecializationType(
6441 TypeLocBuilder &TLB, DeducedTemplateSpecializationTypeLoc TL) {
6442 const DeducedTemplateSpecializationType *T = TL.getTypePtr();
6443
6444 CXXScopeSpec SS;
6445 TemplateName TemplateName = getDerived().TransformTemplateName(
6446 SS, T->getTemplateName(), TL.getTemplateNameLoc());
6447 if (TemplateName.isNull())
6448 return QualType();
6449
6450 QualType OldDeduced = T->getDeducedType();
6451 QualType NewDeduced;
6452 if (!OldDeduced.isNull()) {
6453 NewDeduced = getDerived().TransformType(OldDeduced);
6454 if (NewDeduced.isNull())
6455 return QualType();
6456 }
6457
6458 QualType Result = getDerived().RebuildDeducedTemplateSpecializationType(
6459 TemplateName, NewDeduced);
6460 if (Result.isNull())
6461 return QualType();
6462
6463 DeducedTemplateSpecializationTypeLoc NewTL =
6464 TLB.push<DeducedTemplateSpecializationTypeLoc>(Result);
6465 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6466
6467 return Result;
6468}
6469
6470template<typename Derived>
6471QualType TreeTransform<Derived>::TransformRecordType(TypeLocBuilder &TLB,
6472 RecordTypeLoc TL) {
6473 const RecordType *T = TL.getTypePtr();
6474 RecordDecl *Record
6475 = cast_or_null<RecordDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6476 T->getDecl()));
6477 if (!Record)
6478 return QualType();
6479
6480 QualType Result = TL.getType();
6481 if (getDerived().AlwaysRebuild() ||
6482 Record != T->getDecl()) {
6483 Result = getDerived().RebuildRecordType(Record);
6484 if (Result.isNull())
6485 return QualType();
6486 }
6487
6488 RecordTypeLoc NewTL = TLB.push<RecordTypeLoc>(Result);
6489 NewTL.setNameLoc(TL.getNameLoc());
6490
6491 return Result;
6492}
6493
6494template<typename Derived>
6495QualType TreeTransform<Derived>::TransformEnumType(TypeLocBuilder &TLB,
6496 EnumTypeLoc TL) {
6497 const EnumType *T = TL.getTypePtr();
6498 EnumDecl *Enum
6499 = cast_or_null<EnumDecl>(getDerived().TransformDecl(TL.getNameLoc(),
6500 T->getDecl()));
6501 if (!Enum)
6502 return QualType();
6503
6504 QualType Result = TL.getType();
6505 if (getDerived().AlwaysRebuild() ||
6506 Enum != T->getDecl()) {
6507 Result = getDerived().RebuildEnumType(Enum);
6508 if (Result.isNull())
6509 return QualType();
6510 }
6511
6512 EnumTypeLoc NewTL = TLB.push<EnumTypeLoc>(Result);
6513 NewTL.setNameLoc(TL.getNameLoc());
6514
6515 return Result;
6516}
6517
6518template<typename Derived>
6519QualType TreeTransform<Derived>::TransformInjectedClassNameType(
6520 TypeLocBuilder &TLB,
6521 InjectedClassNameTypeLoc TL) {
6522 Decl *D = getDerived().TransformDecl(TL.getNameLoc(),
6523 TL.getTypePtr()->getDecl());
6524 if (!D) return QualType();
6525
6526 QualType T = SemaRef.Context.getTypeDeclType(cast<TypeDecl>(D));
6527 TLB.pushTypeSpec(T).setNameLoc(TL.getNameLoc());
6528 return T;
6529}
6530
6531template<typename Derived>
6532QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6533 TypeLocBuilder &TLB,
6534 TemplateTypeParmTypeLoc TL) {
6535 return getDerived().TransformTemplateTypeParmType(
6536 TLB, TL,
6537 /*SuppressObjCLifetime=*/false);
6538}
6539
6540template <typename Derived>
6541QualType TreeTransform<Derived>::TransformTemplateTypeParmType(
6542 TypeLocBuilder &TLB, TemplateTypeParmTypeLoc TL, bool) {
6543 return TransformTypeSpecType(TLB, TL);
6544}
6545
6546template<typename Derived>
6547QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmType(
6548 TypeLocBuilder &TLB,
6549 SubstTemplateTypeParmTypeLoc TL) {
6550 const SubstTemplateTypeParmType *T = TL.getTypePtr();
6551
6552 Decl *NewReplaced =
6553 getDerived().TransformDecl(TL.getNameLoc(), T->getAssociatedDecl());
6554
6555 // Substitute into the replacement type, which itself might involve something
6556 // that needs to be transformed. This only tends to occur with default
6557 // template arguments of template template parameters.
6558 TemporaryBase Rebase(*this, TL.getNameLoc(), DeclarationName());
6559 QualType Replacement = getDerived().TransformType(T->getReplacementType());
6560 if (Replacement.isNull())
6561 return QualType();
6562
6563 QualType Result = SemaRef.Context.getSubstTemplateTypeParmType(
6564 Replacement, NewReplaced, T->getIndex(), T->getPackIndex());
6565
6566 // Propagate type-source information.
6567 SubstTemplateTypeParmTypeLoc NewTL
6568 = TLB.push<SubstTemplateTypeParmTypeLoc>(Result);
6569 NewTL.setNameLoc(TL.getNameLoc());
6570 return Result;
6571
6572}
6573
6574template<typename Derived>
6575QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6576 TypeLocBuilder &TLB,
6577 SubstTemplateTypeParmPackTypeLoc TL) {
6578 return getDerived().TransformSubstTemplateTypeParmPackType(
6579 TLB, TL, /*SuppressObjCLifetime=*/false);
6580}
6581
6582template <typename Derived>
6583QualType TreeTransform<Derived>::TransformSubstTemplateTypeParmPackType(
6584 TypeLocBuilder &TLB, SubstTemplateTypeParmPackTypeLoc TL, bool) {
6585 return TransformTypeSpecType(TLB, TL);
6586}
6587
6588template<typename Derived>
6589QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6590 TypeLocBuilder &TLB,
6591 TemplateSpecializationTypeLoc TL) {
6592 const TemplateSpecializationType *T = TL.getTypePtr();
6593
6594 // The nested-name-specifier never matters in a TemplateSpecializationType,
6595 // because we can't have a dependent nested-name-specifier anyway.
6596 CXXScopeSpec SS;
6597 TemplateName Template
6598 = getDerived().TransformTemplateName(SS, T->getTemplateName(),
6599 TL.getTemplateNameLoc());
6600 if (Template.isNull())
6601 return QualType();
6602
6603 return getDerived().TransformTemplateSpecializationType(TLB, TL, Template);
6604}
6605
6606template<typename Derived>
6607QualType TreeTransform<Derived>::TransformAtomicType(TypeLocBuilder &TLB,
6608 AtomicTypeLoc TL) {
6609 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6610 if (ValueType.isNull())
6611 return QualType();
6612
6613 QualType Result = TL.getType();
6614 if (getDerived().AlwaysRebuild() ||
6615 ValueType != TL.getValueLoc().getType()) {
6616 Result = getDerived().RebuildAtomicType(ValueType, TL.getKWLoc());
6617 if (Result.isNull())
6618 return QualType();
6619 }
6620
6621 AtomicTypeLoc NewTL = TLB.push<AtomicTypeLoc>(Result);
6622 NewTL.setKWLoc(TL.getKWLoc());
6623 NewTL.setLParenLoc(TL.getLParenLoc());
6624 NewTL.setRParenLoc(TL.getRParenLoc());
6625
6626 return Result;
6627}
6628
6629template <typename Derived>
6630QualType TreeTransform<Derived>::TransformPipeType(TypeLocBuilder &TLB,
6631 PipeTypeLoc TL) {
6632 QualType ValueType = getDerived().TransformType(TLB, TL.getValueLoc());
6633 if (ValueType.isNull())
6634 return QualType();
6635
6636 QualType Result = TL.getType();
6637 if (getDerived().AlwaysRebuild() || ValueType != TL.getValueLoc().getType()) {
6638 const PipeType *PT = Result->castAs<PipeType>();
6639 bool isReadPipe = PT->isReadOnly();
6640 Result = getDerived().RebuildPipeType(ValueType, TL.getKWLoc(), isReadPipe);
6641 if (Result.isNull())
6642 return QualType();
6643 }
6644
6645 PipeTypeLoc NewTL = TLB.push<PipeTypeLoc>(Result);
6646 NewTL.setKWLoc(TL.getKWLoc());
6647
6648 return Result;
6649}
6650
6651template <typename Derived>
6652QualType TreeTransform<Derived>::TransformBitIntType(TypeLocBuilder &TLB,
6653 BitIntTypeLoc TL) {
6654 const BitIntType *EIT = TL.getTypePtr();
6655 QualType Result = TL.getType();
6656
6657 if (getDerived().AlwaysRebuild()) {
6658 Result = getDerived().RebuildBitIntType(EIT->isUnsigned(),
6659 EIT->getNumBits(), TL.getNameLoc());
6660 if (Result.isNull())
6661 return QualType();
6662 }
6663
6664 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6665 NewTL.setNameLoc(TL.getNameLoc());
6666 return Result;
6667}
6668
6669template <typename Derived>
6670QualType TreeTransform<Derived>::TransformDependentBitIntType(
6671 TypeLocBuilder &TLB, DependentBitIntTypeLoc TL) {
6672 const DependentBitIntType *EIT = TL.getTypePtr();
6673
6674 EnterExpressionEvaluationContext Unevaluated(
6675 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
6676 ExprResult BitsExpr = getDerived().TransformExpr(EIT->getNumBitsExpr());
6677 BitsExpr = SemaRef.ActOnConstantExpression(BitsExpr);
6678
6679 if (BitsExpr.isInvalid())
6680 return QualType();
6681
6682 QualType Result = TL.getType();
6683
6684 if (getDerived().AlwaysRebuild() || BitsExpr.get() != EIT->getNumBitsExpr()) {
6685 Result = getDerived().RebuildDependentBitIntType(
6686 EIT->isUnsigned(), BitsExpr.get(), TL.getNameLoc());
6687
6688 if (Result.isNull())
6689 return QualType();
6690 }
6691
6692 if (isa<DependentBitIntType>(Result)) {
6693 DependentBitIntTypeLoc NewTL = TLB.push<DependentBitIntTypeLoc>(Result);
6694 NewTL.setNameLoc(TL.getNameLoc());
6695 } else {
6696 BitIntTypeLoc NewTL = TLB.push<BitIntTypeLoc>(Result);
6697 NewTL.setNameLoc(TL.getNameLoc());
6698 }
6699 return Result;
6700}
6701
6702 /// Simple iterator that traverses the template arguments in a
6703 /// container that provides a \c getArgLoc() member function.
6704 ///
6705 /// This iterator is intended to be used with the iterator form of
6706 /// \c TreeTransform<Derived>::TransformTemplateArguments().
6707 template<typename ArgLocContainer>
6708 class TemplateArgumentLocContainerIterator {
6709 ArgLocContainer *Container;
6710 unsigned Index;
6711
6712 public:
6713 typedef TemplateArgumentLoc value_type;
6714 typedef TemplateArgumentLoc reference;
6715 typedef int difference_type;
6716 typedef std::input_iterator_tag iterator_category;
6717
6718 class pointer {
6719 TemplateArgumentLoc Arg;
6720
6721 public:
6722 explicit pointer(TemplateArgumentLoc Arg) : Arg(Arg) { }
6723
6724 const TemplateArgumentLoc *operator->() const {
6725 return &Arg;
6726 }
6727 };
6728
6729
6730 TemplateArgumentLocContainerIterator() {}
6731
6732 TemplateArgumentLocContainerIterator(ArgLocContainer &Container,
6733 unsigned Index)
6734 : Container(&Container), Index(Index) { }
6735
6736 TemplateArgumentLocContainerIterator &operator++() {
6737 ++Index;
6738 return *this;
6739 }
6740
6741 TemplateArgumentLocContainerIterator operator++(int) {
6742 TemplateArgumentLocContainerIterator Old(*this);
6743 ++(*this);
6744 return Old;
6745 }
6746
6747 TemplateArgumentLoc operator*() const {
6748 return Container->getArgLoc(Index);
6749 }
6750
6751 pointer operator->() const {
6752 return pointer(Container->getArgLoc(Index));
6753 }
6754
6755 friend bool operator==(const TemplateArgumentLocContainerIterator &X,
6756 const TemplateArgumentLocContainerIterator &Y) {
6757 return X.Container == Y.Container && X.Index == Y.Index;
6758 }
6759
6760 friend bool operator!=(const TemplateArgumentLocContainerIterator &X,
6761 const TemplateArgumentLocContainerIterator &Y) {
6762 return !(X == Y);
6763 }
6764 };
6765
6766template<typename Derived>
6767QualType TreeTransform<Derived>::TransformAutoType(TypeLocBuilder &TLB,
6768 AutoTypeLoc TL) {
6769 const AutoType *T = TL.getTypePtr();
6770 QualType OldDeduced = T->getDeducedType();
6771 QualType NewDeduced;
6772 if (!OldDeduced.isNull()) {
6773 NewDeduced = getDerived().TransformType(OldDeduced);
6774 if (NewDeduced.isNull())
6775 return QualType();
6776 }
6777
6778 ConceptDecl *NewCD = nullptr;
6779 TemplateArgumentListInfo NewTemplateArgs;
6780 NestedNameSpecifierLoc NewNestedNameSpec;
6781 if (T->isConstrained()) {
6782 NewCD = cast_or_null<ConceptDecl>(getDerived().TransformDecl(
6783 TL.getConceptNameLoc(), T->getTypeConstraintConcept()));
6784
6785 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6786 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6787 typedef TemplateArgumentLocContainerIterator<AutoTypeLoc> ArgIterator;
6788 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6789 ArgIterator(TL,
6790 TL.getNumArgs()),
6791 NewTemplateArgs))
6792 return QualType();
6793
6794 if (TL.getNestedNameSpecifierLoc()) {
6795 NewNestedNameSpec
6796 = getDerived().TransformNestedNameSpecifierLoc(
6797 TL.getNestedNameSpecifierLoc());
6798 if (!NewNestedNameSpec)
6799 return QualType();
6800 }
6801 }
6802
6803 QualType Result = TL.getType();
6804 if (getDerived().AlwaysRebuild() || NewDeduced != OldDeduced ||
6805 T->isDependentType() || T->isConstrained()) {
6806 // FIXME: Maybe don't rebuild if all template arguments are the same.
6807 llvm::SmallVector<TemplateArgument, 4> NewArgList;
6808 NewArgList.reserve(NewTemplateArgs.size());
6809 for (const auto &ArgLoc : NewTemplateArgs.arguments())
6810 NewArgList.push_back(ArgLoc.getArgument());
6811 Result = getDerived().RebuildAutoType(NewDeduced, T->getKeyword(), NewCD,
6812 NewArgList);
6813 if (Result.isNull())
6814 return QualType();
6815 }
6816
6817 AutoTypeLoc NewTL = TLB.push<AutoTypeLoc>(Result);
6818 NewTL.setNameLoc(TL.getNameLoc());
6819 NewTL.setNestedNameSpecifierLoc(NewNestedNameSpec);
6820 NewTL.setTemplateKWLoc(TL.getTemplateKWLoc());
6821 NewTL.setConceptNameLoc(TL.getConceptNameLoc());
6822 NewTL.setFoundDecl(TL.getFoundDecl());
6823 NewTL.setLAngleLoc(TL.getLAngleLoc());
6824 NewTL.setRAngleLoc(TL.getRAngleLoc());
6825 NewTL.setRParenLoc(TL.getRParenLoc());
6826 for (unsigned I = 0; I < NewTL.getNumArgs(); ++I)
6827 NewTL.setArgLocInfo(I, NewTemplateArgs.arguments()[I].getLocInfo());
6828
6829 return Result;
6830}
6831
6832template <typename Derived>
6833QualType TreeTransform<Derived>::TransformTemplateSpecializationType(
6834 TypeLocBuilder &TLB,
6835 TemplateSpecializationTypeLoc TL,
6836 TemplateName Template) {
6837 TemplateArgumentListInfo NewTemplateArgs;
6838 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6839 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6840 typedef TemplateArgumentLocContainerIterator<TemplateSpecializationTypeLoc>
6841 ArgIterator;
6842 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6843 ArgIterator(TL, TL.getNumArgs()),
6844 NewTemplateArgs))
6845 return QualType();
6846
6847 // FIXME: maybe don't rebuild if all the template arguments are the same.
6848
6849 QualType Result =
6850 getDerived().RebuildTemplateSpecializationType(Template,
6851 TL.getTemplateNameLoc(),
6852 NewTemplateArgs);
6853
6854 if (!Result.isNull()) {
6855 // Specializations of template template parameters are represented as
6856 // TemplateSpecializationTypes, and substitution of type alias templates
6857 // within a dependent context can transform them into
6858 // DependentTemplateSpecializationTypes.
6859 if (isa<DependentTemplateSpecializationType>(Result)) {
6860 DependentTemplateSpecializationTypeLoc NewTL
6861 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6862 NewTL.setElaboratedKeywordLoc(SourceLocation());
6863 NewTL.setQualifierLoc(NestedNameSpecifierLoc());
6864 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6865 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6866 NewTL.setLAngleLoc(TL.getLAngleLoc());
6867 NewTL.setRAngleLoc(TL.getRAngleLoc());
6868 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6869 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6870 return Result;
6871 }
6872
6873 TemplateSpecializationTypeLoc NewTL
6874 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6875 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6876 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6877 NewTL.setLAngleLoc(TL.getLAngleLoc());
6878 NewTL.setRAngleLoc(TL.getRAngleLoc());
6879 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6880 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6881 }
6882
6883 return Result;
6884}
6885
6886template <typename Derived>
6887QualType TreeTransform<Derived>::TransformDependentTemplateSpecializationType(
6888 TypeLocBuilder &TLB,
6889 DependentTemplateSpecializationTypeLoc TL,
6890 TemplateName Template,
6891 CXXScopeSpec &SS) {
6892 TemplateArgumentListInfo NewTemplateArgs;
6893 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
6894 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
6895 typedef TemplateArgumentLocContainerIterator<
6896 DependentTemplateSpecializationTypeLoc> ArgIterator;
6897 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
6898 ArgIterator(TL, TL.getNumArgs()),
6899 NewTemplateArgs))
6900 return QualType();
6901
6902 // FIXME: maybe don't rebuild if all the template arguments are the same.
6903
6904 if (DependentTemplateName *DTN = Template.getAsDependentTemplateName()) {
6905 QualType Result = getSema().Context.getDependentTemplateSpecializationType(
6906 TL.getTypePtr()->getKeyword(), DTN->getQualifier(),
6907 DTN->getIdentifier(), NewTemplateArgs.arguments());
6908
6909 DependentTemplateSpecializationTypeLoc NewTL
6910 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
6911 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6912 NewTL.setQualifierLoc(SS.getWithLocInContext(SemaRef.Context));
6913 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6914 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6915 NewTL.setLAngleLoc(TL.getLAngleLoc());
6916 NewTL.setRAngleLoc(TL.getRAngleLoc());
6917 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6918 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6919 return Result;
6920 }
6921
6922 QualType Result
6923 = getDerived().RebuildTemplateSpecializationType(Template,
6924 TL.getTemplateNameLoc(),
6925 NewTemplateArgs);
6926
6927 if (!Result.isNull()) {
6928 /// FIXME: Wrap this in an elaborated-type-specifier?
6929 TemplateSpecializationTypeLoc NewTL
6930 = TLB.push<TemplateSpecializationTypeLoc>(Result);
6931 NewTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
6932 NewTL.setTemplateNameLoc(TL.getTemplateNameLoc());
6933 NewTL.setLAngleLoc(TL.getLAngleLoc());
6934 NewTL.setRAngleLoc(TL.getRAngleLoc());
6935 for (unsigned i = 0, e = NewTemplateArgs.size(); i != e; ++i)
6936 NewTL.setArgLocInfo(i, NewTemplateArgs[i].getLocInfo());
6937 }
6938
6939 return Result;
6940}
6941
6942template<typename Derived>
6943QualType
6944TreeTransform<Derived>::TransformElaboratedType(TypeLocBuilder &TLB,
6945 ElaboratedTypeLoc TL) {
6946 const ElaboratedType *T = TL.getTypePtr();
6947
6948 NestedNameSpecifierLoc QualifierLoc;
6949 // NOTE: the qualifier in an ElaboratedType is optional.
6950 if (TL.getQualifierLoc()) {
6951 QualifierLoc
6952 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
6953 if (!QualifierLoc)
6954 return QualType();
6955 }
6956
6957 QualType NamedT = getDerived().TransformType(TLB, TL.getNamedTypeLoc());
6958 if (NamedT.isNull())
6959 return QualType();
6960
6961 // C++0x [dcl.type.elab]p2:
6962 // If the identifier resolves to a typedef-name or the simple-template-id
6963 // resolves to an alias template specialization, the
6964 // elaborated-type-specifier is ill-formed.
6965 if (T->getKeyword() != ETK_None && T->getKeyword() != ETK_Typename) {
6966 if (const TemplateSpecializationType *TST =
6967 NamedT->getAs<TemplateSpecializationType>()) {
6968 TemplateName Template = TST->getTemplateName();
6969 if (TypeAliasTemplateDecl *TAT = dyn_cast_or_null<TypeAliasTemplateDecl>(
6970 Template.getAsTemplateDecl())) {
6971 SemaRef.Diag(TL.getNamedTypeLoc().getBeginLoc(),
6972 diag::err_tag_reference_non_tag)
6973 << TAT << Sema::NTK_TypeAliasTemplate
6974 << ElaboratedType::getTagTypeKindForKeyword(T->getKeyword());
6975 SemaRef.Diag(TAT->getLocation(), diag::note_declared_at);
6976 }
6977 }
6978 }
6979
6980 QualType Result = TL.getType();
6981 if (getDerived().AlwaysRebuild() ||
6982 QualifierLoc != TL.getQualifierLoc() ||
6983 NamedT != T->getNamedType()) {
6984 Result = getDerived().RebuildElaboratedType(TL.getElaboratedKeywordLoc(),
6985 T->getKeyword(),
6986 QualifierLoc, NamedT);
6987 if (Result.isNull())
6988 return QualType();
6989 }
6990
6991 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
6992 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
6993 NewTL.setQualifierLoc(QualifierLoc);
6994 return Result;
6995}
6996
6997template<typename Derived>
6998QualType TreeTransform<Derived>::TransformAttributedType(
6999 TypeLocBuilder &TLB,
7000 AttributedTypeLoc TL) {
7001 const AttributedType *oldType = TL.getTypePtr();
7002 QualType modifiedType = getDerived().TransformType(TLB, TL.getModifiedLoc());
7003 if (modifiedType.isNull())
7004 return QualType();
7005
7006 // oldAttr can be null if we started with a QualType rather than a TypeLoc.
7007 const Attr *oldAttr = TL.getAttr();
7008 const Attr *newAttr = oldAttr ? getDerived().TransformAttr(oldAttr) : nullptr;
7009 if (oldAttr && !newAttr)
7010 return QualType();
7011
7012 QualType result = TL.getType();
7013
7014 // FIXME: dependent operand expressions?
7015 if (getDerived().AlwaysRebuild() ||
7016 modifiedType != oldType->getModifiedType()) {
7017 // TODO: this is really lame; we should really be rebuilding the
7018 // equivalent type from first principles.
7019 QualType equivalentType
7020 = getDerived().TransformType(oldType->getEquivalentType());
7021 if (equivalentType.isNull())
7022 return QualType();
7023
7024 // Check whether we can add nullability; it is only represented as
7025 // type sugar, and therefore cannot be diagnosed in any other way.
7026 if (auto nullability = oldType->getImmediateNullability()) {
7027 if (!modifiedType->canHaveNullability()) {
7028 SemaRef.Diag((TL.getAttr() ? TL.getAttr()->getLocation()
7029 : TL.getModifiedLoc().getBeginLoc()),
7030 diag::err_nullability_nonpointer)
7031 << DiagNullabilityKind(*nullability, false) << modifiedType;
7032 return QualType();
7033 }
7034 }
7035
7036 result = SemaRef.Context.getAttributedType(TL.getAttrKind(),
7037 modifiedType,
7038 equivalentType);
7039 }
7040
7041 AttributedTypeLoc newTL = TLB.push<AttributedTypeLoc>(result);
7042 newTL.setAttr(newAttr);
7043 return result;
7044}
7045
7046template <typename Derived>
7047QualType TreeTransform<Derived>::TransformBTFTagAttributedType(
7048 TypeLocBuilder &TLB, BTFTagAttributedTypeLoc TL) {
7049 // The BTFTagAttributedType is available for C only.
7050 llvm_unreachable("Unexpected TreeTransform for BTFTagAttributedType")::llvm::llvm_unreachable_internal("Unexpected TreeTransform for BTFTagAttributedType"
, "clang/lib/Sema/TreeTransform.h", 7050)
;
7051}
7052
7053template<typename Derived>
7054QualType
7055TreeTransform<Derived>::TransformParenType(TypeLocBuilder &TLB,
7056 ParenTypeLoc TL) {
7057 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7058 if (Inner.isNull())
7059 return QualType();
7060
7061 QualType Result = TL.getType();
7062 if (getDerived().AlwaysRebuild() ||
7063 Inner != TL.getInnerLoc().getType()) {
7064 Result = getDerived().RebuildParenType(Inner);
7065 if (Result.isNull())
7066 return QualType();
7067 }
7068
7069 ParenTypeLoc NewTL = TLB.push<ParenTypeLoc>(Result);
7070 NewTL.setLParenLoc(TL.getLParenLoc());
7071 NewTL.setRParenLoc(TL.getRParenLoc());
7072 return Result;
7073}
7074
7075template <typename Derived>
7076QualType
7077TreeTransform<Derived>::TransformMacroQualifiedType(TypeLocBuilder &TLB,
7078 MacroQualifiedTypeLoc TL) {
7079 QualType Inner = getDerived().TransformType(TLB, TL.getInnerLoc());
7080 if (Inner.isNull())
7081 return QualType();
7082
7083 QualType Result = TL.getType();
7084 if (getDerived().AlwaysRebuild() || Inner != TL.getInnerLoc().getType()) {
7085 Result =
7086 getDerived().RebuildMacroQualifiedType(Inner, TL.getMacroIdentifier());
7087 if (Result.isNull())
7088 return QualType();
7089 }
7090
7091 MacroQualifiedTypeLoc NewTL = TLB.push<MacroQualifiedTypeLoc>(Result);
7092 NewTL.setExpansionLoc(TL.getExpansionLoc());
7093 return Result;
7094}
7095
7096template<typename Derived>
7097QualType TreeTransform<Derived>::TransformDependentNameType(
7098 TypeLocBuilder &TLB, DependentNameTypeLoc TL) {
7099 return TransformDependentNameType(TLB, TL, false);
7100}
7101
7102template<typename Derived>
7103QualType TreeTransform<Derived>::TransformDependentNameType(
7104 TypeLocBuilder &TLB, DependentNameTypeLoc TL, bool DeducedTSTContext) {
7105 const DependentNameType *T = TL.getTypePtr();
7106
7107 NestedNameSpecifierLoc QualifierLoc
7108 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7109 if (!QualifierLoc)
7110 return QualType();
7111
7112 QualType Result
7113 = getDerived().RebuildDependentNameType(T->getKeyword(),
7114 TL.getElaboratedKeywordLoc(),
7115 QualifierLoc,
7116 T->getIdentifier(),
7117 TL.getNameLoc(),
7118 DeducedTSTContext);
7119 if (Result.isNull())
7120 return QualType();
7121
7122 if (const ElaboratedType* ElabT = Result->getAs<ElaboratedType>()) {
7123 QualType NamedT = ElabT->getNamedType();
7124 TLB.pushTypeSpec(NamedT).setNameLoc(TL.getNameLoc());
7125
7126 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7127 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7128 NewTL.setQualifierLoc(QualifierLoc);
7129 } else {
7130 DependentNameTypeLoc NewTL = TLB.push<DependentNameTypeLoc>(Result);
7131 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7132 NewTL.setQualifierLoc(QualifierLoc);
7133 NewTL.setNameLoc(TL.getNameLoc());
7134 }
7135 return Result;
7136}
7137
7138template<typename Derived>
7139QualType TreeTransform<Derived>::
7140 TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7141 DependentTemplateSpecializationTypeLoc TL) {
7142 NestedNameSpecifierLoc QualifierLoc;
7143 if (TL.getQualifierLoc()) {
7144 QualifierLoc
7145 = getDerived().TransformNestedNameSpecifierLoc(TL.getQualifierLoc());
7146 if (!QualifierLoc)
7147 return QualType();
7148 }
7149
7150 return getDerived()
7151 .TransformDependentTemplateSpecializationType(TLB, TL, QualifierLoc);
7152}
7153
7154template<typename Derived>
7155QualType TreeTransform<Derived>::
7156TransformDependentTemplateSpecializationType(TypeLocBuilder &TLB,
7157 DependentTemplateSpecializationTypeLoc TL,
7158 NestedNameSpecifierLoc QualifierLoc) {
7159 const DependentTemplateSpecializationType *T = TL.getTypePtr();
7160
7161 TemplateArgumentListInfo NewTemplateArgs;
7162 NewTemplateArgs.setLAngleLoc(TL.getLAngleLoc());
7163 NewTemplateArgs.setRAngleLoc(TL.getRAngleLoc());
7164
7165 typedef TemplateArgumentLocContainerIterator<
7166 DependentTemplateSpecializationTypeLoc> ArgIterator;
7167 if (getDerived().TransformTemplateArguments(ArgIterator(TL, 0),
7168 ArgIterator(TL, TL.getNumArgs()),
7169 NewTemplateArgs))
7170 return QualType();
7171
7172 QualType Result = getDerived().RebuildDependentTemplateSpecializationType(
7173 T->getKeyword(), QualifierLoc, TL.getTemplateKeywordLoc(),
7174 T->getIdentifier(), TL.getTemplateNameLoc(), NewTemplateArgs,
7175 /*AllowInjectedClassName*/ false);
7176 if (Result.isNull())
7177 return QualType();
7178
7179 if (const ElaboratedType *ElabT = dyn_cast<ElaboratedType>(Result)) {
7180 QualType NamedT = ElabT->getNamedType();
7181
7182 // Copy information relevant to the template specialization.
7183 TemplateSpecializationTypeLoc NamedTL
7184 = TLB.push<TemplateSpecializationTypeLoc>(NamedT);
7185 NamedTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7186 NamedTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7187 NamedTL.setLAngleLoc(TL.getLAngleLoc());
7188 NamedTL.setRAngleLoc(TL.getRAngleLoc());
7189 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7190 NamedTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7191
7192 // Copy information relevant to the elaborated type.
7193 ElaboratedTypeLoc NewTL = TLB.push<ElaboratedTypeLoc>(Result);
7194 NewTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7195 NewTL.setQualifierLoc(QualifierLoc);
7196 } else if (isa<DependentTemplateSpecializationType>(Result)) {
7197 DependentTemplateSpecializationTypeLoc SpecTL
7198 = TLB.push<DependentTemplateSpecializationTypeLoc>(Result);
7199 SpecTL.setElaboratedKeywordLoc(TL.getElaboratedKeywordLoc());
7200 SpecTL.setQualifierLoc(QualifierLoc);
7201 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7202 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7203 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7204 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7205 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7206 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7207 } else {
7208 TemplateSpecializationTypeLoc SpecTL
7209 = TLB.push<TemplateSpecializationTypeLoc>(Result);
7210 SpecTL.setTemplateKeywordLoc(TL.getTemplateKeywordLoc());
7211 SpecTL.setTemplateNameLoc(TL.getTemplateNameLoc());
7212 SpecTL.setLAngleLoc(TL.getLAngleLoc());
7213 SpecTL.setRAngleLoc(TL.getRAngleLoc());
7214 for (unsigned I = 0, E = NewTemplateArgs.size(); I != E; ++I)
7215 SpecTL.setArgLocInfo(I, NewTemplateArgs[I].getLocInfo());
7216 }
7217 return Result;
7218}
7219
7220template<typename Derived>
7221QualType TreeTransform<Derived>::TransformPackExpansionType(TypeLocBuilder &TLB,
7222 PackExpansionTypeLoc TL) {
7223 QualType Pattern
7224 = getDerived().TransformType(TLB, TL.getPatternLoc());
7225 if (Pattern.isNull())
7226 return QualType();
7227
7228 QualType Result = TL.getType();
7229 if (getDerived().AlwaysRebuild() ||
7230 Pattern != TL.getPatternLoc().getType()) {
7231 Result = getDerived().RebuildPackExpansionType(Pattern,
7232 TL.getPatternLoc().getSourceRange(),
7233 TL.getEllipsisLoc(),
7234 TL.getTypePtr()->getNumExpansions());
7235 if (Result.isNull())
7236 return QualType();
7237 }
7238
7239 PackExpansionTypeLoc NewT = TLB.push<PackExpansionTypeLoc>(Result);
7240 NewT.setEllipsisLoc(TL.getEllipsisLoc());
7241 return Result;
7242}
7243
7244template<typename Derived>
7245QualType
7246TreeTransform<Derived>::TransformObjCInterfaceType(TypeLocBuilder &TLB,
7247 ObjCInterfaceTypeLoc TL) {
7248 // ObjCInterfaceType is never dependent.
7249 TLB.pushFullCopy(TL);
7250 return TL.getType();
7251}
7252
7253template<typename Derived>
7254QualType
7255TreeTransform<Derived>::TransformObjCTypeParamType(TypeLocBuilder &TLB,
7256 ObjCTypeParamTypeLoc TL) {
7257 const ObjCTypeParamType *T = TL.getTypePtr();
7258 ObjCTypeParamDecl *OTP = cast_or_null<ObjCTypeParamDecl>(
7259 getDerived().TransformDecl(T->getDecl()->getLocation(), T->getDecl()));
7260 if (!OTP)
7261 return QualType();
7262
7263 QualType Result = TL.getType();
7264 if (getDerived().AlwaysRebuild() ||
7265 OTP != T->getDecl()) {
7266 Result = getDerived().RebuildObjCTypeParamType(
7267 OTP, TL.getProtocolLAngleLoc(),
7268 llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7269 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7270 if (Result.isNull())
7271 return QualType();
7272 }
7273
7274 ObjCTypeParamTypeLoc NewTL = TLB.push<ObjCTypeParamTypeLoc>(Result);
7275 if (TL.getNumProtocols()) {
7276 NewTL.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7277 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7278 NewTL.setProtocolLoc(i, TL.getProtocolLoc(i));
7279 NewTL.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7280 }
7281 return Result;
7282}
7283
7284template<typename Derived>
7285QualType
7286TreeTransform<Derived>::TransformObjCObjectType(TypeLocBuilder &TLB,
7287 ObjCObjectTypeLoc TL) {
7288 // Transform base type.
7289 QualType BaseType = getDerived().TransformType(TLB, TL.getBaseLoc());
7290 if (BaseType.isNull())
7291 return QualType();
7292
7293 bool AnyChanged = BaseType != TL.getBaseLoc().getType();
7294
7295 // Transform type arguments.
7296 SmallVector<TypeSourceInfo *, 4> NewTypeArgInfos;
7297 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i) {
7298 TypeSourceInfo *TypeArgInfo = TL.getTypeArgTInfo(i);
7299 TypeLoc TypeArgLoc = TypeArgInfo->getTypeLoc();
7300 QualType TypeArg = TypeArgInfo->getType();
7301 if (auto PackExpansionLoc = TypeArgLoc.getAs<PackExpansionTypeLoc>()) {
7302 AnyChanged = true;
7303
7304 // We have a pack expansion. Instantiate it.
7305 const auto *PackExpansion = PackExpansionLoc.getType()
7306 ->castAs<PackExpansionType>();
7307 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
7308 SemaRef.collectUnexpandedParameterPacks(PackExpansion->getPattern(),
7309 Unexpanded);
7310 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 7310, __extension__ __PRETTY_FUNCTION__
))
;
7311
7312 // Determine whether the set of unexpanded parameter packs can
7313 // and should be expanded.
7314 TypeLoc PatternLoc = PackExpansionLoc.getPatternLoc();
7315 bool Expand = false;
7316 bool RetainExpansion = false;
7317 std::optional<unsigned> NumExpansions = PackExpansion->getNumExpansions();
7318 if (getDerived().TryExpandParameterPacks(
7319 PackExpansionLoc.getEllipsisLoc(), PatternLoc.getSourceRange(),
7320 Unexpanded, Expand, RetainExpansion, NumExpansions))
7321 return QualType();
7322
7323 if (!Expand) {
7324 // We can't expand this pack expansion into separate arguments yet;
7325 // just substitute into the pattern and create a new pack expansion
7326 // type.
7327 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
7328
7329 TypeLocBuilder TypeArgBuilder;
7330 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7331 QualType NewPatternType = getDerived().TransformType(TypeArgBuilder,
7332 PatternLoc);
7333 if (NewPatternType.isNull())
7334 return QualType();
7335
7336 QualType NewExpansionType = SemaRef.Context.getPackExpansionType(
7337 NewPatternType, NumExpansions);
7338 auto NewExpansionLoc = TLB.push<PackExpansionTypeLoc>(NewExpansionType);
7339 NewExpansionLoc.setEllipsisLoc(PackExpansionLoc.getEllipsisLoc());
7340 NewTypeArgInfos.push_back(
7341 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewExpansionType));
7342 continue;
7343 }
7344
7345 // Substitute into the pack expansion pattern for each slice of the
7346 // pack.
7347 for (unsigned ArgIdx = 0; ArgIdx != *NumExpansions; ++ArgIdx) {
7348 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), ArgIdx);
7349
7350 TypeLocBuilder TypeArgBuilder;
7351 TypeArgBuilder.reserve(PatternLoc.getFullDataSize());
7352
7353 QualType NewTypeArg = getDerived().TransformType(TypeArgBuilder,
7354 PatternLoc);
7355 if (NewTypeArg.isNull())
7356 return QualType();
7357
7358 NewTypeArgInfos.push_back(
7359 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7360 }
7361
7362 continue;
7363 }
7364
7365 TypeLocBuilder TypeArgBuilder;
7366 TypeArgBuilder.reserve(TypeArgLoc.getFullDataSize());
7367 QualType NewTypeArg =
7368 getDerived().TransformType(TypeArgBuilder, TypeArgLoc);
7369 if (NewTypeArg.isNull())
7370 return QualType();
7371
7372 // If nothing changed, just keep the old TypeSourceInfo.
7373 if (NewTypeArg == TypeArg) {
7374 NewTypeArgInfos.push_back(TypeArgInfo);
7375 continue;
7376 }
7377
7378 NewTypeArgInfos.push_back(
7379 TypeArgBuilder.getTypeSourceInfo(SemaRef.Context, NewTypeArg));
7380 AnyChanged = true;
7381 }
7382
7383 QualType Result = TL.getType();
7384 if (getDerived().AlwaysRebuild() || AnyChanged) {
7385 // Rebuild the type.
7386 Result = getDerived().RebuildObjCObjectType(
7387 BaseType, TL.getBeginLoc(), TL.getTypeArgsLAngleLoc(), NewTypeArgInfos,
7388 TL.getTypeArgsRAngleLoc(), TL.getProtocolLAngleLoc(),
7389 llvm::ArrayRef(TL.getTypePtr()->qual_begin(), TL.getNumProtocols()),
7390 TL.getProtocolLocs(), TL.getProtocolRAngleLoc());
7391
7392 if (Result.isNull())
7393 return QualType();
7394 }
7395
7396 ObjCObjectTypeLoc NewT = TLB.push<ObjCObjectTypeLoc>(Result);
7397 NewT.setHasBaseTypeAsWritten(true);
7398 NewT.setTypeArgsLAngleLoc(TL.getTypeArgsLAngleLoc());
7399 for (unsigned i = 0, n = TL.getNumTypeArgs(); i != n; ++i)
7400 NewT.setTypeArgTInfo(i, NewTypeArgInfos[i]);
7401 NewT.setTypeArgsRAngleLoc(TL.getTypeArgsRAngleLoc());
7402 NewT.setProtocolLAngleLoc(TL.getProtocolLAngleLoc());
7403 for (unsigned i = 0, n = TL.getNumProtocols(); i != n; ++i)
7404 NewT.setProtocolLoc(i, TL.getProtocolLoc(i));
7405 NewT.setProtocolRAngleLoc(TL.getProtocolRAngleLoc());
7406 return Result;
7407}
7408
7409template<typename Derived>
7410QualType
7411TreeTransform<Derived>::TransformObjCObjectPointerType(TypeLocBuilder &TLB,
7412 ObjCObjectPointerTypeLoc TL) {
7413 QualType PointeeType = getDerived().TransformType(TLB, TL.getPointeeLoc());
7414 if (PointeeType.isNull())
7415 return QualType();
7416
7417 QualType Result = TL.getType();
7418 if (getDerived().AlwaysRebuild() ||
7419 PointeeType != TL.getPointeeLoc().getType()) {
7420 Result = getDerived().RebuildObjCObjectPointerType(PointeeType,
7421 TL.getStarLoc());
7422 if (Result.isNull())
7423 return QualType();
7424 }
7425
7426 ObjCObjectPointerTypeLoc NewT = TLB.push<ObjCObjectPointerTypeLoc>(Result);
7427 NewT.setStarLoc(TL.getStarLoc());
7428 return Result;
7429}
7430
7431//===----------------------------------------------------------------------===//
7432// Statement transformation
7433//===----------------------------------------------------------------------===//
7434template<typename Derived>
7435StmtResult
7436TreeTransform<Derived>::TransformNullStmt(NullStmt *S) {
7437 return S;
7438}
7439
7440template<typename Derived>
7441StmtResult
7442TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S) {
7443 return getDerived().TransformCompoundStmt(S, false);
7444}
7445
7446template<typename Derived>
7447StmtResult
7448TreeTransform<Derived>::TransformCompoundStmt(CompoundStmt *S,
7449 bool IsStmtExpr) {
7450 Sema::CompoundScopeRAII CompoundScope(getSema());
7451
7452 const Stmt *ExprResult = S->getStmtExprResult();
7453 bool SubStmtInvalid = false;
7454 bool SubStmtChanged = false;
7455 SmallVector<Stmt*, 8> Statements;
7456 for (auto *B : S->body()) {
7457 StmtResult Result = getDerived().TransformStmt(
7458 B, IsStmtExpr && B == ExprResult ? SDK_StmtExprResult : SDK_Discarded);
7459
7460 if (Result.isInvalid()) {
7461 // Immediately fail if this was a DeclStmt, since it's very
7462 // likely that this will cause problems for future statements.
7463 if (isa<DeclStmt>(B))
7464 return StmtError();
7465
7466 // Otherwise, just keep processing substatements and fail later.
7467 SubStmtInvalid = true;
7468 continue;
7469 }
7470
7471 SubStmtChanged = SubStmtChanged || Result.get() != B;
7472 Statements.push_back(Result.getAs<Stmt>());
7473 }
7474
7475 if (SubStmtInvalid)
7476 return StmtError();
7477
7478 if (!getDerived().AlwaysRebuild() &&
7479 !SubStmtChanged)
7480 return S;
7481
7482 return getDerived().RebuildCompoundStmt(S->getLBracLoc(),
7483 Statements,
7484 S->getRBracLoc(),
7485 IsStmtExpr);
7486}
7487
7488template<typename Derived>
7489StmtResult
7490TreeTransform<Derived>::TransformCaseStmt(CaseStmt *S) {
7491 ExprResult LHS, RHS;
7492 {
7493 EnterExpressionEvaluationContext Unevaluated(
7494 SemaRef, Sema::ExpressionEvaluationContext::ConstantEvaluated);
7495
7496 // Transform the left-hand case value.
7497 LHS = getDerived().TransformExpr(S->getLHS());
7498 LHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), LHS);
7499 if (LHS.isInvalid())
7500 return StmtError();
7501
7502 // Transform the right-hand case value (for the GNU case-range extension).
7503 RHS = getDerived().TransformExpr(S->getRHS());
7504 RHS = SemaRef.ActOnCaseExpr(S->getCaseLoc(), RHS);
7505 if (RHS.isInvalid())
7506 return StmtError();
7507 }
7508
7509 // Build the case statement.
7510 // Case statements are always rebuilt so that they will attached to their
7511 // transformed switch statement.
7512 StmtResult Case = getDerived().RebuildCaseStmt(S->getCaseLoc(),
7513 LHS.get(),
7514 S->getEllipsisLoc(),
7515 RHS.get(),
7516 S->getColonLoc());
7517 if (Case.isInvalid())
7518 return StmtError();
7519
7520 // Transform the statement following the case
7521 StmtResult SubStmt =
7522 getDerived().TransformStmt(S->getSubStmt());
7523 if (SubStmt.isInvalid())
7524 return StmtError();
7525
7526 // Attach the body to the case statement
7527 return getDerived().RebuildCaseStmtBody(Case.get(), SubStmt.get());
7528}
7529
7530template <typename Derived>
7531StmtResult TreeTransform<Derived>::TransformDefaultStmt(DefaultStmt *S) {
7532 // Transform the statement following the default case
7533 StmtResult SubStmt =
7534 getDerived().TransformStmt(S->getSubStmt());
7535 if (SubStmt.isInvalid())
7536 return StmtError();
7537
7538 // Default statements are always rebuilt
7539 return getDerived().RebuildDefaultStmt(S->getDefaultLoc(), S->getColonLoc(),
7540 SubStmt.get());
7541}
7542
7543template<typename Derived>
7544StmtResult
7545TreeTransform<Derived>::TransformLabelStmt(LabelStmt *S, StmtDiscardKind SDK) {
7546 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7547 if (SubStmt.isInvalid())
7548 return StmtError();
7549
7550 Decl *LD = getDerived().TransformDecl(S->getDecl()->getLocation(),
7551 S->getDecl());
7552 if (!LD)
7553 return StmtError();
7554
7555 // If we're transforming "in-place" (we're not creating new local
7556 // declarations), assume we're replacing the old label statement
7557 // and clear out the reference to it.
7558 if (LD == S->getDecl())
7559 S->getDecl()->setStmt(nullptr);
7560
7561 // FIXME: Pass the real colon location in.
7562 return getDerived().RebuildLabelStmt(S->getIdentLoc(),
7563 cast<LabelDecl>(LD), SourceLocation(),
7564 SubStmt.get());
7565}
7566
7567template <typename Derived>
7568const Attr *TreeTransform<Derived>::TransformAttr(const Attr *R) {
7569 if (!R)
7570 return R;
7571
7572 switch (R->getKind()) {
7573// Transform attributes by calling TransformXXXAttr.
7574#define ATTR(X) \
7575 case attr::X: \
7576 return getDerived().Transform##X##Attr(cast<X##Attr>(R));
7577#include "clang/Basic/AttrList.inc"
7578 }
7579 return R;
7580}
7581
7582template <typename Derived>
7583const Attr *TreeTransform<Derived>::TransformStmtAttr(const Stmt *OrigS,
7584 const Stmt *InstS,
7585 const Attr *R) {
7586 if (!R)
7587 return R;
7588
7589 switch (R->getKind()) {
7590// Transform attributes by calling TransformStmtXXXAttr.
7591#define ATTR(X) \
7592 case attr::X: \
7593 return getDerived().TransformStmt##X##Attr(OrigS, InstS, cast<X##Attr>(R));
7594#include "clang/Basic/AttrList.inc"
7595 }
7596 return TransformAttr(R);
7597}
7598
7599template <typename Derived>
7600StmtResult
7601TreeTransform<Derived>::TransformAttributedStmt(AttributedStmt *S,
7602 StmtDiscardKind SDK) {
7603 StmtResult SubStmt = getDerived().TransformStmt(S->getSubStmt(), SDK);
7604 if (SubStmt.isInvalid())
7605 return StmtError();
7606
7607 bool AttrsChanged = false;
7608 SmallVector<const Attr *, 1> Attrs;
7609
7610 // Visit attributes and keep track if any are transformed.
7611 for (const auto *I : S->getAttrs()) {
7612 const Attr *R =
7613 getDerived().TransformStmtAttr(S->getSubStmt(), SubStmt.get(), I);
7614 AttrsChanged |= (I != R);
7615 if (R)
7616 Attrs.push_back(R);
7617 }
7618
7619 if (SubStmt.get() == S->getSubStmt() && !AttrsChanged)
7620 return S;
7621
7622 // If transforming the attributes failed for all of the attributes in the
7623 // statement, don't make an AttributedStmt without attributes.
7624 if (Attrs.empty())
7625 return SubStmt;
7626
7627 return getDerived().RebuildAttributedStmt(S->getAttrLoc(), Attrs,
7628 SubStmt.get());
7629}
7630
7631template<typename Derived>
7632StmtResult
7633TreeTransform<Derived>::TransformIfStmt(IfStmt *S) {
7634 // Transform the initialization statement
7635 StmtResult Init = getDerived().TransformStmt(S->getInit());
7636 if (Init.isInvalid())
7637 return StmtError();
7638
7639 Sema::ConditionResult Cond;
7640 if (!S->isConsteval()) {
7641 // Transform the condition
7642 Cond = getDerived().TransformCondition(
7643 S->getIfLoc(), S->getConditionVariable(), S->getCond(),
7644 S->isConstexpr() ? Sema::ConditionKind::ConstexprIf
7645 : Sema::ConditionKind::Boolean);
7646 if (Cond.isInvalid())
7647 return StmtError();
7648 }
7649
7650 // If this is a constexpr if, determine which arm we should instantiate.
7651 std::optional<bool> ConstexprConditionValue;
7652 if (S->isConstexpr())
7653 ConstexprConditionValue = Cond.getKnownValue();
7654
7655 // Transform the "then" branch.
7656 StmtResult Then;
7657 if (!ConstexprConditionValue || *ConstexprConditionValue) {
7658 Then = getDerived().TransformStmt(S->getThen());
7659 if (Then.isInvalid())
7660 return StmtError();
7661 } else {
7662 Then = new (getSema().Context) NullStmt(S->getThen()->getBeginLoc());
7663 }
7664
7665 // Transform the "else" branch.
7666 StmtResult Else;
7667 if (!ConstexprConditionValue || !*ConstexprConditionValue) {
7668 Else = getDerived().TransformStmt(S->getElse());
7669 if (Else.isInvalid())
7670 return StmtError();
7671 }
7672
7673 if (!getDerived().AlwaysRebuild() &&
7674 Init.get() == S->getInit() &&
7675 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7676 Then.get() == S->getThen() &&
7677 Else.get() == S->getElse())
7678 return S;
7679
7680 return getDerived().RebuildIfStmt(
7681 S->getIfLoc(), S->getStatementKind(), S->getLParenLoc(), Cond,
7682 S->getRParenLoc(), Init.get(), Then.get(), S->getElseLoc(), Else.get());
7683}
7684
7685template<typename Derived>
7686StmtResult
7687TreeTransform<Derived>::TransformSwitchStmt(SwitchStmt *S) {
7688 // Transform the initialization statement
7689 StmtResult Init = getDerived().TransformStmt(S->getInit());
7690 if (Init.isInvalid())
7691 return StmtError();
7692
7693 // Transform the condition.
7694 Sema::ConditionResult Cond = getDerived().TransformCondition(
7695 S->getSwitchLoc(), S->getConditionVariable(), S->getCond(),
7696 Sema::ConditionKind::Switch);
7697 if (Cond.isInvalid())
7698 return StmtError();
7699
7700 // Rebuild the switch statement.
7701 StmtResult Switch =
7702 getDerived().RebuildSwitchStmtStart(S->getSwitchLoc(), S->getLParenLoc(),
7703 Init.get(), Cond, S->getRParenLoc());
7704 if (Switch.isInvalid())
7705 return StmtError();
7706
7707 // Transform the body of the switch statement.
7708 StmtResult Body = getDerived().TransformStmt(S->getBody());
7709 if (Body.isInvalid())
7710 return StmtError();
7711
7712 // Complete the switch statement.
7713 return getDerived().RebuildSwitchStmtBody(S->getSwitchLoc(), Switch.get(),
7714 Body.get());
7715}
7716
7717template<typename Derived>
7718StmtResult
7719TreeTransform<Derived>::TransformWhileStmt(WhileStmt *S) {
7720 // Transform the condition
7721 Sema::ConditionResult Cond = getDerived().TransformCondition(
7722 S->getWhileLoc(), S->getConditionVariable(), S->getCond(),
7723 Sema::ConditionKind::Boolean);
7724 if (Cond.isInvalid())
7725 return StmtError();
7726
7727 // Transform the body
7728 StmtResult Body = getDerived().TransformStmt(S->getBody());
7729 if (Body.isInvalid())
7730 return StmtError();
7731
7732 if (!getDerived().AlwaysRebuild() &&
7733 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7734 Body.get() == S->getBody())
7735 return Owned(S);
7736
7737 return getDerived().RebuildWhileStmt(S->getWhileLoc(), S->getLParenLoc(),
7738 Cond, S->getRParenLoc(), Body.get());
7739}
7740
7741template<typename Derived>
7742StmtResult
7743TreeTransform<Derived>::TransformDoStmt(DoStmt *S) {
7744 // Transform the body
7745 StmtResult Body = getDerived().TransformStmt(S->getBody());
7746 if (Body.isInvalid())
7747 return StmtError();
7748
7749 // Transform the condition
7750 ExprResult Cond = getDerived().TransformExpr(S->getCond());
7751 if (Cond.isInvalid())
7752 return StmtError();
7753
7754 if (!getDerived().AlwaysRebuild() &&
7755 Cond.get() == S->getCond() &&
7756 Body.get() == S->getBody())
7757 return S;
7758
7759 return getDerived().RebuildDoStmt(S->getDoLoc(), Body.get(), S->getWhileLoc(),
7760 /*FIXME:*/S->getWhileLoc(), Cond.get(),
7761 S->getRParenLoc());
7762}
7763
7764template<typename Derived>
7765StmtResult
7766TreeTransform<Derived>::TransformForStmt(ForStmt *S) {
7767 if (getSema().getLangOpts().OpenMP)
7768 getSema().startOpenMPLoop();
7769
7770 // Transform the initialization statement
7771 StmtResult Init = getDerived().TransformStmt(S->getInit());
7772 if (Init.isInvalid())
7773 return StmtError();
7774
7775 // In OpenMP loop region loop control variable must be captured and be
7776 // private. Perform analysis of first part (if any).
7777 if (getSema().getLangOpts().OpenMP && Init.isUsable())
7778 getSema().ActOnOpenMPLoopInitialization(S->getForLoc(), Init.get());
7779
7780 // Transform the condition
7781 Sema::ConditionResult Cond = getDerived().TransformCondition(
7782 S->getForLoc(), S->getConditionVariable(), S->getCond(),
7783 Sema::ConditionKind::Boolean);
7784 if (Cond.isInvalid())
7785 return StmtError();
7786
7787 // Transform the increment
7788 ExprResult Inc = getDerived().TransformExpr(S->getInc());
7789 if (Inc.isInvalid())
7790 return StmtError();
7791
7792 Sema::FullExprArg FullInc(getSema().MakeFullDiscardedValueExpr(Inc.get()));
7793 if (S->getInc() && !FullInc.get())
7794 return StmtError();
7795
7796 // Transform the body
7797 StmtResult Body = getDerived().TransformStmt(S->getBody());
7798 if (Body.isInvalid())
7799 return StmtError();
7800
7801 if (!getDerived().AlwaysRebuild() &&
7802 Init.get() == S->getInit() &&
7803 Cond.get() == std::make_pair(S->getConditionVariable(), S->getCond()) &&
7804 Inc.get() == S->getInc() &&
7805 Body.get() == S->getBody())
7806 return S;
7807
7808 return getDerived().RebuildForStmt(S->getForLoc(), S->getLParenLoc(),
7809 Init.get(), Cond, FullInc,
7810 S->getRParenLoc(), Body.get());
7811}
7812
7813template<typename Derived>
7814StmtResult
7815TreeTransform<Derived>::TransformGotoStmt(GotoStmt *S) {
7816 Decl *LD = getDerived().TransformDecl(S->getLabel()->getLocation(),
7817 S->getLabel());
7818 if (!LD)
7819 return StmtError();
7820
7821 // Goto statements must always be rebuilt, to resolve the label.
7822 return getDerived().RebuildGotoStmt(S->getGotoLoc(), S->getLabelLoc(),
7823 cast<LabelDecl>(LD));
7824}
7825
7826template<typename Derived>
7827StmtResult
7828TreeTransform<Derived>::TransformIndirectGotoStmt(IndirectGotoStmt *S) {
7829 ExprResult Target = getDerived().TransformExpr(S->getTarget());
7830 if (Target.isInvalid())
7831 return StmtError();
7832 Target = SemaRef.MaybeCreateExprWithCleanups(Target.get());
7833
7834 if (!getDerived().AlwaysRebuild() &&
7835 Target.get() == S->getTarget())
7836 return S;
7837
7838 return getDerived().RebuildIndirectGotoStmt(S->getGotoLoc(), S->getStarLoc(),
7839 Target.get());
7840}
7841
7842template<typename Derived>
7843StmtResult
7844TreeTransform<Derived>::TransformContinueStmt(ContinueStmt *S) {
7845 return S;
7846}
7847
7848template<typename Derived>
7849StmtResult
7850TreeTransform<Derived>::TransformBreakStmt(BreakStmt *S) {
7851 return S;
7852}
7853
7854template<typename Derived>
7855StmtResult
7856TreeTransform<Derived>::TransformReturnStmt(ReturnStmt *S) {
7857 ExprResult Result = getDerived().TransformInitializer(S->getRetValue(),
7858 /*NotCopyInit*/false);
7859 if (Result.isInvalid())
7860 return StmtError();
7861
7862 // FIXME: We always rebuild the return statement because there is no way
7863 // to tell whether the return type of the function has changed.
7864 return getDerived().RebuildReturnStmt(S->getReturnLoc(), Result.get());
7865}
7866
7867template<typename Derived>
7868StmtResult
7869TreeTransform<Derived>::TransformDeclStmt(DeclStmt *S) {
7870 bool DeclChanged = false;
7871 SmallVector<Decl *, 4> Decls;
7872 for (auto *D : S->decls()) {
7873 Decl *Transformed = getDerived().TransformDefinition(D->getLocation(), D);
7874 if (!Transformed)
7875 return StmtError();
7876
7877 if (Transformed != D)
7878 DeclChanged = true;
7879
7880 Decls.push_back(Transformed);
7881 }
7882
7883 if (!getDerived().AlwaysRebuild() && !DeclChanged)
7884 return S;
7885
7886 return getDerived().RebuildDeclStmt(Decls, S->getBeginLoc(), S->getEndLoc());
7887}
7888
7889template<typename Derived>
7890StmtResult
7891TreeTransform<Derived>::TransformGCCAsmStmt(GCCAsmStmt *S) {
7892
7893 SmallVector<Expr*, 8> Constraints;
7894 SmallVector<Expr*, 8> Exprs;
7895 SmallVector<IdentifierInfo *, 4> Names;
7896
7897 ExprResult AsmString;
7898 SmallVector<Expr*, 8> Clobbers;
7899
7900 bool ExprsChanged = false;
7901
7902 // Go through the outputs.
7903 for (unsigned I = 0, E = S->getNumOutputs(); I != E; ++I) {
7904 Names.push_back(S->getOutputIdentifier(I));
7905
7906 // No need to transform the constraint literal.
7907 Constraints.push_back(S->getOutputConstraintLiteral(I));
7908
7909 // Transform the output expr.
7910 Expr *OutputExpr = S->getOutputExpr(I);
7911 ExprResult Result = getDerived().TransformExpr(OutputExpr);
7912 if (Result.isInvalid())
7913 return StmtError();
7914
7915 ExprsChanged |= Result.get() != OutputExpr;
7916
7917 Exprs.push_back(Result.get());
7918 }
7919
7920 // Go through the inputs.
7921 for (unsigned I = 0, E = S->getNumInputs(); I != E; ++I) {
7922 Names.push_back(S->getInputIdentifier(I));
7923
7924 // No need to transform the constraint literal.
7925 Constraints.push_back(S->getInputConstraintLiteral(I));
7926
7927 // Transform the input expr.
7928 Expr *InputExpr = S->getInputExpr(I);
7929 ExprResult Result = getDerived().TransformExpr(InputExpr);
7930 if (Result.isInvalid())
7931 return StmtError();
7932
7933 ExprsChanged |= Result.get() != InputExpr;
7934
7935 Exprs.push_back(Result.get());
7936 }
7937
7938 // Go through the Labels.
7939 for (unsigned I = 0, E = S->getNumLabels(); I != E; ++I) {
7940 Names.push_back(S->getLabelIdentifier(I));
7941
7942 ExprResult Result = getDerived().TransformExpr(S->getLabelExpr(I));
7943 if (Result.isInvalid())
7944 return StmtError();
7945 ExprsChanged |= Result.get() != S->getLabelExpr(I);
7946 Exprs.push_back(Result.get());
7947 }
7948 if (!getDerived().AlwaysRebuild() && !ExprsChanged)
7949 return S;
7950
7951 // Go through the clobbers.
7952 for (unsigned I = 0, E = S->getNumClobbers(); I != E; ++I)
7953 Clobbers.push_back(S->getClobberStringLiteral(I));
7954
7955 // No need to transform the asm string literal.
7956 AsmString = S->getAsmString();
7957 return getDerived().RebuildGCCAsmStmt(S->getAsmLoc(), S->isSimple(),
7958 S->isVolatile(), S->getNumOutputs(),
7959 S->getNumInputs(), Names.data(),
7960 Constraints, Exprs, AsmString.get(),
7961 Clobbers, S->getNumLabels(),
7962 S->getRParenLoc());
7963}
7964
7965template<typename Derived>
7966StmtResult
7967TreeTransform<Derived>::TransformMSAsmStmt(MSAsmStmt *S) {
7968 ArrayRef<Token> AsmToks = llvm::ArrayRef(S->getAsmToks(), S->getNumAsmToks());
7969
7970 bool HadError = false, HadChange = false;
7971
7972 ArrayRef<Expr*> SrcExprs = S->getAllExprs();
7973 SmallVector<Expr*, 8> TransformedExprs;
7974 TransformedExprs.reserve(SrcExprs.size());
7975 for (unsigned i = 0, e = SrcExprs.size(); i != e; ++i) {
7976 ExprResult Result = getDerived().TransformExpr(SrcExprs[i]);
7977 if (!Result.isUsable()) {
7978 HadError = true;
7979 } else {
7980 HadChange |= (Result.get() != SrcExprs[i]);
7981 TransformedExprs.push_back(Result.get());
7982 }
7983 }
7984
7985 if (HadError) return StmtError();
7986 if (!HadChange && !getDerived().AlwaysRebuild())
7987 return Owned(S);
7988
7989 return getDerived().RebuildMSAsmStmt(S->getAsmLoc(), S->getLBraceLoc(),
7990 AsmToks, S->getAsmString(),
7991 S->getNumOutputs(), S->getNumInputs(),
7992 S->getAllConstraints(), S->getClobbers(),
7993 TransformedExprs, S->getEndLoc());
7994}
7995
7996// C++ Coroutines
7997template<typename Derived>
7998StmtResult
7999TreeTransform<Derived>::TransformCoroutineBodyStmt(CoroutineBodyStmt *S) {
8000 auto *ScopeInfo = SemaRef.getCurFunction();
8001 auto *FD = cast<FunctionDecl>(SemaRef.CurContext);
8002 assert(FD && ScopeInfo && !ScopeInfo->CoroutinePromise &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8003 ScopeInfo->NeedsCoroutineSuspends &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8004 ScopeInfo->CoroutineSuspends.first == nullptr &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8005 ScopeInfo->CoroutineSuspends.second == nullptr &&(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
8006 "expected clean scope info")(static_cast <bool> (FD && ScopeInfo &&
!ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends
&& ScopeInfo->CoroutineSuspends.first == nullptr &&
ScopeInfo->CoroutineSuspends.second == nullptr &&
"expected clean scope info") ? void (0) : __assert_fail ("FD && ScopeInfo && !ScopeInfo->CoroutinePromise && ScopeInfo->NeedsCoroutineSuspends && ScopeInfo->CoroutineSuspends.first == nullptr && ScopeInfo->CoroutineSuspends.second == nullptr && \"expected clean scope info\""
, "clang/lib/Sema/TreeTransform.h", 8006, __extension__ __PRETTY_FUNCTION__
))
;
8007
8008 // Set that we have (possibly-invalid) suspend points before we do anything
8009 // that may fail.
8010 ScopeInfo->setNeedsCoroutineSuspends(false);
8011
8012 // We re-build the coroutine promise object (and the coroutine parameters its
8013 // type and constructor depend on) based on the types used in our current
8014 // function. We must do so, and set it on the current FunctionScopeInfo,
8015 // before attempting to transform the other parts of the coroutine body
8016 // statement, such as the implicit suspend statements (because those
8017 // statements reference the FunctionScopeInfo::CoroutinePromise).
8018 if (!SemaRef.buildCoroutineParameterMoves(FD->getLocation()))
8019 return StmtError();
8020 auto *Promise = SemaRef.buildCoroutinePromise(FD->getLocation());
8021 if (!Promise)
8022 return StmtError();
8023 getDerived().transformedLocalDecl(S->getPromiseDecl(), {Promise});
8024 ScopeInfo->CoroutinePromise = Promise;
8025
8026 // Transform the implicit coroutine statements constructed using dependent
8027 // types during the previous parse: initial and final suspensions, the return
8028 // object, and others. We also transform the coroutine function's body.
8029 StmtResult InitSuspend = getDerived().TransformStmt(S->getInitSuspendStmt());
8030 if (InitSuspend.isInvalid())
8031 return StmtError();
8032 StmtResult FinalSuspend =
8033 getDerived().TransformStmt(S->getFinalSuspendStmt());
8034 if (FinalSuspend.isInvalid() ||
8035 !SemaRef.checkFinalSuspendNoThrow(FinalSuspend.get()))
8036 return StmtError();
8037 ScopeInfo->setCoroutineSuspends(InitSuspend.get(), FinalSuspend.get());
8038 assert(isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get()))(static_cast <bool> (isa<Expr>(InitSuspend.get())
&& isa<Expr>(FinalSuspend.get())) ? void (0) :
__assert_fail ("isa<Expr>(InitSuspend.get()) && isa<Expr>(FinalSuspend.get())"
, "clang/lib/Sema/TreeTransform.h", 8038, __extension__ __PRETTY_FUNCTION__
))
;
8039
8040 StmtResult BodyRes = getDerived().TransformStmt(S->getBody());
8041 if (BodyRes.isInvalid())
8042 return StmtError();
8043
8044 CoroutineStmtBuilder Builder(SemaRef, *FD, *ScopeInfo, BodyRes.get());
8045 if (Builder.isInvalid())
8046 return StmtError();
8047
8048 Expr *ReturnObject = S->getReturnValueInit();
8049 assert(ReturnObject && "the return object is expected to be valid")(static_cast <bool> (ReturnObject && "the return object is expected to be valid"
) ? void (0) : __assert_fail ("ReturnObject && \"the return object is expected to be valid\""
, "clang/lib/Sema/TreeTransform.h", 8049, __extension__ __PRETTY_FUNCTION__
))
;
8050 ExprResult Res = getDerived().TransformInitializer(ReturnObject,
8051 /*NoCopyInit*/ false);
8052 if (Res.isInvalid())
8053 return StmtError();
8054 Builder.ReturnValue = Res.get();
8055
8056 // If during the previous parse the coroutine still had a dependent promise
8057 // statement, we may need to build some implicit coroutine statements
8058 // (such as exception and fallthrough handlers) for the first time.
8059 if (S->hasDependentPromiseType()) {
8060 // We can only build these statements, however, if the current promise type
8061 // is not dependent.
8062 if (!Promise->getType()->isDependentType()) {
8063 assert(!S->getFallthroughHandler() && !S->getExceptionHandler() &&(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
8064 !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() &&(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
8065 "these nodes should not have been built yet")(static_cast <bool> (!S->getFallthroughHandler() &&
!S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure
() && !S->getDeallocate() && "these nodes should not have been built yet"
) ? void (0) : __assert_fail ("!S->getFallthroughHandler() && !S->getExceptionHandler() && !S->getReturnStmtOnAllocFailure() && !S->getDeallocate() && \"these nodes should not have been built yet\""
, "clang/lib/Sema/TreeTransform.h", 8065, __extension__ __PRETTY_FUNCTION__
))
;
8066 if (!Builder.buildDependentStatements())
8067 return StmtError();
8068 }
8069 } else {
8070 if (auto *OnFallthrough = S->getFallthroughHandler()) {
8071 StmtResult Res = getDerived().TransformStmt(OnFallthrough);
8072 if (Res.isInvalid())
8073 return StmtError();
8074 Builder.OnFallthrough = Res.get();
8075 }
8076
8077 if (auto *OnException = S->getExceptionHandler()) {
8078 StmtResult Res = getDerived().TransformStmt(OnException);
8079 if (Res.isInvalid())
8080 return StmtError();
8081 Builder.OnException = Res.get();
8082 }
8083
8084 if (auto *OnAllocFailure = S->getReturnStmtOnAllocFailure()) {
8085 StmtResult Res = getDerived().TransformStmt(OnAllocFailure);
8086 if (Res.isInvalid())
8087 return StmtError();
8088 Builder.ReturnStmtOnAllocFailure = Res.get();
8089 }
8090
8091 // Transform any additional statements we may have already built
8092 assert(S->getAllocate() && S->getDeallocate() &&(static_cast <bool> (S->getAllocate() && S->
getDeallocate() && "allocation and deallocation calls must already be built"
) ? void (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "clang/lib/Sema/TreeTransform.h", 8093, __extension__ __PRETTY_FUNCTION__
))
8093 "allocation and deallocation calls must already be built")(static_cast <bool> (S->getAllocate() && S->
getDeallocate() && "allocation and deallocation calls must already be built"
) ? void (0) : __assert_fail ("S->getAllocate() && S->getDeallocate() && \"allocation and deallocation calls must already be built\""
, "clang/lib/Sema/TreeTransform.h", 8093, __extension__ __PRETTY_FUNCTION__
))
;
8094 ExprResult AllocRes = getDerived().TransformExpr(S->getAllocate());
8095 if (AllocRes.isInvalid())
8096 return StmtError();
8097 Builder.Allocate = AllocRes.get();
8098
8099 ExprResult DeallocRes = getDerived().TransformExpr(S->getDeallocate());
8100 if (DeallocRes.isInvalid())
8101 return StmtError();
8102 Builder.Deallocate = DeallocRes.get();
8103
8104 if (auto *ResultDecl = S->getResultDecl()) {
8105 StmtResult Res = getDerived().TransformStmt(ResultDecl);
8106 if (Res.isInvalid())
8107 return StmtError();
8108 Builder.ResultDecl = Res.get();
8109 }
8110
8111 if (auto *ReturnStmt = S->getReturnStmt()) {
8112 StmtResult Res = getDerived().TransformStmt(ReturnStmt);
8113 if (Res.isInvalid())
8114 return StmtError();
8115 Builder.ReturnStmt = Res.get();
8116 }
8117 }
8118
8119 return getDerived().RebuildCoroutineBodyStmt(Builder);
8120}
8121
8122template<typename Derived>
8123StmtResult
8124TreeTransform<Derived>::TransformCoreturnStmt(CoreturnStmt *S) {
8125 ExprResult Result = getDerived().TransformInitializer(S->getOperand(),
8126 /*NotCopyInit*/false);
8127 if (Result.isInvalid())
8128 return StmtError();
8129
8130 // Always rebuild; we don't know if this needs to be injected into a new
8131 // context or if the promise type has changed.
8132 return getDerived().RebuildCoreturnStmt(S->getKeywordLoc(), Result.get(),
8133 S->isImplicit());
8134}
8135
8136template <typename Derived>
8137ExprResult TreeTransform<Derived>::TransformCoawaitExpr(CoawaitExpr *E) {
8138 ExprResult Operand = getDerived().TransformInitializer(E->getOperand(),
8139 /*NotCopyInit*/ false);
8140 if (Operand.isInvalid())
8141 return ExprError();
8142
8143 // Rebuild the common-expr from the operand rather than transforming it
8144 // separately.
8145
8146 // FIXME: getCurScope() should not be used during template instantiation.
8147 // We should pick up the set of unqualified lookup results for operator
8148 // co_await during the initial parse.
8149 ExprResult Lookup = getSema().BuildOperatorCoawaitLookupExpr(
8150 getSema().getCurScope(), E->getKeywordLoc());
8151
8152 // Always rebuild; we don't know if this needs to be injected into a new
8153 // context or if the promise type has changed.
8154 return getDerived().RebuildCoawaitExpr(
8155 E->getKeywordLoc(), Operand.get(),
8156 cast<UnresolvedLookupExpr>(Lookup.get()), E->isImplicit());
8157}
8158
8159template <typename Derived>
8160ExprResult
8161TreeTransform<Derived>::TransformDependentCoawaitExpr(DependentCoawaitExpr *E) {
8162 ExprResult OperandResult = getDerived().TransformInitializer(E->getOperand(),
8163 /*NotCopyInit*/ false);
8164 if (OperandResult.isInvalid())
8165 return ExprError();
8166
8167 ExprResult LookupResult = getDerived().TransformUnresolvedLookupExpr(
8168 E->getOperatorCoawaitLookup());
8169
8170 if (LookupResult.isInvalid())
8171 return ExprError();
8172
8173 // Always rebuild; we don't know if this needs to be injected into a new
8174 // context or if the promise type has changed.
8175 return getDerived().RebuildDependentCoawaitExpr(
8176 E->getKeywordLoc(), OperandResult.get(),
8177 cast<UnresolvedLookupExpr>(LookupResult.get()));
8178}
8179
8180template<typename Derived>
8181ExprResult
8182TreeTransform<Derived>::TransformCoyieldExpr(CoyieldExpr *E) {
8183 ExprResult Result = getDerived().TransformInitializer(E->getOperand(),
8184 /*NotCopyInit*/false);
8185 if (Result.isInvalid())
8186 return ExprError();
8187
8188 // Always rebuild; we don't know if this needs to be injected into a new
8189 // context or if the promise type has changed.
8190 return getDerived().RebuildCoyieldExpr(E->getKeywordLoc(), Result.get());
8191}
8192
8193// Objective-C Statements.
8194
8195template<typename Derived>
8196StmtResult
8197TreeTransform<Derived>::TransformObjCAtTryStmt(ObjCAtTryStmt *S) {
8198 // Transform the body of the @try.
8199 StmtResult TryBody = getDerived().TransformStmt(S->getTryBody());
8200 if (TryBody.isInvalid())
8201 return StmtError();
8202
8203 // Transform the @catch statements (if present).
8204 bool AnyCatchChanged = false;
8205 SmallVector<Stmt*, 8> CatchStmts;
8206 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
8207 StmtResult Catch = getDerived().TransformStmt(S->getCatchStmt(I));
8208 if (Catch.isInvalid())
8209 return StmtError();
8210 if (Catch.get() != S->getCatchStmt(I))
8211 AnyCatchChanged = true;
8212 CatchStmts.push_back(Catch.get());
8213 }
8214
8215 // Transform the @finally statement (if present).
8216 StmtResult Finally;
8217 if (S->getFinallyStmt()) {
8218 Finally = getDerived().TransformStmt(S->getFinallyStmt());
8219 if (Finally.isInvalid())
8220 return StmtError();
8221 }
8222
8223 // If nothing changed, just retain this statement.
8224 if (!getDerived().AlwaysRebuild() &&
8225 TryBody.get() == S->getTryBody() &&
8226 !AnyCatchChanged &&
8227 Finally.get() == S->getFinallyStmt())
8228 return S;
8229
8230 // Build a new statement.
8231 return getDerived().RebuildObjCAtTryStmt(S->getAtTryLoc(), TryBody.get(),
8232 CatchStmts, Finally.get());
8233}
8234
8235template<typename Derived>
8236StmtResult
8237TreeTransform<Derived>::TransformObjCAtCatchStmt(ObjCAtCatchStmt *S) {
8238 // Transform the @catch parameter, if there is one.
8239 VarDecl *Var = nullptr;
8240 if (VarDecl *FromVar = S->getCatchParamDecl()) {
8241 TypeSourceInfo *TSInfo = nullptr;
8242 if (FromVar->getTypeSourceInfo()) {
8243 TSInfo = getDerived().TransformType(FromVar->getTypeSourceInfo());
8244 if (!TSInfo)
8245 return StmtError();
8246 }
8247
8248 QualType T;
8249 if (TSInfo)
8250 T = TSInfo->getType();
8251 else {
8252 T = getDerived().TransformType(FromVar->getType());
8253 if (T.isNull())
8254 return StmtError();
8255 }
8256
8257 Var = getDerived().RebuildObjCExceptionDecl(FromVar, TSInfo, T);
8258 if (!Var)
8259 return StmtError();
8260 }
8261
8262 StmtResult Body = getDerived().TransformStmt(S->getCatchBody());
8263 if (Body.isInvalid())
8264 return StmtError();
8265
8266 return getDerived().RebuildObjCAtCatchStmt(S->getAtCatchLoc(),
8267 S->getRParenLoc(),
8268 Var, Body.get());
8269}
8270
8271template<typename Derived>
8272StmtResult
8273TreeTransform<Derived>::TransformObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
8274 // Transform the body.
8275 StmtResult Body = getDerived().TransformStmt(S->getFinallyBody());
8276 if (Body.isInvalid())
8277 return StmtError();
8278
8279 // If nothing changed, just retain this statement.
8280 if (!getDerived().AlwaysRebuild() &&
8281 Body.get() == S->getFinallyBody())
8282 return S;
8283
8284 // Build a new statement.
8285 return getDerived().RebuildObjCAtFinallyStmt(S->getAtFinallyLoc(),
8286 Body.get());
8287}
8288
8289template<typename Derived>
8290StmtResult
8291TreeTransform<Derived>::TransformObjCAtThrowStmt(ObjCAtThrowStmt *S) {
8292 ExprResult Operand;
8293 if (S->getThrowExpr()) {
8294 Operand = getDerived().TransformExpr(S->getThrowExpr());
8295 if (Operand.isInvalid())
8296 return StmtError();
8297 }
8298
8299 if (!getDerived().AlwaysRebuild() &&
8300 Operand.get() == S->getThrowExpr())
8301 return S;
8302
8303 return getDerived().RebuildObjCAtThrowStmt(S->getThrowLoc(), Operand.get());
8304}
8305
8306template<typename Derived>
8307StmtResult
8308TreeTransform<Derived>::TransformObjCAtSynchronizedStmt(
8309 ObjCAtSynchronizedStmt *S) {
8310 // Transform the object we are locking.
8311 ExprResult Object = getDerived().TransformExpr(S->getSynchExpr());
8312 if (Object.isInvalid())
8313 return StmtError();
8314 Object =
8315 getDerived().RebuildObjCAtSynchronizedOperand(S->getAtSynchronizedLoc(),
8316 Object.get());
8317 if (Object.isInvalid())
8318 return StmtError();
8319
8320 // Transform the body.
8321 StmtResult Body = getDerived().TransformStmt(S->getSynchBody());
8322 if (Body.isInvalid())
8323 return StmtError();
8324
8325 // If nothing change, just retain the current statement.
8326 if (!getDerived().AlwaysRebuild() &&
8327 Object.get() == S->getSynchExpr() &&
8328 Body.get() == S->getSynchBody())
8329 return S;
8330
8331 // Build a new statement.
8332 return getDerived().RebuildObjCAtSynchronizedStmt(S->getAtSynchronizedLoc(),
8333 Object.get(), Body.get());
8334}
8335
8336template<typename Derived>
8337StmtResult
8338TreeTransform<Derived>::TransformObjCAutoreleasePoolStmt(
8339 ObjCAutoreleasePoolStmt *S) {
8340 // Transform the body.
8341 StmtResult Body = getDerived().TransformStmt(S->getSubStmt());
8342 if (Body.isInvalid())
8343 return StmtError();
8344
8345 // If nothing changed, just retain this statement.
8346 if (!getDerived().AlwaysRebuild() &&
8347 Body.get() == S->getSubStmt())
8348 return S;
8349
8350 // Build a new statement.
8351 return getDerived().RebuildObjCAutoreleasePoolStmt(
8352 S->getAtLoc(), Body.get());
8353}
8354
8355template<typename Derived>
8356StmtResult
8357TreeTransform<Derived>::TransformObjCForCollectionStmt(
8358 ObjCForCollectionStmt *S) {
8359 // Transform the element statement.
8360 StmtResult Element =
8361 getDerived().TransformStmt(S->getElement(), SDK_NotDiscarded);
8362 if (Element.isInvalid())
8363 return StmtError();
8364
8365 // Transform the collection expression.
8366 ExprResult Collection = getDerived().TransformExpr(S->getCollection());
8367 if (Collection.isInvalid())
8368 return StmtError();
8369
8370 // Transform the body.
8371 StmtResult Body = getDerived().TransformStmt(S->getBody());
8372 if (Body.isInvalid())
8373 return StmtError();
8374
8375 // If nothing changed, just retain this statement.
8376 if (!getDerived().AlwaysRebuild() &&
8377 Element.get() == S->getElement() &&
8378 Collection.get() == S->getCollection() &&
8379 Body.get() == S->getBody())
8380 return S;
8381
8382 // Build a new statement.
8383 return getDerived().RebuildObjCForCollectionStmt(S->getForLoc(),
8384 Element.get(),
8385 Collection.get(),
8386 S->getRParenLoc(),
8387 Body.get());
8388}
8389
8390template <typename Derived>
8391StmtResult TreeTransform<Derived>::TransformCXXCatchStmt(CXXCatchStmt *S) {
8392 // Transform the exception declaration, if any.
8393 VarDecl *Var = nullptr;
8394 if (VarDecl *ExceptionDecl = S->getExceptionDecl()) {
8395 TypeSourceInfo *T =
8396 getDerived().TransformType(ExceptionDecl->getTypeSourceInfo());
8397 if (!T)
8398 return StmtError();
8399
8400 Var = getDerived().RebuildExceptionDecl(
8401 ExceptionDecl, T, ExceptionDecl->getInnerLocStart(),
8402 ExceptionDecl->getLocation(), ExceptionDecl->getIdentifier());
8403 if (!Var || Var->isInvalidDecl())
8404 return StmtError();
8405 }
8406
8407 // Transform the actual exception handler.
8408 StmtResult Handler = getDerived().TransformStmt(S->getHandlerBlock());
8409 if (Handler.isInvalid())
8410 return StmtError();
8411
8412 if (!getDerived().AlwaysRebuild() && !Var &&
8413 Handler.get() == S->getHandlerBlock())
8414 return S;
8415
8416 return getDerived().RebuildCXXCatchStmt(S->getCatchLoc(), Var, Handler.get());
8417}
8418
8419template <typename Derived>
8420StmtResult TreeTransform<Derived>::TransformCXXTryStmt(CXXTryStmt *S) {
8421 // Transform the try block itself.
8422 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8423 if (TryBlock.isInvalid())
8424 return StmtError();
8425
8426 // Transform the handlers.
8427 bool HandlerChanged = false;
8428 SmallVector<Stmt *, 8> Handlers;
8429 for (unsigned I = 0, N = S->getNumHandlers(); I != N; ++I) {
8430 StmtResult Handler = getDerived().TransformCXXCatchStmt(S->getHandler(I));
8431 if (Handler.isInvalid())
8432 return StmtError();
8433
8434 HandlerChanged = HandlerChanged || Handler.get() != S->getHandler(I);
8435 Handlers.push_back(Handler.getAs<Stmt>());
8436 }
8437
8438 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8439 !HandlerChanged)
8440 return S;
8441
8442 return getDerived().RebuildCXXTryStmt(S->getTryLoc(), TryBlock.get(),
8443 Handlers);
8444}
8445
8446template<typename Derived>
8447StmtResult
8448TreeTransform<Derived>::TransformCXXForRangeStmt(CXXForRangeStmt *S) {
8449 StmtResult Init =
8450 S->getInit() ? getDerived().TransformStmt(S->getInit()) : StmtResult();
8451 if (Init.isInvalid())
8452 return StmtError();
8453
8454 StmtResult Range = getDerived().TransformStmt(S->getRangeStmt());
8455 if (Range.isInvalid())
8456 return StmtError();
8457
8458 StmtResult Begin = getDerived().TransformStmt(S->getBeginStmt());
8459 if (Begin.isInvalid())
8460 return StmtError();
8461 StmtResult End = getDerived().TransformStmt(S->getEndStmt());
8462 if (End.isInvalid())
8463 return StmtError();
8464
8465 ExprResult Cond = getDerived().TransformExpr(S->getCond());
8466 if (Cond.isInvalid())
8467 return StmtError();
8468 if (Cond.get())
8469 Cond = SemaRef.CheckBooleanCondition(S->getColonLoc(), Cond.get());
8470 if (Cond.isInvalid())
8471 return StmtError();
8472 if (Cond.get())
8473 Cond = SemaRef.MaybeCreateExprWithCleanups(Cond.get());
8474
8475 ExprResult Inc = getDerived().TransformExpr(S->getInc());
8476 if (Inc.isInvalid())
8477 return StmtError();
8478 if (Inc.get())
8479 Inc = SemaRef.MaybeCreateExprWithCleanups(Inc.get());
8480
8481 StmtResult LoopVar = getDerived().TransformStmt(S->getLoopVarStmt());
8482 if (LoopVar.isInvalid())
8483 return StmtError();
8484
8485 StmtResult NewStmt = S;
8486 if (getDerived().AlwaysRebuild() ||
8487 Init.get() != S->getInit() ||
8488 Range.get() != S->getRangeStmt() ||
8489 Begin.get() != S->getBeginStmt() ||
8490 End.get() != S->getEndStmt() ||
8491 Cond.get() != S->getCond() ||
8492 Inc.get() != S->getInc() ||
8493 LoopVar.get() != S->getLoopVarStmt()) {
8494 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8495 S->getCoawaitLoc(), Init.get(),
8496 S->getColonLoc(), Range.get(),
8497 Begin.get(), End.get(),
8498 Cond.get(),
8499 Inc.get(), LoopVar.get(),
8500 S->getRParenLoc());
8501 if (NewStmt.isInvalid() && LoopVar.get() != S->getLoopVarStmt()) {
8502 // Might not have attached any initializer to the loop variable.
8503 getSema().ActOnInitializerError(
8504 cast<DeclStmt>(LoopVar.get())->getSingleDecl());
8505 return StmtError();
8506 }
8507 }
8508
8509 StmtResult Body = getDerived().TransformStmt(S->getBody());
8510 if (Body.isInvalid())
8511 return StmtError();
8512
8513 // Body has changed but we didn't rebuild the for-range statement. Rebuild
8514 // it now so we have a new statement to attach the body to.
8515 if (Body.get() != S->getBody() && NewStmt.get() == S) {
8516 NewStmt = getDerived().RebuildCXXForRangeStmt(S->getForLoc(),
8517 S->getCoawaitLoc(), Init.get(),
8518 S->getColonLoc(), Range.get(),
8519 Begin.get(), End.get(),
8520 Cond.get(),
8521 Inc.get(), LoopVar.get(),
8522 S->getRParenLoc());
8523 if (NewStmt.isInvalid())
8524 return StmtError();
8525 }
8526
8527 if (NewStmt.get() == S)
8528 return S;
8529
8530 return FinishCXXForRangeStmt(NewStmt.get(), Body.get());
8531}
8532
8533template<typename Derived>
8534StmtResult
8535TreeTransform<Derived>::TransformMSDependentExistsStmt(
8536 MSDependentExistsStmt *S) {
8537 // Transform the nested-name-specifier, if any.
8538 NestedNameSpecifierLoc QualifierLoc;
8539 if (S->getQualifierLoc()) {
8540 QualifierLoc
8541 = getDerived().TransformNestedNameSpecifierLoc(S->getQualifierLoc());
8542 if (!QualifierLoc)
8543 return StmtError();
8544 }
8545
8546 // Transform the declaration name.
8547 DeclarationNameInfo NameInfo = S->getNameInfo();
8548 if (NameInfo.getName()) {
8549 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
8550 if (!NameInfo.getName())
8551 return StmtError();
8552 }
8553
8554 // Check whether anything changed.
8555 if (!getDerived().AlwaysRebuild() &&
8556 QualifierLoc == S->getQualifierLoc() &&
8557 NameInfo.getName() == S->getNameInfo().getName())
8558 return S;
8559
8560 // Determine whether this name exists, if we can.
8561 CXXScopeSpec SS;
8562 SS.Adopt(QualifierLoc);
8563 bool Dependent = false;
8564 switch (getSema().CheckMicrosoftIfExistsSymbol(/*S=*/nullptr, SS, NameInfo)) {
8565 case Sema::IER_Exists:
8566 if (S->isIfExists())
8567 break;
8568
8569 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8570
8571 case Sema::IER_DoesNotExist:
8572 if (S->isIfNotExists())
8573 break;
8574
8575 return new (getSema().Context) NullStmt(S->getKeywordLoc());
8576
8577 case Sema::IER_Dependent:
8578 Dependent = true;
8579 break;
8580
8581 case Sema::IER_Error:
8582 return StmtError();
8583 }
8584
8585 // We need to continue with the instantiation, so do so now.
8586 StmtResult SubStmt = getDerived().TransformCompoundStmt(S->getSubStmt());
8587 if (SubStmt.isInvalid())
8588 return StmtError();
8589
8590 // If we have resolved the name, just transform to the substatement.
8591 if (!Dependent)
8592 return SubStmt;
8593
8594 // The name is still dependent, so build a dependent expression again.
8595 return getDerived().RebuildMSDependentExistsStmt(S->getKeywordLoc(),
8596 S->isIfExists(),
8597 QualifierLoc,
8598 NameInfo,
8599 SubStmt.get());
8600}
8601
8602template<typename Derived>
8603ExprResult
8604TreeTransform<Derived>::TransformMSPropertyRefExpr(MSPropertyRefExpr *E) {
8605 NestedNameSpecifierLoc QualifierLoc;
8606 if (E->getQualifierLoc()) {
8607 QualifierLoc
8608 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
8609 if (!QualifierLoc)
8610 return ExprError();
8611 }
8612
8613 MSPropertyDecl *PD = cast_or_null<MSPropertyDecl>(
8614 getDerived().TransformDecl(E->getMemberLoc(), E->getPropertyDecl()));
8615 if (!PD)
8616 return ExprError();
8617
8618 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
8619 if (Base.isInvalid())
8620 return ExprError();
8621
8622 return new (SemaRef.getASTContext())
8623 MSPropertyRefExpr(Base.get(), PD, E->isArrow(),
8624 SemaRef.getASTContext().PseudoObjectTy, VK_LValue,
8625 QualifierLoc, E->getMemberLoc());
8626}
8627
8628template <typename Derived>
8629ExprResult TreeTransform<Derived>::TransformMSPropertySubscriptExpr(
8630 MSPropertySubscriptExpr *E) {
8631 auto BaseRes = getDerived().TransformExpr(E->getBase());
8632 if (BaseRes.isInvalid())
8633 return ExprError();
8634 auto IdxRes = getDerived().TransformExpr(E->getIdx());
8635 if (IdxRes.isInvalid())
8636 return ExprError();
8637
8638 if (!getDerived().AlwaysRebuild() &&
8639 BaseRes.get() == E->getBase() &&
8640 IdxRes.get() == E->getIdx())
8641 return E;
8642
8643 return getDerived().RebuildArraySubscriptExpr(
8644 BaseRes.get(), SourceLocation(), IdxRes.get(), E->getRBracketLoc());
8645}
8646
8647template <typename Derived>
8648StmtResult TreeTransform<Derived>::TransformSEHTryStmt(SEHTryStmt *S) {
8649 StmtResult TryBlock = getDerived().TransformCompoundStmt(S->getTryBlock());
8650 if (TryBlock.isInvalid())
8651 return StmtError();
8652
8653 StmtResult Handler = getDerived().TransformSEHHandler(S->getHandler());
8654 if (Handler.isInvalid())
8655 return StmtError();
8656
8657 if (!getDerived().AlwaysRebuild() && TryBlock.get() == S->getTryBlock() &&
8658 Handler.get() == S->getHandler())
8659 return S;
8660
8661 return getDerived().RebuildSEHTryStmt(S->getIsCXXTry(), S->getTryLoc(),
8662 TryBlock.get(), Handler.get());
8663}
8664
8665template <typename Derived>
8666StmtResult TreeTransform<Derived>::TransformSEHFinallyStmt(SEHFinallyStmt *S) {
8667 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8668 if (Block.isInvalid())
8669 return StmtError();
8670
8671 return getDerived().RebuildSEHFinallyStmt(S->getFinallyLoc(), Block.get());
8672}
8673
8674template <typename Derived>
8675StmtResult TreeTransform<Derived>::TransformSEHExceptStmt(SEHExceptStmt *S) {
8676 ExprResult FilterExpr = getDerived().TransformExpr(S->getFilterExpr());
8677 if (FilterExpr.isInvalid())
8678 return StmtError();
8679
8680 StmtResult Block = getDerived().TransformCompoundStmt(S->getBlock());
8681 if (Block.isInvalid())
8682 return StmtError();
8683
8684 return getDerived().RebuildSEHExceptStmt(S->getExceptLoc(), FilterExpr.get(),
8685 Block.get());
8686}
8687
8688template <typename Derived>
8689StmtResult TreeTransform<Derived>::TransformSEHHandler(Stmt *Handler) {
8690 if (isa<SEHFinallyStmt>(Handler))
8691 return getDerived().TransformSEHFinallyStmt(cast<SEHFinallyStmt>(Handler));
8692 else
8693 return getDerived().TransformSEHExceptStmt(cast<SEHExceptStmt>(Handler));
8694}
8695
8696template<typename Derived>
8697StmtResult
8698TreeTransform<Derived>::TransformSEHLeaveStmt(SEHLeaveStmt *S) {
8699 return S;
8700}
8701
8702//===----------------------------------------------------------------------===//
8703// OpenMP directive transformation
8704//===----------------------------------------------------------------------===//
8705
8706template <typename Derived>
8707StmtResult
8708TreeTransform<Derived>::TransformOMPCanonicalLoop(OMPCanonicalLoop *L) {
8709 // OMPCanonicalLoops are eliminated during transformation, since they will be
8710 // recomputed by semantic analysis of the associated OMPLoopBasedDirective
8711 // after transformation.
8712 return getDerived().TransformStmt(L->getLoopStmt());
8713}
8714
8715template <typename Derived>
8716StmtResult TreeTransform<Derived>::TransformOMPExecutableDirective(
8717 OMPExecutableDirective *D) {
8718
8719 // Transform the clauses
8720 llvm::SmallVector<OMPClause *, 16> TClauses;
8721 ArrayRef<OMPClause *> Clauses = D->clauses();
8722 TClauses.reserve(Clauses.size());
8723 for (ArrayRef<OMPClause *>::iterator I = Clauses.begin(), E = Clauses.end();
8724 I != E; ++I) {
8725 if (*I) {
8726 getDerived().getSema().StartOpenMPClause((*I)->getClauseKind());
8727 OMPClause *Clause = getDerived().TransformOMPClause(*I);
8728 getDerived().getSema().EndOpenMPClause();
8729 if (Clause)
8730 TClauses.push_back(Clause);
8731 } else {
8732 TClauses.push_back(nullptr);
8733 }
8734 }
8735 StmtResult AssociatedStmt;
8736 if (D->hasAssociatedStmt() && D->getAssociatedStmt()) {
8737 getDerived().getSema().ActOnOpenMPRegionStart(D->getDirectiveKind(),
8738 /*CurScope=*/nullptr);
8739 StmtResult Body;
8740 {
8741 Sema::CompoundScopeRAII CompoundScope(getSema());
8742 Stmt *CS;
8743 if (D->getDirectiveKind() == OMPD_atomic ||
8744 D->getDirectiveKind() == OMPD_critical ||
8745 D->getDirectiveKind() == OMPD_section ||
8746 D->getDirectiveKind() == OMPD_master)
8747 CS = D->getAssociatedStmt();
8748 else
8749 CS = D->getRawStmt();
8750 Body = getDerived().TransformStmt(CS);
8751 if (Body.isUsable() && isOpenMPLoopDirective(D->getDirectiveKind()) &&
8752 getSema().getLangOpts().OpenMPIRBuilder)
8753 Body = getDerived().RebuildOMPCanonicalLoop(Body.get());
8754 }
8755 AssociatedStmt =
8756 getDerived().getSema().ActOnOpenMPRegionEnd(Body, TClauses);
8757 if (AssociatedStmt.isInvalid()) {
8758 return StmtError();
8759 }
8760 }
8761 if (TClauses.size() != Clauses.size()) {
8762 return StmtError();
8763 }
8764
8765 // Transform directive name for 'omp critical' directive.
8766 DeclarationNameInfo DirName;
8767 if (D->getDirectiveKind() == OMPD_critical) {
8768 DirName = cast<OMPCriticalDirective>(D)->getDirectiveName();
8769 DirName = getDerived().TransformDeclarationNameInfo(DirName);
8770 }
8771 OpenMPDirectiveKind CancelRegion = OMPD_unknown;
8772 if (D->getDirectiveKind() == OMPD_cancellation_point) {
8773 CancelRegion = cast<OMPCancellationPointDirective>(D)->getCancelRegion();
8774 } else if (D->getDirectiveKind() == OMPD_cancel) {
8775 CancelRegion = cast<OMPCancelDirective>(D)->getCancelRegion();
8776 }
8777
8778 return getDerived().RebuildOMPExecutableDirective(
8779 D->getDirectiveKind(), DirName, CancelRegion, TClauses,
8780 AssociatedStmt.get(), D->getBeginLoc(), D->getEndLoc());
8781}
8782
8783template <typename Derived>
8784StmtResult
8785TreeTransform<Derived>::TransformOMPMetaDirective(OMPMetaDirective *D) {
8786 // TODO: Fix This
8787 SemaRef.Diag(D->getBeginLoc(), diag::err_omp_instantiation_not_supported)
8788 << getOpenMPDirectiveName(D->getDirectiveKind());
8789 return StmtError();
8790}
8791
8792template <typename Derived>
8793StmtResult
8794TreeTransform<Derived>::TransformOMPParallelDirective(OMPParallelDirective *D) {
8795 DeclarationNameInfo DirName;
8796 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel, DirName, nullptr,
8797 D->getBeginLoc());
8798 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8799 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8800 return Res;
8801}
8802
8803template <typename Derived>
8804StmtResult
8805TreeTransform<Derived>::TransformOMPSimdDirective(OMPSimdDirective *D) {
8806 DeclarationNameInfo DirName;
8807 getDerived().getSema().StartOpenMPDSABlock(OMPD_simd, DirName, nullptr,
8808 D->getBeginLoc());
8809 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8810 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8811 return Res;
8812}
8813
8814template <typename Derived>
8815StmtResult
8816TreeTransform<Derived>::TransformOMPTileDirective(OMPTileDirective *D) {
8817 DeclarationNameInfo DirName;
8818 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8819 nullptr, D->getBeginLoc());
8820 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8821 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8822 return Res;
8823}
8824
8825template <typename Derived>
8826StmtResult
8827TreeTransform<Derived>::TransformOMPUnrollDirective(OMPUnrollDirective *D) {
8828 DeclarationNameInfo DirName;
8829 getDerived().getSema().StartOpenMPDSABlock(D->getDirectiveKind(), DirName,
8830 nullptr, D->getBeginLoc());
8831 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8832 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8833 return Res;
8834}
8835
8836template <typename Derived>
8837StmtResult
8838TreeTransform<Derived>::TransformOMPForDirective(OMPForDirective *D) {
8839 DeclarationNameInfo DirName;
8840 getDerived().getSema().StartOpenMPDSABlock(OMPD_for, DirName, nullptr,
8841 D->getBeginLoc());
8842 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8843 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8844 return Res;
8845}
8846
8847template <typename Derived>
8848StmtResult
8849TreeTransform<Derived>::TransformOMPForSimdDirective(OMPForSimdDirective *D) {
8850 DeclarationNameInfo DirName;
8851 getDerived().getSema().StartOpenMPDSABlock(OMPD_for_simd, DirName, nullptr,
8852 D->getBeginLoc());
8853 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8854 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8855 return Res;
8856}
8857
8858template <typename Derived>
8859StmtResult
8860TreeTransform<Derived>::TransformOMPSectionsDirective(OMPSectionsDirective *D) {
8861 DeclarationNameInfo DirName;
8862 getDerived().getSema().StartOpenMPDSABlock(OMPD_sections, DirName, nullptr,
8863 D->getBeginLoc());
8864 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8865 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8866 return Res;
8867}
8868
8869template <typename Derived>
8870StmtResult
8871TreeTransform<Derived>::TransformOMPSectionDirective(OMPSectionDirective *D) {
8872 DeclarationNameInfo DirName;
8873 getDerived().getSema().StartOpenMPDSABlock(OMPD_section, DirName, nullptr,
8874 D->getBeginLoc());
8875 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8876 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8877 return Res;
8878}
8879
8880template <typename Derived>
8881StmtResult
8882TreeTransform<Derived>::TransformOMPSingleDirective(OMPSingleDirective *D) {
8883 DeclarationNameInfo DirName;
8884 getDerived().getSema().StartOpenMPDSABlock(OMPD_single, DirName, nullptr,
8885 D->getBeginLoc());
8886 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8887 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8888 return Res;
8889}
8890
8891template <typename Derived>
8892StmtResult
8893TreeTransform<Derived>::TransformOMPMasterDirective(OMPMasterDirective *D) {
8894 DeclarationNameInfo DirName;
8895 getDerived().getSema().StartOpenMPDSABlock(OMPD_master, DirName, nullptr,
8896 D->getBeginLoc());
8897 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8898 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8899 return Res;
8900}
8901
8902template <typename Derived>
8903StmtResult
8904TreeTransform<Derived>::TransformOMPCriticalDirective(OMPCriticalDirective *D) {
8905 getDerived().getSema().StartOpenMPDSABlock(
8906 OMPD_critical, D->getDirectiveName(), nullptr, D->getBeginLoc());
8907 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8908 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8909 return Res;
8910}
8911
8912template <typename Derived>
8913StmtResult TreeTransform<Derived>::TransformOMPParallelForDirective(
8914 OMPParallelForDirective *D) {
8915 DeclarationNameInfo DirName;
8916 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for, DirName,
8917 nullptr, D->getBeginLoc());
8918 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8919 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8920 return Res;
8921}
8922
8923template <typename Derived>
8924StmtResult TreeTransform<Derived>::TransformOMPParallelForSimdDirective(
8925 OMPParallelForSimdDirective *D) {
8926 DeclarationNameInfo DirName;
8927 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_for_simd, DirName,
8928 nullptr, D->getBeginLoc());
8929 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8930 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8931 return Res;
8932}
8933
8934template <typename Derived>
8935StmtResult TreeTransform<Derived>::TransformOMPParallelMasterDirective(
8936 OMPParallelMasterDirective *D) {
8937 DeclarationNameInfo DirName;
8938 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_master, DirName,
8939 nullptr, D->getBeginLoc());
8940 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8941 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8942 return Res;
8943}
8944
8945template <typename Derived>
8946StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedDirective(
8947 OMPParallelMaskedDirective *D) {
8948 DeclarationNameInfo DirName;
8949 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_masked, DirName,
8950 nullptr, D->getBeginLoc());
8951 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8952 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8953 return Res;
8954}
8955
8956template <typename Derived>
8957StmtResult TreeTransform<Derived>::TransformOMPParallelSectionsDirective(
8958 OMPParallelSectionsDirective *D) {
8959 DeclarationNameInfo DirName;
8960 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_sections, DirName,
8961 nullptr, D->getBeginLoc());
8962 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8963 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8964 return Res;
8965}
8966
8967template <typename Derived>
8968StmtResult
8969TreeTransform<Derived>::TransformOMPTaskDirective(OMPTaskDirective *D) {
8970 DeclarationNameInfo DirName;
8971 getDerived().getSema().StartOpenMPDSABlock(OMPD_task, DirName, nullptr,
8972 D->getBeginLoc());
8973 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8974 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8975 return Res;
8976}
8977
8978template <typename Derived>
8979StmtResult TreeTransform<Derived>::TransformOMPTaskyieldDirective(
8980 OMPTaskyieldDirective *D) {
8981 DeclarationNameInfo DirName;
8982 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskyield, DirName, nullptr,
8983 D->getBeginLoc());
8984 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8985 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8986 return Res;
8987}
8988
8989template <typename Derived>
8990StmtResult
8991TreeTransform<Derived>::TransformOMPBarrierDirective(OMPBarrierDirective *D) {
8992 DeclarationNameInfo DirName;
8993 getDerived().getSema().StartOpenMPDSABlock(OMPD_barrier, DirName, nullptr,
8994 D->getBeginLoc());
8995 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
8996 getDerived().getSema().EndOpenMPDSABlock(Res.get());
8997 return Res;
8998}
8999
9000template <typename Derived>
9001StmtResult
9002TreeTransform<Derived>::TransformOMPTaskwaitDirective(OMPTaskwaitDirective *D) {
9003 DeclarationNameInfo DirName;
9004 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskwait, DirName, nullptr,
9005 D->getBeginLoc());
9006 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9007 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9008 return Res;
9009}
9010
9011template <typename Derived>
9012StmtResult
9013TreeTransform<Derived>::TransformOMPErrorDirective(OMPErrorDirective *D) {
9014 DeclarationNameInfo DirName;
9015 getDerived().getSema().StartOpenMPDSABlock(OMPD_error, DirName, nullptr,
9016 D->getBeginLoc());
9017 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9018 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9019 return Res;
9020}
9021
9022template <typename Derived>
9023StmtResult TreeTransform<Derived>::TransformOMPTaskgroupDirective(
9024 OMPTaskgroupDirective *D) {
9025 DeclarationNameInfo DirName;
9026 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskgroup, DirName, nullptr,
9027 D->getBeginLoc());
9028 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9029 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9030 return Res;
9031}
9032
9033template <typename Derived>
9034StmtResult
9035TreeTransform<Derived>::TransformOMPFlushDirective(OMPFlushDirective *D) {
9036 DeclarationNameInfo DirName;
9037 getDerived().getSema().StartOpenMPDSABlock(OMPD_flush, DirName, nullptr,
9038 D->getBeginLoc());
9039 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9040 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9041 return Res;
9042}
9043
9044template <typename Derived>
9045StmtResult
9046TreeTransform<Derived>::TransformOMPDepobjDirective(OMPDepobjDirective *D) {
9047 DeclarationNameInfo DirName;
9048 getDerived().getSema().StartOpenMPDSABlock(OMPD_depobj, DirName, nullptr,
9049 D->getBeginLoc());
9050 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9051 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9052 return Res;
9053}
9054
9055template <typename Derived>
9056StmtResult
9057TreeTransform<Derived>::TransformOMPScanDirective(OMPScanDirective *D) {
9058 DeclarationNameInfo DirName;
9059 getDerived().getSema().StartOpenMPDSABlock(OMPD_scan, DirName, nullptr,
9060 D->getBeginLoc());
9061 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9062 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9063 return Res;
9064}
9065
9066template <typename Derived>
9067StmtResult
9068TreeTransform<Derived>::TransformOMPOrderedDirective(OMPOrderedDirective *D) {
9069 DeclarationNameInfo DirName;
9070 getDerived().getSema().StartOpenMPDSABlock(OMPD_ordered, DirName, nullptr,
9071 D->getBeginLoc());
9072 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9073 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9074 return Res;
9075}
9076
9077template <typename Derived>
9078StmtResult
9079TreeTransform<Derived>::TransformOMPAtomicDirective(OMPAtomicDirective *D) {
9080 DeclarationNameInfo DirName;
9081 getDerived().getSema().StartOpenMPDSABlock(OMPD_atomic, DirName, nullptr,
9082 D->getBeginLoc());
9083 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9084 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9085 return Res;
9086}
9087
9088template <typename Derived>
9089StmtResult
9090TreeTransform<Derived>::TransformOMPTargetDirective(OMPTargetDirective *D) {
9091 DeclarationNameInfo DirName;
9092 getDerived().getSema().StartOpenMPDSABlock(OMPD_target, DirName, nullptr,
9093 D->getBeginLoc());
9094 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9095 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9096 return Res;
9097}
9098
9099template <typename Derived>
9100StmtResult TreeTransform<Derived>::TransformOMPTargetDataDirective(
9101 OMPTargetDataDirective *D) {
9102 DeclarationNameInfo DirName;
9103 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_data, DirName, nullptr,
9104 D->getBeginLoc());
9105 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9106 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9107 return Res;
9108}
9109
9110template <typename Derived>
9111StmtResult TreeTransform<Derived>::TransformOMPTargetEnterDataDirective(
9112 OMPTargetEnterDataDirective *D) {
9113 DeclarationNameInfo DirName;
9114 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_enter_data, DirName,
9115 nullptr, D->getBeginLoc());
9116 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9117 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9118 return Res;
9119}
9120
9121template <typename Derived>
9122StmtResult TreeTransform<Derived>::TransformOMPTargetExitDataDirective(
9123 OMPTargetExitDataDirective *D) {
9124 DeclarationNameInfo DirName;
9125 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_exit_data, DirName,
9126 nullptr, D->getBeginLoc());
9127 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9128 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9129 return Res;
9130}
9131
9132template <typename Derived>
9133StmtResult TreeTransform<Derived>::TransformOMPTargetParallelDirective(
9134 OMPTargetParallelDirective *D) {
9135 DeclarationNameInfo DirName;
9136 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel, DirName,
9137 nullptr, D->getBeginLoc());
9138 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9139 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9140 return Res;
9141}
9142
9143template <typename Derived>
9144StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForDirective(
9145 OMPTargetParallelForDirective *D) {
9146 DeclarationNameInfo DirName;
9147 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_for, DirName,
9148 nullptr, D->getBeginLoc());
9149 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9150 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9151 return Res;
9152}
9153
9154template <typename Derived>
9155StmtResult TreeTransform<Derived>::TransformOMPTargetUpdateDirective(
9156 OMPTargetUpdateDirective *D) {
9157 DeclarationNameInfo DirName;
9158 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_update, DirName,
9159 nullptr, D->getBeginLoc());
9160 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9161 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9162 return Res;
9163}
9164
9165template <typename Derived>
9166StmtResult
9167TreeTransform<Derived>::TransformOMPTeamsDirective(OMPTeamsDirective *D) {
9168 DeclarationNameInfo DirName;
9169 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams, DirName, nullptr,
9170 D->getBeginLoc());
9171 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9172 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9173 return Res;
9174}
9175
9176template <typename Derived>
9177StmtResult TreeTransform<Derived>::TransformOMPCancellationPointDirective(
9178 OMPCancellationPointDirective *D) {
9179 DeclarationNameInfo DirName;
9180 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancellation_point, DirName,
9181 nullptr, D->getBeginLoc());
9182 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9183 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9184 return Res;
9185}
9186
9187template <typename Derived>
9188StmtResult
9189TreeTransform<Derived>::TransformOMPCancelDirective(OMPCancelDirective *D) {
9190 DeclarationNameInfo DirName;
9191 getDerived().getSema().StartOpenMPDSABlock(OMPD_cancel, DirName, nullptr,
9192 D->getBeginLoc());
9193 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9194 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9195 return Res;
9196}
9197
9198template <typename Derived>
9199StmtResult
9200TreeTransform<Derived>::TransformOMPTaskLoopDirective(OMPTaskLoopDirective *D) {
9201 DeclarationNameInfo DirName;
9202 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop, DirName, nullptr,
9203 D->getBeginLoc());
9204 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9205 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9206 return Res;
9207}
9208
9209template <typename Derived>
9210StmtResult TreeTransform<Derived>::TransformOMPTaskLoopSimdDirective(
9211 OMPTaskLoopSimdDirective *D) {
9212 DeclarationNameInfo DirName;
9213 getDerived().getSema().StartOpenMPDSABlock(OMPD_taskloop_simd, DirName,
9214 nullptr, D->getBeginLoc());
9215 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9216 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9217 return Res;
9218}
9219
9220template <typename Derived>
9221StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopDirective(
9222 OMPMasterTaskLoopDirective *D) {
9223 DeclarationNameInfo DirName;
9224 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop, DirName,
9225 nullptr, D->getBeginLoc());
9226 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9227 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9228 return Res;
9229}
9230
9231template <typename Derived>
9232StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopDirective(
9233 OMPMaskedTaskLoopDirective *D) {
9234 DeclarationNameInfo DirName;
9235 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop, DirName,
9236 nullptr, D->getBeginLoc());
9237 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9238 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9239 return Res;
9240}
9241
9242template <typename Derived>
9243StmtResult TreeTransform<Derived>::TransformOMPMasterTaskLoopSimdDirective(
9244 OMPMasterTaskLoopSimdDirective *D) {
9245 DeclarationNameInfo DirName;
9246 getDerived().getSema().StartOpenMPDSABlock(OMPD_master_taskloop_simd, DirName,
9247 nullptr, D->getBeginLoc());
9248 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9249 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9250 return Res;
9251}
9252
9253template <typename Derived>
9254StmtResult TreeTransform<Derived>::TransformOMPMaskedTaskLoopSimdDirective(
9255 OMPMaskedTaskLoopSimdDirective *D) {
9256 DeclarationNameInfo DirName;
9257 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked_taskloop_simd, DirName,
9258 nullptr, D->getBeginLoc());
9259 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9260 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9261 return Res;
9262}
9263
9264template <typename Derived>
9265StmtResult TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopDirective(
9266 OMPParallelMasterTaskLoopDirective *D) {
9267 DeclarationNameInfo DirName;
9268 getDerived().getSema().StartOpenMPDSABlock(
9269 OMPD_parallel_master_taskloop, DirName, nullptr, D->getBeginLoc());
9270 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9271 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9272 return Res;
9273}
9274
9275template <typename Derived>
9276StmtResult TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopDirective(
9277 OMPParallelMaskedTaskLoopDirective *D) {
9278 DeclarationNameInfo DirName;
9279 getDerived().getSema().StartOpenMPDSABlock(
9280 OMPD_parallel_masked_taskloop, DirName, nullptr, D->getBeginLoc());
9281 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9282 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9283 return Res;
9284}
9285
9286template <typename Derived>
9287StmtResult
9288TreeTransform<Derived>::TransformOMPParallelMasterTaskLoopSimdDirective(
9289 OMPParallelMasterTaskLoopSimdDirective *D) {
9290 DeclarationNameInfo DirName;
9291 getDerived().getSema().StartOpenMPDSABlock(
9292 OMPD_parallel_master_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9293 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9294 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9295 return Res;
9296}
9297
9298template <typename Derived>
9299StmtResult
9300TreeTransform<Derived>::TransformOMPParallelMaskedTaskLoopSimdDirective(
9301 OMPParallelMaskedTaskLoopSimdDirective *D) {
9302 DeclarationNameInfo DirName;
9303 getDerived().getSema().StartOpenMPDSABlock(
9304 OMPD_parallel_masked_taskloop_simd, DirName, nullptr, D->getBeginLoc());
9305 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9306 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9307 return Res;
9308}
9309
9310template <typename Derived>
9311StmtResult TreeTransform<Derived>::TransformOMPDistributeDirective(
9312 OMPDistributeDirective *D) {
9313 DeclarationNameInfo DirName;
9314 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute, DirName, nullptr,
9315 D->getBeginLoc());
9316 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9317 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9318 return Res;
9319}
9320
9321template <typename Derived>
9322StmtResult TreeTransform<Derived>::TransformOMPDistributeParallelForDirective(
9323 OMPDistributeParallelForDirective *D) {
9324 DeclarationNameInfo DirName;
9325 getDerived().getSema().StartOpenMPDSABlock(
9326 OMPD_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9327 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9328 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9329 return Res;
9330}
9331
9332template <typename Derived>
9333StmtResult
9334TreeTransform<Derived>::TransformOMPDistributeParallelForSimdDirective(
9335 OMPDistributeParallelForSimdDirective *D) {
9336 DeclarationNameInfo DirName;
9337 getDerived().getSema().StartOpenMPDSABlock(
9338 OMPD_distribute_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9339 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9340 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9341 return Res;
9342}
9343
9344template <typename Derived>
9345StmtResult TreeTransform<Derived>::TransformOMPDistributeSimdDirective(
9346 OMPDistributeSimdDirective *D) {
9347 DeclarationNameInfo DirName;
9348 getDerived().getSema().StartOpenMPDSABlock(OMPD_distribute_simd, DirName,
9349 nullptr, D->getBeginLoc());
9350 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9351 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9352 return Res;
9353}
9354
9355template <typename Derived>
9356StmtResult TreeTransform<Derived>::TransformOMPTargetParallelForSimdDirective(
9357 OMPTargetParallelForSimdDirective *D) {
9358 DeclarationNameInfo DirName;
9359 getDerived().getSema().StartOpenMPDSABlock(
9360 OMPD_target_parallel_for_simd, DirName, nullptr, D->getBeginLoc());
9361 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9362 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9363 return Res;
9364}
9365
9366template <typename Derived>
9367StmtResult TreeTransform<Derived>::TransformOMPTargetSimdDirective(
9368 OMPTargetSimdDirective *D) {
9369 DeclarationNameInfo DirName;
9370 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_simd, DirName, nullptr,
9371 D->getBeginLoc());
9372 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9373 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9374 return Res;
9375}
9376
9377template <typename Derived>
9378StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeDirective(
9379 OMPTeamsDistributeDirective *D) {
9380 DeclarationNameInfo DirName;
9381 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_distribute, DirName,
9382 nullptr, D->getBeginLoc());
9383 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9384 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9385 return Res;
9386}
9387
9388template <typename Derived>
9389StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeSimdDirective(
9390 OMPTeamsDistributeSimdDirective *D) {
9391 DeclarationNameInfo DirName;
9392 getDerived().getSema().StartOpenMPDSABlock(
9393 OMPD_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9394 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9395 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9396 return Res;
9397}
9398
9399template <typename Derived>
9400StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForSimdDirective(
9401 OMPTeamsDistributeParallelForSimdDirective *D) {
9402 DeclarationNameInfo DirName;
9403 getDerived().getSema().StartOpenMPDSABlock(
9404 OMPD_teams_distribute_parallel_for_simd, DirName, nullptr,
9405 D->getBeginLoc());
9406 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9407 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9408 return Res;
9409}
9410
9411template <typename Derived>
9412StmtResult TreeTransform<Derived>::TransformOMPTeamsDistributeParallelForDirective(
9413 OMPTeamsDistributeParallelForDirective *D) {
9414 DeclarationNameInfo DirName;
9415 getDerived().getSema().StartOpenMPDSABlock(
9416 OMPD_teams_distribute_parallel_for, DirName, nullptr, D->getBeginLoc());
9417 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9418 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9419 return Res;
9420}
9421
9422template <typename Derived>
9423StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDirective(
9424 OMPTargetTeamsDirective *D) {
9425 DeclarationNameInfo DirName;
9426 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams, DirName,
9427 nullptr, D->getBeginLoc());
9428 auto Res = getDerived().TransformOMPExecutableDirective(D);
9429 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9430 return Res;
9431}
9432
9433template <typename Derived>
9434StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsDistributeDirective(
9435 OMPTargetTeamsDistributeDirective *D) {
9436 DeclarationNameInfo DirName;
9437 getDerived().getSema().StartOpenMPDSABlock(
9438 OMPD_target_teams_distribute, DirName, nullptr, D->getBeginLoc());
9439 auto Res = getDerived().TransformOMPExecutableDirective(D);
9440 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9441 return Res;
9442}
9443
9444template <typename Derived>
9445StmtResult
9446TreeTransform<Derived>::TransformOMPTargetTeamsDistributeParallelForDirective(
9447 OMPTargetTeamsDistributeParallelForDirective *D) {
9448 DeclarationNameInfo DirName;
9449 getDerived().getSema().StartOpenMPDSABlock(
9450 OMPD_target_teams_distribute_parallel_for, DirName, nullptr,
9451 D->getBeginLoc());
9452 auto Res = getDerived().TransformOMPExecutableDirective(D);
9453 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9454 return Res;
9455}
9456
9457template <typename Derived>
9458StmtResult TreeTransform<Derived>::
9459 TransformOMPTargetTeamsDistributeParallelForSimdDirective(
9460 OMPTargetTeamsDistributeParallelForSimdDirective *D) {
9461 DeclarationNameInfo DirName;
9462 getDerived().getSema().StartOpenMPDSABlock(
9463 OMPD_target_teams_distribute_parallel_for_simd, DirName, nullptr,
9464 D->getBeginLoc());
9465 auto Res = getDerived().TransformOMPExecutableDirective(D);
9466 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9467 return Res;
9468}
9469
9470template <typename Derived>
9471StmtResult
9472TreeTransform<Derived>::TransformOMPTargetTeamsDistributeSimdDirective(
9473 OMPTargetTeamsDistributeSimdDirective *D) {
9474 DeclarationNameInfo DirName;
9475 getDerived().getSema().StartOpenMPDSABlock(
9476 OMPD_target_teams_distribute_simd, DirName, nullptr, D->getBeginLoc());
9477 auto Res = getDerived().TransformOMPExecutableDirective(D);
9478 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9479 return Res;
9480}
9481
9482template <typename Derived>
9483StmtResult
9484TreeTransform<Derived>::TransformOMPInteropDirective(OMPInteropDirective *D) {
9485 DeclarationNameInfo DirName;
9486 getDerived().getSema().StartOpenMPDSABlock(OMPD_interop, DirName, nullptr,
9487 D->getBeginLoc());
9488 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9489 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9490 return Res;
9491}
9492
9493template <typename Derived>
9494StmtResult
9495TreeTransform<Derived>::TransformOMPDispatchDirective(OMPDispatchDirective *D) {
9496 DeclarationNameInfo DirName;
9497 getDerived().getSema().StartOpenMPDSABlock(OMPD_dispatch, DirName, nullptr,
9498 D->getBeginLoc());
9499 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9500 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9501 return Res;
9502}
9503
9504template <typename Derived>
9505StmtResult
9506TreeTransform<Derived>::TransformOMPMaskedDirective(OMPMaskedDirective *D) {
9507 DeclarationNameInfo DirName;
9508 getDerived().getSema().StartOpenMPDSABlock(OMPD_masked, DirName, nullptr,
9509 D->getBeginLoc());
9510 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9511 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9512 return Res;
9513}
9514
9515template <typename Derived>
9516StmtResult TreeTransform<Derived>::TransformOMPGenericLoopDirective(
9517 OMPGenericLoopDirective *D) {
9518 DeclarationNameInfo DirName;
9519 getDerived().getSema().StartOpenMPDSABlock(OMPD_loop, DirName, nullptr,
9520 D->getBeginLoc());
9521 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9522 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9523 return Res;
9524}
9525
9526template <typename Derived>
9527StmtResult TreeTransform<Derived>::TransformOMPTeamsGenericLoopDirective(
9528 OMPTeamsGenericLoopDirective *D) {
9529 DeclarationNameInfo DirName;
9530 getDerived().getSema().StartOpenMPDSABlock(OMPD_teams_loop, DirName, nullptr,
9531 D->getBeginLoc());
9532 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9533 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9534 return Res;
9535}
9536
9537template <typename Derived>
9538StmtResult TreeTransform<Derived>::TransformOMPTargetTeamsGenericLoopDirective(
9539 OMPTargetTeamsGenericLoopDirective *D) {
9540 DeclarationNameInfo DirName;
9541 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_teams_loop, DirName,
9542 nullptr, D->getBeginLoc());
9543 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9544 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9545 return Res;
9546}
9547
9548template <typename Derived>
9549StmtResult TreeTransform<Derived>::TransformOMPParallelGenericLoopDirective(
9550 OMPParallelGenericLoopDirective *D) {
9551 DeclarationNameInfo DirName;
9552 getDerived().getSema().StartOpenMPDSABlock(OMPD_parallel_loop, DirName,
9553 nullptr, D->getBeginLoc());
9554 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9555 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9556 return Res;
9557}
9558
9559template <typename Derived>
9560StmtResult
9561TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
9562 OMPTargetParallelGenericLoopDirective *D) {
9563 DeclarationNameInfo DirName;
9564 getDerived().getSema().StartOpenMPDSABlock(OMPD_target_parallel_loop, DirName,
9565 nullptr, D->getBeginLoc());
9566 StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
9567 getDerived().getSema().EndOpenMPDSABlock(Res.get());
9568 return Res;
9569}
9570
9571//===----------------------------------------------------------------------===//
9572// OpenMP clause transformation
9573//===----------------------------------------------------------------------===//
9574template <typename Derived>
9575OMPClause *TreeTransform<Derived>::TransformOMPIfClause(OMPIfClause *C) {
9576 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9577 if (Cond.isInvalid())
9578 return nullptr;
9579 return getDerived().RebuildOMPIfClause(
9580 C->getNameModifier(), Cond.get(), C->getBeginLoc(), C->getLParenLoc(),
9581 C->getNameModifierLoc(), C->getColonLoc(), C->getEndLoc());
9582}
9583
9584template <typename Derived>
9585OMPClause *TreeTransform<Derived>::TransformOMPFinalClause(OMPFinalClause *C) {
9586 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9587 if (Cond.isInvalid())
9588 return nullptr;
9589 return getDerived().RebuildOMPFinalClause(Cond.get(), C->getBeginLoc(),
9590 C->getLParenLoc(), C->getEndLoc());
9591}
9592
9593template <typename Derived>
9594OMPClause *
9595TreeTransform<Derived>::TransformOMPNumThreadsClause(OMPNumThreadsClause *C) {
9596 ExprResult NumThreads = getDerived().TransformExpr(C->getNumThreads());
9597 if (NumThreads.isInvalid())
9598 return nullptr;
9599 return getDerived().RebuildOMPNumThreadsClause(
9600 NumThreads.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9601}
9602
9603template <typename Derived>
9604OMPClause *
9605TreeTransform<Derived>::TransformOMPSafelenClause(OMPSafelenClause *C) {
9606 ExprResult E = getDerived().TransformExpr(C->getSafelen());
9607 if (E.isInvalid())
9608 return nullptr;
9609 return getDerived().RebuildOMPSafelenClause(
9610 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9611}
9612
9613template <typename Derived>
9614OMPClause *
9615TreeTransform<Derived>::TransformOMPAllocatorClause(OMPAllocatorClause *C) {
9616 ExprResult E = getDerived().TransformExpr(C->getAllocator());
9617 if (E.isInvalid())
9618 return nullptr;
9619 return getDerived().RebuildOMPAllocatorClause(
9620 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9621}
9622
9623template <typename Derived>
9624OMPClause *
9625TreeTransform<Derived>::TransformOMPSimdlenClause(OMPSimdlenClause *C) {
9626 ExprResult E = getDerived().TransformExpr(C->getSimdlen());
9627 if (E.isInvalid())
9628 return nullptr;
9629 return getDerived().RebuildOMPSimdlenClause(
9630 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9631}
9632
9633template <typename Derived>
9634OMPClause *TreeTransform<Derived>::TransformOMPSizesClause(OMPSizesClause *C) {
9635 SmallVector<Expr *, 4> TransformedSizes;
9636 TransformedSizes.reserve(C->getNumSizes());
9637 bool Changed = false;
9638 for (Expr *E : C->getSizesRefs()) {
9639 if (!E) {
9640 TransformedSizes.push_back(nullptr);
9641 continue;
9642 }
9643
9644 ExprResult T = getDerived().TransformExpr(E);
9645 if (T.isInvalid())
9646 return nullptr;
9647 if (E != T.get())
9648 Changed = true;
9649 TransformedSizes.push_back(T.get());
9650 }
9651
9652 if (!Changed && !getDerived().AlwaysRebuild())
9653 return C;
9654 return RebuildOMPSizesClause(TransformedSizes, C->getBeginLoc(),
9655 C->getLParenLoc(), C->getEndLoc());
9656}
9657
9658template <typename Derived>
9659OMPClause *TreeTransform<Derived>::TransformOMPFullClause(OMPFullClause *C) {
9660 if (!getDerived().AlwaysRebuild())
9661 return C;
9662 return RebuildOMPFullClause(C->getBeginLoc(), C->getEndLoc());
9663}
9664
9665template <typename Derived>
9666OMPClause *
9667TreeTransform<Derived>::TransformOMPPartialClause(OMPPartialClause *C) {
9668 ExprResult T = getDerived().TransformExpr(C->getFactor());
9669 if (T.isInvalid())
9670 return nullptr;
9671 Expr *Factor = T.get();
9672 bool Changed = Factor != C->getFactor();
9673
9674 if (!Changed && !getDerived().AlwaysRebuild())
9675 return C;
9676 return RebuildOMPPartialClause(Factor, C->getBeginLoc(), C->getLParenLoc(),
9677 C->getEndLoc());
9678}
9679
9680template <typename Derived>
9681OMPClause *
9682TreeTransform<Derived>::TransformOMPCollapseClause(OMPCollapseClause *C) {
9683 ExprResult E = getDerived().TransformExpr(C->getNumForLoops());
9684 if (E.isInvalid())
9685 return nullptr;
9686 return getDerived().RebuildOMPCollapseClause(
9687 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9688}
9689
9690template <typename Derived>
9691OMPClause *
9692TreeTransform<Derived>::TransformOMPDefaultClause(OMPDefaultClause *C) {
9693 return getDerived().RebuildOMPDefaultClause(
9694 C->getDefaultKind(), C->getDefaultKindKwLoc(), C->getBeginLoc(),
9695 C->getLParenLoc(), C->getEndLoc());
9696}
9697
9698template <typename Derived>
9699OMPClause *
9700TreeTransform<Derived>::TransformOMPProcBindClause(OMPProcBindClause *C) {
9701 return getDerived().RebuildOMPProcBindClause(
9702 C->getProcBindKind(), C->getProcBindKindKwLoc(), C->getBeginLoc(),
9703 C->getLParenLoc(), C->getEndLoc());
9704}
9705
9706template <typename Derived>
9707OMPClause *
9708TreeTransform<Derived>::TransformOMPScheduleClause(OMPScheduleClause *C) {
9709 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
9710 if (E.isInvalid())
9711 return nullptr;
9712 return getDerived().RebuildOMPScheduleClause(
9713 C->getFirstScheduleModifier(), C->getSecondScheduleModifier(),
9714 C->getScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
9715 C->getFirstScheduleModifierLoc(), C->getSecondScheduleModifierLoc(),
9716 C->getScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
9717}
9718
9719template <typename Derived>
9720OMPClause *
9721TreeTransform<Derived>::TransformOMPOrderedClause(OMPOrderedClause *C) {
9722 ExprResult E;
9723 if (auto *Num = C->getNumForLoops()) {
9724 E = getDerived().TransformExpr(Num);
9725 if (E.isInvalid())
9726 return nullptr;
9727 }
9728 return getDerived().RebuildOMPOrderedClause(C->getBeginLoc(), C->getEndLoc(),
9729 C->getLParenLoc(), E.get());
9730}
9731
9732template <typename Derived>
9733OMPClause *
9734TreeTransform<Derived>::TransformOMPDetachClause(OMPDetachClause *C) {
9735 ExprResult E;
9736 if (Expr *Evt = C->getEventHandler()) {
9737 E = getDerived().TransformExpr(Evt);
9738 if (E.isInvalid())
9739 return nullptr;
9740 }
9741 return getDerived().RebuildOMPDetachClause(E.get(), C->getBeginLoc(),
9742 C->getLParenLoc(), C->getEndLoc());
9743}
9744
9745template <typename Derived>
9746OMPClause *
9747TreeTransform<Derived>::TransformOMPNowaitClause(OMPNowaitClause *C) {
9748 // No need to rebuild this clause, no template-dependent parameters.
9749 return C;
9750}
9751
9752template <typename Derived>
9753OMPClause *
9754TreeTransform<Derived>::TransformOMPUntiedClause(OMPUntiedClause *C) {
9755 // No need to rebuild this clause, no template-dependent parameters.
9756 return C;
9757}
9758
9759template <typename Derived>
9760OMPClause *
9761TreeTransform<Derived>::TransformOMPMergeableClause(OMPMergeableClause *C) {
9762 // No need to rebuild this clause, no template-dependent parameters.
9763 return C;
9764}
9765
9766template <typename Derived>
9767OMPClause *TreeTransform<Derived>::TransformOMPReadClause(OMPReadClause *C) {
9768 // No need to rebuild this clause, no template-dependent parameters.
9769 return C;
9770}
9771
9772template <typename Derived>
9773OMPClause *TreeTransform<Derived>::TransformOMPWriteClause(OMPWriteClause *C) {
9774 // No need to rebuild this clause, no template-dependent parameters.
9775 return C;
9776}
9777
9778template <typename Derived>
9779OMPClause *
9780TreeTransform<Derived>::TransformOMPUpdateClause(OMPUpdateClause *C) {
9781 // No need to rebuild this clause, no template-dependent parameters.
9782 return C;
9783}
9784
9785template <typename Derived>
9786OMPClause *
9787TreeTransform<Derived>::TransformOMPCaptureClause(OMPCaptureClause *C) {
9788 // No need to rebuild this clause, no template-dependent parameters.
9789 return C;
9790}
9791
9792template <typename Derived>
9793OMPClause *
9794TreeTransform<Derived>::TransformOMPCompareClause(OMPCompareClause *C) {
9795 // No need to rebuild this clause, no template-dependent parameters.
9796 return C;
9797}
9798
9799template <typename Derived>
9800OMPClause *
9801TreeTransform<Derived>::TransformOMPSeqCstClause(OMPSeqCstClause *C) {
9802 // No need to rebuild this clause, no template-dependent parameters.
9803 return C;
9804}
9805
9806template <typename Derived>
9807OMPClause *
9808TreeTransform<Derived>::TransformOMPAcqRelClause(OMPAcqRelClause *C) {
9809 // No need to rebuild this clause, no template-dependent parameters.
9810 return C;
9811}
9812
9813template <typename Derived>
9814OMPClause *
9815TreeTransform<Derived>::TransformOMPAcquireClause(OMPAcquireClause *C) {
9816 // No need to rebuild this clause, no template-dependent parameters.
9817 return C;
9818}
9819
9820template <typename Derived>
9821OMPClause *
9822TreeTransform<Derived>::TransformOMPReleaseClause(OMPReleaseClause *C) {
9823 // No need to rebuild this clause, no template-dependent parameters.
9824 return C;
9825}
9826
9827template <typename Derived>
9828OMPClause *
9829TreeTransform<Derived>::TransformOMPRelaxedClause(OMPRelaxedClause *C) {
9830 // No need to rebuild this clause, no template-dependent parameters.
9831 return C;
9832}
9833
9834template <typename Derived>
9835OMPClause *
9836TreeTransform<Derived>::TransformOMPThreadsClause(OMPThreadsClause *C) {
9837 // No need to rebuild this clause, no template-dependent parameters.
9838 return C;
9839}
9840
9841template <typename Derived>
9842OMPClause *TreeTransform<Derived>::TransformOMPSIMDClause(OMPSIMDClause *C) {
9843 // No need to rebuild this clause, no template-dependent parameters.
9844 return C;
9845}
9846
9847template <typename Derived>
9848OMPClause *
9849TreeTransform<Derived>::TransformOMPNogroupClause(OMPNogroupClause *C) {
9850 // No need to rebuild this clause, no template-dependent parameters.
9851 return C;
9852}
9853
9854template <typename Derived>
9855OMPClause *TreeTransform<Derived>::TransformOMPInitClause(OMPInitClause *C) {
9856 ExprResult IVR = getDerived().TransformExpr(C->getInteropVar());
9857 if (IVR.isInvalid())
9858 return nullptr;
9859
9860 OMPInteropInfo InteropInfo(C->getIsTarget(), C->getIsTargetSync());
9861 InteropInfo.PreferTypes.reserve(C->varlist_size() - 1);
9862 for (Expr *E : llvm::drop_begin(C->varlists())) {
9863 ExprResult ER = getDerived().TransformExpr(cast<Expr>(E));
9864 if (ER.isInvalid())
9865 return nullptr;
9866 InteropInfo.PreferTypes.push_back(ER.get());
9867 }
9868 return getDerived().RebuildOMPInitClause(IVR.get(), InteropInfo,
9869 C->getBeginLoc(), C->getLParenLoc(),
9870 C->getVarLoc(), C->getEndLoc());
9871}
9872
9873template <typename Derived>
9874OMPClause *TreeTransform<Derived>::TransformOMPUseClause(OMPUseClause *C) {
9875 ExprResult ER = getDerived().TransformExpr(C->getInteropVar());
9876 if (ER.isInvalid())
9877 return nullptr;
9878 return getDerived().RebuildOMPUseClause(ER.get(), C->getBeginLoc(),
9879 C->getLParenLoc(), C->getVarLoc(),
9880 C->getEndLoc());
9881}
9882
9883template <typename Derived>
9884OMPClause *
9885TreeTransform<Derived>::TransformOMPDestroyClause(OMPDestroyClause *C) {
9886 ExprResult ER;
9887 if (Expr *IV = C->getInteropVar()) {
9888 ER = getDerived().TransformExpr(IV);
9889 if (ER.isInvalid())
9890 return nullptr;
9891 }
9892 return getDerived().RebuildOMPDestroyClause(ER.get(), C->getBeginLoc(),
9893 C->getLParenLoc(), C->getVarLoc(),
9894 C->getEndLoc());
9895}
9896
9897template <typename Derived>
9898OMPClause *
9899TreeTransform<Derived>::TransformOMPNovariantsClause(OMPNovariantsClause *C) {
9900 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9901 if (Cond.isInvalid())
9902 return nullptr;
9903 return getDerived().RebuildOMPNovariantsClause(
9904 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9905}
9906
9907template <typename Derived>
9908OMPClause *
9909TreeTransform<Derived>::TransformOMPNocontextClause(OMPNocontextClause *C) {
9910 ExprResult Cond = getDerived().TransformExpr(C->getCondition());
9911 if (Cond.isInvalid())
9912 return nullptr;
9913 return getDerived().RebuildOMPNocontextClause(
9914 Cond.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
9915}
9916
9917template <typename Derived>
9918OMPClause *
9919TreeTransform<Derived>::TransformOMPFilterClause(OMPFilterClause *C) {
9920 ExprResult ThreadID = getDerived().TransformExpr(C->getThreadID());
9921 if (ThreadID.isInvalid())
9922 return nullptr;
9923 return getDerived().RebuildOMPFilterClause(ThreadID.get(), C->getBeginLoc(),
9924 C->getLParenLoc(), C->getEndLoc());
9925}
9926
9927template <typename Derived>
9928OMPClause *TreeTransform<Derived>::TransformOMPAlignClause(OMPAlignClause *C) {
9929 ExprResult E = getDerived().TransformExpr(C->getAlignment());
9930 if (E.isInvalid())
9931 return nullptr;
9932 return getDerived().RebuildOMPAlignClause(E.get(), C->getBeginLoc(),
9933 C->getLParenLoc(), C->getEndLoc());
9934}
9935
9936template <typename Derived>
9937OMPClause *TreeTransform<Derived>::TransformOMPUnifiedAddressClause(
9938 OMPUnifiedAddressClause *C) {
9939 llvm_unreachable("unified_address clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_address clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9939)
;
9940}
9941
9942template <typename Derived>
9943OMPClause *TreeTransform<Derived>::TransformOMPUnifiedSharedMemoryClause(
9944 OMPUnifiedSharedMemoryClause *C) {
9945 llvm_unreachable(::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9946)
9946 "unified_shared_memory clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("unified_shared_memory clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9946)
;
9947}
9948
9949template <typename Derived>
9950OMPClause *TreeTransform<Derived>::TransformOMPReverseOffloadClause(
9951 OMPReverseOffloadClause *C) {
9952 llvm_unreachable("reverse_offload clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("reverse_offload clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9952)
;
9953}
9954
9955template <typename Derived>
9956OMPClause *TreeTransform<Derived>::TransformOMPDynamicAllocatorsClause(
9957 OMPDynamicAllocatorsClause *C) {
9958 llvm_unreachable(::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9959)
9959 "dynamic_allocators clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("dynamic_allocators clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9959)
;
9960}
9961
9962template <typename Derived>
9963OMPClause *TreeTransform<Derived>::TransformOMPAtomicDefaultMemOrderClause(
9964 OMPAtomicDefaultMemOrderClause *C) {
9965 llvm_unreachable(::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9966)
9966 "atomic_default_mem_order clause cannot appear in dependent context")::llvm::llvm_unreachable_internal("atomic_default_mem_order clause cannot appear in dependent context"
, "clang/lib/Sema/TreeTransform.h", 9966)
;
9967}
9968
9969template <typename Derived>
9970OMPClause *TreeTransform<Derived>::TransformOMPAtClause(OMPAtClause *C) {
9971 return getDerived().RebuildOMPAtClause(C->getAtKind(), C->getAtKindKwLoc(),
9972 C->getBeginLoc(), C->getLParenLoc(),
9973 C->getEndLoc());
9974}
9975
9976template <typename Derived>
9977OMPClause *
9978TreeTransform<Derived>::TransformOMPSeverityClause(OMPSeverityClause *C) {
9979 return getDerived().RebuildOMPSeverityClause(
9980 C->getSeverityKind(), C->getSeverityKindKwLoc(), C->getBeginLoc(),
9981 C->getLParenLoc(), C->getEndLoc());
9982}
9983
9984template <typename Derived>
9985OMPClause *
9986TreeTransform<Derived>::TransformOMPMessageClause(OMPMessageClause *C) {
9987 ExprResult E = getDerived().TransformExpr(C->getMessageString());
9988 if (E.isInvalid())
9989 return nullptr;
9990 return getDerived().RebuildOMPMessageClause(
9991 C->getMessageString(), C->getBeginLoc(), C->getLParenLoc(),
9992 C->getEndLoc());
9993}
9994
9995template <typename Derived>
9996OMPClause *
9997TreeTransform<Derived>::TransformOMPPrivateClause(OMPPrivateClause *C) {
9998 llvm::SmallVector<Expr *, 16> Vars;
9999 Vars.reserve(C->varlist_size());
10000 for (auto *VE : C->varlists()) {
10001 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10002 if (EVar.isInvalid())
10003 return nullptr;
10004 Vars.push_back(EVar.get());
10005 }
10006 return getDerived().RebuildOMPPrivateClause(
10007 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10008}
10009
10010template <typename Derived>
10011OMPClause *TreeTransform<Derived>::TransformOMPFirstprivateClause(
10012 OMPFirstprivateClause *C) {
10013 llvm::SmallVector<Expr *, 16> Vars;
10014 Vars.reserve(C->varlist_size());
10015 for (auto *VE : C->varlists()) {
10016 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10017 if (EVar.isInvalid())
10018 return nullptr;
10019 Vars.push_back(EVar.get());
10020 }
10021 return getDerived().RebuildOMPFirstprivateClause(
10022 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10023}
10024
10025template <typename Derived>
10026OMPClause *
10027TreeTransform<Derived>::TransformOMPLastprivateClause(OMPLastprivateClause *C) {
10028 llvm::SmallVector<Expr *, 16> Vars;
10029 Vars.reserve(C->varlist_size());
10030 for (auto *VE : C->varlists()) {
10031 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10032 if (EVar.isInvalid())
10033 return nullptr;
10034 Vars.push_back(EVar.get());
10035 }
10036 return getDerived().RebuildOMPLastprivateClause(
10037 Vars, C->getKind(), C->getKindLoc(), C->getColonLoc(), C->getBeginLoc(),
10038 C->getLParenLoc(), C->getEndLoc());
10039}
10040
10041template <typename Derived>
10042OMPClause *
10043TreeTransform<Derived>::TransformOMPSharedClause(OMPSharedClause *C) {
10044 llvm::SmallVector<Expr *, 16> Vars;
10045 Vars.reserve(C->varlist_size());
10046 for (auto *VE : C->varlists()) {
10047 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10048 if (EVar.isInvalid())
10049 return nullptr;
10050 Vars.push_back(EVar.get());
10051 }
10052 return getDerived().RebuildOMPSharedClause(Vars, C->getBeginLoc(),
10053 C->getLParenLoc(), C->getEndLoc());
10054}
10055
10056template <typename Derived>
10057OMPClause *
10058TreeTransform<Derived>::TransformOMPReductionClause(OMPReductionClause *C) {
10059 llvm::SmallVector<Expr *, 16> Vars;
10060 Vars.reserve(C->varlist_size());
10061 for (auto *VE : C->varlists()) {
10062 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10063 if (EVar.isInvalid())
10064 return nullptr;
10065 Vars.push_back(EVar.get());
10066 }
10067 CXXScopeSpec ReductionIdScopeSpec;
10068 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10069
10070 DeclarationNameInfo NameInfo = C->getNameInfo();
10071 if (NameInfo.getName()) {
10072 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10073 if (!NameInfo.getName())
10074 return nullptr;
10075 }
10076 // Build a list of all UDR decls with the same names ranged by the Scopes.
10077 // The Scope boundary is a duplication of the previous decl.
10078 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10079 for (auto *E : C->reduction_ops()) {
10080 // Transform all the decls.
10081 if (E) {
10082 auto *ULE = cast<UnresolvedLookupExpr>(E);
10083 UnresolvedSet<8> Decls;
10084 for (auto *D : ULE->decls()) {
10085 NamedDecl *InstD =
10086 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10087 Decls.addDecl(InstD, InstD->getAccess());
10088 }
10089 UnresolvedReductions.push_back(
10090 UnresolvedLookupExpr::Create(
10091 SemaRef.Context, /*NamingClass=*/nullptr,
10092 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context),
10093 NameInfo, /*ADL=*/true, ULE->isOverloaded(),
10094 Decls.begin(), Decls.end()));
10095 } else
10096 UnresolvedReductions.push_back(nullptr);
10097 }
10098 return getDerived().RebuildOMPReductionClause(
10099 Vars, C->getModifier(), C->getBeginLoc(), C->getLParenLoc(),
10100 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc(),
10101 ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10102}
10103
10104template <typename Derived>
10105OMPClause *TreeTransform<Derived>::TransformOMPTaskReductionClause(
10106 OMPTaskReductionClause *C) {
10107 llvm::SmallVector<Expr *, 16> Vars;
10108 Vars.reserve(C->varlist_size());
10109 for (auto *VE : C->varlists()) {
10110 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10111 if (EVar.isInvalid())
10112 return nullptr;
10113 Vars.push_back(EVar.get());
10114 }
10115 CXXScopeSpec ReductionIdScopeSpec;
10116 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10117
10118 DeclarationNameInfo NameInfo = C->getNameInfo();
10119 if (NameInfo.getName()) {
10120 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10121 if (!NameInfo.getName())
10122 return nullptr;
10123 }
10124 // Build a list of all UDR decls with the same names ranged by the Scopes.
10125 // The Scope boundary is a duplication of the previous decl.
10126 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10127 for (auto *E : C->reduction_ops()) {
10128 // Transform all the decls.
10129 if (E) {
10130 auto *ULE = cast<UnresolvedLookupExpr>(E);
10131 UnresolvedSet<8> Decls;
10132 for (auto *D : ULE->decls()) {
10133 NamedDecl *InstD =
10134 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10135 Decls.addDecl(InstD, InstD->getAccess());
10136 }
10137 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10138 SemaRef.Context, /*NamingClass=*/nullptr,
10139 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10140 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10141 } else
10142 UnresolvedReductions.push_back(nullptr);
10143 }
10144 return getDerived().RebuildOMPTaskReductionClause(
10145 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10146 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10147}
10148
10149template <typename Derived>
10150OMPClause *
10151TreeTransform<Derived>::TransformOMPInReductionClause(OMPInReductionClause *C) {
10152 llvm::SmallVector<Expr *, 16> Vars;
10153 Vars.reserve(C->varlist_size());
10154 for (auto *VE : C->varlists()) {
10155 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10156 if (EVar.isInvalid())
10157 return nullptr;
10158 Vars.push_back(EVar.get());
10159 }
10160 CXXScopeSpec ReductionIdScopeSpec;
10161 ReductionIdScopeSpec.Adopt(C->getQualifierLoc());
10162
10163 DeclarationNameInfo NameInfo = C->getNameInfo();
10164 if (NameInfo.getName()) {
10165 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10166 if (!NameInfo.getName())
10167 return nullptr;
10168 }
10169 // Build a list of all UDR decls with the same names ranged by the Scopes.
10170 // The Scope boundary is a duplication of the previous decl.
10171 llvm::SmallVector<Expr *, 16> UnresolvedReductions;
10172 for (auto *E : C->reduction_ops()) {
10173 // Transform all the decls.
10174 if (E) {
10175 auto *ULE = cast<UnresolvedLookupExpr>(E);
10176 UnresolvedSet<8> Decls;
10177 for (auto *D : ULE->decls()) {
10178 NamedDecl *InstD =
10179 cast<NamedDecl>(getDerived().TransformDecl(E->getExprLoc(), D));
10180 Decls.addDecl(InstD, InstD->getAccess());
10181 }
10182 UnresolvedReductions.push_back(UnresolvedLookupExpr::Create(
10183 SemaRef.Context, /*NamingClass=*/nullptr,
10184 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), NameInfo,
10185 /*ADL=*/true, ULE->isOverloaded(), Decls.begin(), Decls.end()));
10186 } else
10187 UnresolvedReductions.push_back(nullptr);
10188 }
10189 return getDerived().RebuildOMPInReductionClause(
10190 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10191 C->getEndLoc(), ReductionIdScopeSpec, NameInfo, UnresolvedReductions);
10192}
10193
10194template <typename Derived>
10195OMPClause *
10196TreeTransform<Derived>::TransformOMPLinearClause(OMPLinearClause *C) {
10197 llvm::SmallVector<Expr *, 16> Vars;
10198 Vars.reserve(C->varlist_size());
10199 for (auto *VE : C->varlists()) {
10200 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10201 if (EVar.isInvalid())
10202 return nullptr;
10203 Vars.push_back(EVar.get());
10204 }
10205 ExprResult Step = getDerived().TransformExpr(C->getStep());
10206 if (Step.isInvalid())
10207 return nullptr;
10208 return getDerived().RebuildOMPLinearClause(
10209 Vars, Step.get(), C->getBeginLoc(), C->getLParenLoc(), C->getModifier(),
10210 C->getModifierLoc(), C->getColonLoc(), C->getEndLoc());
10211}
10212
10213template <typename Derived>
10214OMPClause *
10215TreeTransform<Derived>::TransformOMPAlignedClause(OMPAlignedClause *C) {
10216 llvm::SmallVector<Expr *, 16> Vars;
10217 Vars.reserve(C->varlist_size());
10218 for (auto *VE : C->varlists()) {
10219 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10220 if (EVar.isInvalid())
10221 return nullptr;
10222 Vars.push_back(EVar.get());
10223 }
10224 ExprResult Alignment = getDerived().TransformExpr(C->getAlignment());
10225 if (Alignment.isInvalid())
10226 return nullptr;
10227 return getDerived().RebuildOMPAlignedClause(
10228 Vars, Alignment.get(), C->getBeginLoc(), C->getLParenLoc(),
10229 C->getColonLoc(), C->getEndLoc());
10230}
10231
10232template <typename Derived>
10233OMPClause *
10234TreeTransform<Derived>::TransformOMPCopyinClause(OMPCopyinClause *C) {
10235 llvm::SmallVector<Expr *, 16> Vars;
10236 Vars.reserve(C->varlist_size());
10237 for (auto *VE : C->varlists()) {
10238 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10239 if (EVar.isInvalid())
10240 return nullptr;
10241 Vars.push_back(EVar.get());
10242 }
10243 return getDerived().RebuildOMPCopyinClause(Vars, C->getBeginLoc(),
10244 C->getLParenLoc(), C->getEndLoc());
10245}
10246
10247template <typename Derived>
10248OMPClause *
10249TreeTransform<Derived>::TransformOMPCopyprivateClause(OMPCopyprivateClause *C) {
10250 llvm::SmallVector<Expr *, 16> Vars;
10251 Vars.reserve(C->varlist_size());
10252 for (auto *VE : C->varlists()) {
10253 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10254 if (EVar.isInvalid())
10255 return nullptr;
10256 Vars.push_back(EVar.get());
10257 }
10258 return getDerived().RebuildOMPCopyprivateClause(
10259 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10260}
10261
10262template <typename Derived>
10263OMPClause *TreeTransform<Derived>::TransformOMPFlushClause(OMPFlushClause *C) {
10264 llvm::SmallVector<Expr *, 16> Vars;
10265 Vars.reserve(C->varlist_size());
10266 for (auto *VE : C->varlists()) {
10267 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10268 if (EVar.isInvalid())
10269 return nullptr;
10270 Vars.push_back(EVar.get());
10271 }
10272 return getDerived().RebuildOMPFlushClause(Vars, C->getBeginLoc(),
10273 C->getLParenLoc(), C->getEndLoc());
10274}
10275
10276template <typename Derived>
10277OMPClause *
10278TreeTransform<Derived>::TransformOMPDepobjClause(OMPDepobjClause *C) {
10279 ExprResult E = getDerived().TransformExpr(C->getDepobj());
10280 if (E.isInvalid())
10281 return nullptr;
10282 return getDerived().RebuildOMPDepobjClause(E.get(), C->getBeginLoc(),
10283 C->getLParenLoc(), C->getEndLoc());
10284}
10285
10286template <typename Derived>
10287OMPClause *
10288TreeTransform<Derived>::TransformOMPDependClause(OMPDependClause *C) {
10289 llvm::SmallVector<Expr *, 16> Vars;
10290 Expr *DepModifier = C->getModifier();
10291 if (DepModifier) {
10292 ExprResult DepModRes = getDerived().TransformExpr(DepModifier);
10293 if (DepModRes.isInvalid())
10294 return nullptr;
10295 DepModifier = DepModRes.get();
10296 }
10297 Vars.reserve(C->varlist_size());
10298 for (auto *VE : C->varlists()) {
10299 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10300 if (EVar.isInvalid())
10301 return nullptr;
10302 Vars.push_back(EVar.get());
10303 }
10304 return getDerived().RebuildOMPDependClause(
10305 {C->getDependencyKind(), C->getDependencyLoc(), C->getColonLoc(),
10306 C->getOmpAllMemoryLoc()},
10307 DepModifier, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10308}
10309
10310template <typename Derived>
10311OMPClause *
10312TreeTransform<Derived>::TransformOMPDeviceClause(OMPDeviceClause *C) {
10313 ExprResult E = getDerived().TransformExpr(C->getDevice());
10314 if (E.isInvalid())
10315 return nullptr;
10316 return getDerived().RebuildOMPDeviceClause(
10317 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10318 C->getModifierLoc(), C->getEndLoc());
10319}
10320
10321template <typename Derived, class T>
10322bool transformOMPMappableExprListClause(
10323 TreeTransform<Derived> &TT, OMPMappableExprListClause<T> *C,
10324 llvm::SmallVectorImpl<Expr *> &Vars, CXXScopeSpec &MapperIdScopeSpec,
10325 DeclarationNameInfo &MapperIdInfo,
10326 llvm::SmallVectorImpl<Expr *> &UnresolvedMappers) {
10327 // Transform expressions in the list.
10328 Vars.reserve(C->varlist_size());
10329 for (auto *VE : C->varlists()) {
10330 ExprResult EVar = TT.getDerived().TransformExpr(cast<Expr>(VE));
10331 if (EVar.isInvalid())
10332 return true;
10333 Vars.push_back(EVar.get());
10334 }
10335 // Transform mapper scope specifier and identifier.
10336 NestedNameSpecifierLoc QualifierLoc;
10337 if (C->getMapperQualifierLoc()) {
10338 QualifierLoc = TT.getDerived().TransformNestedNameSpecifierLoc(
10339 C->getMapperQualifierLoc());
10340 if (!QualifierLoc)
10341 return true;
10342 }
10343 MapperIdScopeSpec.Adopt(QualifierLoc);
10344 MapperIdInfo = C->getMapperIdInfo();
10345 if (MapperIdInfo.getName()) {
10346 MapperIdInfo = TT.getDerived().TransformDeclarationNameInfo(MapperIdInfo);
10347 if (!MapperIdInfo.getName())
10348 return true;
10349 }
10350 // Build a list of all candidate OMPDeclareMapperDecls, which is provided by
10351 // the previous user-defined mapper lookup in dependent environment.
10352 for (auto *E : C->mapperlists()) {
10353 // Transform all the decls.
10354 if (E) {
10355 auto *ULE = cast<UnresolvedLookupExpr>(E);
10356 UnresolvedSet<8> Decls;
10357 for (auto *D : ULE->decls()) {
10358 NamedDecl *InstD =
10359 cast<NamedDecl>(TT.getDerived().TransformDecl(E->getExprLoc(), D));
10360 Decls.addDecl(InstD, InstD->getAccess());
10361 }
10362 UnresolvedMappers.push_back(UnresolvedLookupExpr::Create(
10363 TT.getSema().Context, /*NamingClass=*/nullptr,
10364 MapperIdScopeSpec.getWithLocInContext(TT.getSema().Context),
10365 MapperIdInfo, /*ADL=*/true, ULE->isOverloaded(), Decls.begin(),
10366 Decls.end()));
10367 } else {
10368 UnresolvedMappers.push_back(nullptr);
10369 }
10370 }
10371 return false;
10372}
10373
10374template <typename Derived>
10375OMPClause *TreeTransform<Derived>::TransformOMPMapClause(OMPMapClause *C) {
10376 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10377 llvm::SmallVector<Expr *, 16> Vars;
10378 Expr *IteratorModifier = C->getIteratorModifier();
10379 if (IteratorModifier) {
10380 ExprResult MapModRes = getDerived().TransformExpr(IteratorModifier);
10381 if (MapModRes.isInvalid())
10382 return nullptr;
10383 IteratorModifier = MapModRes.get();
10384 }
10385 CXXScopeSpec MapperIdScopeSpec;
10386 DeclarationNameInfo MapperIdInfo;
10387 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10388 if (transformOMPMappableExprListClause<Derived, OMPMapClause>(
10389 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10390 return nullptr;
10391 return getDerived().RebuildOMPMapClause(
10392 IteratorModifier, C->getMapTypeModifiers(), C->getMapTypeModifiersLoc(),
10393 MapperIdScopeSpec, MapperIdInfo, C->getMapType(), C->isImplicitMapType(),
10394 C->getMapLoc(), C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10395}
10396
10397template <typename Derived>
10398OMPClause *
10399TreeTransform<Derived>::TransformOMPAllocateClause(OMPAllocateClause *C) {
10400 Expr *Allocator = C->getAllocator();
10401 if (Allocator) {
10402 ExprResult AllocatorRes = getDerived().TransformExpr(Allocator);
10403 if (AllocatorRes.isInvalid())
10404 return nullptr;
10405 Allocator = AllocatorRes.get();
10406 }
10407 llvm::SmallVector<Expr *, 16> Vars;
10408 Vars.reserve(C->varlist_size());
10409 for (auto *VE : C->varlists()) {
10410 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10411 if (EVar.isInvalid())
10412 return nullptr;
10413 Vars.push_back(EVar.get());
10414 }
10415 return getDerived().RebuildOMPAllocateClause(
10416 Allocator, Vars, C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(),
10417 C->getEndLoc());
10418}
10419
10420template <typename Derived>
10421OMPClause *
10422TreeTransform<Derived>::TransformOMPNumTeamsClause(OMPNumTeamsClause *C) {
10423 ExprResult E = getDerived().TransformExpr(C->getNumTeams());
10424 if (E.isInvalid())
10425 return nullptr;
10426 return getDerived().RebuildOMPNumTeamsClause(
10427 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10428}
10429
10430template <typename Derived>
10431OMPClause *
10432TreeTransform<Derived>::TransformOMPThreadLimitClause(OMPThreadLimitClause *C) {
10433 ExprResult E = getDerived().TransformExpr(C->getThreadLimit());
10434 if (E.isInvalid())
10435 return nullptr;
10436 return getDerived().RebuildOMPThreadLimitClause(
10437 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10438}
10439
10440template <typename Derived>
10441OMPClause *
10442TreeTransform<Derived>::TransformOMPPriorityClause(OMPPriorityClause *C) {
10443 ExprResult E = getDerived().TransformExpr(C->getPriority());
10444 if (E.isInvalid())
10445 return nullptr;
10446 return getDerived().RebuildOMPPriorityClause(
10447 E.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10448}
10449
10450template <typename Derived>
10451OMPClause *
10452TreeTransform<Derived>::TransformOMPGrainsizeClause(OMPGrainsizeClause *C) {
10453 ExprResult E = getDerived().TransformExpr(C->getGrainsize());
10454 if (E.isInvalid())
10455 return nullptr;
10456 return getDerived().RebuildOMPGrainsizeClause(
10457 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10458 C->getModifierLoc(), C->getEndLoc());
10459}
10460
10461template <typename Derived>
10462OMPClause *
10463TreeTransform<Derived>::TransformOMPNumTasksClause(OMPNumTasksClause *C) {
10464 ExprResult E = getDerived().TransformExpr(C->getNumTasks());
10465 if (E.isInvalid())
10466 return nullptr;
10467 return getDerived().RebuildOMPNumTasksClause(
10468 C->getModifier(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10469 C->getModifierLoc(), C->getEndLoc());
10470}
10471
10472template <typename Derived>
10473OMPClause *TreeTransform<Derived>::TransformOMPHintClause(OMPHintClause *C) {
10474 ExprResult E = getDerived().TransformExpr(C->getHint());
10475 if (E.isInvalid())
10476 return nullptr;
10477 return getDerived().RebuildOMPHintClause(E.get(), C->getBeginLoc(),
10478 C->getLParenLoc(), C->getEndLoc());
10479}
10480
10481template <typename Derived>
10482OMPClause *TreeTransform<Derived>::TransformOMPDistScheduleClause(
10483 OMPDistScheduleClause *C) {
10484 ExprResult E = getDerived().TransformExpr(C->getChunkSize());
10485 if (E.isInvalid())
10486 return nullptr;
10487 return getDerived().RebuildOMPDistScheduleClause(
10488 C->getDistScheduleKind(), E.get(), C->getBeginLoc(), C->getLParenLoc(),
10489 C->getDistScheduleKindLoc(), C->getCommaLoc(), C->getEndLoc());
10490}
10491
10492template <typename Derived>
10493OMPClause *
10494TreeTransform<Derived>::TransformOMPDefaultmapClause(OMPDefaultmapClause *C) {
10495 // Rebuild Defaultmap Clause since we need to invoke the checking of
10496 // defaultmap(none:variable-category) after template initialization.
10497 return getDerived().RebuildOMPDefaultmapClause(C->getDefaultmapModifier(),
10498 C->getDefaultmapKind(),
10499 C->getBeginLoc(),
10500 C->getLParenLoc(),
10501 C->getDefaultmapModifierLoc(),
10502 C->getDefaultmapKindLoc(),
10503 C->getEndLoc());
10504}
10505
10506template <typename Derived>
10507OMPClause *TreeTransform<Derived>::TransformOMPToClause(OMPToClause *C) {
10508 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10509 llvm::SmallVector<Expr *, 16> Vars;
10510 CXXScopeSpec MapperIdScopeSpec;
10511 DeclarationNameInfo MapperIdInfo;
10512 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10513 if (transformOMPMappableExprListClause<Derived, OMPToClause>(
10514 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10515 return nullptr;
10516 return getDerived().RebuildOMPToClause(
10517 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10518 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10519}
10520
10521template <typename Derived>
10522OMPClause *TreeTransform<Derived>::TransformOMPFromClause(OMPFromClause *C) {
10523 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10524 llvm::SmallVector<Expr *, 16> Vars;
10525 CXXScopeSpec MapperIdScopeSpec;
10526 DeclarationNameInfo MapperIdInfo;
10527 llvm::SmallVector<Expr *, 16> UnresolvedMappers;
10528 if (transformOMPMappableExprListClause<Derived, OMPFromClause>(
10529 *this, C, Vars, MapperIdScopeSpec, MapperIdInfo, UnresolvedMappers))
10530 return nullptr;
10531 return getDerived().RebuildOMPFromClause(
10532 C->getMotionModifiers(), C->getMotionModifiersLoc(), MapperIdScopeSpec,
10533 MapperIdInfo, C->getColonLoc(), Vars, Locs, UnresolvedMappers);
10534}
10535
10536template <typename Derived>
10537OMPClause *TreeTransform<Derived>::TransformOMPUseDevicePtrClause(
10538 OMPUseDevicePtrClause *C) {
10539 llvm::SmallVector<Expr *, 16> Vars;
10540 Vars.reserve(C->varlist_size());
10541 for (auto *VE : C->varlists()) {
10542 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10543 if (EVar.isInvalid())
10544 return nullptr;
10545 Vars.push_back(EVar.get());
10546 }
10547 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10548 return getDerived().RebuildOMPUseDevicePtrClause(Vars, Locs);
10549}
10550
10551template <typename Derived>
10552OMPClause *TreeTransform<Derived>::TransformOMPUseDeviceAddrClause(
10553 OMPUseDeviceAddrClause *C) {
10554 llvm::SmallVector<Expr *, 16> Vars;
10555 Vars.reserve(C->varlist_size());
10556 for (auto *VE : C->varlists()) {
10557 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10558 if (EVar.isInvalid())
10559 return nullptr;
10560 Vars.push_back(EVar.get());
10561 }
10562 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10563 return getDerived().RebuildOMPUseDeviceAddrClause(Vars, Locs);
10564}
10565
10566template <typename Derived>
10567OMPClause *
10568TreeTransform<Derived>::TransformOMPIsDevicePtrClause(OMPIsDevicePtrClause *C) {
10569 llvm::SmallVector<Expr *, 16> Vars;
10570 Vars.reserve(C->varlist_size());
10571 for (auto *VE : C->varlists()) {
10572 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10573 if (EVar.isInvalid())
10574 return nullptr;
10575 Vars.push_back(EVar.get());
10576 }
10577 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10578 return getDerived().RebuildOMPIsDevicePtrClause(Vars, Locs);
10579}
10580
10581template <typename Derived>
10582OMPClause *TreeTransform<Derived>::TransformOMPHasDeviceAddrClause(
10583 OMPHasDeviceAddrClause *C) {
10584 llvm::SmallVector<Expr *, 16> Vars;
10585 Vars.reserve(C->varlist_size());
10586 for (auto *VE : C->varlists()) {
10587 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10588 if (EVar.isInvalid())
10589 return nullptr;
10590 Vars.push_back(EVar.get());
10591 }
10592 OMPVarListLocTy Locs(C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10593 return getDerived().RebuildOMPHasDeviceAddrClause(Vars, Locs);
10594}
10595
10596template <typename Derived>
10597OMPClause *
10598TreeTransform<Derived>::TransformOMPNontemporalClause(OMPNontemporalClause *C) {
10599 llvm::SmallVector<Expr *, 16> Vars;
10600 Vars.reserve(C->varlist_size());
10601 for (auto *VE : C->varlists()) {
10602 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10603 if (EVar.isInvalid())
10604 return nullptr;
10605 Vars.push_back(EVar.get());
10606 }
10607 return getDerived().RebuildOMPNontemporalClause(
10608 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10609}
10610
10611template <typename Derived>
10612OMPClause *
10613TreeTransform<Derived>::TransformOMPInclusiveClause(OMPInclusiveClause *C) {
10614 llvm::SmallVector<Expr *, 16> Vars;
10615 Vars.reserve(C->varlist_size());
10616 for (auto *VE : C->varlists()) {
10617 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10618 if (EVar.isInvalid())
10619 return nullptr;
10620 Vars.push_back(EVar.get());
10621 }
10622 return getDerived().RebuildOMPInclusiveClause(
10623 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10624}
10625
10626template <typename Derived>
10627OMPClause *
10628TreeTransform<Derived>::TransformOMPExclusiveClause(OMPExclusiveClause *C) {
10629 llvm::SmallVector<Expr *, 16> Vars;
10630 Vars.reserve(C->varlist_size());
10631 for (auto *VE : C->varlists()) {
10632 ExprResult EVar = getDerived().TransformExpr(cast<Expr>(VE));
10633 if (EVar.isInvalid())
10634 return nullptr;
10635 Vars.push_back(EVar.get());
10636 }
10637 return getDerived().RebuildOMPExclusiveClause(
10638 Vars, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10639}
10640
10641template <typename Derived>
10642OMPClause *TreeTransform<Derived>::TransformOMPUsesAllocatorsClause(
10643 OMPUsesAllocatorsClause *C) {
10644 SmallVector<Sema::UsesAllocatorsData, 16> Data;
10645 Data.reserve(C->getNumberOfAllocators());
10646 for (unsigned I = 0, E = C->getNumberOfAllocators(); I < E; ++I) {
10647 OMPUsesAllocatorsClause::Data D = C->getAllocatorData(I);
10648 ExprResult Allocator = getDerived().TransformExpr(D.Allocator);
10649 if (Allocator.isInvalid())
10650 continue;
10651 ExprResult AllocatorTraits;
10652 if (Expr *AT = D.AllocatorTraits) {
10653 AllocatorTraits = getDerived().TransformExpr(AT);
10654 if (AllocatorTraits.isInvalid())
10655 continue;
10656 }
10657 Sema::UsesAllocatorsData &NewD = Data.emplace_back();
10658 NewD.Allocator = Allocator.get();
10659 NewD.AllocatorTraits = AllocatorTraits.get();
10660 NewD.LParenLoc = D.LParenLoc;
10661 NewD.RParenLoc = D.RParenLoc;
10662 }
10663 return getDerived().RebuildOMPUsesAllocatorsClause(
10664 Data, C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10665}
10666
10667template <typename Derived>
10668OMPClause *
10669TreeTransform<Derived>::TransformOMPAffinityClause(OMPAffinityClause *C) {
10670 SmallVector<Expr *, 4> Locators;
10671 Locators.reserve(C->varlist_size());
10672 ExprResult ModifierRes;
10673 if (Expr *Modifier = C->getModifier()) {
10674 ModifierRes = getDerived().TransformExpr(Modifier);
10675 if (ModifierRes.isInvalid())
10676 return nullptr;
10677 }
10678 for (Expr *E : C->varlists()) {
10679 ExprResult Locator = getDerived().TransformExpr(E);
10680 if (Locator.isInvalid())
10681 continue;
10682 Locators.push_back(Locator.get());
10683 }
10684 return getDerived().RebuildOMPAffinityClause(
10685 C->getBeginLoc(), C->getLParenLoc(), C->getColonLoc(), C->getEndLoc(),
10686 ModifierRes.get(), Locators);
10687}
10688
10689template <typename Derived>
10690OMPClause *TreeTransform<Derived>::TransformOMPOrderClause(OMPOrderClause *C) {
10691 return getDerived().RebuildOMPOrderClause(
10692 C->getKind(), C->getKindKwLoc(), C->getBeginLoc(), C->getLParenLoc(),
10693 C->getEndLoc(), C->getModifier(), C->getModifierKwLoc());
10694}
10695
10696template <typename Derived>
10697OMPClause *TreeTransform<Derived>::TransformOMPBindClause(OMPBindClause *C) {
10698 return getDerived().RebuildOMPBindClause(
10699 C->getBindKind(), C->getBindKindLoc(), C->getBeginLoc(),
10700 C->getLParenLoc(), C->getEndLoc());
10701}
10702
10703template <typename Derived>
10704OMPClause *TreeTransform<Derived>::TransformOMPXDynCGroupMemClause(
10705 OMPXDynCGroupMemClause *C) {
10706 ExprResult Size = getDerived().TransformExpr(C->getSize());
10707 if (Size.isInvalid())
10708 return nullptr;
10709 return getDerived().RebuildOMPXDynCGroupMemClause(
10710 Size.get(), C->getBeginLoc(), C->getLParenLoc(), C->getEndLoc());
10711}
10712
10713//===----------------------------------------------------------------------===//
10714// Expression transformation
10715//===----------------------------------------------------------------------===//
10716template<typename Derived>
10717ExprResult
10718TreeTransform<Derived>::TransformConstantExpr(ConstantExpr *E) {
10719 return TransformExpr(E->getSubExpr());
10720}
10721
10722template <typename Derived>
10723ExprResult TreeTransform<Derived>::TransformSYCLUniqueStableNameExpr(
10724 SYCLUniqueStableNameExpr *E) {
10725 if (!E->isTypeDependent())
10726 return E;
10727
10728 TypeSourceInfo *NewT = getDerived().TransformType(E->getTypeSourceInfo());
10729
10730 if (!NewT)
10731 return ExprError();
10732
10733 if (!getDerived().AlwaysRebuild() && E->getTypeSourceInfo() == NewT)
10734 return E;
10735
10736 return getDerived().RebuildSYCLUniqueStableNameExpr(
10737 E->getLocation(), E->getLParenLocation(), E->getRParenLocation(), NewT);
10738}
10739
10740template<typename Derived>
10741ExprResult
10742TreeTransform<Derived>::TransformPredefinedExpr(PredefinedExpr *E) {
10743 if (!E->isTypeDependent())
10744 return E;
10745
10746 return getDerived().RebuildPredefinedExpr(E->getLocation(),
10747 E->getIdentKind());
10748}
10749
10750template<typename Derived>
10751ExprResult
10752TreeTransform<Derived>::TransformDeclRefExpr(DeclRefExpr *E) {
10753 NestedNameSpecifierLoc QualifierLoc;
10754 if (E->getQualifierLoc()) {
10755 QualifierLoc
10756 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
10757 if (!QualifierLoc)
10758 return ExprError();
10759 }
10760
10761 ValueDecl *ND
10762 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getLocation(),
10763 E->getDecl()));
10764 if (!ND)
10765 return ExprError();
10766
10767 NamedDecl *Found = ND;
10768 if (E->getFoundDecl() != E->getDecl()) {
10769 Found = cast_or_null<NamedDecl>(
10770 getDerived().TransformDecl(E->getLocation(), E->getFoundDecl()));
10771 if (!Found)
10772 return ExprError();
10773 }
10774
10775 DeclarationNameInfo NameInfo = E->getNameInfo();
10776 if (NameInfo.getName()) {
10777 NameInfo = getDerived().TransformDeclarationNameInfo(NameInfo);
10778 if (!NameInfo.getName())
10779 return ExprError();
10780 }
10781
10782 if (!getDerived().AlwaysRebuild() &&
10783 QualifierLoc == E->getQualifierLoc() &&
10784 ND == E->getDecl() &&
10785 Found == E->getFoundDecl() &&
10786 NameInfo.getName() == E->getDecl()->getDeclName() &&
10787 !E->hasExplicitTemplateArgs()) {
10788
10789 // Mark it referenced in the new context regardless.
10790 // FIXME: this is a bit instantiation-specific.
10791 SemaRef.MarkDeclRefReferenced(E);
10792
10793 return E;
10794 }
10795
10796 TemplateArgumentListInfo TransArgs, *TemplateArgs = nullptr;
10797 if (E->hasExplicitTemplateArgs()) {
10798 TemplateArgs = &TransArgs;
10799 TransArgs.setLAngleLoc(E->getLAngleLoc());
10800 TransArgs.setRAngleLoc(E->getRAngleLoc());
10801 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
10802 E->getNumTemplateArgs(),
10803 TransArgs))
10804 return ExprError();
10805 }
10806
10807 return getDerived().RebuildDeclRefExpr(QualifierLoc, ND, NameInfo,
10808 Found, TemplateArgs);
10809}
10810
10811template<typename Derived>
10812ExprResult
10813TreeTransform<Derived>::TransformIntegerLiteral(IntegerLiteral *E) {
10814 return E;
10815}
10816
10817template <typename Derived>
10818ExprResult TreeTransform<Derived>::TransformFixedPointLiteral(
10819 FixedPointLiteral *E) {
10820 return E;
10821}
10822
10823template<typename Derived>
10824ExprResult
10825TreeTransform<Derived>::TransformFloatingLiteral(FloatingLiteral *E) {
10826 return E;
10827}
10828
10829template<typename Derived>
10830ExprResult
10831TreeTransform<Derived>::TransformImaginaryLiteral(ImaginaryLiteral *E) {
10832 return E;
10833}
10834
10835template<typename Derived>
10836ExprResult
10837TreeTransform<Derived>::TransformStringLiteral(StringLiteral *E) {
10838 return E;
10839}
10840
10841template<typename Derived>
10842ExprResult
10843TreeTransform<Derived>::TransformCharacterLiteral(CharacterLiteral *E) {
10844 return E;
10845}
10846
10847template<typename Derived>
10848ExprResult
10849TreeTransform<Derived>::TransformUserDefinedLiteral(UserDefinedLiteral *E) {
10850 return getDerived().TransformCallExpr(E);
10851}
10852
10853template<typename Derived>
10854ExprResult
10855TreeTransform<Derived>::TransformGenericSelectionExpr(GenericSelectionExpr *E) {
10856 ExprResult ControllingExpr =
10857 getDerived().TransformExpr(E->getControllingExpr());
10858 if (ControllingExpr.isInvalid())
10859 return ExprError();
10860
10861 SmallVector<Expr *, 4> AssocExprs;
10862 SmallVector<TypeSourceInfo *, 4> AssocTypes;
10863 for (const GenericSelectionExpr::Association Assoc : E->associations()) {
10864 TypeSourceInfo *TSI = Assoc.getTypeSourceInfo();
10865 if (TSI) {
10866 TypeSourceInfo *AssocType = getDerived().TransformType(TSI);
10867 if (!AssocType)
10868 return ExprError();
10869 AssocTypes.push_back(AssocType);
10870 } else {
10871 AssocTypes.push_back(nullptr);
10872 }
10873
10874 ExprResult AssocExpr =
10875 getDerived().TransformExpr(Assoc.getAssociationExpr());
10876 if (AssocExpr.isInvalid())
10877 return ExprError();
10878 AssocExprs.push_back(AssocExpr.get());
10879 }
10880
10881 return getDerived().RebuildGenericSelectionExpr(E->getGenericLoc(),
10882 E->getDefaultLoc(),
10883 E->getRParenLoc(),
10884 ControllingExpr.get(),
10885 AssocTypes,
10886 AssocExprs);
10887}
10888
10889template<typename Derived>
10890ExprResult
10891TreeTransform<Derived>::TransformParenExpr(ParenExpr *E) {
10892 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
10893 if (SubExpr.isInvalid())
10894 return ExprError();
10895
10896 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10897 return E;
10898
10899 return getDerived().RebuildParenExpr(SubExpr.get(), E->getLParen(),
10900 E->getRParen());
10901}
10902
10903/// The operand of a unary address-of operator has special rules: it's
10904/// allowed to refer to a non-static member of a class even if there's no 'this'
10905/// object available.
10906template<typename Derived>
10907ExprResult
10908TreeTransform<Derived>::TransformAddressOfOperand(Expr *E) {
10909 if (DependentScopeDeclRefExpr *DRE = dyn_cast<DependentScopeDeclRefExpr>(E))
10910 return getDerived().TransformDependentScopeDeclRefExpr(DRE, true, nullptr);
10911 else
10912 return getDerived().TransformExpr(E);
10913}
10914
10915template<typename Derived>
10916ExprResult
10917TreeTransform<Derived>::TransformUnaryOperator(UnaryOperator *E) {
10918 ExprResult SubExpr;
10919 if (E->getOpcode() == UO_AddrOf)
10920 SubExpr = TransformAddressOfOperand(E->getSubExpr());
10921 else
10922 SubExpr = TransformExpr(E->getSubExpr());
10923 if (SubExpr.isInvalid())
10924 return ExprError();
10925
10926 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getSubExpr())
10927 return E;
10928
10929 return getDerived().RebuildUnaryOperator(E->getOperatorLoc(),
10930 E->getOpcode(),
10931 SubExpr.get());
10932}
10933
10934template<typename Derived>
10935ExprResult
10936TreeTransform<Derived>::TransformOffsetOfExpr(OffsetOfExpr *E) {
10937 // Transform the type.
10938 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
10939 if (!Type)
10940 return ExprError();
10941
10942 // Transform all of the components into components similar to what the
10943 // parser uses.
10944 // FIXME: It would be slightly more efficient in the non-dependent case to
10945 // just map FieldDecls, rather than requiring the rebuilder to look for
10946 // the fields again. However, __builtin_offsetof is rare enough in
10947 // template code that we don't care.
10948 bool ExprChanged = false;
10949 typedef Sema::OffsetOfComponent Component;
10950 SmallVector<Component, 4> Components;
10951 for (unsigned I = 0, N = E->getNumComponents(); I != N; ++I) {
10952 const OffsetOfNode &ON = E->getComponent(I);
10953 Component Comp;
10954 Comp.isBrackets = true;
10955 Comp.LocStart = ON.getSourceRange().getBegin();
10956 Comp.LocEnd = ON.getSourceRange().getEnd();
10957 switch (ON.getKind()) {
10958 case OffsetOfNode::Array: {
10959 Expr *FromIndex = E->getIndexExpr(ON.getArrayExprIndex());
10960 ExprResult Index = getDerived().TransformExpr(FromIndex);
10961 if (Index.isInvalid())
10962 return ExprError();
10963
10964 ExprChanged = ExprChanged || Index.get() != FromIndex;
10965 Comp.isBrackets = true;
10966 Comp.U.E = Index.get();
10967 break;
10968 }
10969
10970 case OffsetOfNode::Field:
10971 case OffsetOfNode::Identifier:
10972 Comp.isBrackets = false;
10973 Comp.U.IdentInfo = ON.getFieldName();
10974 if (!Comp.U.IdentInfo)
10975 continue;
10976
10977 break;
10978
10979 case OffsetOfNode::Base:
10980 // Will be recomputed during the rebuild.
10981 continue;
10982 }
10983
10984 Components.push_back(Comp);
10985 }
10986
10987 // If nothing changed, retain the existing expression.
10988 if (!getDerived().AlwaysRebuild() &&
10989 Type == E->getTypeSourceInfo() &&
10990 !ExprChanged)
10991 return E;
10992
10993 // Build a new offsetof expression.
10994 return getDerived().RebuildOffsetOfExpr(E->getOperatorLoc(), Type,
10995 Components, E->getRParenLoc());
10996}
10997
10998template<typename Derived>
10999ExprResult
11000TreeTransform<Derived>::TransformOpaqueValueExpr(OpaqueValueExpr *E) {
11001 assert((!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) &&(static_cast <bool> ((!E->getSourceExpr() || getDerived
().AlreadyTransformed(E->getType())) && "opaque value expression requires transformation"
) ? void (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "clang/lib/Sema/TreeTransform.h", 11002, __extension__ __PRETTY_FUNCTION__
))
11002 "opaque value expression requires transformation")(static_cast <bool> ((!E->getSourceExpr() || getDerived
().AlreadyTransformed(E->getType())) && "opaque value expression requires transformation"
) ? void (0) : __assert_fail ("(!E->getSourceExpr() || getDerived().AlreadyTransformed(E->getType())) && \"opaque value expression requires transformation\""
, "clang/lib/Sema/TreeTransform.h", 11002, __extension__ __PRETTY_FUNCTION__
))
;
11003 return E;
11004}
11005
11006template<typename Derived>
11007ExprResult
11008TreeTransform<Derived>::TransformTypoExpr(TypoExpr *E) {
11009 return E;
11010}
11011
11012template <typename Derived>
11013ExprResult TreeTransform<Derived>::TransformRecoveryExpr(RecoveryExpr *E) {
11014 llvm::SmallVector<Expr *, 8> Children;
11015 bool Changed = false;
11016 for (Expr *C : E->subExpressions()) {
11017 ExprResult NewC = getDerived().TransformExpr(C);
11018 if (NewC.isInvalid())
11019 return ExprError();
11020 Children.push_back(NewC.get());
11021
11022 Changed |= NewC.get() != C;
11023 }
11024 if (!getDerived().AlwaysRebuild() && !Changed)
11025 return E;
11026 return getDerived().RebuildRecoveryExpr(E->getBeginLoc(), E->getEndLoc(),
11027 Children, E->getType());
11028}
11029
11030template<typename Derived>
11031ExprResult
11032TreeTransform<Derived>::TransformPseudoObjectExpr(PseudoObjectExpr *E) {
11033 // Rebuild the syntactic form. The original syntactic form has
11034 // opaque-value expressions in it, so strip those away and rebuild
11035 // the result. This is a really awful way of doing this, but the
11036 // better solution (rebuilding the semantic expressions and
11037 // rebinding OVEs as necessary) doesn't work; we'd need
11038 // TreeTransform to not strip away implicit conversions.
11039 Expr *newSyntacticForm = SemaRef.recreateSyntacticForm(E);
11040 ExprResult result = getDerived().TransformExpr(newSyntacticForm);
11041 if (result.isInvalid()) return ExprError();
11042
11043 // If that gives us a pseudo-object result back, the pseudo-object
11044 // expression must have been an lvalue-to-rvalue conversion which we
11045 // should reapply.
11046 if (result.get()->hasPlaceholderType(BuiltinType::PseudoObject))
11047 result = SemaRef.checkPseudoObjectRValue(result.get());
11048
11049 return result;
11050}
11051
11052template<typename Derived>
11053ExprResult
11054TreeTransform<Derived>::TransformUnaryExprOrTypeTraitExpr(
11055 UnaryExprOrTypeTraitExpr *E) {
11056 if (E->isArgumentType()) {
11057 TypeSourceInfo *OldT = E->getArgumentTypeInfo();
11058
11059 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11060 if (!NewT)
11061 return ExprError();
11062
11063 if (!getDerived().AlwaysRebuild() && OldT == NewT)
11064 return E;
11065
11066 return getDerived().RebuildUnaryExprOrTypeTrait(NewT, E->getOperatorLoc(),
11067 E->getKind(),
11068 E->getSourceRange());
11069 }
11070
11071 // C++0x [expr.sizeof]p1:
11072 // The operand is either an expression, which is an unevaluated operand
11073 // [...]
11074 EnterExpressionEvaluationContext Unevaluated(
11075 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
11076 Sema::ReuseLambdaContextDecl);
11077
11078 // Try to recover if we have something like sizeof(T::X) where X is a type.
11079 // Notably, there must be *exactly* one set of parens if X is a type.
11080 TypeSourceInfo *RecoveryTSI = nullptr;
11081 ExprResult SubExpr;
11082 auto *PE = dyn_cast<ParenExpr>(E->getArgumentExpr());
11083 if (auto *DRE =
11084 PE ? dyn_cast<DependentScopeDeclRefExpr>(PE->getSubExpr()) : nullptr)
11085 SubExpr = getDerived().TransformParenDependentScopeDeclRefExpr(
11086 PE, DRE, false, &RecoveryTSI);
11087 else
11088 SubExpr = getDerived().TransformExpr(E->getArgumentExpr());
11089
11090 if (RecoveryTSI) {
11091 return getDerived().RebuildUnaryExprOrTypeTrait(
11092 RecoveryTSI, E->getOperatorLoc(), E->getKind(), E->getSourceRange());
11093 } else if (SubExpr.isInvalid())
11094 return ExprError();
11095
11096 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getArgumentExpr())
11097 return E;
11098
11099 return getDerived().RebuildUnaryExprOrTypeTrait(SubExpr.get(),
11100 E->getOperatorLoc(),
11101 E->getKind(),
11102 E->getSourceRange());
11103}
11104
11105template<typename Derived>
11106ExprResult
11107TreeTransform<Derived>::TransformArraySubscriptExpr(ArraySubscriptExpr *E) {
11108 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11109 if (LHS.isInvalid())
11110 return ExprError();
11111
11112 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11113 if (RHS.isInvalid())
11114 return ExprError();
11115
11116
11117 if (!getDerived().AlwaysRebuild() &&
11118 LHS.get() == E->getLHS() &&
11119 RHS.get() == E->getRHS())
11120 return E;
11121
11122 return getDerived().RebuildArraySubscriptExpr(
11123 LHS.get(),
11124 /*FIXME:*/ E->getLHS()->getBeginLoc(), RHS.get(), E->getRBracketLoc());
11125}
11126
11127template <typename Derived>
11128ExprResult
11129TreeTransform<Derived>::TransformMatrixSubscriptExpr(MatrixSubscriptExpr *E) {
11130 ExprResult Base = getDerived().TransformExpr(E->getBase());
11131 if (Base.isInvalid())
11132 return ExprError();
11133
11134 ExprResult RowIdx = getDerived().TransformExpr(E->getRowIdx());
11135 if (RowIdx.isInvalid())
11136 return ExprError();
11137
11138 ExprResult ColumnIdx = getDerived().TransformExpr(E->getColumnIdx());
11139 if (ColumnIdx.isInvalid())
11140 return ExprError();
11141
11142 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11143 RowIdx.get() == E->getRowIdx() && ColumnIdx.get() == E->getColumnIdx())
11144 return E;
11145
11146 return getDerived().RebuildMatrixSubscriptExpr(
11147 Base.get(), RowIdx.get(), ColumnIdx.get(), E->getRBracketLoc());
11148}
11149
11150template <typename Derived>
11151ExprResult
11152TreeTransform<Derived>::TransformOMPArraySectionExpr(OMPArraySectionExpr *E) {
11153 ExprResult Base = getDerived().TransformExpr(E->getBase());
11154 if (Base.isInvalid())
11155 return ExprError();
11156
11157 ExprResult LowerBound;
11158 if (E->getLowerBound()) {
11159 LowerBound = getDerived().TransformExpr(E->getLowerBound());
11160 if (LowerBound.isInvalid())
11161 return ExprError();
11162 }
11163
11164 ExprResult Length;
11165 if (E->getLength()) {
11166 Length = getDerived().TransformExpr(E->getLength());
11167 if (Length.isInvalid())
11168 return ExprError();
11169 }
11170
11171 ExprResult Stride;
11172 if (Expr *Str = E->getStride()) {
11173 Stride = getDerived().TransformExpr(Str);
11174 if (Stride.isInvalid())
11175 return ExprError();
11176 }
11177
11178 if (!getDerived().AlwaysRebuild() && Base.get() == E->getBase() &&
11179 LowerBound.get() == E->getLowerBound() && Length.get() == E->getLength())
11180 return E;
11181
11182 return getDerived().RebuildOMPArraySectionExpr(
11183 Base.get(), E->getBase()->getEndLoc(), LowerBound.get(),
11184 E->getColonLocFirst(), E->getColonLocSecond(), Length.get(), Stride.get(),
11185 E->getRBracketLoc());
11186}
11187
11188template <typename Derived>
11189ExprResult
11190TreeTransform<Derived>::TransformOMPArrayShapingExpr(OMPArrayShapingExpr *E) {
11191 ExprResult Base = getDerived().TransformExpr(E->getBase());
11192 if (Base.isInvalid())
11193 return ExprError();
11194
11195 SmallVector<Expr *, 4> Dims;
11196 bool ErrorFound = false;
11197 for (Expr *Dim : E->getDimensions()) {
11198 ExprResult DimRes = getDerived().TransformExpr(Dim);
11199 if (DimRes.isInvalid()) {
11200 ErrorFound = true;
11201 continue;
11202 }
11203 Dims.push_back(DimRes.get());
11204 }
11205
11206 if (ErrorFound)
11207 return ExprError();
11208 return getDerived().RebuildOMPArrayShapingExpr(Base.get(), E->getLParenLoc(),
11209 E->getRParenLoc(), Dims,
11210 E->getBracketsRanges());
11211}
11212
11213template <typename Derived>
11214ExprResult
11215TreeTransform<Derived>::TransformOMPIteratorExpr(OMPIteratorExpr *E) {
11216 unsigned NumIterators = E->numOfIterators();
11217 SmallVector<Sema::OMPIteratorData, 4> Data(NumIterators);
11218
11219 bool ErrorFound = false;
11220 bool NeedToRebuild = getDerived().AlwaysRebuild();
11221 for (unsigned I = 0; I < NumIterators; ++I) {
11222 auto *D = cast<VarDecl>(E->getIteratorDecl(I));
11223 Data[I].DeclIdent = D->getIdentifier();
11224 Data[I].DeclIdentLoc = D->getLocation();
11225 if (D->getLocation() == D->getBeginLoc()) {
11226 assert(SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) &&(static_cast <bool> (SemaRef.Context.hasSameType(D->
getType(), SemaRef.Context.IntTy) && "Implicit type must be int."
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "clang/lib/Sema/TreeTransform.h", 11227, __extension__ __PRETTY_FUNCTION__
))
11227 "Implicit type must be int.")(static_cast <bool> (SemaRef.Context.hasSameType(D->
getType(), SemaRef.Context.IntTy) && "Implicit type must be int."
) ? void (0) : __assert_fail ("SemaRef.Context.hasSameType(D->getType(), SemaRef.Context.IntTy) && \"Implicit type must be int.\""
, "clang/lib/Sema/TreeTransform.h", 11227, __extension__ __PRETTY_FUNCTION__
))
;
11228 } else {
11229 TypeSourceInfo *TSI = getDerived().TransformType(D->getTypeSourceInfo());
11230 QualType DeclTy = getDerived().TransformType(D->getType());
11231 Data[I].Type = SemaRef.CreateParsedType(DeclTy, TSI);
11232 }
11233 OMPIteratorExpr::IteratorRange Range = E->getIteratorRange(I);
11234 ExprResult Begin = getDerived().TransformExpr(Range.Begin);
11235 ExprResult End = getDerived().TransformExpr(Range.End);
11236 ExprResult Step = getDerived().TransformExpr(Range.Step);
11237 ErrorFound = ErrorFound ||
11238 !(!D->getTypeSourceInfo() || (Data[I].Type.getAsOpaquePtr() &&
11239 !Data[I].Type.get().isNull())) ||
11240 Begin.isInvalid() || End.isInvalid() || Step.isInvalid();
11241 if (ErrorFound)
11242 continue;
11243 Data[I].Range.Begin = Begin.get();
11244 Data[I].Range.End = End.get();
11245 Data[I].Range.Step = Step.get();
11246 Data[I].AssignLoc = E->getAssignLoc(I);
11247 Data[I].ColonLoc = E->getColonLoc(I);
11248 Data[I].SecColonLoc = E->getSecondColonLoc(I);
11249 NeedToRebuild =
11250 NeedToRebuild ||
11251 (D->getTypeSourceInfo() && Data[I].Type.get().getTypePtrOrNull() !=
11252 D->getType().getTypePtrOrNull()) ||
11253 Range.Begin != Data[I].Range.Begin || Range.End != Data[I].Range.End ||
11254 Range.Step != Data[I].Range.Step;
11255 }
11256 if (ErrorFound)
11257 return ExprError();
11258 if (!NeedToRebuild)
11259 return E;
11260
11261 ExprResult Res = getDerived().RebuildOMPIteratorExpr(
11262 E->getIteratorKwLoc(), E->getLParenLoc(), E->getRParenLoc(), Data);
11263 if (!Res.isUsable())
11264 return Res;
11265 auto *IE = cast<OMPIteratorExpr>(Res.get());
11266 for (unsigned I = 0; I < NumIterators; ++I)
11267 getDerived().transformedLocalDecl(E->getIteratorDecl(I),
11268 IE->getIteratorDecl(I));
11269 return Res;
11270}
11271
11272template<typename Derived>
11273ExprResult
11274TreeTransform<Derived>::TransformCallExpr(CallExpr *E) {
11275 // Transform the callee.
11276 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11277 if (Callee.isInvalid())
11278 return ExprError();
11279
11280 // Transform arguments.
11281 bool ArgChanged = false;
11282 SmallVector<Expr*, 8> Args;
11283 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
11284 &ArgChanged))
11285 return ExprError();
11286
11287 if (!getDerived().AlwaysRebuild() &&
11288 Callee.get() == E->getCallee() &&
11289 !ArgChanged)
11290 return SemaRef.MaybeBindToTemporary(E);
11291
11292 // FIXME: Wrong source location information for the '('.
11293 SourceLocation FakeLParenLoc
11294 = ((Expr *)Callee.get())->getSourceRange().getBegin();
11295
11296 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11297 if (E->hasStoredFPFeatures()) {
11298 FPOptionsOverride NewOverrides = E->getFPFeatures();
11299 getSema().CurFPFeatures =
11300 NewOverrides.applyOverrides(getSema().getLangOpts());
11301 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11302 }
11303
11304 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
11305 Args,
11306 E->getRParenLoc());
11307}
11308
11309template<typename Derived>
11310ExprResult
11311TreeTransform<Derived>::TransformMemberExpr(MemberExpr *E) {
11312 ExprResult Base = getDerived().TransformExpr(E->getBase());
11313 if (Base.isInvalid())
11314 return ExprError();
11315
11316 NestedNameSpecifierLoc QualifierLoc;
11317 if (E->hasQualifier()) {
11318 QualifierLoc
11319 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
11320
11321 if (!QualifierLoc)
11322 return ExprError();
11323 }
11324 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
11325
11326 ValueDecl *Member
11327 = cast_or_null<ValueDecl>(getDerived().TransformDecl(E->getMemberLoc(),
11328 E->getMemberDecl()));
11329 if (!Member)
11330 return ExprError();
11331
11332 NamedDecl *FoundDecl = E->getFoundDecl();
11333 if (FoundDecl == E->getMemberDecl()) {
11334 FoundDecl = Member;
11335 } else {
11336 FoundDecl = cast_or_null<NamedDecl>(
11337 getDerived().TransformDecl(E->getMemberLoc(), FoundDecl));
11338 if (!FoundDecl)
11339 return ExprError();
11340 }
11341
11342 if (!getDerived().AlwaysRebuild() &&
11343 Base.get() == E->getBase() &&
11344 QualifierLoc == E->getQualifierLoc() &&
11345 Member == E->getMemberDecl() &&
11346 FoundDecl == E->getFoundDecl() &&
11347 !E->hasExplicitTemplateArgs()) {
11348
11349 // Skip for member expression of (this->f), rebuilt thisi->f is needed
11350 // for Openmp where the field need to be privatizized in the case.
11351 if (!(isa<CXXThisExpr>(E->getBase()) &&
11352 getSema().isOpenMPRebuildMemberExpr(cast<ValueDecl>(Member)))) {
11353 // Mark it referenced in the new context regardless.
11354 // FIXME: this is a bit instantiation-specific.
11355 SemaRef.MarkMemberReferenced(E);
11356 return E;
11357 }
11358 }
11359
11360 TemplateArgumentListInfo TransArgs;
11361 if (E->hasExplicitTemplateArgs()) {
11362 TransArgs.setLAngleLoc(E->getLAngleLoc());
11363 TransArgs.setRAngleLoc(E->getRAngleLoc());
11364 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
11365 E->getNumTemplateArgs(),
11366 TransArgs))
11367 return ExprError();
11368 }
11369
11370 // FIXME: Bogus source location for the operator
11371 SourceLocation FakeOperatorLoc =
11372 SemaRef.getLocForEndOfToken(E->getBase()->getSourceRange().getEnd());
11373
11374 // FIXME: to do this check properly, we will need to preserve the
11375 // first-qualifier-in-scope here, just in case we had a dependent
11376 // base (and therefore couldn't do the check) and a
11377 // nested-name-qualifier (and therefore could do the lookup).
11378 NamedDecl *FirstQualifierInScope = nullptr;
11379 DeclarationNameInfo MemberNameInfo = E->getMemberNameInfo();
11380 if (MemberNameInfo.getName()) {
11381 MemberNameInfo = getDerived().TransformDeclarationNameInfo(MemberNameInfo);
11382 if (!MemberNameInfo.getName())
11383 return ExprError();
11384 }
11385
11386 return getDerived().RebuildMemberExpr(Base.get(), FakeOperatorLoc,
11387 E->isArrow(),
11388 QualifierLoc,
11389 TemplateKWLoc,
11390 MemberNameInfo,
11391 Member,
11392 FoundDecl,
11393 (E->hasExplicitTemplateArgs()
11394 ? &TransArgs : nullptr),
11395 FirstQualifierInScope);
11396}
11397
11398template<typename Derived>
11399ExprResult
11400TreeTransform<Derived>::TransformBinaryOperator(BinaryOperator *E) {
11401 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11402 if (LHS.isInvalid())
11403 return ExprError();
11404
11405 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11406 if (RHS.isInvalid())
11407 return ExprError();
11408
11409 if (!getDerived().AlwaysRebuild() &&
11410 LHS.get() == E->getLHS() &&
11411 RHS.get() == E->getRHS())
11412 return E;
11413
11414 if (E->isCompoundAssignmentOp())
11415 // FPFeatures has already been established from trailing storage
11416 return getDerived().RebuildBinaryOperator(
11417 E->getOperatorLoc(), E->getOpcode(), LHS.get(), RHS.get());
11418 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11419 FPOptionsOverride NewOverrides(E->getFPFeatures());
11420 getSema().CurFPFeatures =
11421 NewOverrides.applyOverrides(getSema().getLangOpts());
11422 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11423 return getDerived().RebuildBinaryOperator(E->getOperatorLoc(), E->getOpcode(),
11424 LHS.get(), RHS.get());
11425}
11426
11427template <typename Derived>
11428ExprResult TreeTransform<Derived>::TransformCXXRewrittenBinaryOperator(
11429 CXXRewrittenBinaryOperator *E) {
11430 CXXRewrittenBinaryOperator::DecomposedForm Decomp = E->getDecomposedForm();
11431
11432 ExprResult LHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.LHS));
11433 if (LHS.isInvalid())
11434 return ExprError();
11435
11436 ExprResult RHS = getDerived().TransformExpr(const_cast<Expr*>(Decomp.RHS));
11437 if (RHS.isInvalid())
11438 return ExprError();
11439
11440 // Extract the already-resolved callee declarations so that we can restrict
11441 // ourselves to using them as the unqualified lookup results when rebuilding.
11442 UnresolvedSet<2> UnqualLookups;
11443 bool ChangedAnyLookups = false;
11444 Expr *PossibleBinOps[] = {E->getSemanticForm(),
11445 const_cast<Expr *>(Decomp.InnerBinOp)};
11446 for (Expr *PossibleBinOp : PossibleBinOps) {
11447 auto *Op = dyn_cast<CXXOperatorCallExpr>(PossibleBinOp->IgnoreImplicit());
11448 if (!Op)
11449 continue;
11450 auto *Callee = dyn_cast<DeclRefExpr>(Op->getCallee()->IgnoreImplicit());
11451 if (!Callee || isa<CXXMethodDecl>(Callee->getDecl()))
11452 continue;
11453
11454 // Transform the callee in case we built a call to a local extern
11455 // declaration.
11456 NamedDecl *Found = cast_or_null<NamedDecl>(getDerived().TransformDecl(
11457 E->getOperatorLoc(), Callee->getFoundDecl()));
11458 if (!Found)
11459 return ExprError();
11460 if (Found != Callee->getFoundDecl())
11461 ChangedAnyLookups = true;
11462 UnqualLookups.addDecl(Found);
11463 }
11464
11465 if (!getDerived().AlwaysRebuild() && !ChangedAnyLookups &&
11466 LHS.get() == Decomp.LHS && RHS.get() == Decomp.RHS) {
11467 // Mark all functions used in the rewrite as referenced. Note that when
11468 // a < b is rewritten to (a <=> b) < 0, both the <=> and the < might be
11469 // function calls, and/or there might be a user-defined conversion sequence
11470 // applied to the operands of the <.
11471 // FIXME: this is a bit instantiation-specific.
11472 const Expr *StopAt[] = {Decomp.LHS, Decomp.RHS};
11473 SemaRef.MarkDeclarationsReferencedInExpr(E, false, StopAt);
11474 return E;
11475 }
11476
11477 return getDerived().RebuildCXXRewrittenBinaryOperator(
11478 E->getOperatorLoc(), Decomp.Opcode, UnqualLookups, LHS.get(), RHS.get());
11479}
11480
11481template<typename Derived>
11482ExprResult
11483TreeTransform<Derived>::TransformCompoundAssignOperator(
11484 CompoundAssignOperator *E) {
11485 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11486 FPOptionsOverride NewOverrides(E->getFPFeatures());
11487 getSema().CurFPFeatures =
11488 NewOverrides.applyOverrides(getSema().getLangOpts());
11489 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11490 return getDerived().TransformBinaryOperator(E);
11491}
11492
11493template<typename Derived>
11494ExprResult TreeTransform<Derived>::
11495TransformBinaryConditionalOperator(BinaryConditionalOperator *e) {
11496 // Just rebuild the common and RHS expressions and see whether we
11497 // get any changes.
11498
11499 ExprResult commonExpr = getDerived().TransformExpr(e->getCommon());
11500 if (commonExpr.isInvalid())
11501 return ExprError();
11502
11503 ExprResult rhs = getDerived().TransformExpr(e->getFalseExpr());
11504 if (rhs.isInvalid())
11505 return ExprError();
11506
11507 if (!getDerived().AlwaysRebuild() &&
11508 commonExpr.get() == e->getCommon() &&
11509 rhs.get() == e->getFalseExpr())
11510 return e;
11511
11512 return getDerived().RebuildConditionalOperator(commonExpr.get(),
11513 e->getQuestionLoc(),
11514 nullptr,
11515 e->getColonLoc(),
11516 rhs.get());
11517}
11518
11519template<typename Derived>
11520ExprResult
11521TreeTransform<Derived>::TransformConditionalOperator(ConditionalOperator *E) {
11522 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11523 if (Cond.isInvalid())
11524 return ExprError();
11525
11526 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11527 if (LHS.isInvalid())
11528 return ExprError();
11529
11530 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11531 if (RHS.isInvalid())
11532 return ExprError();
11533
11534 if (!getDerived().AlwaysRebuild() &&
11535 Cond.get() == E->getCond() &&
11536 LHS.get() == E->getLHS() &&
11537 RHS.get() == E->getRHS())
11538 return E;
11539
11540 return getDerived().RebuildConditionalOperator(Cond.get(),
11541 E->getQuestionLoc(),
11542 LHS.get(),
11543 E->getColonLoc(),
11544 RHS.get());
11545}
11546
11547template<typename Derived>
11548ExprResult
11549TreeTransform<Derived>::TransformImplicitCastExpr(ImplicitCastExpr *E) {
11550 // Implicit casts are eliminated during transformation, since they
11551 // will be recomputed by semantic analysis after transformation.
11552 return getDerived().TransformExpr(E->getSubExprAsWritten());
11553}
11554
11555template<typename Derived>
11556ExprResult
11557TreeTransform<Derived>::TransformCStyleCastExpr(CStyleCastExpr *E) {
11558 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
11559 if (!Type)
11560 return ExprError();
11561
11562 ExprResult SubExpr
11563 = getDerived().TransformExpr(E->getSubExprAsWritten());
11564 if (SubExpr.isInvalid())
11565 return ExprError();
11566
11567 if (!getDerived().AlwaysRebuild() &&
11568 Type == E->getTypeInfoAsWritten() &&
11569 SubExpr.get() == E->getSubExpr())
11570 return E;
11571
11572 return getDerived().RebuildCStyleCastExpr(E->getLParenLoc(),
11573 Type,
11574 E->getRParenLoc(),
11575 SubExpr.get());
11576}
11577
11578template<typename Derived>
11579ExprResult
11580TreeTransform<Derived>::TransformCompoundLiteralExpr(CompoundLiteralExpr *E) {
11581 TypeSourceInfo *OldT = E->getTypeSourceInfo();
11582 TypeSourceInfo *NewT = getDerived().TransformType(OldT);
11583 if (!NewT)
11584 return ExprError();
11585
11586 ExprResult Init = getDerived().TransformExpr(E->getInitializer());
11587 if (Init.isInvalid())
11588 return ExprError();
11589
11590 if (!getDerived().AlwaysRebuild() &&
11591 OldT == NewT &&
11592 Init.get() == E->getInitializer())
11593 return SemaRef.MaybeBindToTemporary(E);
11594
11595 // Note: the expression type doesn't necessarily match the
11596 // type-as-written, but that's okay, because it should always be
11597 // derivable from the initializer.
11598
11599 return getDerived().RebuildCompoundLiteralExpr(
11600 E->getLParenLoc(), NewT,
11601 /*FIXME:*/ E->getInitializer()->getEndLoc(), Init.get());
11602}
11603
11604template<typename Derived>
11605ExprResult
11606TreeTransform<Derived>::TransformExtVectorElementExpr(ExtVectorElementExpr *E) {
11607 ExprResult Base = getDerived().TransformExpr(E->getBase());
11608 if (Base.isInvalid())
11609 return ExprError();
11610
11611 if (!getDerived().AlwaysRebuild() &&
11612 Base.get() == E->getBase())
11613 return E;
11614
11615 // FIXME: Bad source location
11616 SourceLocation FakeOperatorLoc =
11617 SemaRef.getLocForEndOfToken(E->getBase()->getEndLoc());
11618 return getDerived().RebuildExtVectorElementExpr(
11619 Base.get(), FakeOperatorLoc, E->isArrow(), E->getAccessorLoc(),
11620 E->getAccessor());
11621}
11622
11623template<typename Derived>
11624ExprResult
11625TreeTransform<Derived>::TransformInitListExpr(InitListExpr *E) {
11626 if (InitListExpr *Syntactic = E->getSyntacticForm())
11627 E = Syntactic;
11628
11629 bool InitChanged = false;
11630
11631 EnterExpressionEvaluationContext Context(
11632 getSema(), EnterExpressionEvaluationContext::InitList);
11633
11634 SmallVector<Expr*, 4> Inits;
11635 if (getDerived().TransformExprs(E->getInits(), E->getNumInits(), false,
11636 Inits, &InitChanged))
11637 return ExprError();
11638
11639 if (!getDerived().AlwaysRebuild() && !InitChanged) {
11640 // FIXME: Attempt to reuse the existing syntactic form of the InitListExpr
11641 // in some cases. We can't reuse it in general, because the syntactic and
11642 // semantic forms are linked, and we can't know that semantic form will
11643 // match even if the syntactic form does.
11644 }
11645
11646 return getDerived().RebuildInitList(E->getLBraceLoc(), Inits,
11647 E->getRBraceLoc());
11648}
11649
11650template<typename Derived>
11651ExprResult
11652TreeTransform<Derived>::TransformDesignatedInitExpr(DesignatedInitExpr *E) {
11653 Designation Desig;
11654
11655 // transform the initializer value
11656 ExprResult Init = getDerived().TransformExpr(E->getInit());
11657 if (Init.isInvalid())
11658 return ExprError();
11659
11660 // transform the designators.
11661 SmallVector<Expr*, 4> ArrayExprs;
11662 bool ExprChanged = false;
11663 for (const DesignatedInitExpr::Designator &D : E->designators()) {
11664 if (D.isFieldDesignator()) {
11665 Desig.AddDesignator(Designator::CreateFieldDesignator(
11666 D.getFieldName(), D.getDotLoc(), D.getFieldLoc()));
11667 if (D.getFieldDecl()) {
11668 FieldDecl *Field = cast_or_null<FieldDecl>(
11669 getDerived().TransformDecl(D.getFieldLoc(), D.getFieldDecl()));
11670 if (Field != D.getFieldDecl())
11671 // Rebuild the expression when the transformed FieldDecl is
11672 // different to the already assigned FieldDecl.
11673 ExprChanged = true;
11674 } else {
11675 // Ensure that the designator expression is rebuilt when there isn't
11676 // a resolved FieldDecl in the designator as we don't want to assign
11677 // a FieldDecl to a pattern designator that will be instantiated again.
11678 ExprChanged = true;
11679 }
11680 continue;
11681 }
11682
11683 if (D.isArrayDesignator()) {
11684 ExprResult Index = getDerived().TransformExpr(E->getArrayIndex(D));
11685 if (Index.isInvalid())
11686 return ExprError();
11687
11688 Desig.AddDesignator(
11689 Designator::CreateArrayDesignator(Index.get(), D.getLBracketLoc()));
11690
11691 ExprChanged = ExprChanged || Init.get() != E->getArrayIndex(D);
11692 ArrayExprs.push_back(Index.get());
11693 continue;
11694 }
11695
11696 assert(D.isArrayRangeDesignator() && "New kind of designator?")(static_cast <bool> (D.isArrayRangeDesignator() &&
"New kind of designator?") ? void (0) : __assert_fail ("D.isArrayRangeDesignator() && \"New kind of designator?\""
, "clang/lib/Sema/TreeTransform.h", 11696, __extension__ __PRETTY_FUNCTION__
))
;
11697 ExprResult Start
11698 = getDerived().TransformExpr(E->getArrayRangeStart(D));
11699 if (Start.isInvalid())
11700 return ExprError();
11701
11702 ExprResult End = getDerived().TransformExpr(E->getArrayRangeEnd(D));
11703 if (End.isInvalid())
11704 return ExprError();
11705
11706 Desig.AddDesignator(Designator::CreateArrayRangeDesignator(
11707 Start.get(), End.get(), D.getLBracketLoc(), D.getEllipsisLoc()));
11708
11709 ExprChanged = ExprChanged || Start.get() != E->getArrayRangeStart(D) ||
11710 End.get() != E->getArrayRangeEnd(D);
11711
11712 ArrayExprs.push_back(Start.get());
11713 ArrayExprs.push_back(End.get());
11714 }
11715
11716 if (!getDerived().AlwaysRebuild() &&
11717 Init.get() == E->getInit() &&
11718 !ExprChanged)
11719 return E;
11720
11721 return getDerived().RebuildDesignatedInitExpr(Desig, ArrayExprs,
11722 E->getEqualOrColonLoc(),
11723 E->usesGNUSyntax(), Init.get());
11724}
11725
11726// Seems that if TransformInitListExpr() only works on the syntactic form of an
11727// InitListExpr, then a DesignatedInitUpdateExpr is not encountered.
11728template<typename Derived>
11729ExprResult
11730TreeTransform<Derived>::TransformDesignatedInitUpdateExpr(
11731 DesignatedInitUpdateExpr *E) {
11732 llvm_unreachable("Unexpected DesignatedInitUpdateExpr in syntactic form of "::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11733)
11733 "initializer")::llvm::llvm_unreachable_internal("Unexpected DesignatedInitUpdateExpr in syntactic form of "
"initializer", "clang/lib/Sema/TreeTransform.h", 11733)
;
11734 return ExprError();
11735}
11736
11737template<typename Derived>
11738ExprResult
11739TreeTransform<Derived>::TransformNoInitExpr(
11740 NoInitExpr *E) {
11741 llvm_unreachable("Unexpected NoInitExpr in syntactic form of initializer")::llvm::llvm_unreachable_internal("Unexpected NoInitExpr in syntactic form of initializer"
, "clang/lib/Sema/TreeTransform.h", 11741)
;
11742 return ExprError();
11743}
11744
11745template<typename Derived>
11746ExprResult
11747TreeTransform<Derived>::TransformArrayInitLoopExpr(ArrayInitLoopExpr *E) {
11748 llvm_unreachable("Unexpected ArrayInitLoopExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitLoopExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11748)
;
11749 return ExprError();
11750}
11751
11752template<typename Derived>
11753ExprResult
11754TreeTransform<Derived>::TransformArrayInitIndexExpr(ArrayInitIndexExpr *E) {
11755 llvm_unreachable("Unexpected ArrayInitIndexExpr outside of initializer")::llvm::llvm_unreachable_internal("Unexpected ArrayInitIndexExpr outside of initializer"
, "clang/lib/Sema/TreeTransform.h", 11755)
;
11756 return ExprError();
11757}
11758
11759template<typename Derived>
11760ExprResult
11761TreeTransform<Derived>::TransformImplicitValueInitExpr(
11762 ImplicitValueInitExpr *E) {
11763 TemporaryBase Rebase(*this, E->getBeginLoc(), DeclarationName());
11764
11765 // FIXME: Will we ever have proper type location here? Will we actually
11766 // need to transform the type?
11767 QualType T = getDerived().TransformType(E->getType());
11768 if (T.isNull())
11769 return ExprError();
11770
11771 if (!getDerived().AlwaysRebuild() &&
11772 T == E->getType())
11773 return E;
11774
11775 return getDerived().RebuildImplicitValueInitExpr(T);
11776}
11777
11778template<typename Derived>
11779ExprResult
11780TreeTransform<Derived>::TransformVAArgExpr(VAArgExpr *E) {
11781 TypeSourceInfo *TInfo = getDerived().TransformType(E->getWrittenTypeInfo());
11782 if (!TInfo)
11783 return ExprError();
11784
11785 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
11786 if (SubExpr.isInvalid())
11787 return ExprError();
11788
11789 if (!getDerived().AlwaysRebuild() &&
11790 TInfo == E->getWrittenTypeInfo() &&
11791 SubExpr.get() == E->getSubExpr())
11792 return E;
11793
11794 return getDerived().RebuildVAArgExpr(E->getBuiltinLoc(), SubExpr.get(),
11795 TInfo, E->getRParenLoc());
11796}
11797
11798template<typename Derived>
11799ExprResult
11800TreeTransform<Derived>::TransformParenListExpr(ParenListExpr *E) {
11801 bool ArgumentChanged = false;
11802 SmallVector<Expr*, 4> Inits;
11803 if (TransformExprs(E->getExprs(), E->getNumExprs(), true, Inits,
11804 &ArgumentChanged))
11805 return ExprError();
11806
11807 return getDerived().RebuildParenListExpr(E->getLParenLoc(),
11808 Inits,
11809 E->getRParenLoc());
11810}
11811
11812/// Transform an address-of-label expression.
11813///
11814/// By default, the transformation of an address-of-label expression always
11815/// rebuilds the expression, so that the label identifier can be resolved to
11816/// the corresponding label statement by semantic analysis.
11817template<typename Derived>
11818ExprResult
11819TreeTransform<Derived>::TransformAddrLabelExpr(AddrLabelExpr *E) {
11820 Decl *LD = getDerived().TransformDecl(E->getLabel()->getLocation(),
11821 E->getLabel());
11822 if (!LD)
11823 return ExprError();
11824
11825 return getDerived().RebuildAddrLabelExpr(E->getAmpAmpLoc(), E->getLabelLoc(),
11826 cast<LabelDecl>(LD));
11827}
11828
11829template<typename Derived>
11830ExprResult
11831TreeTransform<Derived>::TransformStmtExpr(StmtExpr *E) {
11832 SemaRef.ActOnStartStmtExpr();
11833 StmtResult SubStmt
11834 = getDerived().TransformCompoundStmt(E->getSubStmt(), true);
11835 if (SubStmt.isInvalid()) {
11836 SemaRef.ActOnStmtExprError();
11837 return ExprError();
11838 }
11839
11840 unsigned OldDepth = E->getTemplateDepth();
11841 unsigned NewDepth = getDerived().TransformTemplateDepth(OldDepth);
11842
11843 if (!getDerived().AlwaysRebuild() && OldDepth == NewDepth &&
11844 SubStmt.get() == E->getSubStmt()) {
11845 // Calling this an 'error' is unintuitive, but it does the right thing.
11846 SemaRef.ActOnStmtExprError();
11847 return SemaRef.MaybeBindToTemporary(E);
11848 }
11849
11850 return getDerived().RebuildStmtExpr(E->getLParenLoc(), SubStmt.get(),
11851 E->getRParenLoc(), NewDepth);
11852}
11853
11854template<typename Derived>
11855ExprResult
11856TreeTransform<Derived>::TransformChooseExpr(ChooseExpr *E) {
11857 ExprResult Cond = getDerived().TransformExpr(E->getCond());
11858 if (Cond.isInvalid())
11859 return ExprError();
11860
11861 ExprResult LHS = getDerived().TransformExpr(E->getLHS());
11862 if (LHS.isInvalid())
11863 return ExprError();
11864
11865 ExprResult RHS = getDerived().TransformExpr(E->getRHS());
11866 if (RHS.isInvalid())
11867 return ExprError();
11868
11869 if (!getDerived().AlwaysRebuild() &&
11870 Cond.get() == E->getCond() &&
11871 LHS.get() == E->getLHS() &&
11872 RHS.get() == E->getRHS())
11873 return E;
11874
11875 return getDerived().RebuildChooseExpr(E->getBuiltinLoc(),
11876 Cond.get(), LHS.get(), RHS.get(),
11877 E->getRParenLoc());
11878}
11879
11880template<typename Derived>
11881ExprResult
11882TreeTransform<Derived>::TransformGNUNullExpr(GNUNullExpr *E) {
11883 return E;
11884}
11885
11886template<typename Derived>
11887ExprResult
11888TreeTransform<Derived>::TransformCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11889 switch (E->getOperator()) {
11890 case OO_New:
11891 case OO_Delete:
11892 case OO_Array_New:
11893 case OO_Array_Delete:
11894 llvm_unreachable("new and delete operators cannot use CXXOperatorCallExpr")::llvm::llvm_unreachable_internal("new and delete operators cannot use CXXOperatorCallExpr"
, "clang/lib/Sema/TreeTransform.h", 11894)
;
11895
11896 case OO_Subscript:
11897 case OO_Call: {
11898 // This is a call to an object's operator().
11899 assert(E->getNumArgs() >= 1 && "Object call is missing arguments")(static_cast <bool> (E->getNumArgs() >= 1 &&
"Object call is missing arguments") ? void (0) : __assert_fail
("E->getNumArgs() >= 1 && \"Object call is missing arguments\""
, "clang/lib/Sema/TreeTransform.h", 11899, __extension__ __PRETTY_FUNCTION__
))
;
11900
11901 // Transform the object itself.
11902 ExprResult Object = getDerived().TransformExpr(E->getArg(0));
11903 if (Object.isInvalid())
11904 return ExprError();
11905
11906 // FIXME: Poor location information
11907 SourceLocation FakeLParenLoc = SemaRef.getLocForEndOfToken(
11908 static_cast<Expr *>(Object.get())->getEndLoc());
11909
11910 // Transform the call arguments.
11911 SmallVector<Expr*, 8> Args;
11912 if (getDerived().TransformExprs(E->getArgs() + 1, E->getNumArgs() - 1, true,
11913 Args))
11914 return ExprError();
11915
11916 if (E->getOperator() == OO_Subscript)
11917 return getDerived().RebuildCxxSubscriptExpr(Object.get(), FakeLParenLoc,
11918 Args, E->getEndLoc());
11919
11920 return getDerived().RebuildCallExpr(Object.get(), FakeLParenLoc, Args,
11921 E->getEndLoc());
11922 }
11923
11924#define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \
11925 case OO_##Name: \
11926 break;
11927
11928#define OVERLOADED_OPERATOR_MULTI(Name,Spelling,Unary,Binary,MemberOnly)
11929#include "clang/Basic/OperatorKinds.def"
11930
11931 case OO_Conditional:
11932 llvm_unreachable("conditional operator is not actually overloadable")::llvm::llvm_unreachable_internal("conditional operator is not actually overloadable"
, "clang/lib/Sema/TreeTransform.h", 11932)
;
11933
11934 case OO_None:
11935 case NUM_OVERLOADED_OPERATORS:
11936 llvm_unreachable("not an overloaded operator?")::llvm::llvm_unreachable_internal("not an overloaded operator?"
, "clang/lib/Sema/TreeTransform.h", 11936)
;
11937 }
11938
11939 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
11940 if (Callee.isInvalid())
11941 return ExprError();
11942
11943 ExprResult First;
11944 if (E->getOperator() == OO_Amp)
11945 First = getDerived().TransformAddressOfOperand(E->getArg(0));
11946 else
11947 First = getDerived().TransformExpr(E->getArg(0));
11948 if (First.isInvalid())
11949 return ExprError();
11950
11951 ExprResult Second;
11952 if (E->getNumArgs() == 2) {
11953 Second = getDerived().TransformExpr(E->getArg(1));
11954 if (Second.isInvalid())
11955 return ExprError();
11956 }
11957
11958 if (!getDerived().AlwaysRebuild() &&
11959 Callee.get() == E->getCallee() &&
11960 First.get() == E->getArg(0) &&
11961 (E->getNumArgs() != 2 || Second.get() == E->getArg(1)))
11962 return SemaRef.MaybeBindToTemporary(E);
11963
11964 Sema::FPFeaturesStateRAII FPFeaturesState(getSema());
11965 FPOptionsOverride NewOverrides(E->getFPFeatures());
11966 getSema().CurFPFeatures =
11967 NewOverrides.applyOverrides(getSema().getLangOpts());
11968 getSema().FpPragmaStack.CurrentValue = NewOverrides;
11969
11970 return getDerived().RebuildCXXOperatorCallExpr(E->getOperator(),
11971 E->getOperatorLoc(),
11972 Callee.get(),
11973 First.get(),
11974 Second.get());
11975}
11976
11977template<typename Derived>
11978ExprResult
11979TreeTransform<Derived>::TransformCXXMemberCallExpr(CXXMemberCallExpr *E) {
11980 return getDerived().TransformCallExpr(E);
11981}
11982
11983template <typename Derived>
11984ExprResult TreeTransform<Derived>::TransformSourceLocExpr(SourceLocExpr *E) {
11985 bool NeedRebuildFunc = E->getIdentKind() == SourceLocExpr::Function &&
11986 getSema().CurContext != E->getParentContext();
11987
11988 if (!getDerived().AlwaysRebuild() && !NeedRebuildFunc)
11989 return E;
11990
11991 return getDerived().RebuildSourceLocExpr(E->getIdentKind(), E->getType(),
11992 E->getBeginLoc(), E->getEndLoc(),
11993 getSema().CurContext);
11994}
11995
11996template<typename Derived>
11997ExprResult
11998TreeTransform<Derived>::TransformCUDAKernelCallExpr(CUDAKernelCallExpr *E) {
11999 // Transform the callee.
12000 ExprResult Callee = getDerived().TransformExpr(E->getCallee());
12001 if (Callee.isInvalid())
12002 return ExprError();
12003
12004 // Transform exec config.
12005 ExprResult EC = getDerived().TransformCallExpr(E->getConfig());
12006 if (EC.isInvalid())
12007 return ExprError();
12008
12009 // Transform arguments.
12010 bool ArgChanged = false;
12011 SmallVector<Expr*, 8> Args;
12012 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
12013 &ArgChanged))
12014 return ExprError();
12015
12016 if (!getDerived().AlwaysRebuild() &&
12017 Callee.get() == E->getCallee() &&
12018 !ArgChanged)
12019 return SemaRef.MaybeBindToTemporary(E);
12020
12021 // FIXME: Wrong source location information for the '('.
12022 SourceLocation FakeLParenLoc
12023 = ((Expr *)Callee.get())->getSourceRange().getBegin();
12024 return getDerived().RebuildCallExpr(Callee.get(), FakeLParenLoc,
12025 Args,
12026 E->getRParenLoc(), EC.get());
12027}
12028
12029template<typename Derived>
12030ExprResult
12031TreeTransform<Derived>::TransformCXXNamedCastExpr(CXXNamedCastExpr *E) {
12032 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeInfoAsWritten());
12033 if (!Type)
12034 return ExprError();
12035
12036 ExprResult SubExpr
12037 = getDerived().TransformExpr(E->getSubExprAsWritten());
12038 if (SubExpr.isInvalid())
12039 return ExprError();
12040
12041 if (!getDerived().AlwaysRebuild() &&
12042 Type == E->getTypeInfoAsWritten() &&
12043 SubExpr.get() == E->getSubExpr())
12044 return E;
12045 return getDerived().RebuildCXXNamedCastExpr(
12046 E->getOperatorLoc(), E->getStmtClass(), E->getAngleBrackets().getBegin(),
12047 Type, E->getAngleBrackets().getEnd(),
12048 // FIXME. this should be '(' location
12049 E->getAngleBrackets().getEnd(), SubExpr.get(), E->getRParenLoc());
12050}
12051
12052template<typename Derived>
12053ExprResult
12054TreeTransform<Derived>::TransformBuiltinBitCastExpr(BuiltinBitCastExpr *BCE) {
12055 TypeSourceInfo *TSI =
12056 getDerived().TransformType(BCE->getTypeInfoAsWritten());
12057 if (!TSI)
12058 return ExprError();
12059
12060 ExprResult Sub = getDerived().TransformExpr(BCE->getSubExpr());
12061 if (Sub.isInvalid())
12062 return ExprError();
12063
12064 return getDerived().RebuildBuiltinBitCastExpr(BCE->getBeginLoc(), TSI,
12065 Sub.get(), BCE->getEndLoc());
12066}
12067
12068template<typename Derived>
12069ExprResult
12070TreeTransform<Derived>::TransformCXXStaticCastExpr(CXXStaticCastExpr *E) {
12071 return getDerived().TransformCXXNamedCastExpr(E);
12072}
12073
12074template<typename Derived>
12075ExprResult
12076TreeTransform<Derived>::TransformCXXDynamicCastExpr(CXXDynamicCastExpr *E) {
12077 return getDerived().TransformCXXNamedCastExpr(E);
12078}
12079
12080template<typename Derived>
12081ExprResult
12082TreeTransform<Derived>::TransformCXXReinterpretCastExpr(
12083 CXXReinterpretCastExpr *E) {
12084 return getDerived().TransformCXXNamedCastExpr(E);
12085}
12086
12087template<typename Derived>
12088ExprResult
12089TreeTransform<Derived>::TransformCXXConstCastExpr(CXXConstCastExpr *E) {
12090 return getDerived().TransformCXXNamedCastExpr(E);
12091}
12092
12093template<typename Derived>
12094ExprResult
12095TreeTransform<Derived>::TransformCXXAddrspaceCastExpr(CXXAddrspaceCastExpr *E) {
12096 return getDerived().TransformCXXNamedCastExpr(E);
12097}
12098
12099template<typename Derived>
12100ExprResult
12101TreeTransform<Derived>::TransformCXXFunctionalCastExpr(
12102 CXXFunctionalCastExpr *E) {
12103 TypeSourceInfo *Type =
12104 getDerived().TransformTypeWithDeducedTST(E->getTypeInfoAsWritten());
12105 if (!Type)
12106 return ExprError();
12107
12108 ExprResult SubExpr
12109 = getDerived().TransformExpr(E->getSubExprAsWritten());
12110 if (SubExpr.isInvalid())
12111 return ExprError();
12112
12113 if (!getDerived().AlwaysRebuild() &&
12114 Type == E->getTypeInfoAsWritten() &&
12115 SubExpr.get() == E->getSubExpr())
12116 return E;
12117
12118 return getDerived().RebuildCXXFunctionalCastExpr(Type,
12119 E->getLParenLoc(),
12120 SubExpr.get(),
12121 E->getRParenLoc(),
12122 E->isListInitialization());
12123}
12124
12125template<typename Derived>
12126ExprResult
12127TreeTransform<Derived>::TransformCXXTypeidExpr(CXXTypeidExpr *E) {
12128 if (E->isTypeOperand()) {
12129 TypeSourceInfo *TInfo
12130 = getDerived().TransformType(E->getTypeOperandSourceInfo());
12131 if (!TInfo)
12132 return ExprError();
12133
12134 if (!getDerived().AlwaysRebuild() &&
12135 TInfo == E->getTypeOperandSourceInfo())
12136 return E;
12137
12138 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12139 TInfo, E->getEndLoc());
12140 }
12141
12142 // Typeid's operand is an unevaluated context, unless it's a polymorphic
12143 // type. We must not unilaterally enter unevaluated context here, as then
12144 // semantic processing can re-transform an already transformed operand.
12145 Expr *Op = E->getExprOperand();
12146 auto EvalCtx = Sema::ExpressionEvaluationContext::Unevaluated;
12147 if (E->isGLValue())
12148 if (auto *RecordT = Op->getType()->getAs<RecordType>())
12149 if (cast<CXXRecordDecl>(RecordT->getDecl())->isPolymorphic())
12150 EvalCtx = SemaRef.ExprEvalContexts.back().Context;
12151
12152 EnterExpressionEvaluationContext Unevaluated(SemaRef, EvalCtx,
12153 Sema::ReuseLambdaContextDecl);
12154
12155 ExprResult SubExpr = getDerived().TransformExpr(Op);
12156 if (SubExpr.isInvalid())
12157 return ExprError();
12158
12159 if (!getDerived().AlwaysRebuild() &&
12160 SubExpr.get() == E->getExprOperand())
12161 return E;
12162
12163 return getDerived().RebuildCXXTypeidExpr(E->getType(), E->getBeginLoc(),
12164 SubExpr.get(), E->getEndLoc());
12165}
12166
12167template<typename Derived>
12168ExprResult
12169TreeTransform<Derived>::TransformCXXUuidofExpr(CXXUuidofExpr *E) {
12170 if (E->isTypeOperand()) {
12171 TypeSourceInfo *TInfo
12172 = getDerived().TransformType(E->getTypeOperandSourceInfo());
12173 if (!TInfo)
12174 return ExprError();
12175
12176 if (!getDerived().AlwaysRebuild() &&
12177 TInfo == E->getTypeOperandSourceInfo())
12178 return E;
12179
12180 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12181 TInfo, E->getEndLoc());
12182 }
12183
12184 EnterExpressionEvaluationContext Unevaluated(
12185 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12186
12187 ExprResult SubExpr = getDerived().TransformExpr(E->getExprOperand());
12188 if (SubExpr.isInvalid())
12189 return ExprError();
12190
12191 if (!getDerived().AlwaysRebuild() &&
12192 SubExpr.get() == E->getExprOperand())
12193 return E;
12194
12195 return getDerived().RebuildCXXUuidofExpr(E->getType(), E->getBeginLoc(),
12196 SubExpr.get(), E->getEndLoc());
12197}
12198
12199template<typename Derived>
12200ExprResult
12201TreeTransform<Derived>::TransformCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) {
12202 return E;
12203}
12204
12205template<typename Derived>
12206ExprResult
12207TreeTransform<Derived>::TransformCXXNullPtrLiteralExpr(
12208 CXXNullPtrLiteralExpr *E) {
12209 return E;
12210}
12211
12212template<typename Derived>
12213ExprResult
12214TreeTransform<Derived>::TransformCXXThisExpr(CXXThisExpr *E) {
12215 QualType T = getSema().getCurrentThisType();
12216
12217 if (!getDerived().AlwaysRebuild() && T == E->getType()) {
12218 // Mark it referenced in the new context regardless.
12219 // FIXME: this is a bit instantiation-specific.
12220 getSema().MarkThisReferenced(E);
12221 return E;
12222 }
12223
12224 return getDerived().RebuildCXXThisExpr(E->getBeginLoc(), T, E->isImplicit());
12225}
12226
12227template<typename Derived>
12228ExprResult
12229TreeTransform<Derived>::TransformCXXThrowExpr(CXXThrowExpr *E) {
12230 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
12231 if (SubExpr.isInvalid())
12232 return ExprError();
12233
12234 if (!getDerived().AlwaysRebuild() &&
12235 SubExpr.get() == E->getSubExpr())
12236 return E;
12237
12238 return getDerived().RebuildCXXThrowExpr(E->getThrowLoc(), SubExpr.get(),
12239 E->isThrownVariableInScope());
12240}
12241
12242template<typename Derived>
12243ExprResult
12244TreeTransform<Derived>::TransformCXXDefaultArgExpr(CXXDefaultArgExpr *E) {
12245 ParmVarDecl *Param = cast_or_null<ParmVarDecl>(
12246 getDerived().TransformDecl(E->getBeginLoc(), E->getParam()));
12247 if (!Param)
12248 return ExprError();
12249
12250 ExprResult InitRes;
12251 if (E->hasRewrittenInit()) {
12252 InitRes = getDerived().TransformExpr(E->getRewrittenExpr());
12253 if (InitRes.isInvalid())
12254 return ExprError();
12255 }
12256
12257 if (!getDerived().AlwaysRebuild() && Param == E->getParam() &&
12258 E->getUsedContext() == SemaRef.CurContext &&
12259 InitRes.get() == E->getRewrittenExpr())
12260 return E;
12261
12262 return getDerived().RebuildCXXDefaultArgExpr(E->getUsedLocation(), Param,
12263 InitRes.get());
12264}
12265
12266template<typename Derived>
12267ExprResult
12268TreeTransform<Derived>::TransformCXXDefaultInitExpr(CXXDefaultInitExpr *E) {
12269 FieldDecl *Field = cast_or_null<FieldDecl>(
12270 getDerived().TransformDecl(E->getBeginLoc(), E->getField()));
12271 if (!Field)
12272 return ExprError();
12273
12274 if (!getDerived().AlwaysRebuild() && Field == E->getField() &&
12275 E->getUsedContext() == SemaRef.CurContext)
12276 return E;
12277
12278 return getDerived().RebuildCXXDefaultInitExpr(E->getExprLoc(), Field);
12279}
12280
12281template<typename Derived>
12282ExprResult
12283TreeTransform<Derived>::TransformCXXScalarValueInitExpr(
12284 CXXScalarValueInitExpr *E) {
12285 TypeSourceInfo *T = getDerived().TransformType(E->getTypeSourceInfo());
12286 if (!T)
12287 return ExprError();
12288
12289 if (!getDerived().AlwaysRebuild() &&
12290 T == E->getTypeSourceInfo())
12291 return E;
12292
12293 return getDerived().RebuildCXXScalarValueInitExpr(T,
12294 /*FIXME:*/T->getTypeLoc().getEndLoc(),
12295 E->getRParenLoc());
12296}
12297
12298template<typename Derived>
12299ExprResult
12300TreeTransform<Derived>::TransformCXXNewExpr(CXXNewExpr *E) {
12301 // Transform the type that we're allocating
12302 TypeSourceInfo *AllocTypeInfo =
12303 getDerived().TransformTypeWithDeducedTST(E->getAllocatedTypeSourceInfo());
12304 if (!AllocTypeInfo)
12305 return ExprError();
12306
12307 // Transform the size of the array we're allocating (if any).
12308 std::optional<Expr *> ArraySize;
12309 if (E->isArray()) {
12310 ExprResult NewArraySize;
12311 if (std::optional<Expr *> OldArraySize = E->getArraySize()) {
12312 NewArraySize = getDerived().TransformExpr(*OldArraySize);
12313 if (NewArraySize.isInvalid())
12314 return ExprError();
12315 }
12316 ArraySize = NewArraySize.get();
12317 }
12318
12319 // Transform the placement arguments (if any).
12320 bool ArgumentChanged = false;
12321 SmallVector<Expr*, 8> PlacementArgs;
12322 if (getDerived().TransformExprs(E->getPlacementArgs(),
12323 E->getNumPlacementArgs(), true,
12324 PlacementArgs, &ArgumentChanged))
12325 return ExprError();
12326
12327 // Transform the initializer (if any).
12328 Expr *OldInit = E->getInitializer();
12329 ExprResult NewInit;
12330 if (OldInit)
12331 NewInit = getDerived().TransformInitializer(OldInit, true);
12332 if (NewInit.isInvalid())
12333 return ExprError();
12334
12335 // Transform new operator and delete operator.
12336 FunctionDecl *OperatorNew = nullptr;
12337 if (E->getOperatorNew()) {
12338 OperatorNew = cast_or_null<FunctionDecl>(
12339 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorNew()));
12340 if (!OperatorNew)
12341 return ExprError();
12342 }
12343
12344 FunctionDecl *OperatorDelete = nullptr;
12345 if (E->getOperatorDelete()) {
12346 OperatorDelete = cast_or_null<FunctionDecl>(
12347 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12348 if (!OperatorDelete)
12349 return ExprError();
12350 }
12351
12352 if (!getDerived().AlwaysRebuild() &&
12353 AllocTypeInfo == E->getAllocatedTypeSourceInfo() &&
12354 ArraySize == E->getArraySize() &&
12355 NewInit.get() == OldInit &&
12356 OperatorNew == E->getOperatorNew() &&
12357 OperatorDelete == E->getOperatorDelete() &&
12358 !ArgumentChanged) {
12359 // Mark any declarations we need as referenced.
12360 // FIXME: instantiation-specific.
12361 if (OperatorNew)
12362 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorNew);
12363 if (OperatorDelete)
12364 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12365
12366 if (E->isArray() && !E->getAllocatedType()->isDependentType()) {
12367 QualType ElementType
12368 = SemaRef.Context.getBaseElementType(E->getAllocatedType());
12369 if (const RecordType *RecordT = ElementType->getAs<RecordType>()) {
12370 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordT->getDecl());
12371 if (CXXDestructorDecl *Destructor = SemaRef.LookupDestructor(Record)) {
12372 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Destructor);
12373 }
12374 }
12375 }
12376
12377 return E;
12378 }
12379
12380 QualType AllocType = AllocTypeInfo->getType();
12381 if (!ArraySize) {
12382 // If no array size was specified, but the new expression was
12383 // instantiated with an array type (e.g., "new T" where T is
12384 // instantiated with "int[4]"), extract the outer bound from the
12385 // array type as our array size. We do this with constant and
12386 // dependently-sized array types.
12387 const ArrayType *ArrayT = SemaRef.Context.getAsArrayType(AllocType);
12388 if (!ArrayT) {
12389 // Do nothing
12390 } else if (const ConstantArrayType *ConsArrayT
12391 = dyn_cast<ConstantArrayType>(ArrayT)) {
12392 ArraySize = IntegerLiteral::Create(SemaRef.Context, ConsArrayT->getSize(),
12393 SemaRef.Context.getSizeType(),
12394 /*FIXME:*/ E->getBeginLoc());
12395 AllocType = ConsArrayT->getElementType();
12396 } else if (const DependentSizedArrayType *DepArrayT
12397 = dyn_cast<DependentSizedArrayType>(ArrayT)) {
12398 if (DepArrayT->getSizeExpr()) {
12399 ArraySize = DepArrayT->getSizeExpr();
12400 AllocType = DepArrayT->getElementType();
12401 }
12402 }
12403 }
12404
12405 return getDerived().RebuildCXXNewExpr(
12406 E->getBeginLoc(), E->isGlobalNew(),
12407 /*FIXME:*/ E->getBeginLoc(), PlacementArgs,
12408 /*FIXME:*/ E->getBeginLoc(), E->getTypeIdParens(), AllocType,
12409 AllocTypeInfo, ArraySize, E->getDirectInitRange(), NewInit.get());
12410}
12411
12412template<typename Derived>
12413ExprResult
12414TreeTransform<Derived>::TransformCXXDeleteExpr(CXXDeleteExpr *E) {
12415 ExprResult Operand = getDerived().TransformExpr(E->getArgument());
12416 if (Operand.isInvalid())
12417 return ExprError();
12418
12419 // Transform the delete operator, if known.
12420 FunctionDecl *OperatorDelete = nullptr;
12421 if (E->getOperatorDelete()) {
12422 OperatorDelete = cast_or_null<FunctionDecl>(
12423 getDerived().TransformDecl(E->getBeginLoc(), E->getOperatorDelete()));
12424 if (!OperatorDelete)
12425 return ExprError();
12426 }
12427
12428 if (!getDerived().AlwaysRebuild() &&
12429 Operand.get() == E->getArgument() &&
12430 OperatorDelete == E->getOperatorDelete()) {
12431 // Mark any declarations we need as referenced.
12432 // FIXME: instantiation-specific.
12433 if (OperatorDelete)
12434 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), OperatorDelete);
12435
12436 if (!E->getArgument()->isTypeDependent()) {
12437 QualType Destroyed = SemaRef.Context.getBaseElementType(
12438 E->getDestroyedType());
12439 if (const RecordType *DestroyedRec = Destroyed->getAs<RecordType>()) {
12440 CXXRecordDecl *Record = cast<CXXRecordDecl>(DestroyedRec->getDecl());
12441 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
12442 SemaRef.LookupDestructor(Record));
12443 }
12444 }
12445
12446 return E;
12447 }
12448
12449 return getDerived().RebuildCXXDeleteExpr(
12450 E->getBeginLoc(), E->isGlobalDelete(), E->isArrayForm(), Operand.get());
12451}
12452
12453template<typename Derived>
12454ExprResult
12455TreeTransform<Derived>::TransformCXXPseudoDestructorExpr(
12456 CXXPseudoDestructorExpr *E) {
12457 ExprResult Base = getDerived().TransformExpr(E->getBase());
12458 if (Base.isInvalid())
12459 return ExprError();
12460
12461 ParsedType ObjectTypePtr;
12462 bool MayBePseudoDestructor = false;
12463 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
12464 E->getOperatorLoc(),
12465 E->isArrow()? tok::arrow : tok::period,
12466 ObjectTypePtr,
12467 MayBePseudoDestructor);
12468 if (Base.isInvalid())
12469 return ExprError();
12470
12471 QualType ObjectType = ObjectTypePtr.get();
12472 NestedNameSpecifierLoc QualifierLoc = E->getQualifierLoc();
12473 if (QualifierLoc) {
12474 QualifierLoc
12475 = getDerived().TransformNestedNameSpecifierLoc(QualifierLoc, ObjectType);
12476 if (!QualifierLoc)
12477 return ExprError();
12478 }
12479 CXXScopeSpec SS;
12480 SS.Adopt(QualifierLoc);
12481
12482 PseudoDestructorTypeStorage Destroyed;
12483 if (E->getDestroyedTypeInfo()) {
12484 TypeSourceInfo *DestroyedTypeInfo
12485 = getDerived().TransformTypeInObjectScope(E->getDestroyedTypeInfo(),
12486 ObjectType, nullptr, SS);
12487 if (!DestroyedTypeInfo)
12488 return ExprError();
12489 Destroyed = DestroyedTypeInfo;
12490 } else if (!ObjectType.isNull() && ObjectType->isDependentType()) {
12491 // We aren't likely to be able to resolve the identifier down to a type
12492 // now anyway, so just retain the identifier.
12493 Destroyed = PseudoDestructorTypeStorage(E->getDestroyedTypeIdentifier(),
12494 E->getDestroyedTypeLoc());
12495 } else {
12496 // Look for a destructor known with the given name.
12497 ParsedType T = SemaRef.getDestructorName(E->getTildeLoc(),
12498 *E->getDestroyedTypeIdentifier(),
12499 E->getDestroyedTypeLoc(),
12500 /*Scope=*/nullptr,
12501 SS, ObjectTypePtr,
12502 false);
12503 if (!T)
12504 return ExprError();
12505
12506 Destroyed
12507 = SemaRef.Context.getTrivialTypeSourceInfo(SemaRef.GetTypeFromParser(T),
12508 E->getDestroyedTypeLoc());
12509 }
12510
12511 TypeSourceInfo *ScopeTypeInfo = nullptr;
12512 if (E->getScopeTypeInfo()) {
12513 CXXScopeSpec EmptySS;
12514 ScopeTypeInfo = getDerived().TransformTypeInObjectScope(
12515 E->getScopeTypeInfo(), ObjectType, nullptr, EmptySS);
12516 if (!ScopeTypeInfo)
12517 return ExprError();
12518 }
12519
12520 return getDerived().RebuildCXXPseudoDestructorExpr(Base.get(),
12521 E->getOperatorLoc(),
12522 E->isArrow(),
12523 SS,
12524 ScopeTypeInfo,
12525 E->getColonColonLoc(),
12526 E->getTildeLoc(),
12527 Destroyed);
12528}
12529
12530template <typename Derived>
12531bool TreeTransform<Derived>::TransformOverloadExprDecls(OverloadExpr *Old,
12532 bool RequiresADL,
12533 LookupResult &R) {
12534 // Transform all the decls.
12535 bool AllEmptyPacks = true;
12536 for (auto *OldD : Old->decls()) {
12537 Decl *InstD = getDerived().TransformDecl(Old->getNameLoc(), OldD);
12538 if (!InstD) {
12539 // Silently ignore these if a UsingShadowDecl instantiated to nothing.
12540 // This can happen because of dependent hiding.
12541 if (isa<UsingShadowDecl>(OldD))
12542 continue;
12543 else {
12544 R.clear();
12545 return true;
12546 }
12547 }
12548
12549 // Expand using pack declarations.
12550 NamedDecl *SingleDecl = cast<NamedDecl>(InstD);
12551 ArrayRef<NamedDecl*> Decls = SingleDecl;
12552 if (auto *UPD = dyn_cast<UsingPackDecl>(InstD))
12553 Decls = UPD->expansions();
12554
12555 // Expand using declarations.
12556 for (auto *D : Decls) {
12557 if (auto *UD = dyn_cast<UsingDecl>(D)) {
12558 for (auto *SD : UD->shadows())
12559 R.addDecl(SD);
12560 } else {
12561 R.addDecl(D);
12562 }
12563 }
12564
12565 AllEmptyPacks &= Decls.empty();
12566 };
12567
12568 // C++ [temp.res]/8.4.2:
12569 // The program is ill-formed, no diagnostic required, if [...] lookup for
12570 // a name in the template definition found a using-declaration, but the
12571 // lookup in the corresponding scope in the instantiation odoes not find
12572 // any declarations because the using-declaration was a pack expansion and
12573 // the corresponding pack is empty
12574 if (AllEmptyPacks && !RequiresADL) {
12575 getSema().Diag(Old->getNameLoc(), diag::err_using_pack_expansion_empty)
12576 << isa<UnresolvedMemberExpr>(Old) << Old->getName();
12577 return true;
12578 }
12579
12580 // Resolve a kind, but don't do any further analysis. If it's
12581 // ambiguous, the callee needs to deal with it.
12582 R.resolveKind();
12583 return false;
12584}
12585
12586template<typename Derived>
12587ExprResult
12588TreeTransform<Derived>::TransformUnresolvedLookupExpr(
12589 UnresolvedLookupExpr *Old) {
12590 LookupResult R(SemaRef, Old->getName(), Old->getNameLoc(),
12591 Sema::LookupOrdinaryName);
12592
12593 // Transform the declaration set.
12594 if (TransformOverloadExprDecls(Old, Old->requiresADL(), R))
12595 return ExprError();
12596
12597 // Rebuild the nested-name qualifier, if present.
12598 CXXScopeSpec SS;
12599 if (Old->getQualifierLoc()) {
12600 NestedNameSpecifierLoc QualifierLoc
12601 = getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
12602 if (!QualifierLoc)
12603 return ExprError();
12604
12605 SS.Adopt(QualifierLoc);
12606 }
12607
12608 if (Old->getNamingClass()) {
12609 CXXRecordDecl *NamingClass
12610 = cast_or_null<CXXRecordDecl>(getDerived().TransformDecl(
12611 Old->getNameLoc(),
12612 Old->getNamingClass()));
12613 if (!NamingClass) {
12614 R.clear();
12615 return ExprError();
12616 }
12617
12618 R.setNamingClass(NamingClass);
12619 }
12620
12621 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
12622
12623 // If we have neither explicit template arguments, nor the template keyword,
12624 // it's a normal declaration name or member reference.
12625 if (!Old->hasExplicitTemplateArgs() && !TemplateKWLoc.isValid()) {
12626 NamedDecl *D = R.getAsSingle<NamedDecl>();
12627 // In a C++11 unevaluated context, an UnresolvedLookupExpr might refer to an
12628 // instance member. In other contexts, BuildPossibleImplicitMemberExpr will
12629 // give a good diagnostic.
12630 if (D && D->isCXXInstanceMember()) {
12631 return SemaRef.BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R,
12632 /*TemplateArgs=*/nullptr,
12633 /*Scope=*/nullptr);
12634 }
12635
12636 return getDerived().RebuildDeclarationNameExpr(SS, R, Old->requiresADL());
12637 }
12638
12639 // If we have template arguments, rebuild them, then rebuild the
12640 // templateid expression.
12641 TemplateArgumentListInfo TransArgs(Old->getLAngleLoc(), Old->getRAngleLoc());
12642 if (Old->hasExplicitTemplateArgs() &&
12643 getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12644 Old->getNumTemplateArgs(),
12645 TransArgs)) {
12646 R.clear();
12647 return ExprError();
12648 }
12649
12650 return getDerived().RebuildTemplateIdExpr(SS, TemplateKWLoc, R,
12651 Old->requiresADL(), &TransArgs);
12652}
12653
12654template<typename Derived>
12655ExprResult
12656TreeTransform<Derived>::TransformTypeTraitExpr(TypeTraitExpr *E) {
12657 bool ArgChanged = false;
12658 SmallVector<TypeSourceInfo *, 4> Args;
12659 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) {
12660 TypeSourceInfo *From = E->getArg(I);
12661 TypeLoc FromTL = From->getTypeLoc();
12662 if (!FromTL.getAs<PackExpansionTypeLoc>()) {
12663 TypeLocBuilder TLB;
12664 TLB.reserve(FromTL.getFullDataSize());
12665 QualType To = getDerived().TransformType(TLB, FromTL);
12666 if (To.isNull())
12667 return ExprError();
12668
12669 if (To == From->getType())
12670 Args.push_back(From);
12671 else {
12672 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12673 ArgChanged = true;
12674 }
12675 continue;
12676 }
12677
12678 ArgChanged = true;
12679
12680 // We have a pack expansion. Instantiate it.
12681 PackExpansionTypeLoc ExpansionTL = FromTL.castAs<PackExpansionTypeLoc>();
12682 TypeLoc PatternTL = ExpansionTL.getPatternLoc();
12683 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
12684 SemaRef.collectUnexpandedParameterPacks(PatternTL, Unexpanded);
12685
12686 // Determine whether the set of unexpanded parameter packs can and should
12687 // be expanded.
12688 bool Expand = true;
12689 bool RetainExpansion = false;
12690 std::optional<unsigned> OrigNumExpansions =
12691 ExpansionTL.getTypePtr()->getNumExpansions();
12692 std::optional<unsigned> NumExpansions = OrigNumExpansions;
12693 if (getDerived().TryExpandParameterPacks(ExpansionTL.getEllipsisLoc(),
12694 PatternTL.getSourceRange(),
12695 Unexpanded,
12696 Expand, RetainExpansion,
12697 NumExpansions))
12698 return ExprError();
12699
12700 if (!Expand) {
12701 // The transform has determined that we should perform a simple
12702 // transformation on the pack expansion, producing another pack
12703 // expansion.
12704 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
12705
12706 TypeLocBuilder TLB;
12707 TLB.reserve(From->getTypeLoc().getFullDataSize());
12708
12709 QualType To = getDerived().TransformType(TLB, PatternTL);
12710 if (To.isNull())
12711 return ExprError();
12712
12713 To = getDerived().RebuildPackExpansionType(To,
12714 PatternTL.getSourceRange(),
12715 ExpansionTL.getEllipsisLoc(),
12716 NumExpansions);
12717 if (To.isNull())
12718 return ExprError();
12719
12720 PackExpansionTypeLoc ToExpansionTL
12721 = TLB.push<PackExpansionTypeLoc>(To);
12722 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12723 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12724 continue;
12725 }
12726
12727 // Expand the pack expansion by substituting for each argument in the
12728 // pack(s).
12729 for (unsigned I = 0; I != *NumExpansions; ++I) {
12730 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(SemaRef, I);
12731 TypeLocBuilder TLB;
12732 TLB.reserve(PatternTL.getFullDataSize());
12733 QualType To = getDerived().TransformType(TLB, PatternTL);
12734 if (To.isNull())
12735 return ExprError();
12736
12737 if (To->containsUnexpandedParameterPack()) {
12738 To = getDerived().RebuildPackExpansionType(To,
12739 PatternTL.getSourceRange(),
12740 ExpansionTL.getEllipsisLoc(),
12741 NumExpansions);
12742 if (To.isNull())
12743 return ExprError();
12744
12745 PackExpansionTypeLoc ToExpansionTL
12746 = TLB.push<PackExpansionTypeLoc>(To);
12747 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12748 }
12749
12750 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12751 }
12752
12753 if (!RetainExpansion)
12754 continue;
12755
12756 // If we're supposed to retain a pack expansion, do so by temporarily
12757 // forgetting the partially-substituted parameter pack.
12758 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
12759
12760 TypeLocBuilder TLB;
12761 TLB.reserve(From->getTypeLoc().getFullDataSize());
12762
12763 QualType To = getDerived().TransformType(TLB, PatternTL);
12764 if (To.isNull())
12765 return ExprError();
12766
12767 To = getDerived().RebuildPackExpansionType(To,
12768 PatternTL.getSourceRange(),
12769 ExpansionTL.getEllipsisLoc(),
12770 NumExpansions);
12771 if (To.isNull())
12772 return ExprError();
12773
12774 PackExpansionTypeLoc ToExpansionTL
12775 = TLB.push<PackExpansionTypeLoc>(To);
12776 ToExpansionTL.setEllipsisLoc(ExpansionTL.getEllipsisLoc());
12777 Args.push_back(TLB.getTypeSourceInfo(SemaRef.Context, To));
12778 }
12779
12780 if (!getDerived().AlwaysRebuild() && !ArgChanged)
12781 return E;
12782
12783 return getDerived().RebuildTypeTrait(E->getTrait(), E->getBeginLoc(), Args,
12784 E->getEndLoc());
12785}
12786
12787template<typename Derived>
12788ExprResult
12789TreeTransform<Derived>::TransformConceptSpecializationExpr(
12790 ConceptSpecializationExpr *E) {
12791 const ASTTemplateArgumentListInfo *Old = E->getTemplateArgsAsWritten();
12792 TemplateArgumentListInfo TransArgs(Old->LAngleLoc, Old->RAngleLoc);
12793 if (getDerived().TransformTemplateArguments(Old->getTemplateArgs(),
12794 Old->NumTemplateArgs, TransArgs))
12795 return ExprError();
12796
12797 return getDerived().RebuildConceptSpecializationExpr(
12798 E->getNestedNameSpecifierLoc(), E->getTemplateKWLoc(),
12799 E->getConceptNameInfo(), E->getFoundDecl(), E->getNamedConcept(),
12800 &TransArgs);
12801}
12802
12803template<typename Derived>
12804ExprResult
12805TreeTransform<Derived>::TransformRequiresExpr(RequiresExpr *E) {
12806 SmallVector<ParmVarDecl*, 4> TransParams;
12807 SmallVector<QualType, 4> TransParamTypes;
12808 Sema::ExtParameterInfoBuilder ExtParamInfos;
12809
12810 // C++2a [expr.prim.req]p2
12811 // Expressions appearing within a requirement-body are unevaluated operands.
12812 EnterExpressionEvaluationContext Ctx(
12813 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated,
12814 Sema::ReuseLambdaContextDecl);
12815
12816 RequiresExprBodyDecl *Body = RequiresExprBodyDecl::Create(
12817 getSema().Context, getSema().CurContext,
12818 E->getBody()->getBeginLoc());
12819
12820 Sema::ContextRAII SavedContext(getSema(), Body, /*NewThisContext*/false);
12821
12822 ExprResult TypeParamResult = getDerived().TransformRequiresTypeParams(
12823 E->getRequiresKWLoc(), E->getRBraceLoc(), E, Body,
12824 E->getLocalParameters(), TransParamTypes, TransParams, ExtParamInfos);
12825
12826 for (ParmVarDecl *Param : TransParams)
12827 if (Param)
12828 Param->setDeclContext(Body);
12829
12830 // On failure to transform, TransformRequiresTypeParams returns an expression
12831 // in the event that the transformation of the type params failed in some way.
12832 // It is expected that this will result in a 'not satisfied' Requires clause
12833 // when instantiating.
12834 if (!TypeParamResult.isUnset())
12835 return TypeParamResult;
12836
12837 SmallVector<concepts::Requirement *, 4> TransReqs;
12838 if (getDerived().TransformRequiresExprRequirements(E->getRequirements(),
12839 TransReqs))
12840 return ExprError();
12841
12842 for (concepts::Requirement *Req : TransReqs) {
12843 if (auto *ER = dyn_cast<concepts::ExprRequirement>(Req)) {
12844 if (ER->getReturnTypeRequirement().isTypeConstraint()) {
12845 ER->getReturnTypeRequirement()
12846 .getTypeConstraintTemplateParameterList()->getParam(0)
12847 ->setDeclContext(Body);
12848 }
12849 }
12850 }
12851
12852 return getDerived().RebuildRequiresExpr(E->getRequiresKWLoc(), Body,
12853 TransParams, TransReqs,
12854 E->getRBraceLoc());
12855}
12856
12857template<typename Derived>
12858bool TreeTransform<Derived>::TransformRequiresExprRequirements(
12859 ArrayRef<concepts::Requirement *> Reqs,
12860 SmallVectorImpl<concepts::Requirement *> &Transformed) {
12861 for (concepts::Requirement *Req : Reqs) {
12862 concepts::Requirement *TransReq = nullptr;
12863 if (auto *TypeReq = dyn_cast<concepts::TypeRequirement>(Req))
12864 TransReq = getDerived().TransformTypeRequirement(TypeReq);
12865 else if (auto *ExprReq = dyn_cast<concepts::ExprRequirement>(Req))
12866 TransReq = getDerived().TransformExprRequirement(ExprReq);
12867 else
12868 TransReq = getDerived().TransformNestedRequirement(
12869 cast<concepts::NestedRequirement>(Req));
12870 if (!TransReq)
12871 return true;
12872 Transformed.push_back(TransReq);
12873 }
12874 return false;
12875}
12876
12877template<typename Derived>
12878concepts::TypeRequirement *
12879TreeTransform<Derived>::TransformTypeRequirement(
12880 concepts::TypeRequirement *Req) {
12881 if (Req->isSubstitutionFailure()) {
12882 if (getDerived().AlwaysRebuild())
12883 return getDerived().RebuildTypeRequirement(
12884 Req->getSubstitutionDiagnostic());
12885 return Req;
12886 }
12887 TypeSourceInfo *TransType = getDerived().TransformType(Req->getType());
12888 if (!TransType)
12889 return nullptr;
12890 return getDerived().RebuildTypeRequirement(TransType);
12891}
12892
12893template<typename Derived>
12894concepts::ExprRequirement *
12895TreeTransform<Derived>::TransformExprRequirement(concepts::ExprRequirement *Req) {
12896 llvm::PointerUnion<Expr *, concepts::Requirement::SubstitutionDiagnostic *> TransExpr;
12897 if (Req->isExprSubstitutionFailure())
12898 TransExpr = Req->getExprSubstitutionDiagnostic();
12899 else {
12900 ExprResult TransExprRes = getDerived().TransformExpr(Req->getExpr());
12901 if (TransExprRes.isUsable() && TransExprRes.get()->hasPlaceholderType())
12902 TransExprRes = SemaRef.CheckPlaceholderExpr(TransExprRes.get());
12903 if (TransExprRes.isInvalid())
12904 return nullptr;
12905 TransExpr = TransExprRes.get();
12906 }
12907
12908 std::optional<concepts::ExprRequirement::ReturnTypeRequirement> TransRetReq;
12909 const auto &RetReq = Req->getReturnTypeRequirement();
12910 if (RetReq.isEmpty())
12911 TransRetReq.emplace();
12912 else if (RetReq.isSubstitutionFailure())
12913 TransRetReq.emplace(RetReq.getSubstitutionDiagnostic());
12914 else if (RetReq.isTypeConstraint()) {
12915 TemplateParameterList *OrigTPL =
12916 RetReq.getTypeConstraintTemplateParameterList();
12917 TemplateParameterList *TPL =
12918 getDerived().TransformTemplateParameterList(OrigTPL);
12919 if (!TPL)
12920 return nullptr;
12921 TransRetReq.emplace(TPL);
12922 }
12923 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/TreeTransform.h", 12923, __extension__ __PRETTY_FUNCTION__
))
;
12924 if (Expr *E = TransExpr.dyn_cast<Expr *>())
12925 return getDerived().RebuildExprRequirement(E, Req->isSimple(),
12926 Req->getNoexceptLoc(),
12927 std::move(*TransRetReq));
12928 return getDerived().RebuildExprRequirement(
12929 TransExpr.get<concepts::Requirement::SubstitutionDiagnostic *>(),
12930 Req->isSimple(), Req->getNoexceptLoc(), std::move(*TransRetReq));
12931}
12932
12933template<typename Derived>
12934concepts::NestedRequirement *
12935TreeTransform<Derived>::TransformNestedRequirement(
12936 concepts::NestedRequirement *Req) {
12937 if (Req->hasInvalidConstraint()) {
12938 if (getDerived().AlwaysRebuild())
12939 return getDerived().RebuildNestedRequirement(
12940 Req->getInvalidConstraintEntity(), Req->getConstraintSatisfaction());
12941 return Req;
12942 }
12943 ExprResult TransConstraint =
12944 getDerived().TransformExpr(Req->getConstraintExpr());
12945 if (TransConstraint.isInvalid())
12946 return nullptr;
12947 return getDerived().RebuildNestedRequirement(TransConstraint.get());
12948}
12949
12950template<typename Derived>
12951ExprResult
12952TreeTransform<Derived>::TransformArrayTypeTraitExpr(ArrayTypeTraitExpr *E) {
12953 TypeSourceInfo *T = getDerived().TransformType(E->getQueriedTypeSourceInfo());
12954 if (!T)
12955 return ExprError();
12956
12957 if (!getDerived().AlwaysRebuild() &&
12958 T == E->getQueriedTypeSourceInfo())
12959 return E;
12960
12961 ExprResult SubExpr;
12962 {
12963 EnterExpressionEvaluationContext Unevaluated(
12964 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12965 SubExpr = getDerived().TransformExpr(E->getDimensionExpression());
12966 if (SubExpr.isInvalid())
12967 return ExprError();
12968
12969 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getDimensionExpression())
12970 return E;
12971 }
12972
12973 return getDerived().RebuildArrayTypeTrait(E->getTrait(), E->getBeginLoc(), T,
12974 SubExpr.get(), E->getEndLoc());
12975}
12976
12977template<typename Derived>
12978ExprResult
12979TreeTransform<Derived>::TransformExpressionTraitExpr(ExpressionTraitExpr *E) {
12980 ExprResult SubExpr;
12981 {
12982 EnterExpressionEvaluationContext Unevaluated(
12983 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
12984 SubExpr = getDerived().TransformExpr(E->getQueriedExpression());
12985 if (SubExpr.isInvalid())
12986 return ExprError();
12987
12988 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getQueriedExpression())
12989 return E;
12990 }
12991
12992 return getDerived().RebuildExpressionTrait(E->getTrait(), E->getBeginLoc(),
12993 SubExpr.get(), E->getEndLoc());
12994}
12995
12996template <typename Derived>
12997ExprResult TreeTransform<Derived>::TransformParenDependentScopeDeclRefExpr(
12998 ParenExpr *PE, DependentScopeDeclRefExpr *DRE, bool AddrTaken,
12999 TypeSourceInfo **RecoveryTSI) {
13000 ExprResult NewDRE = getDerived().TransformDependentScopeDeclRefExpr(
13001 DRE, AddrTaken, RecoveryTSI);
13002
13003 // Propagate both errors and recovered types, which return ExprEmpty.
13004 if (!NewDRE.isUsable())
13005 return NewDRE;
13006
13007 // We got an expr, wrap it up in parens.
13008 if (!getDerived().AlwaysRebuild() && NewDRE.get() == DRE)
13009 return PE;
13010 return getDerived().RebuildParenExpr(NewDRE.get(), PE->getLParen(),
13011 PE->getRParen());
13012}
13013
13014template <typename Derived>
13015ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13016 DependentScopeDeclRefExpr *E) {
13017 return TransformDependentScopeDeclRefExpr(E, /*IsAddressOfOperand=*/false,
13018 nullptr);
13019}
13020
13021template <typename Derived>
13022ExprResult TreeTransform<Derived>::TransformDependentScopeDeclRefExpr(
13023 DependentScopeDeclRefExpr *E, bool IsAddressOfOperand,
13024 TypeSourceInfo **RecoveryTSI) {
13025 assert(E->getQualifierLoc())(static_cast <bool> (E->getQualifierLoc()) ? void (0
) : __assert_fail ("E->getQualifierLoc()", "clang/lib/Sema/TreeTransform.h"
, 13025, __extension__ __PRETTY_FUNCTION__))
;
13026 NestedNameSpecifierLoc QualifierLoc =
13027 getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc());
13028 if (!QualifierLoc)
13029 return ExprError();
13030 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13031
13032 // TODO: If this is a conversion-function-id, verify that the
13033 // destination type name (if present) resolves the same way after
13034 // instantiation as it did in the local scope.
13035
13036 DeclarationNameInfo NameInfo =
13037 getDerived().TransformDeclarationNameInfo(E->getNameInfo());
13038 if (!NameInfo.getName())
13039 return ExprError();
13040
13041 if (!E->hasExplicitTemplateArgs()) {
13042 if (!getDerived().AlwaysRebuild() && QualifierLoc == E->getQualifierLoc() &&
13043 // Note: it is sufficient to compare the Name component of NameInfo:
13044 // if name has not changed, DNLoc has not changed either.
13045 NameInfo.getName() == E->getDeclName())
13046 return E;
13047
13048 return getDerived().RebuildDependentScopeDeclRefExpr(
13049 QualifierLoc, TemplateKWLoc, NameInfo, /*TemplateArgs=*/nullptr,
13050 IsAddressOfOperand, RecoveryTSI);
13051 }
13052
13053 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13054 if (getDerived().TransformTemplateArguments(
13055 E->getTemplateArgs(), E->getNumTemplateArgs(), TransArgs))
13056 return ExprError();
13057
13058 return getDerived().RebuildDependentScopeDeclRefExpr(
13059 QualifierLoc, TemplateKWLoc, NameInfo, &TransArgs, IsAddressOfOperand,
13060 RecoveryTSI);
13061}
13062
13063template<typename Derived>
13064ExprResult
13065TreeTransform<Derived>::TransformCXXConstructExpr(CXXConstructExpr *E) {
13066 // CXXConstructExprs other than for list-initialization and
13067 // CXXTemporaryObjectExpr are always implicit, so when we have
13068 // a 1-argument construction we just transform that argument.
13069 if (getDerived().AllowSkippingCXXConstructExpr() &&
13070 ((E->getNumArgs() == 1 ||
13071 (E->getNumArgs() > 1 && getDerived().DropCallArgument(E->getArg(1)))) &&
13072 (!getDerived().DropCallArgument(E->getArg(0))) &&
13073 !E->isListInitialization()))
13074 return getDerived().TransformInitializer(E->getArg(0),
13075 /*DirectInit*/ false);
13076
13077 TemporaryBase Rebase(*this, /*FIXME*/ E->getBeginLoc(), DeclarationName());
13078
13079 QualType T = getDerived().TransformType(E->getType());
13080 if (T.isNull())
13081 return ExprError();
13082
13083 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13084 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13085 if (!Constructor)
13086 return ExprError();
13087
13088 bool ArgumentChanged = false;
13089 SmallVector<Expr*, 8> Args;
13090 {
13091 EnterExpressionEvaluationContext Context(
13092 getSema(), EnterExpressionEvaluationContext::InitList,
13093 E->isListInitialization());
13094 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13095 &ArgumentChanged))
13096 return ExprError();
13097 }
13098
13099 if (!getDerived().AlwaysRebuild() &&
13100 T == E->getType() &&
13101 Constructor == E->getConstructor() &&
13102 !ArgumentChanged) {
13103 // Mark the constructor as referenced.
13104 // FIXME: Instantiation-specific
13105 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13106 return E;
13107 }
13108
13109 return getDerived().RebuildCXXConstructExpr(
13110 T, /*FIXME:*/ E->getBeginLoc(), Constructor, E->isElidable(), Args,
13111 E->hadMultipleCandidates(), E->isListInitialization(),
13112 E->isStdInitListInitialization(), E->requiresZeroInitialization(),
13113 E->getConstructionKind(), E->getParenOrBraceRange());
13114}
13115
13116template<typename Derived>
13117ExprResult TreeTransform<Derived>::TransformCXXInheritedCtorInitExpr(
13118 CXXInheritedCtorInitExpr *E) {
13119 QualType T = getDerived().TransformType(E->getType());
13120 if (T.isNull())
13121 return ExprError();
13122
13123 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13124 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13125 if (!Constructor)
13126 return ExprError();
13127
13128 if (!getDerived().AlwaysRebuild() &&
13129 T == E->getType() &&
13130 Constructor == E->getConstructor()) {
13131 // Mark the constructor as referenced.
13132 // FIXME: Instantiation-specific
13133 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13134 return E;
13135 }
13136
13137 return getDerived().RebuildCXXInheritedCtorInitExpr(
13138 T, E->getLocation(), Constructor,
13139 E->constructsVBase(), E->inheritedFromVBase());
13140}
13141
13142/// Transform a C++ temporary-binding expression.
13143///
13144/// Since CXXBindTemporaryExpr nodes are implicitly generated, we just
13145/// transform the subexpression and return that.
13146template<typename Derived>
13147ExprResult
13148TreeTransform<Derived>::TransformCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) {
13149 if (auto *Dtor = E->getTemporary()->getDestructor())
13150 SemaRef.MarkFunctionReferenced(E->getBeginLoc(),
13151 const_cast<CXXDestructorDecl *>(Dtor));
13152 return getDerived().TransformExpr(E->getSubExpr());
13153}
13154
13155/// Transform a C++ expression that contains cleanups that should
13156/// be run after the expression is evaluated.
13157///
13158/// Since ExprWithCleanups nodes are implicitly generated, we
13159/// just transform the subexpression and return that.
13160template<typename Derived>
13161ExprResult
13162TreeTransform<Derived>::TransformExprWithCleanups(ExprWithCleanups *E) {
13163 return getDerived().TransformExpr(E->getSubExpr());
13164}
13165
13166template<typename Derived>
13167ExprResult
13168TreeTransform<Derived>::TransformCXXTemporaryObjectExpr(
13169 CXXTemporaryObjectExpr *E) {
13170 TypeSourceInfo *T =
13171 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13172 if (!T)
13173 return ExprError();
13174
13175 CXXConstructorDecl *Constructor = cast_or_null<CXXConstructorDecl>(
13176 getDerived().TransformDecl(E->getBeginLoc(), E->getConstructor()));
13177 if (!Constructor)
13178 return ExprError();
13179
13180 bool ArgumentChanged = false;
13181 SmallVector<Expr*, 8> Args;
13182 Args.reserve(E->getNumArgs());
13183 {
13184 EnterExpressionEvaluationContext Context(
13185 getSema(), EnterExpressionEvaluationContext::InitList,
13186 E->isListInitialization());
13187 if (TransformExprs(E->getArgs(), E->getNumArgs(), true, Args,
13188 &ArgumentChanged))
13189 return ExprError();
13190 }
13191
13192 if (!getDerived().AlwaysRebuild() &&
13193 T == E->getTypeSourceInfo() &&
13194 Constructor == E->getConstructor() &&
13195 !ArgumentChanged) {
13196 // FIXME: Instantiation-specific
13197 SemaRef.MarkFunctionReferenced(E->getBeginLoc(), Constructor);
13198 return SemaRef.MaybeBindToTemporary(E);
13199 }
13200
13201 // FIXME: We should just pass E->isListInitialization(), but we're not
13202 // prepared to handle list-initialization without a child InitListExpr.
13203 SourceLocation LParenLoc = T->getTypeLoc().getEndLoc();
13204 return getDerived().RebuildCXXTemporaryObjectExpr(
13205 T, LParenLoc, Args, E->getEndLoc(),
13206 /*ListInitialization=*/LParenLoc.isInvalid());
13207}
13208
13209template<typename Derived>
13210ExprResult
13211TreeTransform<Derived>::TransformLambdaExpr(LambdaExpr *E) {
13212 // Transform any init-capture expressions before entering the scope of the
13213 // lambda body, because they are not semantically within that scope.
13214 typedef std::pair<ExprResult, QualType> InitCaptureInfoTy;
13215 struct TransformedInitCapture {
13216 // The location of the ... if the result is retaining a pack expansion.
13217 SourceLocation EllipsisLoc;
13218 // Zero or more expansions of the init-capture.
13219 SmallVector<InitCaptureInfoTy, 4> Expansions;
13220 };
13221 SmallVector<TransformedInitCapture, 4> InitCaptures;
13222 InitCaptures.resize(E->explicit_capture_end() - E->explicit_capture_begin());
13223 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13224 CEnd = E->capture_end();
13225 C != CEnd; ++C) {
13226 if (!E->isInitCapture(C))
13227 continue;
13228
13229 TransformedInitCapture &Result = InitCaptures[C - E->capture_begin()];
13230 auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13231
13232 auto SubstInitCapture = [&](SourceLocation EllipsisLoc,
13233 std::optional<unsigned> NumExpansions) {
13234 ExprResult NewExprInitResult = getDerived().TransformInitializer(
13235 OldVD->getInit(), OldVD->getInitStyle() == VarDecl::CallInit);
13236
13237 if (NewExprInitResult.isInvalid()) {
13238 Result.Expansions.push_back(InitCaptureInfoTy(ExprError(), QualType()));
13239 return;
13240 }
13241 Expr *NewExprInit = NewExprInitResult.get();
13242
13243 QualType NewInitCaptureType =
13244 getSema().buildLambdaInitCaptureInitialization(
13245 C->getLocation(), C->getCaptureKind() == LCK_ByRef,
13246 EllipsisLoc, NumExpansions, OldVD->getIdentifier(),
13247 cast<VarDecl>(C->getCapturedVar())->getInitStyle() !=
13248 VarDecl::CInit,
13249 NewExprInit);
13250 Result.Expansions.push_back(
13251 InitCaptureInfoTy(NewExprInit, NewInitCaptureType));
13252 };
13253
13254 // If this is an init-capture pack, consider expanding the pack now.
13255 if (OldVD->isParameterPack()) {
13256 PackExpansionTypeLoc ExpansionTL = OldVD->getTypeSourceInfo()
13257 ->getTypeLoc()
13258 .castAs<PackExpansionTypeLoc>();
13259 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13260 SemaRef.collectUnexpandedParameterPacks(OldVD->getInit(), Unexpanded);
13261
13262 // Determine whether the set of unexpanded parameter packs can and should
13263 // be expanded.
13264 bool Expand = true;
13265 bool RetainExpansion = false;
13266 std::optional<unsigned> OrigNumExpansions =
13267 ExpansionTL.getTypePtr()->getNumExpansions();
13268 std::optional<unsigned> NumExpansions = OrigNumExpansions;
13269 if (getDerived().TryExpandParameterPacks(
13270 ExpansionTL.getEllipsisLoc(),
13271 OldVD->getInit()->getSourceRange(), Unexpanded, Expand,
13272 RetainExpansion, NumExpansions))
13273 return ExprError();
13274 if (Expand) {
13275 for (unsigned I = 0; I != *NumExpansions; ++I) {
13276 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13277 SubstInitCapture(SourceLocation(), std::nullopt);
13278 }
13279 }
13280 if (!Expand || RetainExpansion) {
13281 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
13282 SubstInitCapture(ExpansionTL.getEllipsisLoc(), NumExpansions);
13283 Result.EllipsisLoc = ExpansionTL.getEllipsisLoc();
13284 }
13285 } else {
13286 SubstInitCapture(SourceLocation(), std::nullopt);
13287 }
13288 }
13289
13290 LambdaScopeInfo *LSI = getSema().PushLambdaScope();
13291 Sema::FunctionScopeRAII FuncScopeCleanup(getSema());
13292
13293 // Create the local class that will describe the lambda.
13294
13295 // FIXME: DependencyKind below is wrong when substituting inside a templated
13296 // context that isn't a DeclContext (such as a variable template), or when
13297 // substituting an unevaluated lambda inside of a function's parameter's type
13298 // - as parameter types are not instantiated from within a function's DC. We
13299 // use evaluation contexts to distinguish the function parameter case.
13300 CXXRecordDecl::LambdaDependencyKind DependencyKind =
13301 CXXRecordDecl::LDK_Unknown;
13302 if ((getSema().isUnevaluatedContext() ||
13303 getSema().isConstantEvaluatedContext()) &&
13304 (getSema().CurContext->isFileContext() ||
13305 !getSema().CurContext->getParent()->isDependentContext()))
13306 DependencyKind = CXXRecordDecl::LDK_NeverDependent;
13307
13308 CXXRecordDecl *OldClass = E->getLambdaClass();
13309 CXXRecordDecl *Class = getSema().createLambdaClosureType(
13310 E->getIntroducerRange(), /*Info=*/nullptr, DependencyKind,
13311 E->getCaptureDefault());
13312 getDerived().transformedLocalDecl(OldClass, {Class});
13313
13314 CXXMethodDecl *NewCallOperator =
13315 getSema().CreateLambdaCallOperator(E->getIntroducerRange(), Class);
13316 NewCallOperator->setLexicalDeclContext(getSema().CurContext);
13317
13318 // Enter the scope of the lambda.
13319 getSema().buildLambdaScope(LSI, NewCallOperator, E->getIntroducerRange(),
13320 E->getCaptureDefault(), E->getCaptureDefaultLoc(),
13321 E->hasExplicitParameters(), E->isMutable());
13322
13323 // Introduce the context of the call operator.
13324 Sema::ContextRAII SavedContext(getSema(), NewCallOperator,
13325 /*NewThisContext*/false);
13326
13327 bool Invalid = false;
13328
13329 // Transform captures.
13330 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13331 CEnd = E->capture_end();
13332 C != CEnd; ++C) {
13333 // When we hit the first implicit capture, tell Sema that we've finished
13334 // the list of explicit captures.
13335 if (C->isImplicit())
13336 break;
13337
13338 // Capturing 'this' is trivial.
13339 if (C->capturesThis()) {
13340 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13341 /*BuildAndDiagnose*/ true, nullptr,
13342 C->getCaptureKind() == LCK_StarThis);
13343 continue;
13344 }
13345 // Captured expression will be recaptured during captured variables
13346 // rebuilding.
13347 if (C->capturesVLAType())
13348 continue;
13349
13350 // Rebuild init-captures, including the implied field declaration.
13351 if (E->isInitCapture(C)) {
13352 TransformedInitCapture &NewC = InitCaptures[C - E->capture_begin()];
13353
13354 auto *OldVD = cast<VarDecl>(C->getCapturedVar());
13355 llvm::SmallVector<Decl*, 4> NewVDs;
13356
13357 for (InitCaptureInfoTy &Info : NewC.Expansions) {
13358 ExprResult Init = Info.first;
13359 QualType InitQualType = Info.second;
13360 if (Init.isInvalid() || InitQualType.isNull()) {
13361 Invalid = true;
13362 break;
13363 }
13364 VarDecl *NewVD = getSema().createLambdaInitCaptureVarDecl(
13365 OldVD->getLocation(), InitQualType, NewC.EllipsisLoc,
13366 OldVD->getIdentifier(), OldVD->getInitStyle(), Init.get(),
13367 getSema().CurContext);
13368 if (!NewVD) {
13369 Invalid = true;
13370 break;
13371 }
13372 NewVDs.push_back(NewVD);
13373 getSema().addInitCapture(LSI, NewVD, C->getCaptureKind() == LCK_ByRef);
13374 }
13375
13376 if (Invalid)
13377 break;
13378
13379 getDerived().transformedLocalDecl(OldVD, NewVDs);
13380 continue;
13381 }
13382
13383 assert(C->capturesVariable() && "unexpected kind of lambda capture")(static_cast <bool> (C->capturesVariable() &&
"unexpected kind of lambda capture") ? void (0) : __assert_fail
("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "clang/lib/Sema/TreeTransform.h", 13383, __extension__ __PRETTY_FUNCTION__
))
;
13384
13385 // Determine the capture kind for Sema.
13386 Sema::TryCaptureKind Kind
13387 = C->isImplicit()? Sema::TryCapture_Implicit
13388 : C->getCaptureKind() == LCK_ByCopy
13389 ? Sema::TryCapture_ExplicitByVal
13390 : Sema::TryCapture_ExplicitByRef;
13391 SourceLocation EllipsisLoc;
13392 if (C->isPackExpansion()) {
13393 UnexpandedParameterPack Unexpanded(C->getCapturedVar(), C->getLocation());
13394 bool ShouldExpand = false;
13395 bool RetainExpansion = false;
13396 std::optional<unsigned> NumExpansions;
13397 if (getDerived().TryExpandParameterPacks(C->getEllipsisLoc(),
13398 C->getLocation(),
13399 Unexpanded,
13400 ShouldExpand, RetainExpansion,
13401 NumExpansions)) {
13402 Invalid = true;
13403 continue;
13404 }
13405
13406 if (ShouldExpand) {
13407 // The transform has determined that we should perform an expansion;
13408 // transform and capture each of the arguments.
13409 // expansion of the pattern. Do so.
13410 auto *Pack = cast<VarDecl>(C->getCapturedVar());
13411 for (unsigned I = 0; I != *NumExpansions; ++I) {
13412 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
13413 VarDecl *CapturedVar
13414 = cast_or_null<VarDecl>(getDerived().TransformDecl(C->getLocation(),
13415 Pack));
13416 if (!CapturedVar) {
13417 Invalid = true;
13418 continue;
13419 }
13420
13421 // Capture the transformed variable.
13422 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind);
13423 }
13424
13425 // FIXME: Retain a pack expansion if RetainExpansion is true.
13426
13427 continue;
13428 }
13429
13430 EllipsisLoc = C->getEllipsisLoc();
13431 }
13432
13433 // Transform the captured variable.
13434 auto *CapturedVar = cast_or_null<ValueDecl>(
13435 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13436 if (!CapturedVar || CapturedVar->isInvalidDecl()) {
13437 Invalid = true;
13438 continue;
13439 }
13440
13441 // Capture the transformed variable.
13442 getSema().tryCaptureVariable(CapturedVar, C->getLocation(), Kind,
13443 EllipsisLoc);
13444 }
13445 getSema().finishLambdaExplicitCaptures(LSI);
13446
13447 // Transform the template parameters, and add them to the current
13448 // instantiation scope. The null case is handled correctly.
13449 auto TPL = getDerived().TransformTemplateParameterList(
13450 E->getTemplateParameterList());
13451 LSI->GLTemplateParameterList = TPL;
13452
13453 // Transform the type of the original lambda's call operator.
13454 // The transformation MUST be done in the CurrentInstantiationScope since
13455 // it introduces a mapping of the original to the newly created
13456 // transformed parameters.
13457 TypeSourceInfo *NewCallOpTSI = nullptr;
13458 {
13459 TypeSourceInfo *OldCallOpTSI = E->getCallOperator()->getTypeSourceInfo();
13460 auto OldCallOpFPTL =
13461 OldCallOpTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
13462
13463 TypeLocBuilder NewCallOpTLBuilder;
13464 SmallVector<QualType, 4> ExceptionStorage;
13465 TreeTransform *This = this; // Work around gcc.gnu.org/PR56135.
13466 QualType NewCallOpType = TransformFunctionProtoType(
13467 NewCallOpTLBuilder, OldCallOpFPTL, nullptr, Qualifiers(),
13468 [&](FunctionProtoType::ExceptionSpecInfo &ESI, bool &Changed) {
13469 return This->TransformExceptionSpec(OldCallOpFPTL.getBeginLoc(), ESI,
13470 ExceptionStorage, Changed);
13471 });
13472 if (NewCallOpType.isNull())
13473 return ExprError();
13474 NewCallOpTSI =
13475 NewCallOpTLBuilder.getTypeSourceInfo(getSema().Context, NewCallOpType);
13476 }
13477
13478 getSema().CompleteLambdaCallOperator(
13479 NewCallOperator, E->getCallOperator()->getLocation(),
13480 E->getCallOperator()->getInnerLocStart(),
13481 E->getCallOperator()->getTrailingRequiresClause(), NewCallOpTSI,
13482 E->getCallOperator()->getConstexprKind(),
13483 E->getCallOperator()->getStorageClass(),
13484 NewCallOpTSI->getTypeLoc().castAs<FunctionProtoTypeLoc>().getParams(),
13485 E->hasExplicitResultType());
13486
13487 getDerived().transformAttrs(E->getCallOperator(), NewCallOperator);
13488 getDerived().transformedLocalDecl(E->getCallOperator(), {NewCallOperator});
13489
13490 {
13491 // Number the lambda for linkage purposes if necessary.
13492 Sema::ContextRAII ManglingContext(getSema(), Class->getDeclContext());
13493
13494 std::optional<CXXRecordDecl::LambdaNumbering> Numbering;
13495 if (getDerived().ReplacingOriginal()) {
13496 Numbering = OldClass->getLambdaNumbering();
13497 }
13498
13499 getSema().handleLambdaNumbering(Class, NewCallOperator, Numbering);
13500 }
13501
13502 // FIXME: Sema's lambda-building mechanism expects us to push an expression
13503 // evaluation context even if we're not transforming the function body.
13504 getSema().PushExpressionEvaluationContext(
13505 Sema::ExpressionEvaluationContext::PotentiallyEvaluated);
13506
13507 // Instantiate the body of the lambda expression.
13508 StmtResult Body =
13509 Invalid ? StmtError() : getDerived().TransformLambdaBody(E, E->getBody());
13510
13511 // ActOnLambda* will pop the function scope for us.
13512 FuncScopeCleanup.disable();
13513
13514 if (Body.isInvalid()) {
13515 SavedContext.pop();
13516 getSema().ActOnLambdaError(E->getBeginLoc(), /*CurScope=*/nullptr,
13517 /*IsInstantiation=*/true);
13518 return ExprError();
13519 }
13520
13521 // Copy the LSI before ActOnFinishFunctionBody removes it.
13522 // FIXME: This is dumb. Store the lambda information somewhere that outlives
13523 // the call operator.
13524 auto LSICopy = *LSI;
13525 getSema().ActOnFinishFunctionBody(NewCallOperator, Body.get(),
13526 /*IsInstantiation*/ true);
13527 SavedContext.pop();
13528
13529 return getSema().BuildLambdaExpr(E->getBeginLoc(), Body.get()->getEndLoc(),
13530 &LSICopy);
13531}
13532
13533template<typename Derived>
13534StmtResult
13535TreeTransform<Derived>::TransformLambdaBody(LambdaExpr *E, Stmt *S) {
13536 return TransformStmt(S);
13537}
13538
13539template<typename Derived>
13540StmtResult
13541TreeTransform<Derived>::SkipLambdaBody(LambdaExpr *E, Stmt *S) {
13542 // Transform captures.
13543 for (LambdaExpr::capture_iterator C = E->capture_begin(),
13544 CEnd = E->capture_end();
13545 C != CEnd; ++C) {
13546 // When we hit the first implicit capture, tell Sema that we've finished
13547 // the list of explicit captures.
13548 if (!C->isImplicit())
13549 continue;
13550
13551 // Capturing 'this' is trivial.
13552 if (C->capturesThis()) {
13553 getSema().CheckCXXThisCapture(C->getLocation(), C->isExplicit(),
13554 /*BuildAndDiagnose*/ true, nullptr,
13555 C->getCaptureKind() == LCK_StarThis);
13556 continue;
13557 }
13558 // Captured expression will be recaptured during captured variables
13559 // rebuilding.
13560 if (C->capturesVLAType())
13561 continue;
13562
13563 assert(C->capturesVariable() && "unexpected kind of lambda capture")(static_cast <bool> (C->capturesVariable() &&
"unexpected kind of lambda capture") ? void (0) : __assert_fail
("C->capturesVariable() && \"unexpected kind of lambda capture\""
, "clang/lib/Sema/TreeTransform.h", 13563, __extension__ __PRETTY_FUNCTION__
))
;
13564 assert(!E->isInitCapture(C) && "implicit init-capture?")(static_cast <bool> (!E->isInitCapture(C) &&
"implicit init-capture?") ? void (0) : __assert_fail ("!E->isInitCapture(C) && \"implicit init-capture?\""
, "clang/lib/Sema/TreeTransform.h", 13564, __extension__ __PRETTY_FUNCTION__
))
;
13565
13566 // Transform the captured variable.
13567 VarDecl *CapturedVar = cast_or_null<VarDecl>(
13568 getDerived().TransformDecl(C->getLocation(), C->getCapturedVar()));
13569 if (!CapturedVar || CapturedVar->isInvalidDecl())
13570 return StmtError();
13571
13572 // Capture the transformed variable.
13573 getSema().tryCaptureVariable(CapturedVar, C->getLocation());
13574 }
13575
13576 return S;
13577}
13578
13579template<typename Derived>
13580ExprResult
13581TreeTransform<Derived>::TransformCXXUnresolvedConstructExpr(
13582 CXXUnresolvedConstructExpr *E) {
13583 TypeSourceInfo *T =
13584 getDerived().TransformTypeWithDeducedTST(E->getTypeSourceInfo());
13585 if (!T)
13586 return ExprError();
13587
13588 bool ArgumentChanged = false;
13589 SmallVector<Expr*, 8> Args;
13590 Args.reserve(E->getNumArgs());
13591 {
13592 EnterExpressionEvaluationContext Context(
13593 getSema(), EnterExpressionEvaluationContext::InitList,
13594 E->isListInitialization());
13595 if (getDerived().TransformExprs(E->arg_begin(), E->getNumArgs(), true, Args,
13596 &ArgumentChanged))
13597 return ExprError();
13598 }
13599
13600 if (!getDerived().AlwaysRebuild() &&
13601 T == E->getTypeSourceInfo() &&
13602 !ArgumentChanged)
13603 return E;
13604
13605 // FIXME: we're faking the locations of the commas
13606 return getDerived().RebuildCXXUnresolvedConstructExpr(
13607 T, E->getLParenLoc(), Args, E->getRParenLoc(), E->isListInitialization());
13608}
13609
13610template<typename Derived>
13611ExprResult
13612TreeTransform<Derived>::TransformCXXDependentScopeMemberExpr(
13613 CXXDependentScopeMemberExpr *E) {
13614 // Transform the base of the expression.
13615 ExprResult Base((Expr*) nullptr);
13616 Expr *OldBase;
13617 QualType BaseType;
13618 QualType ObjectType;
13619 if (!E->isImplicitAccess()) {
13620 OldBase = E->getBase();
13621 Base = getDerived().TransformExpr(OldBase);
13622 if (Base.isInvalid())
13623 return ExprError();
13624
13625 // Start the member reference and compute the object's type.
13626 ParsedType ObjectTy;
13627 bool MayBePseudoDestructor = false;
13628 Base = SemaRef.ActOnStartCXXMemberReference(nullptr, Base.get(),
13629 E->getOperatorLoc(),
13630 E->isArrow()? tok::arrow : tok::period,
13631 ObjectTy,
13632 MayBePseudoDestructor);
13633 if (Base.isInvalid())
13634 return ExprError();
13635
13636 ObjectType = ObjectTy.get();
13637 BaseType = ((Expr*) Base.get())->getType();
13638 } else {
13639 OldBase = nullptr;
13640 BaseType = getDerived().TransformType(E->getBaseType());
13641 ObjectType = BaseType->castAs<PointerType>()->getPointeeType();
13642 }
13643
13644 // Transform the first part of the nested-name-specifier that qualifies
13645 // the member name.
13646 NamedDecl *FirstQualifierInScope
13647 = getDerived().TransformFirstQualifierInScope(
13648 E->getFirstQualifierFoundInScope(),
13649 E->getQualifierLoc().getBeginLoc());
13650
13651 NestedNameSpecifierLoc QualifierLoc;
13652 if (E->getQualifier()) {
13653 QualifierLoc
13654 = getDerived().TransformNestedNameSpecifierLoc(E->getQualifierLoc(),
13655 ObjectType,
13656 FirstQualifierInScope);
13657 if (!QualifierLoc)
13658 return ExprError();
13659 }
13660
13661 SourceLocation TemplateKWLoc = E->getTemplateKeywordLoc();
13662
13663 // TODO: If this is a conversion-function-id, verify that the
13664 // destination type name (if present) resolves the same way after
13665 // instantiation as it did in the local scope.
13666
13667 DeclarationNameInfo NameInfo
13668 = getDerived().TransformDeclarationNameInfo(E->getMemberNameInfo());
13669 if (!NameInfo.getName())
13670 return ExprError();
13671
13672 if (!E->hasExplicitTemplateArgs()) {
13673 // This is a reference to a member without an explicitly-specified
13674 // template argument list. Optimize for this common case.
13675 if (!getDerived().AlwaysRebuild() &&
13676 Base.get() == OldBase &&
13677 BaseType == E->getBaseType() &&
13678 QualifierLoc == E->getQualifierLoc() &&
13679 NameInfo.getName() == E->getMember() &&
13680 FirstQualifierInScope == E->getFirstQualifierFoundInScope())
13681 return E;
13682
13683 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13684 BaseType,
13685 E->isArrow(),
13686 E->getOperatorLoc(),
13687 QualifierLoc,
13688 TemplateKWLoc,
13689 FirstQualifierInScope,
13690 NameInfo,
13691 /*TemplateArgs*/nullptr);
13692 }
13693
13694 TemplateArgumentListInfo TransArgs(E->getLAngleLoc(), E->getRAngleLoc());
13695 if (getDerived().TransformTemplateArguments(E->getTemplateArgs(),
13696 E->getNumTemplateArgs(),
13697 TransArgs))
13698 return ExprError();
13699
13700 return getDerived().RebuildCXXDependentScopeMemberExpr(Base.get(),
13701 BaseType,
13702 E->isArrow(),
13703 E->getOperatorLoc(),
13704 QualifierLoc,
13705 TemplateKWLoc,
13706 FirstQualifierInScope,
13707 NameInfo,
13708 &TransArgs);
13709}
13710
13711template <typename Derived>
13712ExprResult TreeTransform<Derived>::TransformUnresolvedMemberExpr(
13713 UnresolvedMemberExpr *Old) {
13714 // Transform the base of the expression.
13715 ExprResult Base((Expr *)nullptr);
13716 QualType BaseType;
13717 if (!Old->isImplicitAccess()) {
13718 Base = getDerived().TransformExpr(Old->getBase());
13719 if (Base.isInvalid())
13720 return ExprError();
13721 Base =
13722 getSema().PerformMemberExprBaseConversion(Base.get(), Old->isArrow());
13723 if (Base.isInvalid())
13724 return ExprError();
13725 BaseType = Base.get()->getType();
13726 } else {
13727 BaseType = getDerived().TransformType(Old->getBaseType());
13728 }
13729
13730 NestedNameSpecifierLoc QualifierLoc;
13731 if (Old->getQualifierLoc()) {
13732 QualifierLoc =
13733 getDerived().TransformNestedNameSpecifierLoc(Old->getQualifierLoc());
13734 if (!QualifierLoc)
13735 return ExprError();
13736 }
13737
13738 SourceLocation TemplateKWLoc = Old->getTemplateKeywordLoc();
13739
13740 LookupResult R(SemaRef, Old->getMemberNameInfo(), Sema::LookupOrdinaryName);
13741
13742 // Transform the declaration set.
13743 if (TransformOverloadExprDecls(Old, /*RequiresADL*/ false, R))
13744 return ExprError();
13745
13746 // Determine the naming class.
13747 if (Old->getNamingClass()) {
13748 CXXRecordDecl *NamingClass = cast_or_null<CXXRecordDecl>(
13749 getDerived().TransformDecl(Old->getMemberLoc(), Old->getNamingClass()));
13750 if (!NamingClass)
13751 return ExprError();
13752
13753 R.setNamingClass(NamingClass);
13754 }
13755
13756 TemplateArgumentListInfo TransArgs;
13757 if (Old->hasExplicitTemplateArgs()) {
13758 TransArgs.setLAngleLoc(Old->getLAngleLoc());
13759 TransArgs.setRAngleLoc(Old->getRAngleLoc());
13760 if (getDerived().TransformTemplateArguments(
13761 Old->getTemplateArgs(), Old->getNumTemplateArgs(), TransArgs))
13762 return ExprError();
13763 }
13764
13765 // FIXME: to do this check properly, we will need to preserve the
13766 // first-qualifier-in-scope here, just in case we had a dependent
13767 // base (and therefore couldn't do the check) and a
13768 // nested-name-qualifier (and therefore could do the lookup).
13769 NamedDecl *FirstQualifierInScope = nullptr;
13770
13771 return getDerived().RebuildUnresolvedMemberExpr(
13772 Base.get(), BaseType, Old->getOperatorLoc(), Old->isArrow(), QualifierLoc,
13773 TemplateKWLoc, FirstQualifierInScope, R,
13774 (Old->hasExplicitTemplateArgs() ? &TransArgs : nullptr));
13775}
13776
13777template<typename Derived>
13778ExprResult
13779TreeTransform<Derived>::TransformCXXNoexceptExpr(CXXNoexceptExpr *E) {
13780 EnterExpressionEvaluationContext Unevaluated(
13781 SemaRef, Sema::ExpressionEvaluationContext::Unevaluated);
13782 ExprResult SubExpr = getDerived().TransformExpr(E->getOperand());
13783 if (SubExpr.isInvalid())
13784 return ExprError();
13785
13786 if (!getDerived().AlwaysRebuild() && SubExpr.get() == E->getOperand())
13787 return E;
13788
13789 return getDerived().RebuildCXXNoexceptExpr(E->getSourceRange(),SubExpr.get());
13790}
13791
13792template<typename Derived>
13793ExprResult
13794TreeTransform<Derived>::TransformPackExpansionExpr(PackExpansionExpr *E) {
13795 ExprResult Pattern = getDerived().TransformExpr(E->getPattern());
13796 if (Pattern.isInvalid())
13797 return ExprError();
13798
13799 if (!getDerived().AlwaysRebuild() && Pattern.get() == E->getPattern())
13800 return E;
13801
13802 return getDerived().RebuildPackExpansion(Pattern.get(), E->getEllipsisLoc(),
13803 E->getNumExpansions());
13804}
13805
13806template<typename Derived>
13807ExprResult
13808TreeTransform<Derived>::TransformSizeOfPackExpr(SizeOfPackExpr *E) {
13809 // If E is not value-dependent, then nothing will change when we transform it.
13810 // Note: This is an instantiation-centric view.
13811 if (!E->isValueDependent())
13812 return E;
13813
13814 EnterExpressionEvaluationContext Unevaluated(
13815 getSema(), Sema::ExpressionEvaluationContext::Unevaluated);
13816
13817 ArrayRef<TemplateArgument> PackArgs;
13818 TemplateArgument ArgStorage;
13819
13820 // Find the argument list to transform.
13821 if (E->isPartiallySubstituted()) {
13822 PackArgs = E->getPartialArguments();
13823 } else if (E->isValueDependent()) {
13824 UnexpandedParameterPack Unexpanded(E->getPack(), E->getPackLoc());
13825 bool ShouldExpand = false;
13826 bool RetainExpansion = false;
13827 std::optional<unsigned> NumExpansions;
13828 if (getDerived().TryExpandParameterPacks(E->getOperatorLoc(), E->getPackLoc(),
13829 Unexpanded,
13830 ShouldExpand, RetainExpansion,
13831 NumExpansions))
13832 return ExprError();
13833
13834 // If we need to expand the pack, build a template argument from it and
13835 // expand that.
13836 if (ShouldExpand) {
13837 auto *Pack = E->getPack();
13838 if (auto *TTPD = dyn_cast<TemplateTypeParmDecl>(Pack)) {
13839 ArgStorage = getSema().Context.getPackExpansionType(
13840 getSema().Context.getTypeDeclType(TTPD), std::nullopt);
13841 } else if (auto *TTPD = dyn_cast<TemplateTemplateParmDecl>(Pack)) {
13842 ArgStorage = TemplateArgument(TemplateName(TTPD), std::nullopt);
13843 } else {
13844 auto *VD = cast<ValueDecl>(Pack);
13845 ExprResult DRE = getSema().BuildDeclRefExpr(
13846 VD, VD->getType().getNonLValueExprType(getSema().Context),
13847 VD->getType()->isReferenceType() ? VK_LValue : VK_PRValue,
13848 E->getPackLoc());
13849 if (DRE.isInvalid())
13850 return ExprError();
13851 ArgStorage = new (getSema().Context)
13852 PackExpansionExpr(getSema().Context.DependentTy, DRE.get(),
13853 E->getPackLoc(), std::nullopt);
13854 }
13855 PackArgs = ArgStorage;
13856 }
13857 }
13858
13859 // If we're not expanding the pack, just transform the decl.
13860 if (!PackArgs.size()) {
13861 auto *Pack = cast_or_null<NamedDecl>(
13862 getDerived().TransformDecl(E->getPackLoc(), E->getPack()));
13863 if (!Pack)
13864 return ExprError();
13865 return getDerived().RebuildSizeOfPackExpr(
13866 E->getOperatorLoc(), Pack, E->getPackLoc(), E->getRParenLoc(),
13867 std::nullopt, std::nullopt);
13868 }
13869
13870 // Try to compute the result without performing a partial substitution.
13871 std::optional<unsigned> Result = 0;
13872 for (const TemplateArgument &Arg : PackArgs) {
13873 if (!Arg.isPackExpansion()) {
13874 Result = *Result + 1;
13875 continue;
13876 }
13877
13878 TemplateArgumentLoc ArgLoc;
13879 InventTemplateArgumentLoc(Arg, ArgLoc);
13880
13881 // Find the pattern of the pack expansion.
13882 SourceLocation Ellipsis;
13883 std::optional<unsigned> OrigNumExpansions;
13884 TemplateArgumentLoc Pattern =
13885 getSema().getTemplateArgumentPackExpansionPattern(ArgLoc, Ellipsis,
13886 OrigNumExpansions);
13887
13888 // Substitute under the pack expansion. Do not expand the pack (yet).
13889 TemplateArgumentLoc OutPattern;
13890 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
13891 if (getDerived().TransformTemplateArgument(Pattern, OutPattern,
13892 /*Uneval*/ true))
13893 return true;
13894
13895 // See if we can determine the number of arguments from the result.
13896 std::optional<unsigned> NumExpansions =
13897 getSema().getFullyPackExpandedSize(OutPattern.getArgument());
13898 if (!NumExpansions) {
13899 // No: we must be in an alias template expansion, and we're going to need
13900 // to actually expand the packs.
13901 Result = std::nullopt;
13902 break;
13903 }
13904
13905 Result = *Result + *NumExpansions;
13906 }
13907
13908 // Common case: we could determine the number of expansions without
13909 // substituting.
13910 if (Result)
13911 return getDerived().RebuildSizeOfPackExpr(
13912 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13913 *Result, std::nullopt);
13914
13915 TemplateArgumentListInfo TransformedPackArgs(E->getPackLoc(),
13916 E->getPackLoc());
13917 {
13918 TemporaryBase Rebase(*this, E->getPackLoc(), getBaseEntity());
13919 typedef TemplateArgumentLocInventIterator<
13920 Derived, const TemplateArgument*> PackLocIterator;
13921 if (TransformTemplateArguments(PackLocIterator(*this, PackArgs.begin()),
13922 PackLocIterator(*this, PackArgs.end()),
13923 TransformedPackArgs, /*Uneval*/true))
13924 return ExprError();
13925 }
13926
13927 // Check whether we managed to fully-expand the pack.
13928 // FIXME: Is it possible for us to do so and not hit the early exit path?
13929 SmallVector<TemplateArgument, 8> Args;
13930 bool PartialSubstitution = false;
13931 for (auto &Loc : TransformedPackArgs.arguments()) {
13932 Args.push_back(Loc.getArgument());
13933 if (Loc.getArgument().isPackExpansion())
13934 PartialSubstitution = true;
13935 }
13936
13937 if (PartialSubstitution)
13938 return getDerived().RebuildSizeOfPackExpr(
13939 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc(),
13940 std::nullopt, Args);
13941
13942 return getDerived().RebuildSizeOfPackExpr(E->getOperatorLoc(), E->getPack(),
13943 E->getPackLoc(), E->getRParenLoc(),
13944 Args.size(), std::nullopt);
13945}
13946
13947template<typename Derived>
13948ExprResult
13949TreeTransform<Derived>::TransformSubstNonTypeTemplateParmPackExpr(
13950 SubstNonTypeTemplateParmPackExpr *E) {
13951 // Default behavior is to do nothing with this transformation.
13952 return E;
13953}
13954
13955template<typename Derived>
13956ExprResult
13957TreeTransform<Derived>::TransformSubstNonTypeTemplateParmExpr(
13958 SubstNonTypeTemplateParmExpr *E) {
13959 // Default behavior is to do nothing with this transformation.
13960 return E;
13961}
13962
13963template<typename Derived>
13964ExprResult
13965TreeTransform<Derived>::TransformFunctionParmPackExpr(FunctionParmPackExpr *E) {
13966 // Default behavior is to do nothing with this transformation.
13967 return E;
13968}
13969
13970template<typename Derived>
13971ExprResult
13972TreeTransform<Derived>::TransformMaterializeTemporaryExpr(
13973 MaterializeTemporaryExpr *E) {
13974 return getDerived().TransformExpr(E->getSubExpr());
13975}
13976
13977template<typename Derived>
13978ExprResult
13979TreeTransform<Derived>::TransformCXXFoldExpr(CXXFoldExpr *E) {
13980 UnresolvedLookupExpr *Callee = nullptr;
13981 if (Expr *OldCallee = E->getCallee()) {
13982 ExprResult CalleeResult = getDerived().TransformExpr(OldCallee);
13983 if (CalleeResult.isInvalid())
13984 return ExprError();
13985 Callee = cast<UnresolvedLookupExpr>(CalleeResult.get());
13986 }
13987
13988 Expr *Pattern = E->getPattern();
13989
13990 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
13991 getSema().collectUnexpandedParameterPacks(Pattern, Unexpanded);
13992 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 13992, __extension__ __PRETTY_FUNCTION__
))
;
13993
13994 // Determine whether the set of unexpanded parameter packs can and should
13995 // be expanded.
13996 bool Expand = true;
13997 bool RetainExpansion = false;
13998 std::optional<unsigned> OrigNumExpansions = E->getNumExpansions(),
13999 NumExpansions = OrigNumExpansions;
14000 if (getDerived().TryExpandParameterPacks(E->getEllipsisLoc(),
14001 Pattern->getSourceRange(),
14002 Unexpanded,
14003 Expand, RetainExpansion,
14004 NumExpansions))
14005 return true;
14006
14007 if (!Expand) {
14008 // Do not expand any packs here, just transform and rebuild a fold
14009 // expression.
14010 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14011
14012 ExprResult LHS =
14013 E->getLHS() ? getDerived().TransformExpr(E->getLHS()) : ExprResult();
14014 if (LHS.isInvalid())
14015 return true;
14016
14017 ExprResult RHS =
14018 E->getRHS() ? getDerived().TransformExpr(E->getRHS()) : ExprResult();
14019 if (RHS.isInvalid())
14020 return true;
14021
14022 if (!getDerived().AlwaysRebuild() &&
14023 LHS.get() == E->getLHS() && RHS.get() == E->getRHS())
14024 return E;
14025
14026 return getDerived().RebuildCXXFoldExpr(
14027 Callee, E->getBeginLoc(), LHS.get(), E->getOperator(),
14028 E->getEllipsisLoc(), RHS.get(), E->getEndLoc(), NumExpansions);
14029 }
14030
14031 // Formally a fold expression expands to nested parenthesized expressions.
14032 // Enforce this limit to avoid creating trees so deep we can't safely traverse
14033 // them.
14034 if (NumExpansions && SemaRef.getLangOpts().BracketDepth < NumExpansions) {
14035 SemaRef.Diag(E->getEllipsisLoc(),
14036 clang::diag::err_fold_expression_limit_exceeded)
14037 << *NumExpansions << SemaRef.getLangOpts().BracketDepth
14038 << E->getSourceRange();
14039 SemaRef.Diag(E->getEllipsisLoc(), diag::note_bracket_depth);
14040 return ExprError();
14041 }
14042
14043 // The transform has determined that we should perform an elementwise
14044 // expansion of the pattern. Do so.
14045 ExprResult Result = getDerived().TransformExpr(E->getInit());
14046 if (Result.isInvalid())
14047 return true;
14048 bool LeftFold = E->isLeftFold();
14049
14050 // If we're retaining an expansion for a right fold, it is the innermost
14051 // component and takes the init (if any).
14052 if (!LeftFold && RetainExpansion) {
14053 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14054
14055 ExprResult Out = getDerived().TransformExpr(Pattern);
14056 if (Out.isInvalid())
14057 return true;
14058
14059 Result = getDerived().RebuildCXXFoldExpr(
14060 Callee, E->getBeginLoc(), Out.get(), E->getOperator(),
14061 E->getEllipsisLoc(), Result.get(), E->getEndLoc(), OrigNumExpansions);
14062 if (Result.isInvalid())
14063 return true;
14064 }
14065
14066 for (unsigned I = 0; I != *NumExpansions; ++I) {
14067 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(
14068 getSema(), LeftFold ? I : *NumExpansions - I - 1);
14069 ExprResult Out = getDerived().TransformExpr(Pattern);
14070 if (Out.isInvalid())
14071 return true;
14072
14073 if (Out.get()->containsUnexpandedParameterPack()) {
14074 // We still have a pack; retain a pack expansion for this slice.
14075 Result = getDerived().RebuildCXXFoldExpr(
14076 Callee, E->getBeginLoc(), LeftFold ? Result.get() : Out.get(),
14077 E->getOperator(), E->getEllipsisLoc(),
14078 LeftFold ? Out.get() : Result.get(), E->getEndLoc(),
14079 OrigNumExpansions);
14080 } else if (Result.isUsable()) {
14081 // We've got down to a single element; build a binary operator.
14082 Expr *LHS = LeftFold ? Result.get() : Out.get();
14083 Expr *RHS = LeftFold ? Out.get() : Result.get();
14084 if (Callee)
14085 Result = getDerived().RebuildCXXOperatorCallExpr(
14086 BinaryOperator::getOverloadedOperator(E->getOperator()),
14087 E->getEllipsisLoc(), Callee, LHS, RHS);
14088 else
14089 Result = getDerived().RebuildBinaryOperator(E->getEllipsisLoc(),
14090 E->getOperator(), LHS, RHS);
14091 } else
14092 Result = Out;
14093
14094 if (Result.isInvalid())
14095 return true;
14096 }
14097
14098 // If we're retaining an expansion for a left fold, it is the outermost
14099 // component and takes the complete expansion so far as its init (if any).
14100 if (LeftFold && RetainExpansion) {
14101 ForgetPartiallySubstitutedPackRAII Forget(getDerived());
14102
14103 ExprResult Out = getDerived().TransformExpr(Pattern);
14104 if (Out.isInvalid())
14105 return true;
14106
14107 Result = getDerived().RebuildCXXFoldExpr(
14108 Callee, E->getBeginLoc(), Result.get(), E->getOperator(),
14109 E->getEllipsisLoc(), Out.get(), E->getEndLoc(), OrigNumExpansions);
14110 if (Result.isInvalid())
14111 return true;
14112 }
14113
14114 // If we had no init and an empty pack, and we're not retaining an expansion,
14115 // then produce a fallback value or error.
14116 if (Result.isUnset())
14117 return getDerived().RebuildEmptyCXXFoldExpr(E->getEllipsisLoc(),
14118 E->getOperator());
14119
14120 return Result;
14121}
14122
14123template <typename Derived>
14124ExprResult
14125TreeTransform<Derived>::TransformCXXParenListInitExpr(CXXParenListInitExpr *E) {
14126 SmallVector<Expr *, 4> TransformedInits;
14127 ArrayRef<Expr *> InitExprs = E->getInitExprs();
14128 if (TransformExprs(InitExprs.data(), InitExprs.size(), true,
14129 TransformedInits))
14130 return ExprError();
14131
14132 return getDerived().RebuildParenListExpr(E->getBeginLoc(), TransformedInits,
14133 E->getEndLoc());
14134}
14135
14136template<typename Derived>
14137ExprResult
14138TreeTransform<Derived>::TransformCXXStdInitializerListExpr(
14139 CXXStdInitializerListExpr *E) {
14140 return getDerived().TransformExpr(E->getSubExpr());
14141}
14142
14143template<typename Derived>
14144ExprResult
14145TreeTransform<Derived>::TransformObjCStringLiteral(ObjCStringLiteral *E) {
14146 return SemaRef.MaybeBindToTemporary(E);
14147}
14148
14149template<typename Derived>
14150ExprResult
14151TreeTransform<Derived>::TransformObjCBoolLiteralExpr(ObjCBoolLiteralExpr *E) {
14152 return E;
14153}
14154
14155template<typename Derived>
14156ExprResult
14157TreeTransform<Derived>::TransformObjCBoxedExpr(ObjCBoxedExpr *E) {
14158 ExprResult SubExpr = getDerived().TransformExpr(E->getSubExpr());
14159 if (SubExpr.isInvalid())
14160 return ExprError();
14161
14162 if (!getDerived().AlwaysRebuild() &&
14163 SubExpr.get() == E->getSubExpr())
14164 return E;
14165
14166 return getDerived().RebuildObjCBoxedExpr(E->getSourceRange(), SubExpr.get());
14167}
14168
14169template<typename Derived>
14170ExprResult
14171TreeTransform<Derived>::TransformObjCArrayLiteral(ObjCArrayLiteral *E) {
14172 // Transform each of the elements.
14173 SmallVector<Expr *, 8> Elements;
14174 bool ArgChanged = false;
14175 if (getDerived().TransformExprs(E->getElements(), E->getNumElements(),
14176 /*IsCall=*/false, Elements, &ArgChanged))
14177 return ExprError();
14178
14179 if (!getDerived().AlwaysRebuild() && !ArgChanged)
14180 return SemaRef.MaybeBindToTemporary(E);
14181
14182 return getDerived().RebuildObjCArrayLiteral(E->getSourceRange(),
14183 Elements.data(),
14184 Elements.size());
14185}
14186
14187template<typename Derived>
14188ExprResult
14189TreeTransform<Derived>::TransformObjCDictionaryLiteral(
14190 ObjCDictionaryLiteral *E) {
14191 // Transform each of the elements.
14192 SmallVector<ObjCDictionaryElement, 8> Elements;
14193 bool ArgChanged = false;
14194 for (unsigned I = 0, N = E->getNumElements(); I != N; ++I) {
14195 ObjCDictionaryElement OrigElement = E->getKeyValueElement(I);
14196
14197 if (OrigElement.isPackExpansion()) {
14198 // This key/value element is a pack expansion.
14199 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14200 getSema().collectUnexpandedParameterPacks(OrigElement.Key, Unexpanded);
14201 getSema().collectUnexpandedParameterPacks(OrigElement.Value, Unexpanded);
14202 assert(!Unexpanded.empty() && "Pack expansion without parameter packs?")(static_cast <bool> (!Unexpanded.empty() && "Pack expansion without parameter packs?"
) ? void (0) : __assert_fail ("!Unexpanded.empty() && \"Pack expansion without parameter packs?\""
, "clang/lib/Sema/TreeTransform.h", 14202, __extension__ __PRETTY_FUNCTION__
))
;
14203
14204 // Determine whether the set of unexpanded parameter packs can
14205 // and should be expanded.
14206 bool Expand = true;
14207 bool RetainExpansion = false;
14208 std::optional<unsigned> OrigNumExpansions = OrigElement.NumExpansions;
14209 std::optional<unsigned> NumExpansions = OrigNumExpansions;
14210 SourceRange PatternRange(OrigElement.Key->getBeginLoc(),
14211 OrigElement.Value->getEndLoc());
14212 if (getDerived().TryExpandParameterPacks(OrigElement.EllipsisLoc,
14213 PatternRange, Unexpanded, Expand,
14214 RetainExpansion, NumExpansions))
14215 return ExprError();
14216
14217 if (!Expand) {
14218 // The transform has determined that we should perform a simple
14219 // transformation on the pack expansion, producing another pack
14220 // expansion.
14221 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), -1);
14222 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14223 if (Key.isInvalid())
14224 return ExprError();
14225
14226 if (Key.get() != OrigElement.Key)
14227 ArgChanged = true;
14228
14229 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14230 if (Value.isInvalid())
14231 return ExprError();
14232
14233 if (Value.get() != OrigElement.Value)
14234 ArgChanged = true;
14235
14236 ObjCDictionaryElement Expansion = {
14237 Key.get(), Value.get(), OrigElement.EllipsisLoc, NumExpansions
14238 };
14239 Elements.push_back(Expansion);
14240 continue;
14241 }
14242
14243 // Record right away that the argument was changed. This needs
14244 // to happen even if the array expands to nothing.
14245 ArgChanged = true;
14246
14247 // The transform has determined that we should perform an elementwise
14248 // expansion of the pattern. Do so.
14249 for (unsigned I = 0; I != *NumExpansions; ++I) {
14250 Sema::ArgumentPackSubstitutionIndexRAII SubstIndex(getSema(), I);
14251 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14252 if (Key.isInvalid())
14253 return ExprError();
14254
14255 ExprResult Value = getDerived().TransformExpr(OrigElement.Value);
14256 if (Value.isInvalid())
14257 return ExprError();
14258
14259 ObjCDictionaryElement Element = {
14260 Key.get(), Value.get(), SourceLocation(), NumExpansions
14261 };
14262
14263 // If any unexpanded parameter packs remain, we still have a
14264 // pack expansion.
14265 // FIXME: Can this really happen?
14266 if (Key.get()->containsUnexpandedParameterPack() ||
14267 Value.get()->containsUnexpandedParameterPack())
14268 Element.EllipsisLoc = OrigElement.EllipsisLoc;
14269
14270 Elements.push_back(Element);
14271 }
14272
14273 // FIXME: Retain a pack expansion if RetainExpansion is true.
14274
14275 // We've finished with this pack expansion.
14276 continue;
14277 }
14278
14279 // Transform and check key.
14280 ExprResult Key = getDerived().TransformExpr(OrigElement.Key);
14281 if (Key.isInvalid())
14282 return ExprError();
14283
14284 if (Key.get() != OrigElement.Key)
14285 ArgChanged = true;
14286
14287 // Transform and check value.
14288 ExprResult Value
14289 = getDerived().TransformExpr(OrigElement.Value);
14290 if (Value.isInvalid())
14291 return ExprError();
14292
14293 if (Value.get() != OrigElement.Value)
14294 ArgChanged = true;
14295
14296 ObjCDictionaryElement Element = {Key.get(), Value.get(), SourceLocation(),
14297 std::nullopt};
14298 Elements.push_back(Element);
14299 }
14300
14301 if (!getDerived().AlwaysRebuild() && !ArgChanged)
14302 return SemaRef.MaybeBindToTemporary(E);
14303
14304 return getDerived().RebuildObjCDictionaryLiteral(E->getSourceRange(),
14305 Elements);
14306}
14307
14308template<typename Derived>
14309ExprResult
14310TreeTransform<Derived>::TransformObjCEncodeExpr(ObjCEncodeExpr *E) {
14311 TypeSourceInfo *EncodedTypeInfo
14312 = getDerived().TransformType(E->getEncodedTypeSourceInfo());
14313 if (!EncodedTypeInfo)
14314 return ExprError();
14315
14316 if (!getDerived().AlwaysRebuild() &&
14317 EncodedTypeInfo == E->getEncodedTypeSourceInfo())
14318 return E;
14319
14320 return getDerived().RebuildObjCEncodeExpr(E->getAtLoc(),
14321 EncodedTypeInfo,
14322 E->getRParenLoc());
14323}
14324
14325template<typename Derived>
14326ExprResult TreeTransform<Derived>::
14327TransformObjCIndirectCopyRestoreExpr(ObjCIndirectCopyRestoreExpr *E) {
14328 // This is a kind of implicit conversion, and it needs to get dropped
14329 // and recomputed for the same general reasons that ImplicitCastExprs
14330 // do, as well a more specific one: this expression is only valid when
14331 // it appears *immediately* as an argument expression.
14332 return getDerived().TransformExpr(E->getSubExpr());
14333}
14334
14335template<typename Derived>
14336ExprResult TreeTransform<Derived>::
14337TransformObjCBridgedCastExpr(ObjCBridgedCastExpr *E) {
14338 TypeSourceInfo *TSInfo
14339 = getDerived().TransformType(E->getTypeInfoAsWritten());
14340 if (!TSInfo)
14341 return ExprError();
14342
14343 ExprResult Result = getDerived().TransformExpr(E->getSubExpr());
14344 if (Result.isInvalid())
14345 return ExprError();
14346
14347 if (!getDerived().AlwaysRebuild() &&
14348 TSInfo == E->getTypeInfoAsWritten() &&
14349 Result.get() == E->getSubExpr())
14350 return E;
14351
14352 return SemaRef.BuildObjCBridgedCast(E->getLParenLoc(), E->getBridgeKind(),
14353 E->getBridgeKeywordLoc(), TSInfo,
14354 Result.get());
14355}
14356
14357template <typename Derived>
14358ExprResult TreeTransform<Derived>::TransformObjCAvailabilityCheckExpr(
14359 ObjCAvailabilityCheckExpr *E) {
14360 return E;
14361}
14362
14363template<typename Derived>
14364ExprResult
14365TreeTransform<Derived>::TransformObjCMessageExpr(ObjCMessageExpr *E) {
14366 // Transform arguments.
14367 bool ArgChanged = false;
14368 SmallVector<Expr*, 8> Args;
14369 Args.reserve(E->getNumArgs());
14370 if (getDerived().TransformExprs(E->getArgs(), E->getNumArgs(), false, Args,
14371 &ArgChanged))
14372 return ExprError();
14373
14374 if (E->getReceiverKind() == ObjCMessageExpr::Class) {
14375 // Class message: transform the receiver type.
14376 TypeSourceInfo *ReceiverTypeInfo
14377 = getDerived().TransformType(E->getClassReceiverTypeInfo());
14378 if (!ReceiverTypeInfo)
14379 return ExprError();
14380
14381 // If nothing changed, just retain the existing message send.
14382 if (!getDerived().AlwaysRebuild() &&
14383 ReceiverTypeInfo == E->getClassReceiverTypeInfo() && !ArgChanged)
14384 return SemaRef.MaybeBindToTemporary(E);
14385
14386 // Build a new class message send.
14387 SmallVector<SourceLocation, 16> SelLocs;
14388 E->getSelectorLocs(SelLocs);
14389 return getDerived().RebuildObjCMessageExpr(ReceiverTypeInfo,
14390 E->getSelector(),
14391 SelLocs,
14392 E->getMethodDecl(),
14393 E->getLeftLoc(),
14394 Args,
14395 E->getRightLoc());
14396 }
14397 else if (E->getReceiverKind() == ObjCMessageExpr::SuperClass ||
14398 E->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14399 if (!E->getMethodDecl())
14400 return ExprError();
14401
14402 // Build a new class message send to 'super'.
14403 SmallVector<SourceLocation, 16> SelLocs;
14404 E->getSelectorLocs(SelLocs);
14405 return getDerived().RebuildObjCMessageExpr(E->getSuperLoc(),
14406 E->getSelector(),
14407 SelLocs,
14408 E->getReceiverType(),
14409 E->getMethodDecl(),
14410 E->getLeftLoc(),
14411 Args,
14412 E->getRightLoc());
14413 }
14414
14415 // Instance message: transform the receiver
14416 assert(E->getReceiverKind() == ObjCMessageExpr::Instance &&(static_cast <bool> (E->getReceiverKind() == ObjCMessageExpr
::Instance && "Only class and instance messages may be instantiated"
) ? void (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "clang/lib/Sema/TreeTransform.h", 14417, __extension__ __PRETTY_FUNCTION__
))
14417 "Only class and instance messages may be instantiated")(static_cast <bool> (E->getReceiverKind() == ObjCMessageExpr
::Instance && "Only class and instance messages may be instantiated"
) ? void (0) : __assert_fail ("E->getReceiverKind() == ObjCMessageExpr::Instance && \"Only class and instance messages may be instantiated\""
, "clang/lib/Sema/TreeTransform.h", 14417, __extension__ __PRETTY_FUNCTION__
))
;
14418 ExprResult Receiver
14419 = getDerived().TransformExpr(E->getInstanceReceiver());
14420 if (Receiver.isInvalid())
14421 return ExprError();
14422
14423 // If nothing changed, just retain the existing message send.
14424 if (!getDerived().AlwaysRebuild() &&
14425 Receiver.get() == E->getInstanceReceiver() && !ArgChanged)
14426 return SemaRef.MaybeBindToTemporary(E);
14427
14428 // Build a new instance message send.
14429 SmallVector<SourceLocation, 16> SelLocs;
14430 E->getSelectorLocs(SelLocs);
14431 return getDerived().RebuildObjCMessageExpr(Receiver.get(),
14432 E->getSelector(),
14433 SelLocs,
14434 E->getMethodDecl(),
14435 E->getLeftLoc(),
14436 Args,
14437 E->getRightLoc());
14438}
14439
14440template<typename Derived>
14441ExprResult
14442TreeTransform<Derived>::TransformObjCSelectorExpr(ObjCSelectorExpr *E) {
14443 return E;
14444}
14445
14446template<typename Derived>
14447ExprResult
14448TreeTransform<Derived>::TransformObjCProtocolExpr(ObjCProtocolExpr *E) {
14449 return E;
14450}
14451
14452template<typename Derived>
14453ExprResult
14454TreeTransform<Derived>::TransformObjCIvarRefExpr(ObjCIvarRefExpr *E) {
14455 // Transform the base expression.
14456 ExprResult Base = getDerived().TransformExpr(E->getBase());
14457 if (Base.isInvalid())
14458 return ExprError();
14459
14460 // We don't need to transform the ivar; it will never change.
14461
14462 // If nothing changed, just retain the existing expression.
14463 if (!getDerived().AlwaysRebuild() &&
14464 Base.get() == E->getBase())
14465 return E;
14466
14467 return getDerived().RebuildObjCIvarRefExpr(Base.get(), E->getDecl(),
14468 E->getLocation(),
14469 E->isArrow(), E->isFreeIvar());
14470}
14471
14472template<typename Derived>
14473ExprResult
14474TreeTransform<Derived>::TransformObjCPropertyRefExpr(ObjCPropertyRefExpr *E) {
14475 // 'super' and types never change. Property never changes. Just
14476 // retain the existing expression.
14477 if (!E->isObjectReceiver())
14478 return E;
14479
14480 // Transform the base expression.
14481 ExprResult Base = getDerived().TransformExpr(E->getBase());
14482 if (Base.isInvalid())
14483 return ExprError();
14484
14485 // We don't need to transform the property; it will never change.
14486
14487 // If nothing changed, just retain the existing expression.
14488 if (!getDerived().AlwaysRebuild() &&
14489 Base.get() == E->getBase())
14490 return E;
14491
14492 if (E->isExplicitProperty())
14493 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14494 E->getExplicitProperty(),
14495 E->getLocation());
14496
14497 return getDerived().RebuildObjCPropertyRefExpr(Base.get(),
14498 SemaRef.Context.PseudoObjectTy,
14499 E->getImplicitPropertyGetter(),
14500 E->getImplicitPropertySetter(),
14501 E->getLocation());
14502}
14503
14504template<typename Derived>
14505ExprResult
14506TreeTransform<Derived>::TransformObjCSubscriptRefExpr(ObjCSubscriptRefExpr *E) {
14507 // Transform the base expression.
14508 ExprResult Base = getDerived().TransformExpr(E->getBaseExpr());
14509 if (Base.isInvalid())
14510 return ExprError();
14511
14512 // Transform the key expression.
14513 ExprResult Key = getDerived().TransformExpr(E->getKeyExpr());
14514 if (Key.isInvalid())
14515 return ExprError();
14516
14517 // If nothing changed, just retain the existing expression.
14518 if (!getDerived().AlwaysRebuild() &&
14519 Key.get() == E->getKeyExpr() && Base.get() == E->getBaseExpr())
14520 return E;
14521
14522 return getDerived().RebuildObjCSubscriptRefExpr(E->getRBracket(),
14523 Base.get(), Key.get(),
14524 E->getAtIndexMethodDecl(),
14525 E->setAtIndexMethodDecl());
14526}
14527
14528template<typename Derived>
14529ExprResult
14530TreeTransform<Derived>::TransformObjCIsaExpr(ObjCIsaExpr *E) {
14531 // Transform the base expression.
14532 ExprResult Base = getDerived().TransformExpr(E->getBase());
14533 if (Base.isInvalid())
14534 return ExprError();
14535
14536 // If nothing changed, just retain the existing expression.
14537 if (!getDerived().AlwaysRebuild() &&
14538 Base.get() == E->getBase())
14539 return E;
14540
14541 return getDerived().RebuildObjCIsaExpr(Base.get(), E->getIsaMemberLoc(),
14542 E->getOpLoc(),
14543 E->isArrow());
14544}
14545
14546template<typename Derived>
14547ExprResult
14548TreeTransform<Derived>::TransformShuffleVectorExpr(ShuffleVectorExpr *E) {
14549 bool ArgumentChanged = false;
14550 SmallVector<Expr*, 8> SubExprs;
14551 SubExprs.reserve(E->getNumSubExprs());
14552 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14553 SubExprs, &ArgumentChanged))
14554 return ExprError();
14555
14556 if (!getDerived().AlwaysRebuild() &&
14557 !ArgumentChanged)
14558 return E;
14559
14560 return getDerived().RebuildShuffleVectorExpr(E->getBuiltinLoc(),
14561 SubExprs,
14562 E->getRParenLoc());
14563}
14564
14565template<typename Derived>
14566ExprResult
14567TreeTransform<Derived>::TransformConvertVectorExpr(ConvertVectorExpr *E) {
14568 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14569 if (SrcExpr.isInvalid())
14570 return ExprError();
14571
14572 TypeSourceInfo *Type = getDerived().TransformType(E->getTypeSourceInfo());
14573 if (!Type)
14574 return ExprError();
14575
14576 if (!getDerived().AlwaysRebuild() &&
14577 Type == E->getTypeSourceInfo() &&
14578 SrcExpr.get() == E->getSrcExpr())
14579 return E;
14580
14581 return getDerived().RebuildConvertVectorExpr(E->getBuiltinLoc(),
14582 SrcExpr.get(), Type,
14583 E->getRParenLoc());
14584}
14585
14586template<typename Derived>
14587ExprResult
14588TreeTransform<Derived>::TransformBlockExpr(BlockExpr *E) {
14589 BlockDecl *oldBlock = E->getBlockDecl();
14590
14591 SemaRef.ActOnBlockStart(E->getCaretLocation(), /*Scope=*/nullptr);
14592 BlockScopeInfo *blockScope = SemaRef.getCurBlock();
14593
14594 blockScope->TheDecl->setIsVariadic(oldBlock->isVariadic());
14595 blockScope->TheDecl->setBlockMissingReturnType(
14596 oldBlock->blockMissingReturnType());
14597
14598 SmallVector<ParmVarDecl*, 4> params;
14599 SmallVector<QualType, 4> paramTypes;
14600
14601 const FunctionProtoType *exprFunctionType = E->getFunctionType();
14602
14603 // Parameter substitution.
14604 Sema::ExtParameterInfoBuilder extParamInfos;
14605 if (getDerived().TransformFunctionTypeParams(
14606 E->getCaretLocation(), oldBlock->parameters(), nullptr,
14607 exprFunctionType->getExtParameterInfosOrNull(), paramTypes, &params,
14608 extParamInfos)) {
14609 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14610 return ExprError();
14611 }
14612
14613 QualType exprResultType =
14614 getDerived().TransformType(exprFunctionType->getReturnType());
14615
14616 auto epi = exprFunctionType->getExtProtoInfo();
14617 epi.ExtParameterInfos = extParamInfos.getPointerOrNull(paramTypes.size());
14618
14619 QualType functionType =
14620 getDerived().RebuildFunctionProtoType(exprResultType, paramTypes, epi);
14621 blockScope->FunctionType = functionType;
14622
14623 // Set the parameters on the block decl.
14624 if (!params.empty())
14625 blockScope->TheDecl->setParams(params);
14626
14627 if (!oldBlock->blockMissingReturnType()) {
14628 blockScope->HasImplicitReturnType = false;
14629 blockScope->ReturnType = exprResultType;
14630 }
14631
14632 // Transform the body
14633 StmtResult body = getDerived().TransformStmt(E->getBody());
14634 if (body.isInvalid()) {
14635 getSema().ActOnBlockError(E->getCaretLocation(), /*Scope=*/nullptr);
14636 return ExprError();
14637 }
14638
14639#ifndef NDEBUG
14640 // In builds with assertions, make sure that we captured everything we
14641 // captured before.
14642 if (!SemaRef.getDiagnostics().hasErrorOccurred()) {
14643 for (const auto &I : oldBlock->captures()) {
14644 VarDecl *oldCapture = I.getVariable();
14645
14646 // Ignore parameter packs.
14647 if (oldCapture->isParameterPack())
14648 continue;
14649
14650 VarDecl *newCapture =
14651 cast<VarDecl>(getDerived().TransformDecl(E->getCaretLocation(),
14652 oldCapture));
14653 assert(blockScope->CaptureMap.count(newCapture))(static_cast <bool> (blockScope->CaptureMap.count(newCapture
)) ? void (0) : __assert_fail ("blockScope->CaptureMap.count(newCapture)"
, "clang/lib/Sema/TreeTransform.h", 14653, __extension__ __PRETTY_FUNCTION__
))
;
14654 }
14655
14656 // The this pointer may not be captured by the instantiated block, even when
14657 // it's captured by the original block, if the expression causing the
14658 // capture is in the discarded branch of a constexpr if statement.
14659 assert((!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) &&(static_cast <bool> ((!blockScope->isCXXThisCaptured
() || oldBlock->capturesCXXThis()) && "this pointer isn't captured in the old block"
) ? void (0) : __assert_fail ("(!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) && \"this pointer isn't captured in the old block\""
, "clang/lib/Sema/TreeTransform.h", 14660, __extension__ __PRETTY_FUNCTION__
))
14660 "this pointer isn't captured in the old block")(static_cast <bool> ((!blockScope->isCXXThisCaptured
() || oldBlock->capturesCXXThis()) && "this pointer isn't captured in the old block"
) ? void (0) : __assert_fail ("(!blockScope->isCXXThisCaptured() || oldBlock->capturesCXXThis()) && \"this pointer isn't captured in the old block\""
, "clang/lib/Sema/TreeTransform.h", 14660, __extension__ __PRETTY_FUNCTION__
))
;
14661 }
14662#endif
14663
14664 return SemaRef.ActOnBlockStmtExpr(E->getCaretLocation(), body.get(),
14665 /*Scope=*/nullptr);
14666}
14667
14668template<typename Derived>
14669ExprResult
14670TreeTransform<Derived>::TransformAsTypeExpr(AsTypeExpr *E) {
14671 ExprResult SrcExpr = getDerived().TransformExpr(E->getSrcExpr());
14672 if (SrcExpr.isInvalid())
14673 return ExprError();
14674
14675 QualType Type = getDerived().TransformType(E->getType());
14676
14677 return SemaRef.BuildAsTypeExpr(SrcExpr.get(), Type, E->getBuiltinLoc(),
14678 E->getRParenLoc());
14679}
14680
14681template<typename Derived>
14682ExprResult
14683TreeTransform<Derived>::TransformAtomicExpr(AtomicExpr *E) {
14684 bool ArgumentChanged = false;
14685 SmallVector<Expr*, 8> SubExprs;
14686 SubExprs.reserve(E->getNumSubExprs());
14687 if (getDerived().TransformExprs(E->getSubExprs(), E->getNumSubExprs(), false,
14688 SubExprs, &ArgumentChanged))
14689 return ExprError();
14690
14691 if (!getDerived().AlwaysRebuild() &&
14692 !ArgumentChanged)
14693 return E;
14694
14695 return getDerived().RebuildAtomicExpr(E->getBuiltinLoc(), SubExprs,
14696 E->getOp(), E->getRParenLoc());
14697}
14698
14699//===----------------------------------------------------------------------===//
14700// Type reconstruction
14701//===----------------------------------------------------------------------===//
14702
14703template<typename Derived>
14704QualType TreeTransform<Derived>::RebuildPointerType(QualType PointeeType,
14705 SourceLocation Star) {
14706 return SemaRef.BuildPointerType(PointeeType, Star,
14707 getDerived().getBaseEntity());
14708}
14709
14710template<typename Derived>
14711QualType TreeTransform<Derived>::RebuildBlockPointerType(QualType PointeeType,
14712 SourceLocation Star) {
14713 return SemaRef.BuildBlockPointerType(PointeeType, Star,
14714 getDerived().getBaseEntity());
14715}
14716
14717template<typename Derived>
14718QualType
14719TreeTransform<Derived>::RebuildReferenceType(QualType ReferentType,
14720 bool WrittenAsLValue,
14721 SourceLocation Sigil) {
14722 return SemaRef.BuildReferenceType(ReferentType, WrittenAsLValue,
14723 Sigil, getDerived().getBaseEntity());
14724}
14725
14726template<typename Derived>
14727QualType
14728TreeTransform<Derived>::RebuildMemberPointerType(QualType PointeeType,
14729 QualType ClassType,
14730 SourceLocation Sigil) {
14731 return SemaRef.BuildMemberPointerType(PointeeType, ClassType, Sigil,
14732 getDerived().getBaseEntity());
14733}
14734
14735template<typename Derived>
14736QualType TreeTransform<Derived>::RebuildObjCTypeParamType(
14737 const ObjCTypeParamDecl *Decl,
14738 SourceLocation ProtocolLAngleLoc,
14739 ArrayRef<ObjCProtocolDecl *> Protocols,
14740 ArrayRef<SourceLocation> ProtocolLocs,
14741 SourceLocation ProtocolRAngleLoc) {
14742 return SemaRef.BuildObjCTypeParamType(Decl,
14743 ProtocolLAngleLoc, Protocols,
14744 ProtocolLocs, ProtocolRAngleLoc,
14745 /*FailOnError=*/true);
14746}
14747
14748template<typename Derived>
14749QualType TreeTransform<Derived>::RebuildObjCObjectType(
14750 QualType BaseType,
14751 SourceLocation Loc,
14752 SourceLocation TypeArgsLAngleLoc,
14753 ArrayRef<TypeSourceInfo *> TypeArgs,
14754 SourceLocation TypeArgsRAngleLoc,
14755 SourceLocation ProtocolLAngleLoc,
14756 ArrayRef<ObjCProtocolDecl *> Protocols,
14757 ArrayRef<SourceLocation> ProtocolLocs,
14758 SourceLocation ProtocolRAngleLoc) {
14759 return SemaRef.BuildObjCObjectType(BaseType, Loc, TypeArgsLAngleLoc, TypeArgs,
14760 TypeArgsRAngleLoc, ProtocolLAngleLoc,
14761 Protocols, ProtocolLocs, ProtocolRAngleLoc,
14762 /*FailOnError=*/true,
14763 /*Rebuilding=*/true);
14764}
14765
14766template<typename Derived>
14767QualType TreeTransform<Derived>::RebuildObjCObjectPointerType(
14768 QualType PointeeType,
14769 SourceLocation Star) {
14770 return SemaRef.Context.getObjCObjectPointerType(PointeeType);
14771}
14772
14773template<typename Derived>
14774QualType
14775TreeTransform<Derived>::RebuildArrayType(QualType ElementType,
14776 ArrayType::ArraySizeModifier SizeMod,
14777 const llvm::APInt *Size,
14778 Expr *SizeExpr,
14779 unsigned IndexTypeQuals,
14780 SourceRange BracketsRange) {
14781 if (SizeExpr || !Size)
14782 return SemaRef.BuildArrayType(ElementType, SizeMod, SizeExpr,
14783 IndexTypeQuals, BracketsRange,
14784 getDerived().getBaseEntity());
14785
14786 QualType Types[] = {
14787 SemaRef.Context.UnsignedCharTy, SemaRef.Context.UnsignedShortTy,
14788 SemaRef.Context.UnsignedIntTy, SemaRef.Context.UnsignedLongTy,
14789 SemaRef.Context.UnsignedLongLongTy, SemaRef.Context.UnsignedInt128Ty
14790 };
14791 QualType SizeType;
14792 for (const auto &T : Types)
14793 if (Size->getBitWidth() == SemaRef.Context.getIntWidth(T)) {
14794 SizeType = T;
14795 break;
14796 }
14797
14798 // Note that we can return a VariableArrayType here in the case where
14799 // the element type was a dependent VariableArrayType.
14800 IntegerLiteral *ArraySize
14801 = IntegerLiteral::Create(SemaRef.Context, *Size, SizeType,
14802 /*FIXME*/BracketsRange.getBegin());
14803 return SemaRef.BuildArrayType(ElementType, SizeMod, ArraySize,
14804 IndexTypeQuals, BracketsRange,
14805 getDerived().getBaseEntity());
14806}
14807
14808template<typename Derived>
14809QualType
14810TreeTransform<Derived>::RebuildConstantArrayType(QualType ElementType,
14811 ArrayType::ArraySizeModifier SizeMod,
14812 const llvm::APInt &Size,
14813 Expr *SizeExpr,
14814 unsigned IndexTypeQuals,
14815 SourceRange BracketsRange) {
14816 return getDerived().RebuildArrayType(ElementType, SizeMod, &Size, SizeExpr,
14817 IndexTypeQuals, BracketsRange);
14818}
14819
14820template<typename Derived>
14821QualType
14822TreeTransform<Derived>::RebuildIncompleteArrayType(QualType ElementType,
14823 ArrayType::ArraySizeModifier SizeMod,
14824 unsigned IndexTypeQuals,
14825 SourceRange BracketsRange) {
14826 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr, nullptr,
14827 IndexTypeQuals, BracketsRange);
14828}
14829
14830template<typename Derived>
14831QualType
14832TreeTransform<Derived>::RebuildVariableArrayType(QualType ElementType,
14833 ArrayType::ArraySizeModifier SizeMod,
14834 Expr *SizeExpr,
14835 unsigned IndexTypeQuals,
14836 SourceRange BracketsRange) {
14837 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14838 SizeExpr,
14839 IndexTypeQuals, BracketsRange);
14840}
14841
14842template<typename Derived>
14843QualType
14844TreeTransform<Derived>::RebuildDependentSizedArrayType(QualType ElementType,
14845 ArrayType::ArraySizeModifier SizeMod,
14846 Expr *SizeExpr,
14847 unsigned IndexTypeQuals,
14848 SourceRange BracketsRange) {
14849 return getDerived().RebuildArrayType(ElementType, SizeMod, nullptr,
14850 SizeExpr,
14851 IndexTypeQuals, BracketsRange);
14852}
14853
14854template <typename Derived>
14855QualType TreeTransform<Derived>::RebuildDependentAddressSpaceType(
14856 QualType PointeeType, Expr *AddrSpaceExpr, SourceLocation AttributeLoc) {
14857 return SemaRef.BuildAddressSpaceAttr(PointeeType, AddrSpaceExpr,
14858 AttributeLoc);
14859}
14860
14861template <typename Derived>
14862QualType
14863TreeTransform<Derived>::RebuildVectorType(QualType ElementType,
14864 unsigned NumElements,
14865 VectorType::VectorKind VecKind) {
14866 // FIXME: semantic checking!
14867 return SemaRef.Context.getVectorType(ElementType, NumElements, VecKind);
14868}
14869
14870template <typename Derived>
14871QualType TreeTransform<Derived>::RebuildDependentVectorType(
14872 QualType ElementType, Expr *SizeExpr, SourceLocation AttributeLoc,
14873 VectorType::VectorKind VecKind) {
14874 return SemaRef.BuildVectorType(ElementType, SizeExpr, AttributeLoc);
14875}
14876
14877template<typename Derived>
14878QualType TreeTransform<Derived>::RebuildExtVectorType(QualType ElementType,
14879 unsigned NumElements,
14880 SourceLocation AttributeLoc) {
14881 llvm::APInt numElements(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
14882 NumElements, true);
14883 IntegerLiteral *VectorSize
14884 = IntegerLiteral::Create(SemaRef.Context, numElements, SemaRef.Context.IntTy,
14885 AttributeLoc);
14886 return SemaRef.BuildExtVectorType(ElementType, VectorSize, AttributeLoc);
14887}
14888
14889template<typename Derived>
14890QualType
14891TreeTransform<Derived>::RebuildDependentSizedExtVectorType(QualType ElementType,
14892 Expr *SizeExpr,
14893 SourceLocation AttributeLoc) {
14894 return SemaRef.BuildExtVectorType(ElementType, SizeExpr, AttributeLoc);
14895}
14896
14897template <typename Derived>
14898QualType TreeTransform<Derived>::RebuildConstantMatrixType(
14899 QualType ElementType, unsigned NumRows, unsigned NumColumns) {
14900 return SemaRef.Context.getConstantMatrixType(ElementType, NumRows,
14901 NumColumns);
14902}
14903
14904template <typename Derived>
14905QualType TreeTransform<Derived>::RebuildDependentSizedMatrixType(
14906 QualType ElementType, Expr *RowExpr, Expr *ColumnExpr,
14907 SourceLocation AttributeLoc) {
14908 return SemaRef.BuildMatrixType(ElementType, RowExpr, ColumnExpr,
14909 AttributeLoc);
14910}
14911
14912template<typename Derived>
14913QualType TreeTransform<Derived>::RebuildFunctionProtoType(
14914 QualType T,
14915 MutableArrayRef<QualType> ParamTypes,
14916 const FunctionProtoType::ExtProtoInfo &EPI) {
14917 return SemaRef.BuildFunctionType(T, ParamTypes,
14918 getDerived().getBaseLocation(),
14919 getDerived().getBaseEntity(),
14920 EPI);
14921}
14922
14923template<typename Derived>
14924QualType TreeTransform<Derived>::RebuildFunctionNoProtoType(QualType T) {
14925 return SemaRef.Context.getFunctionNoProtoType(T);
14926}
14927
14928template<typename Derived>
14929QualType TreeTransform<Derived>::RebuildUnresolvedUsingType(SourceLocation Loc,
14930 Decl *D) {
14931 assert(D && "no decl found")(static_cast <bool> (D && "no decl found") ? void
(0) : __assert_fail ("D && \"no decl found\"", "clang/lib/Sema/TreeTransform.h"
, 14931, __extension__ __PRETTY_FUNCTION__))
;
14932 if (D->isInvalidDecl()) return QualType();
14933
14934 // FIXME: Doesn't account for ObjCInterfaceDecl!
14935 if (auto *UPD = dyn_cast<UsingPackDecl>(D)) {
14936 // A valid resolved using typename pack expansion decl can have multiple
14937 // UsingDecls, but they must each have exactly one type, and it must be
14938 // the same type in every case. But we must have at least one expansion!
14939 if (UPD->expansions().empty()) {
14940 getSema().Diag(Loc, diag::err_using_pack_expansion_empty)
14941 << UPD->isCXXClassMember() << UPD;
14942 return QualType();
14943 }
14944
14945 // We might still have some unresolved types. Try to pick a resolved type
14946 // if we can. The final instantiation will check that the remaining
14947 // unresolved types instantiate to the type we pick.
14948 QualType FallbackT;
14949 QualType T;
14950 for (auto *E : UPD->expansions()) {
14951 QualType ThisT = RebuildUnresolvedUsingType(Loc, E);
14952 if (ThisT.isNull())
14953 continue;
14954 else if (ThisT->getAs<UnresolvedUsingType>())
14955 FallbackT = ThisT;
14956 else if (T.isNull())
14957 T = ThisT;
14958 else
14959 assert(getSema().Context.hasSameType(ThisT, T) &&(static_cast <bool> (getSema().Context.hasSameType(ThisT
, T) && "mismatched resolved types in using pack expansion"
) ? void (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 14960, __extension__ __PRETTY_FUNCTION__
))
14960 "mismatched resolved types in using pack expansion")(static_cast <bool> (getSema().Context.hasSameType(ThisT
, T) && "mismatched resolved types in using pack expansion"
) ? void (0) : __assert_fail ("getSema().Context.hasSameType(ThisT, T) && \"mismatched resolved types in using pack expansion\""
, "clang/lib/Sema/TreeTransform.h", 14960, __extension__ __PRETTY_FUNCTION__
))
;
14961 }
14962 return T.isNull() ? FallbackT : T;
14963 } else if (auto *Using = dyn_cast<UsingDecl>(D)) {
14964 assert(Using->hasTypename() &&(static_cast <bool> (Using->hasTypename() &&
"UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? void (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "clang/lib/Sema/TreeTransform.h", 14965, __extension__ __PRETTY_FUNCTION__
))
14965 "UnresolvedUsingTypenameDecl transformed to non-typename using")(static_cast <bool> (Using->hasTypename() &&
"UnresolvedUsingTypenameDecl transformed to non-typename using"
) ? void (0) : __assert_fail ("Using->hasTypename() && \"UnresolvedUsingTypenameDecl transformed to non-typename using\""
, "clang/lib/Sema/TreeTransform.h", 14965, __extension__ __PRETTY_FUNCTION__
))
;
14966
14967 // A valid resolved using typename decl points to exactly one type decl.
14968 assert(++Using->shadow_begin() == Using->shadow_end())(static_cast <bool> (++Using->shadow_begin() == Using
->shadow_end()) ? void (0) : __assert_fail ("++Using->shadow_begin() == Using->shadow_end()"
, "clang/lib/Sema/TreeTransform.h", 14968, __extension__ __PRETTY_FUNCTION__
))
;
14969
14970 UsingShadowDecl *Shadow = *Using->shadow_begin();
14971 if (SemaRef.DiagnoseUseOfDecl(Shadow->getTargetDecl(), Loc))
14972 return QualType();
14973 return SemaRef.Context.getUsingType(
14974 Shadow, SemaRef.Context.getTypeDeclType(
14975 cast<TypeDecl>(Shadow->getTargetDecl())));
14976 } else {
14977 assert(isa<UnresolvedUsingTypenameDecl>(D) &&(static_cast <bool> (isa<UnresolvedUsingTypenameDecl
>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? void (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "clang/lib/Sema/TreeTransform.h", 14978, __extension__ __PRETTY_FUNCTION__
))
14978 "UnresolvedUsingTypenameDecl transformed to non-using decl")(static_cast <bool> (isa<UnresolvedUsingTypenameDecl
>(D) && "UnresolvedUsingTypenameDecl transformed to non-using decl"
) ? void (0) : __assert_fail ("isa<UnresolvedUsingTypenameDecl>(D) && \"UnresolvedUsingTypenameDecl transformed to non-using decl\""
, "clang/lib/Sema/TreeTransform.h", 14978, __extension__ __PRETTY_FUNCTION__
))
;
14979 return SemaRef.Context.getTypeDeclType(
14980 cast<UnresolvedUsingTypenameDecl>(D));
14981 }
14982}
14983
14984template <typename Derived>
14985QualType TreeTransform<Derived>::RebuildTypeOfExprType(Expr *E, SourceLocation,
14986 TypeOfKind Kind) {
14987 return SemaRef.BuildTypeofExprType(E, Kind);
14988}
14989
14990template<typename Derived>
14991QualType TreeTransform<Derived>::RebuildTypeOfType(QualType Underlying,
14992 TypeOfKind Kind) {
14993 return SemaRef.Context.getTypeOfType(Underlying, Kind);
14994}
14995
14996template <typename Derived>
14997QualType TreeTransform<Derived>::RebuildDecltypeType(Expr *E, SourceLocation) {
14998 return SemaRef.BuildDecltypeType(E);
14999}
15000
15001template<typename Derived>
15002QualType TreeTransform<Derived>::RebuildUnaryTransformType(QualType BaseType,
15003 UnaryTransformType::UTTKind UKind,
15004 SourceLocation Loc) {
15005 return SemaRef.BuildUnaryTransformType(BaseType, UKind, Loc);
15006}
15007
15008template<typename Derived>
15009QualType TreeTransform<Derived>::RebuildTemplateSpecializationType(
15010 TemplateName Template,
15011 SourceLocation TemplateNameLoc,
15012 TemplateArgumentListInfo &TemplateArgs) {
15013 return SemaRef.CheckTemplateIdType(Template, TemplateNameLoc, TemplateArgs);
15014}
15015
15016template<typename Derived>
15017QualType TreeTransform<Derived>::RebuildAtomicType(QualType ValueType,
15018 SourceLocation KWLoc) {
15019 return SemaRef.BuildAtomicType(ValueType, KWLoc);
15020}
15021
15022template<typename Derived>
15023QualType TreeTransform<Derived>::RebuildPipeType(QualType ValueType,
15024 SourceLocation KWLoc,
15025 bool isReadPipe) {
15026 return isReadPipe ? SemaRef.BuildReadPipeType(ValueType, KWLoc)
15027 : SemaRef.BuildWritePipeType(ValueType, KWLoc);
15028}
15029
15030template <typename Derived>
15031QualType TreeTransform<Derived>::RebuildBitIntType(bool IsUnsigned,
15032 unsigned NumBits,
15033 SourceLocation Loc) {
15034 llvm::APInt NumBitsAP(SemaRef.Context.getIntWidth(SemaRef.Context.IntTy),
15035 NumBits, true);
15036 IntegerLiteral *Bits = IntegerLiteral::Create(SemaRef.Context, NumBitsAP,
15037 SemaRef.Context.IntTy, Loc);
15038 return SemaRef.BuildBitIntType(IsUnsigned, Bits, Loc);
15039}
15040
15041template <typename Derived>
15042QualType TreeTransform<Derived>::RebuildDependentBitIntType(
15043 bool IsUnsigned, Expr *NumBitsExpr, SourceLocation Loc) {
15044 return SemaRef.BuildBitIntType(IsUnsigned, NumBitsExpr, Loc);
15045}
15046
15047template<typename Derived>
15048TemplateName
15049TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15050 bool TemplateKW,
15051 TemplateDecl *Template) {
15052 return SemaRef.Context.getQualifiedTemplateName(SS.getScopeRep(), TemplateKW,
15053 TemplateName(Template));
15054}
15055
15056template<typename Derived>
15057TemplateName
15058TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15059 SourceLocation TemplateKWLoc,
15060 const IdentifierInfo &Name,
15061 SourceLocation NameLoc,
15062 QualType ObjectType,
15063 NamedDecl *FirstQualifierInScope,
15064 bool AllowInjectedClassName) {
15065 UnqualifiedId TemplateName;
15066 TemplateName.setIdentifier(&Name, NameLoc);
15067 Sema::TemplateTy Template;
15068 getSema().ActOnTemplateName(/*Scope=*/nullptr, SS, TemplateKWLoc,
15069 TemplateName, ParsedType::make(ObjectType),
15070 /*EnteringContext=*/false, Template,
15071 AllowInjectedClassName);
15072 return Template.get();
15073}
15074
15075template<typename Derived>
15076TemplateName
15077TreeTransform<Derived>::RebuildTemplateName(CXXScopeSpec &SS,
15078 SourceLocation TemplateKWLoc,
15079 OverloadedOperatorKind Operator,
15080 SourceLocation NameLoc,
15081 QualType ObjectType,
15082 bool AllowInjectedClassName) {
15083 UnqualifiedId Name;
15084 // FIXME: Bogus location information.
15085 SourceLocation SymbolLocations[3] = { NameLoc, NameLoc, NameLoc };
15086 Name.setOperatorFunctionId(NameLoc, Operator, SymbolLocations);
15087 Sema::TemplateTy Template;
15088 getSema().ActOnTemplateName(
15089 /*Scope=*/nullptr, SS, TemplateKWLoc, Name, ParsedType::make(ObjectType),
15090 /*EnteringContext=*/false, Template, AllowInjectedClassName);
15091 return Template.get();
15092}
15093
15094template<typename Derived>
15095ExprResult
15096TreeTransform<Derived>::RebuildCXXOperatorCallExpr(OverloadedOperatorKind Op,
15097 SourceLocation OpLoc,
15098 Expr *OrigCallee,
15099 Expr *First,
15100 Expr *Second) {
15101 Expr *Callee = OrigCallee->IgnoreParenCasts();
15102 bool isPostIncDec = Second && (Op == OO_PlusPlus || Op == OO_MinusMinus);
15103
15104 if (First->getObjectKind() == OK_ObjCProperty) {
15105 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15106 if (BinaryOperator::isAssignmentOp(Opc))
15107 return SemaRef.checkPseudoObjectAssignment(/*Scope=*/nullptr, OpLoc, Opc,
15108 First, Second);
15109 ExprResult Result = SemaRef.CheckPlaceholderExpr(First);
15110 if (Result.isInvalid())
15111 return ExprError();
15112 First = Result.get();
15113 }
15114
15115 if (Second && Second->getObjectKind() == OK_ObjCProperty) {
15116 ExprResult Result = SemaRef.CheckPlaceholderExpr(Second);
15117 if (Result.isInvalid())
15118 return ExprError();
15119 Second = Result.get();
15120 }
15121
15122 // Determine whether this should be a builtin operation.
15123 if (Op == OO_Subscript) {
15124 if (!First->getType()->isOverloadableType() &&
15125 !Second->getType()->isOverloadableType())
15126 return getSema().CreateBuiltinArraySubscriptExpr(
15127 First, Callee->getBeginLoc(), Second, OpLoc);
15128 } else if (Op == OO_Arrow) {
15129 // It is possible that the type refers to a RecoveryExpr created earlier
15130 // in the tree transformation.
15131 if (First->getType()->isDependentType())
15132 return ExprError();
15133 // -> is never a builtin operation.
15134 return SemaRef.BuildOverloadedArrowExpr(nullptr, First, OpLoc);
15135 } else if (Second == nullptr || isPostIncDec) {
15136 if (!First->getType()->isOverloadableType() ||
15137 (Op == OO_Amp && getSema().isQualifiedMemberAccess(First))) {
15138 // The argument is not of overloadable type, or this is an expression
15139 // of the form &Class::member, so try to create a built-in unary
15140 // operation.
15141 UnaryOperatorKind Opc
15142 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15143
15144 return getSema().CreateBuiltinUnaryOp(OpLoc, Opc, First);
15145 }
15146 } else {
15147 if (!First->getType()->isOverloadableType() &&
15148 !Second->getType()->isOverloadableType()) {
15149 // Neither of the arguments is an overloadable type, so try to
15150 // create a built-in binary operation.
15151 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15152 ExprResult Result
15153 = SemaRef.CreateBuiltinBinOp(OpLoc, Opc, First, Second);
15154 if (Result.isInvalid())
15155 return ExprError();
15156
15157 return Result;
15158 }
15159 }
15160
15161 // Compute the transformed set of functions (and function templates) to be
15162 // used during overload resolution.
15163 UnresolvedSet<16> Functions;
15164 bool RequiresADL;
15165
15166 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(Callee)) {
15167 Functions.append(ULE->decls_begin(), ULE->decls_end());
15168 // If the overload could not be resolved in the template definition
15169 // (because we had a dependent argument), ADL is performed as part of
15170 // template instantiation.
15171 RequiresADL = ULE->requiresADL();
15172 } else {
15173 // If we've resolved this to a particular non-member function, just call
15174 // that function. If we resolved it to a member function,
15175 // CreateOverloaded* will find that function for us.
15176 NamedDecl *ND = cast<DeclRefExpr>(Callee)->getDecl();
15177 if (!isa<CXXMethodDecl>(ND))
15178 Functions.addDecl(ND);
15179 RequiresADL = false;
15180 }
15181
15182 // Add any functions found via argument-dependent lookup.
15183 Expr *Args[2] = { First, Second };
15184 unsigned NumArgs = 1 + (Second != nullptr);
15185
15186 // Create the overloaded operator invocation for unary operators.
15187 if (NumArgs == 1 || isPostIncDec) {
15188 UnaryOperatorKind Opc
15189 = UnaryOperator::getOverloadedOpcode(Op, isPostIncDec);
15190 return SemaRef.CreateOverloadedUnaryOp(OpLoc, Opc, Functions, First,
15191 RequiresADL);
15192 }
15193
15194 if (Op == OO_Subscript) {
15195 SourceLocation LBrace;
15196 SourceLocation RBrace;
15197
15198 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Callee)) {
15199 DeclarationNameLoc NameLoc = DRE->getNameInfo().getInfo();
15200 LBrace = NameLoc.getCXXOperatorNameBeginLoc();
15201 RBrace = NameLoc.getCXXOperatorNameEndLoc();
15202 } else {
15203 LBrace = Callee->getBeginLoc();
15204 RBrace = OpLoc;
15205 }
15206
15207 return SemaRef.CreateOverloadedArraySubscriptExpr(LBrace, RBrace,
15208 First, Second);
15209 }
15210
15211 // Create the overloaded operator invocation for binary operators.
15212 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(Op);
15213 ExprResult Result = SemaRef.CreateOverloadedBinOp(
15214 OpLoc, Opc, Functions, Args[0], Args[1], RequiresADL);
15215 if (Result.isInvalid())
15216 return ExprError();
15217
15218 return Result;
15219}
15220
15221template<typename Derived>
15222ExprResult
15223TreeTransform<Derived>::RebuildCXXPseudoDestructorExpr(Expr *Base,
15224 SourceLocation OperatorLoc,
15225 bool isArrow,
15226 CXXScopeSpec &SS,
15227 TypeSourceInfo *ScopeType,
15228 SourceLocation CCLoc,
15229 SourceLocation TildeLoc,
15230 PseudoDestructorTypeStorage Destroyed) {
15231 QualType BaseType = Base->getType();
15232 if (Base->isTypeDependent() || Destroyed.getIdentifier() ||
15233 (!isArrow && !BaseType->getAs<RecordType>()) ||
15234 (isArrow && BaseType->getAs<PointerType>() &&
15235 !BaseType->castAs<PointerType>()->getPointeeType()
15236 ->template getAs<RecordType>())){
15237 // This pseudo-destructor expression is still a pseudo-destructor.
15238 return SemaRef.BuildPseudoDestructorExpr(
15239 Base, OperatorLoc, isArrow ? tok::arrow : tok::period, SS, ScopeType,
15240 CCLoc, TildeLoc, Destroyed);
15241 }
15242
15243 TypeSourceInfo *DestroyedType = Destroyed.getTypeSourceInfo();
15244 DeclarationName Name(SemaRef.Context.DeclarationNames.getCXXDestructorName(
15245 SemaRef.Context.getCanonicalType(DestroyedType->getType())));
15246 DeclarationNameInfo NameInfo(Name, Destroyed.getLocation());
15247 NameInfo.setNamedTypeInfo(DestroyedType);
15248
15249 // The scope type is now known to be a valid nested name specifier
15250 // component. Tack it on to the end of the nested name specifier.
15251 if (ScopeType) {
15252 if (!ScopeType->getType()->getAs<TagType>()) {
15253 getSema().Diag(ScopeType->getTypeLoc().getBeginLoc(),
15254 diag::err_expected_class_or_namespace)
15255 << ScopeType->getType() << getSema().getLangOpts().CPlusPlus;
15256 return ExprError();
15257 }
15258 SS.Extend(SemaRef.Context, SourceLocation(), ScopeType->getTypeLoc(),
15259 CCLoc);
15260 }
15261
15262 SourceLocation TemplateKWLoc; // FIXME: retrieve it from caller.
15263 return getSema().BuildMemberReferenceExpr(Base, BaseType,
15264 OperatorLoc, isArrow,
15265 SS, TemplateKWLoc,
15266 /*FIXME: FirstQualifier*/ nullptr,
15267 NameInfo,
15268 /*TemplateArgs*/ nullptr,
15269 /*S*/nullptr);
15270}
15271
15272template<typename Derived>
15273StmtResult
15274TreeTransform<Derived>::TransformCapturedStmt(CapturedStmt *S) {
15275 SourceLocation Loc = S->getBeginLoc();
15276 CapturedDecl *CD = S->getCapturedDecl();
15277 unsigned NumParams = CD->getNumParams();
15278 unsigned ContextParamPos = CD->getContextParamPosition();
15279 SmallVector<Sema::CapturedParamNameType, 4> Params;
15280 for (unsigned I = 0; I < NumParams; ++I) {
15281 if (I != ContextParamPos) {
15282 Params.push_back(
15283 std::make_pair(
15284 CD->getParam(I)->getName(),
15285 getDerived().TransformType(CD->getParam(I)->getType())));
15286 } else {
15287 Params.push_back(std::make_pair(StringRef(), QualType()));
15288 }
15289 }
15290 getSema().ActOnCapturedRegionStart(Loc, /*CurScope*/nullptr,
15291 S->getCapturedRegionKind(), Params);
15292 StmtResult Body;
15293 {
15294 Sema::CompoundScopeRAII CompoundScope(getSema());
15295 Body = getDerived().TransformStmt(S->getCapturedStmt());
15296 }
15297
15298 if (Body.isInvalid()) {
15299 getSema().ActOnCapturedRegionError();
15300 return StmtError();
15301 }
15302
15303 return getSema().ActOnCapturedRegionEnd(Body.get());
15304}
15305
15306} // end namespace clang
15307
15308#endif // LLVM_CLANG_LIB_SEMA_TREETRANSFORM_H

tools/clang/include/clang/AST/TypeNodes.inc

1/*===- TableGen'erated file -------------------------------------*- C++ -*-===*\
2|* *|
3|* An x-macro database of Clang type nodes *|
4|* *|
5|* Automatically generated file, do not edit! *|
6|* *|
7\*===----------------------------------------------------------------------===*/
8
9#ifndef ABSTRACT_TYPE
10# define ABSTRACT_TYPE(Class, Base) TYPE(Class, Base)
11#endif
12#ifndef NON_CANONICAL_TYPE
13# define NON_CANONICAL_TYPE(Class, Base) TYPE(Class, Base)
14#endif
15#ifndef DEPENDENT_TYPE
16# define DEPENDENT_TYPE(Class, Base) TYPE(Class, Base)
17#endif
18#ifndef NON_CANONICAL_UNLESS_DEPENDENT_TYPE
19# define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Class, Base) TYPE(Class, Base)
20#endif
21NON_CANONICAL_TYPE(Adjusted, Type)
22NON_CANONICAL_TYPE(Decayed, AdjustedType)
23ABSTRACT_TYPE(Array, Type)
24TYPE(ConstantArray, ArrayType)
25DEPENDENT_TYPE(DependentSizedArray, ArrayType)
26TYPE(IncompleteArray, ArrayType)
27TYPE(VariableArray, ArrayType)
28TYPE(Atomic, Type)
29NON_CANONICAL_TYPE(Attributed, Type)
30NON_CANONICAL_TYPE(BTFTagAttributed, Type)
31TYPE(BitInt, Type)
32TYPE(BlockPointer, Type)
33TYPE(Builtin, Type)
34TYPE(Complex, Type)
35NON_CANONICAL_UNLESS_DEPENDENT_TYPE(Decltype, Type)
36ABSTRACT_TYPE(Deduced, Type)
37TYPE(Auto, DeducedType)
38TYPE(DeducedTemplateSpecialization, DeducedType)
39DEPENDENT_TYPE(DependentAddressSpace, Type)
40DEPENDENT_TYPE(DependentBitInt, Type)
41DEPENDENT_TYPE(DependentName, Type)
42DEPENDENT_TYPE(DependentSizedExtVector, Type)
43DEPENDENT_TYPE(DependentTemplateSpecialization, Type)
44DEPENDENT_TYPE(DependentVector, Type)
45NON_CANONICAL_TYPE(Elaborated, Type)
46ABSTRACT_TYPE(Function, Type)
47TYPE(FunctionNoProto, FunctionType)
48TYPE(FunctionProto, FunctionType)
49DEPENDENT_TYPE(InjectedClassName, Type)
50NON_CANONICAL_TYPE(MacroQualified, Type)
51ABSTRACT_TYPE(Matrix, Type)
52TYPE(ConstantMatrix, MatrixType)
53DEPENDENT_TYPE(DependentSizedMatrix, MatrixType)
54TYPE(MemberPointer, Type)
55TYPE(ObjCObjectPointer, Type)
56TYPE(ObjCObject, Type)
57TYPE(ObjCInterface, ObjCObjectType)
58NON_CANONICAL_TYPE(ObjCTypeParam, Type)
59DEPENDENT_TYPE(PackExpansion, Type)
60NON_CANONICAL_TYPE(Paren, Type)
61TYPE(Pipe, Type)
62TYPE(Pointer, Type)
63ABSTRACT_TYPE(Reference, Type)
64TYPE(LValueReference, ReferenceType)
65TYPE(RValueReference, ReferenceType)
66DEPENDENT_TYPE(SubstTemplateTypeParmPack, Type)
67NON_CANONICAL_TYPE(SubstTemplateTypeParm, Type)
68ABSTRACT_TYPE(Tag, Type)
69TYPE(Enum, TagType)
70TYPE(Record, TagType)
71NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TemplateSpecialization, Type)
72DEPENDENT_TYPE(TemplateTypeParm, Type)
73NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TypeOfExpr, Type)
16
Calling 'TreeTransform::TransformTypeOfExprType'
74NON_CANONICAL_UNLESS_DEPENDENT_TYPE(TypeOf, Type)
75NON_CANONICAL_TYPE(Typedef, Type)
76NON_CANONICAL_UNLESS_DEPENDENT_TYPE(UnaryTransform, Type)
77DEPENDENT_TYPE(UnresolvedUsing, Type)
78NON_CANONICAL_TYPE(Using, Type)
79TYPE(Vector, Type)
80TYPE(ExtVector, VectorType)
81#ifdef LAST_TYPE
82LAST_TYPE(ExtVector)
83#undef LAST_TYPE
84#endif
85#ifdef LEAF_TYPE
86LEAF_TYPE(Builtin)
87LEAF_TYPE(Enum)
88LEAF_TYPE(InjectedClassName)
89LEAF_TYPE(ObjCInterface)
90LEAF_TYPE(Record)
91LEAF_TYPE(TemplateTypeParm)
92#undef LEAF_TYPE
93#endif
94#undef TYPE
95#undef ABSTRACT_TYPE
96#undef ABSTRACT_TYPE
97#undef NON_CANONICAL_TYPE
98#undef DEPENDENT_TYPE
99#undef NON_CANONICAL_UNLESS_DEPENDENT_TYPE