1//===- Stmt.cpp - Statement AST Node Implementation -----------------------===//
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//
9// This file implements the Stmt class and statement subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/AST/Stmt.h"
14#include "clang/AST/ASTContext.h"
15#include "clang/AST/ASTDiagnostic.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclGroup.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprConcepts.h"
22#include "clang/AST/ExprObjC.h"
23#include "clang/AST/ExprOpenMP.h"
24#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtOpenACC.h"
27#include "clang/AST/StmtOpenMP.h"
28#include "clang/AST/StmtSYCL.h"
29#include "clang/AST/Type.h"
30#include "clang/Basic/CharInfo.h"
31#include "clang/Basic/LLVM.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/Token.h"
35#include "llvm/ADT/SmallVector.h"
36#include "llvm/ADT/StringExtras.h"
37#include "llvm/ADT/StringRef.h"
38#include "llvm/Support/Compiler.h"
39#include "llvm/Support/ErrorHandling.h"
40#include "llvm/Support/MathExtras.h"
41#include "llvm/Support/raw_ostream.h"
42#include <algorithm>
43#include <cassert>
44#include <cstring>
45#include <optional>
46#include <string>
47#include <utility>
48
49using namespace clang;
50
51#define STMT(CLASS, PARENT)
52#define STMT_RANGE(BASE, FIRST, LAST)
53#define LAST_STMT_RANGE(BASE, FIRST, LAST) \
54 static_assert(llvm::isUInt<NumStmtBits>(Stmt::StmtClass::LAST##Class), \
55 "The number of 'StmtClass'es is strictly bound " \
56 "by a bitfield of width NumStmtBits");
57#define ABSTRACT_STMT(STMT)
58#include "clang/AST/StmtNodes.inc"
59
60static struct StmtClassNameTable {
61 const char *Name;
62 unsigned Counter;
63 unsigned Size;
64} StmtClassInfo[Stmt::lastStmtConstant+1];
65
66static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
67 static bool Initialized = false;
68 if (Initialized)
69 return StmtClassInfo[E];
70
71 // Initialize the table on the first use.
72 Initialized = true;
73#define ABSTRACT_STMT(STMT)
74#define STMT(CLASS, PARENT) \
75 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
76 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
77#include "clang/AST/StmtNodes.inc"
78
79 return StmtClassInfo[E];
80}
81
82void *Stmt::operator new(size_t bytes, const ASTContext& C,
83 unsigned alignment) {
84 return ::operator new(Bytes: bytes, C, Alignment: alignment);
85}
86
87const char *Stmt::getStmtClassName() const {
88 return getStmtInfoTableEntry(E: (StmtClass) StmtBits.sClass).Name;
89}
90
91// Check that no statement / expression class is polymorphic. LLVM style RTTI
92// should be used instead. If absolutely needed an exception can still be added
93// here by defining the appropriate macro (but please don't do this).
94#define STMT(CLASS, PARENT) \
95 static_assert(!std::is_polymorphic<CLASS>::value, \
96 #CLASS " should not be polymorphic!");
97#include "clang/AST/StmtNodes.inc"
98
99// Check that no statement / expression class has a non-trival destructor.
100// Statements and expressions are allocated with the BumpPtrAllocator from
101// ASTContext and therefore their destructor is not executed.
102#define STMT(CLASS, PARENT) \
103 static_assert(std::is_trivially_destructible<CLASS>::value, \
104 #CLASS " should be trivially destructible!");
105// FIXME: InitListExpr is not trivially destructible due to its ASTVector.
106#define INITLISTEXPR(CLASS, PARENT)
107#include "clang/AST/StmtNodes.inc"
108
109void Stmt::PrintStats() {
110 // Ensure the table is primed.
111 getStmtInfoTableEntry(E: Stmt::NullStmtClass);
112
113 unsigned sum = 0;
114 llvm::errs() << "\n*** Stmt/Expr Stats:\n";
115 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
116 if (StmtClassInfo[i].Name == nullptr) continue;
117 sum += StmtClassInfo[i].Counter;
118 }
119 llvm::errs() << " " << sum << " stmts/exprs total.\n";
120 sum = 0;
121 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
122 if (StmtClassInfo[i].Name == nullptr) continue;
123 if (StmtClassInfo[i].Counter == 0) continue;
124 llvm::errs() << " " << StmtClassInfo[i].Counter << " "
125 << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
126 << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
127 << " bytes)\n";
128 sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
129 }
130
131 llvm::errs() << "Total bytes = " << sum << "\n";
132}
133
134void Stmt::addStmtClass(StmtClass s) {
135 ++getStmtInfoTableEntry(E: s).Counter;
136}
137
138bool Stmt::StatisticsEnabled = false;
139void Stmt::EnableStatistics() {
140 StatisticsEnabled = true;
141}
142
143static std::pair<Stmt::Likelihood, const Attr *>
144getLikelihood(ArrayRef<const Attr *> Attrs) {
145 for (const auto *A : Attrs) {
146 if (isa<LikelyAttr>(Val: A))
147 return std::make_pair(x: Stmt::LH_Likely, y&: A);
148
149 if (isa<UnlikelyAttr>(Val: A))
150 return std::make_pair(x: Stmt::LH_Unlikely, y&: A);
151 }
152
153 return std::make_pair(x: Stmt::LH_None, y: nullptr);
154}
155
156static std::pair<Stmt::Likelihood, const Attr *> getLikelihood(const Stmt *S) {
157 if (const auto *AS = dyn_cast_or_null<AttributedStmt>(Val: S))
158 return getLikelihood(Attrs: AS->getAttrs());
159
160 return std::make_pair(x: Stmt::LH_None, y: nullptr);
161}
162
163Stmt::Likelihood Stmt::getLikelihood(ArrayRef<const Attr *> Attrs) {
164 return ::getLikelihood(Attrs).first;
165}
166
167Stmt::Likelihood Stmt::getLikelihood(const Stmt *S) {
168 return ::getLikelihood(S).first;
169}
170
171const Attr *Stmt::getLikelihoodAttr(const Stmt *S) {
172 return ::getLikelihood(S).second;
173}
174
175Stmt::Likelihood Stmt::getLikelihood(const Stmt *Then, const Stmt *Else) {
176 Likelihood LHT = ::getLikelihood(S: Then).first;
177 Likelihood LHE = ::getLikelihood(S: Else).first;
178 if (LHE == LH_None)
179 return LHT;
180
181 // If the same attribute is used on both branches there's a conflict.
182 if (LHT == LHE)
183 return LH_None;
184
185 if (LHT != LH_None)
186 return LHT;
187
188 // Invert the value of Else to get the value for Then.
189 return LHE == LH_Likely ? LH_Unlikely : LH_Likely;
190}
191
192std::tuple<bool, const Attr *, const Attr *>
193Stmt::determineLikelihoodConflict(const Stmt *Then, const Stmt *Else) {
194 std::pair<Likelihood, const Attr *> LHT = ::getLikelihood(S: Then);
195 std::pair<Likelihood, const Attr *> LHE = ::getLikelihood(S: Else);
196 // If the same attribute is used on both branches there's a conflict.
197 if (LHT.first != LH_None && LHT.first == LHE.first)
198 return std::make_tuple(args: true, args&: LHT.second, args&: LHE.second);
199
200 return std::make_tuple(args: false, args: nullptr, args: nullptr);
201}
202
203/// Skip no-op (attributed, compound) container stmts and skip captured
204/// stmt at the top, if \a IgnoreCaptured is true.
205Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
206 Stmt *S = this;
207 if (IgnoreCaptured)
208 if (auto CapS = dyn_cast_or_null<CapturedStmt>(Val: S))
209 S = CapS->getCapturedStmt();
210 while (true) {
211 if (auto AS = dyn_cast_or_null<AttributedStmt>(Val: S))
212 S = AS->getSubStmt();
213 else if (auto CS = dyn_cast_or_null<CompoundStmt>(Val: S)) {
214 if (CS->size() != 1)
215 break;
216 S = CS->body_back();
217 } else
218 break;
219 }
220 return S;
221}
222
223/// Strip off all label-like statements.
224///
225/// This will strip off label statements, case statements, attributed
226/// statements and default statements recursively.
227const Stmt *Stmt::stripLabelLikeStatements() const {
228 const Stmt *S = this;
229 while (true) {
230 if (const auto *LS = dyn_cast<LabelStmt>(Val: S))
231 S = LS->getSubStmt();
232 else if (const auto *SC = dyn_cast<SwitchCase>(Val: S))
233 S = SC->getSubStmt();
234 else if (const auto *AS = dyn_cast<AttributedStmt>(Val: S))
235 S = AS->getSubStmt();
236 else
237 return S;
238 }
239}
240
241namespace {
242
243 struct good {};
244 struct bad {};
245
246 // These silly little functions have to be static inline to suppress
247 // unused warnings, and they have to be defined to suppress other
248 // warnings.
249 static good is_good(good) { return good(); }
250
251 typedef Stmt::child_range children_t();
252 template <class T> good implements_children(children_t T::*) {
253 return good();
254 }
255 [[maybe_unused]]
256 static bad implements_children(children_t Stmt::*) {
257 return bad();
258 }
259
260 typedef SourceLocation getBeginLoc_t() const;
261 template <class T> good implements_getBeginLoc(getBeginLoc_t T::*) {
262 return good();
263 }
264 [[maybe_unused]]
265 static bad implements_getBeginLoc(getBeginLoc_t Stmt::*) {
266 return bad();
267 }
268
269 typedef SourceLocation getLocEnd_t() const;
270 template <class T> good implements_getEndLoc(getLocEnd_t T::*) {
271 return good();
272 }
273 [[maybe_unused]]
274 static bad implements_getEndLoc(getLocEnd_t Stmt::*) {
275 return bad();
276 }
277
278#define ASSERT_IMPLEMENTS_children(type) \
279 (void) is_good(implements_children(&type::children))
280#define ASSERT_IMPLEMENTS_getBeginLoc(type) \
281 (void)is_good(implements_getBeginLoc(&type::getBeginLoc))
282#define ASSERT_IMPLEMENTS_getEndLoc(type) \
283 (void)is_good(implements_getEndLoc(&type::getEndLoc))
284
285} // namespace
286
287/// Check whether the various Stmt classes implement their member
288/// functions.
289[[maybe_unused]]
290static inline void check_implementations() {
291#define ABSTRACT_STMT(type)
292#define STMT(type, base) \
293 ASSERT_IMPLEMENTS_children(type); \
294 ASSERT_IMPLEMENTS_getBeginLoc(type); \
295 ASSERT_IMPLEMENTS_getEndLoc(type);
296#include "clang/AST/StmtNodes.inc"
297}
298
299Stmt::child_range Stmt::children() {
300 switch (getStmtClass()) {
301 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
302#define ABSTRACT_STMT(type)
303#define STMT(type, base) \
304 case Stmt::type##Class: \
305 return static_cast<type*>(this)->children();
306#include "clang/AST/StmtNodes.inc"
307 }
308 llvm_unreachable("unknown statement kind!");
309}
310
311// Amusing macro metaprogramming hack: check whether a class provides
312// a more specific implementation of getSourceRange.
313//
314// See also Expr.cpp:getExprLoc().
315namespace {
316
317 /// This implementation is used when a class provides a custom
318 /// implementation of getSourceRange.
319 template <class S, class T>
320 SourceRange getSourceRangeImpl(const Stmt *stmt,
321 SourceRange (T::*v)() const) {
322 return static_cast<const S*>(stmt)->getSourceRange();
323 }
324
325 /// This implementation is used when a class doesn't provide a custom
326 /// implementation of getSourceRange. Overload resolution should pick it over
327 /// the implementation above because it's more specialized according to
328 /// function template partial ordering.
329 template <class S>
330 SourceRange getSourceRangeImpl(const Stmt *stmt,
331 SourceRange (Stmt::*v)() const) {
332 return SourceRange(static_cast<const S *>(stmt)->getBeginLoc(),
333 static_cast<const S *>(stmt)->getEndLoc());
334 }
335
336} // namespace
337
338SourceRange Stmt::getSourceRange() const {
339 switch (getStmtClass()) {
340 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
341#define ABSTRACT_STMT(type)
342#define STMT(type, base) \
343 case Stmt::type##Class: \
344 return getSourceRangeImpl<type>(this, &type::getSourceRange);
345#include "clang/AST/StmtNodes.inc"
346 }
347 llvm_unreachable("unknown statement kind!");
348}
349
350SourceLocation Stmt::getBeginLoc() const {
351 switch (getStmtClass()) {
352 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
353#define ABSTRACT_STMT(type)
354#define STMT(type, base) \
355 case Stmt::type##Class: \
356 return static_cast<const type *>(this)->getBeginLoc();
357#include "clang/AST/StmtNodes.inc"
358 }
359 llvm_unreachable("unknown statement kind");
360}
361
362SourceLocation Stmt::getEndLoc() const {
363 switch (getStmtClass()) {
364 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
365#define ABSTRACT_STMT(type)
366#define STMT(type, base) \
367 case Stmt::type##Class: \
368 return static_cast<const type *>(this)->getEndLoc();
369#include "clang/AST/StmtNodes.inc"
370 }
371 llvm_unreachable("unknown statement kind");
372}
373
374int64_t Stmt::getID(const ASTContext &Context) const {
375 return Context.getAllocator().identifyKnownAlignedObject<Stmt>(Ptr: this);
376}
377
378CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, FPOptionsOverride FPFeatures,
379 SourceLocation LB, SourceLocation RB)
380 : Stmt(CompoundStmtClass), LBraceLoc(LB), RBraceLoc(RB) {
381 CompoundStmtBits.NumStmts = Stmts.size();
382 CompoundStmtBits.HasFPFeatures = FPFeatures.requiresTrailingStorage();
383 setStmts(Stmts);
384 if (hasStoredFPFeatures())
385 setStoredFPFeatures(FPFeatures);
386}
387
388void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) {
389 assert(CompoundStmtBits.NumStmts == Stmts.size() &&
390 "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
391 llvm::copy(Range&: Stmts, Out: body_begin());
392}
393
394CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
395 FPOptionsOverride FPFeatures,
396 SourceLocation LB, SourceLocation RB) {
397 void *Mem =
398 C.Allocate(Size: totalSizeToAlloc<Stmt *, FPOptionsOverride>(
399 Counts: Stmts.size(), Counts: FPFeatures.requiresTrailingStorage()),
400 Align: alignof(CompoundStmt));
401 return new (Mem) CompoundStmt(Stmts, FPFeatures, LB, RB);
402}
403
404CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C, unsigned NumStmts,
405 bool HasFPFeatures) {
406 void *Mem = C.Allocate(
407 Size: totalSizeToAlloc<Stmt *, FPOptionsOverride>(Counts: NumStmts, Counts: HasFPFeatures),
408 Align: alignof(CompoundStmt));
409 CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell());
410 New->CompoundStmtBits.NumStmts = NumStmts;
411 New->CompoundStmtBits.HasFPFeatures = HasFPFeatures;
412 return New;
413}
414
415const Expr *ValueStmt::getExprStmt() const {
416 const Stmt *S = this;
417 do {
418 if (const auto *E = dyn_cast<Expr>(Val: S))
419 return E;
420
421 if (const auto *LS = dyn_cast<LabelStmt>(Val: S))
422 S = LS->getSubStmt();
423 else if (const auto *AS = dyn_cast<AttributedStmt>(Val: S))
424 S = AS->getSubStmt();
425 else
426 llvm_unreachable("unknown kind of ValueStmt");
427 } while (isa<ValueStmt>(Val: S));
428
429 return nullptr;
430}
431
432const char *LabelStmt::getName() const {
433 return getDecl()->getIdentifier()->getNameStart();
434}
435
436AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
437 ArrayRef<const Attr*> Attrs,
438 Stmt *SubStmt) {
439 assert(!Attrs.empty() && "Attrs should not be empty");
440 void *Mem = C.Allocate(Size: totalSizeToAlloc<const Attr *>(Counts: Attrs.size()),
441 Align: alignof(AttributedStmt));
442 return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
443}
444
445AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
446 unsigned NumAttrs) {
447 assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
448 void *Mem = C.Allocate(Size: totalSizeToAlloc<const Attr *>(Counts: NumAttrs),
449 Align: alignof(AttributedStmt));
450 return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
451}
452
453std::string
454AsmStmt::addVariableConstraints(StringRef Constraint, const Expr &AsmExpr,
455 const TargetInfo &Target, bool EarlyClobber,
456 UnsupportedConstraintCallbackTy UnsupportedCB,
457 std::string *GCCReg) const {
458 const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Val: &AsmExpr);
459 if (!AsmDeclRef)
460 return Constraint.str();
461 const ValueDecl &Value = *AsmDeclRef->getDecl();
462 const VarDecl *Variable = dyn_cast<VarDecl>(Val: &Value);
463 if (!Variable)
464 return Constraint.str();
465 if (Variable->getStorageClass() != SC_Register)
466 return Constraint.str();
467 AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>();
468 if (!Attr)
469 return Constraint.str();
470 StringRef Register = Attr->getLabel();
471 assert(Target.isValidGCCRegisterName(Register));
472 // We're using validateOutputConstraint here because we only care if
473 // this is a register constraint.
474 TargetInfo::ConstraintInfo Info(Constraint, "");
475 if (Target.validateOutputConstraint(Info) && !Info.allowsRegister()) {
476 UnsupportedCB(this, "__asm__");
477 return Constraint.str();
478 }
479 // Canonicalize the register here before returning it.
480 Register = Target.getNormalizedGCCRegisterName(Name: Register);
481 if (GCCReg != nullptr)
482 *GCCReg = Register.str();
483 return (EarlyClobber ? "&{" : "{") + Register.str() + "}";
484}
485
486std::string AsmStmt::generateAsmString(const ASTContext &C) const {
487 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: this))
488 return gccAsmStmt->generateAsmString(C);
489 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(Val: this))
490 return msAsmStmt->generateAsmString(C);
491 llvm_unreachable("unknown asm statement kind!");
492}
493
494std::string AsmStmt::getOutputConstraint(unsigned i) const {
495 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: this))
496 return gccAsmStmt->getOutputConstraint(i);
497 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(Val: this))
498 return msAsmStmt->getOutputConstraint(i).str();
499 llvm_unreachable("unknown asm statement kind!");
500}
501
502const Expr *AsmStmt::getOutputExpr(unsigned i) const {
503 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: this))
504 return gccAsmStmt->getOutputExpr(i);
505 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(Val: this))
506 return msAsmStmt->getOutputExpr(i);
507 llvm_unreachable("unknown asm statement kind!");
508}
509
510std::string AsmStmt::getInputConstraint(unsigned i) const {
511 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: this))
512 return gccAsmStmt->getInputConstraint(i);
513 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(Val: this))
514 return msAsmStmt->getInputConstraint(i).str();
515 llvm_unreachable("unknown asm statement kind!");
516}
517
518const Expr *AsmStmt::getInputExpr(unsigned i) const {
519 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: this))
520 return gccAsmStmt->getInputExpr(i);
521 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(Val: this))
522 return msAsmStmt->getInputExpr(i);
523 llvm_unreachable("unknown asm statement kind!");
524}
525
526std::string AsmStmt::getClobber(unsigned i) const {
527 if (const auto *gccAsmStmt = dyn_cast<GCCAsmStmt>(Val: this))
528 return gccAsmStmt->getClobber(i);
529 if (const auto *msAsmStmt = dyn_cast<MSAsmStmt>(Val: this))
530 return msAsmStmt->getClobber(i).str();
531 llvm_unreachable("unknown asm statement kind!");
532}
533
534/// getNumPlusOperands - Return the number of output operands that have a "+"
535/// constraint.
536unsigned AsmStmt::getNumPlusOperands() const {
537 unsigned Res = 0;
538 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
539 if (isOutputPlusConstraint(i))
540 ++Res;
541 return Res;
542}
543
544char GCCAsmStmt::AsmStringPiece::getModifier() const {
545 assert(isOperand() && "Only Operands can have modifiers.");
546 return isLetter(c: Str[0]) ? Str[0] : '\0';
547}
548
549std::string GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(const Expr *E) {
550 if (auto *SL = llvm::dyn_cast<StringLiteral>(Val: E))
551 return SL->getString().str();
552 assert(E->getDependence() == ExprDependence::None &&
553 "cannot extract a string from a dependent expression");
554 auto *CE = cast<ConstantExpr>(Val: E);
555 APValue Res = CE->getAPValueResult();
556 assert(Res.isArray() && "expected an array");
557
558 std::string Out;
559 Out.reserve(res_arg: Res.getArraySize());
560 for (unsigned I = 0; I < Res.getArraySize(); ++I) {
561 APValue C = Res.getArrayInitializedElt(I);
562 assert(C.isInt());
563 auto Ch = static_cast<char>(C.getInt().getExtValue());
564 Out.push_back(c: Ch);
565 }
566 return Out;
567}
568
569std::string GCCAsmStmt::getAsmString() const {
570 return ExtractStringFromGCCAsmStmtComponent(E: getAsmStringExpr());
571}
572
573std::string GCCAsmStmt::getClobber(unsigned i) const {
574 return ExtractStringFromGCCAsmStmtComponent(E: getClobberExpr(i));
575}
576
577Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
578 return cast<Expr>(Val: Exprs[i]);
579}
580
581/// getOutputConstraint - Return the constraint string for the specified
582/// output operand. All output constraints are known to be non-empty (either
583/// '=' or '+').
584std::string GCCAsmStmt::getOutputConstraint(unsigned i) const {
585 return ExtractStringFromGCCAsmStmtComponent(E: getOutputConstraintExpr(i));
586}
587
588Expr *GCCAsmStmt::getInputExpr(unsigned i) {
589 return cast<Expr>(Val: Exprs[i + NumOutputs]);
590}
591
592void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
593 Exprs[i + NumOutputs] = E;
594}
595
596AddrLabelExpr *GCCAsmStmt::getLabelExpr(unsigned i) const {
597 return cast<AddrLabelExpr>(Val: Exprs[i + NumOutputs + NumInputs]);
598}
599
600StringRef GCCAsmStmt::getLabelName(unsigned i) const {
601 return getLabelExpr(i)->getLabel()->getName();
602}
603
604/// getInputConstraint - Return the specified input constraint. Unlike output
605/// constraints, these can be empty.
606std::string GCCAsmStmt::getInputConstraint(unsigned i) const {
607 return ExtractStringFromGCCAsmStmtComponent(E: getInputConstraintExpr(i));
608}
609
610void GCCAsmStmt::setOutputsAndInputsAndClobbers(
611 const ASTContext &C, IdentifierInfo **Names, Expr **Constraints,
612 Stmt **Exprs, unsigned NumOutputs, unsigned NumInputs, unsigned NumLabels,
613 Expr **Clobbers, unsigned NumClobbers) {
614 this->NumOutputs = NumOutputs;
615 this->NumInputs = NumInputs;
616 this->NumClobbers = NumClobbers;
617 this->NumLabels = NumLabels;
618
619 unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
620
621 C.Deallocate(Ptr: this->Names);
622 this->Names = new (C) IdentifierInfo*[NumExprs];
623 std::copy(first: Names, last: Names + NumExprs, result: this->Names);
624
625 C.Deallocate(Ptr: this->Exprs);
626 this->Exprs = new (C) Stmt*[NumExprs];
627 std::copy(first: Exprs, last: Exprs + NumExprs, result: this->Exprs);
628
629 unsigned NumConstraints = NumOutputs + NumInputs;
630 C.Deallocate(Ptr: this->Constraints);
631 this->Constraints = new (C) Expr *[NumConstraints];
632 std::copy(first: Constraints, last: Constraints + NumConstraints, result: this->Constraints);
633
634 C.Deallocate(Ptr: this->Clobbers);
635 this->Clobbers = new (C) Expr *[NumClobbers];
636 std::copy(first: Clobbers, last: Clobbers + NumClobbers, result: this->Clobbers);
637}
638
639/// getNamedOperand - Given a symbolic operand reference like %[foo],
640/// translate this into a numeric value needed to reference the same operand.
641/// This returns -1 if the operand name is invalid.
642int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
643 // Check if this is an output operand.
644 unsigned NumOutputs = getNumOutputs();
645 for (unsigned i = 0; i != NumOutputs; ++i)
646 if (getOutputName(i) == SymbolicName)
647 return i;
648
649 unsigned NumInputs = getNumInputs();
650 for (unsigned i = 0; i != NumInputs; ++i)
651 if (getInputName(i) == SymbolicName)
652 return NumOutputs + i;
653
654 for (unsigned i = 0, e = getNumLabels(); i != e; ++i)
655 if (getLabelName(i) == SymbolicName)
656 return NumOutputs + NumInputs + getNumPlusOperands() + i;
657
658 // Not found.
659 return -1;
660}
661
662/// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
663/// it into pieces. If the asm string is erroneous, emit errors and return
664/// true, otherwise return false.
665unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
666 const ASTContext &C, unsigned &DiagOffs) const {
667
668 std::string Str = getAsmString();
669 const char *StrStart = Str.data();
670 const char *StrEnd = Str.data() + Str.size();
671 const char *CurPtr = StrStart;
672
673 // "Simple" inline asms have no constraints or operands, just convert the asm
674 // string to escape $'s.
675 if (isSimple()) {
676 std::string Result;
677 for (; CurPtr != StrEnd; ++CurPtr) {
678 switch (*CurPtr) {
679 case '$':
680 Result += "$$";
681 break;
682 default:
683 Result += *CurPtr;
684 break;
685 }
686 }
687 Pieces.push_back(Elt: AsmStringPiece(Result));
688 return 0;
689 }
690
691 // CurStringPiece - The current string that we are building up as we scan the
692 // asm string.
693 std::string CurStringPiece;
694
695 bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
696
697 unsigned LastAsmStringToken = 0;
698 unsigned LastAsmStringOffset = 0;
699
700 while (true) {
701 // Done with the string?
702 if (CurPtr == StrEnd) {
703 if (!CurStringPiece.empty())
704 Pieces.push_back(Elt: AsmStringPiece(CurStringPiece));
705 return 0;
706 }
707
708 char CurChar = *CurPtr++;
709 switch (CurChar) {
710 case '$': CurStringPiece += "$$"; continue;
711 case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
712 case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
713 case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
714 case '%':
715 break;
716 default:
717 CurStringPiece += CurChar;
718 continue;
719 }
720
721 const TargetInfo &TI = C.getTargetInfo();
722
723 // Escaped "%" character in asm string.
724 if (CurPtr == StrEnd) {
725 // % at end of string is invalid (no escape).
726 DiagOffs = CurPtr-StrStart-1;
727 return diag::err_asm_invalid_escape;
728 }
729 // Handle escaped char and continue looping over the asm string.
730 char EscapedChar = *CurPtr++;
731 switch (EscapedChar) {
732 default:
733 // Handle target-specific escaped characters.
734 if (auto MaybeReplaceStr = TI.handleAsmEscapedChar(C: EscapedChar)) {
735 CurStringPiece += *MaybeReplaceStr;
736 continue;
737 }
738 break;
739 case '%': // %% -> %
740 case '{': // %{ -> {
741 case '}': // %} -> }
742 CurStringPiece += EscapedChar;
743 continue;
744 case '=': // %= -> Generate a unique ID.
745 CurStringPiece += "${:uid}";
746 continue;
747 }
748
749 // Otherwise, we have an operand. If we have accumulated a string so far,
750 // add it to the Pieces list.
751 if (!CurStringPiece.empty()) {
752 Pieces.push_back(Elt: AsmStringPiece(CurStringPiece));
753 CurStringPiece.clear();
754 }
755
756 // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
757 // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
758
759 const char *Begin = CurPtr - 1; // Points to the character following '%'.
760 const char *Percent = Begin - 1; // Points to '%'.
761
762 if (isLetter(c: EscapedChar)) {
763 if (CurPtr == StrEnd) { // Premature end.
764 DiagOffs = CurPtr-StrStart-1;
765 return diag::err_asm_invalid_escape;
766 }
767
768 // Specifically handle `cc` which we will alias to `c`.
769 // Note this is the only operand modifier that exists which has two
770 // characters.
771 if (EscapedChar == 'c' && *CurPtr == 'c')
772 CurPtr++;
773
774 EscapedChar = *CurPtr++;
775 }
776
777 const SourceManager &SM = C.getSourceManager();
778 const LangOptions &LO = C.getLangOpts();
779
780 // Handle operands that don't have asmSymbolicName (e.g., %x4).
781 if (isDigit(c: EscapedChar)) {
782 // %n - Assembler operand n
783 unsigned N = 0;
784
785 --CurPtr;
786 while (CurPtr != StrEnd && isDigit(c: *CurPtr))
787 N = N*10 + ((*CurPtr++)-'0');
788
789 unsigned NumOperands = getNumOutputs() + getNumPlusOperands() +
790 getNumInputs() + getNumLabels();
791 if (N >= NumOperands) {
792 DiagOffs = CurPtr-StrStart-1;
793 return diag::err_asm_invalid_operand_number;
794 }
795
796 // Str contains "x4" (Operand without the leading %).
797 std::string Str(Begin, CurPtr - Begin);
798 // (BeginLoc, EndLoc) represents the range of the operand we are currently
799 // processing. Unlike Str, the range includes the leading '%'.
800 SourceLocation BeginLoc, EndLoc;
801 if (auto *SL = dyn_cast<StringLiteral>(Val: getAsmStringExpr())) {
802 BeginLoc =
803 SL->getLocationOfByte(ByteNo: Percent - StrStart, SM, Features: LO, Target: TI,
804 StartToken: &LastAsmStringToken, StartTokenByteOffset: &LastAsmStringOffset);
805 EndLoc =
806 SL->getLocationOfByte(ByteNo: CurPtr - StrStart, SM, Features: LO, Target: TI,
807 StartToken: &LastAsmStringToken, StartTokenByteOffset: &LastAsmStringOffset);
808 } else {
809 BeginLoc = getAsmStringExpr()->getBeginLoc();
810 EndLoc = getAsmStringExpr()->getEndLoc();
811 }
812
813 Pieces.emplace_back(Args&: N, Args: std::move(Str), Args&: BeginLoc, Args&: EndLoc);
814 continue;
815 }
816
817 // Handle operands that have asmSymbolicName (e.g., %x[foo]).
818 if (EscapedChar == '[') {
819 DiagOffs = CurPtr-StrStart-1;
820
821 // Find the ']'.
822 const char *NameEnd = (const char*)memchr(s: CurPtr, c: ']', n: StrEnd-CurPtr);
823 if (NameEnd == nullptr)
824 return diag::err_asm_unterminated_symbolic_operand_name;
825 if (NameEnd == CurPtr)
826 return diag::err_asm_empty_symbolic_operand_name;
827
828 StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
829
830 int N = getNamedOperand(SymbolicName);
831 if (N == -1) {
832 // Verify that an operand with that name exists.
833 DiagOffs = CurPtr-StrStart;
834 return diag::err_asm_unknown_symbolic_operand_name;
835 }
836
837 // Str contains "x[foo]" (Operand without the leading %).
838 std::string Str(Begin, NameEnd + 1 - Begin);
839
840 // (BeginLoc, EndLoc) represents the range of the operand we are currently
841 // processing. Unlike Str, the range includes the leading '%'.
842 SourceLocation BeginLoc, EndLoc;
843 if (auto *SL = dyn_cast<StringLiteral>(Val: getAsmStringExpr())) {
844 BeginLoc =
845 SL->getLocationOfByte(ByteNo: Percent - StrStart, SM, Features: LO, Target: TI,
846 StartToken: &LastAsmStringToken, StartTokenByteOffset: &LastAsmStringOffset);
847 EndLoc =
848 SL->getLocationOfByte(ByteNo: NameEnd + 1 - StrStart, SM, Features: LO, Target: TI,
849 StartToken: &LastAsmStringToken, StartTokenByteOffset: &LastAsmStringOffset);
850 } else {
851 BeginLoc = getAsmStringExpr()->getBeginLoc();
852 EndLoc = getAsmStringExpr()->getEndLoc();
853 }
854
855 Pieces.emplace_back(Args&: N, Args: std::move(Str), Args&: BeginLoc, Args&: EndLoc);
856
857 CurPtr = NameEnd+1;
858 continue;
859 }
860
861 DiagOffs = CurPtr-StrStart-1;
862 return diag::err_asm_invalid_escape;
863 }
864}
865
866/// Assemble final IR asm string (GCC-style).
867std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
868 // Analyze the asm string to decompose it into its pieces. We know that Sema
869 // has already done this, so it is guaranteed to be successful.
870 SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
871 unsigned DiagOffs;
872 AnalyzeAsmString(Pieces, C, DiagOffs);
873
874 std::string AsmString;
875 for (const auto &Piece : Pieces) {
876 if (Piece.isString())
877 AsmString += Piece.getString();
878 else if (Piece.getModifier() == '\0')
879 AsmString += '$' + llvm::utostr(X: Piece.getOperandNo());
880 else
881 AsmString += "${" + llvm::utostr(X: Piece.getOperandNo()) + ':' +
882 Piece.getModifier() + '}';
883 }
884 return AsmString;
885}
886
887/// Assemble final IR asm string (MS-style).
888std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
889 // FIXME: This needs to be translated into the IR string representation.
890 SmallVector<StringRef, 8> Pieces;
891 AsmStr.split(A&: Pieces, Separator: "\n\t");
892 std::string MSAsmString;
893 for (size_t I = 0, E = Pieces.size(); I < E; ++I) {
894 StringRef Instruction = Pieces[I];
895 // For vex/vex2/vex3/evex masm style prefix, convert it to att style
896 // since we don't support masm style prefix in backend.
897 if (Instruction.starts_with(Prefix: "vex "))
898 MSAsmString += '{' + Instruction.substr(Start: 0, N: 3).str() + '}' +
899 Instruction.substr(Start: 3).str();
900 else if (Instruction.starts_with(Prefix: "vex2 ") ||
901 Instruction.starts_with(Prefix: "vex3 ") ||
902 Instruction.starts_with(Prefix: "evex "))
903 MSAsmString += '{' + Instruction.substr(Start: 0, N: 4).str() + '}' +
904 Instruction.substr(Start: 4).str();
905 else
906 MSAsmString += Instruction.str();
907 // If this is not the last instruction, adding back the '\n\t'.
908 if (I < E - 1)
909 MSAsmString += "\n\t";
910 }
911 return MSAsmString;
912}
913
914Expr *MSAsmStmt::getOutputExpr(unsigned i) {
915 return cast<Expr>(Val: Exprs[i]);
916}
917
918Expr *MSAsmStmt::getInputExpr(unsigned i) {
919 return cast<Expr>(Val: Exprs[i + NumOutputs]);
920}
921
922void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
923 Exprs[i + NumOutputs] = E;
924}
925
926//===----------------------------------------------------------------------===//
927// Constructors
928//===----------------------------------------------------------------------===//
929
930GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
931 bool issimple, bool isvolatile, unsigned numoutputs,
932 unsigned numinputs, IdentifierInfo **names,
933 Expr **constraints, Expr **exprs, Expr *asmstr,
934 unsigned numclobbers, Expr **clobbers,
935 unsigned numlabels, SourceLocation rparenloc)
936 : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
937 numinputs, numclobbers),
938 RParenLoc(rparenloc), AsmStr(asmstr), NumLabels(numlabels) {
939 unsigned NumExprs = NumOutputs + NumInputs + NumLabels;
940
941 Names = new (C) IdentifierInfo*[NumExprs];
942 std::copy(first: names, last: names + NumExprs, result: Names);
943
944 Exprs = new (C) Stmt*[NumExprs];
945 std::copy(first: exprs, last: exprs + NumExprs, result: Exprs);
946
947 unsigned NumConstraints = NumOutputs + NumInputs;
948 Constraints = new (C) Expr *[NumConstraints];
949 std::copy(first: constraints, last: constraints + NumConstraints, result: Constraints);
950
951 Clobbers = new (C) Expr *[NumClobbers];
952 std::copy(first: clobbers, last: clobbers + NumClobbers, result: Clobbers);
953}
954
955MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
956 SourceLocation lbraceloc, bool issimple, bool isvolatile,
957 ArrayRef<Token> asmtoks, unsigned numoutputs,
958 unsigned numinputs,
959 ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
960 StringRef asmstr, ArrayRef<StringRef> clobbers,
961 SourceLocation endloc)
962 : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
963 numinputs, clobbers.size()), LBraceLoc(lbraceloc),
964 EndLoc(endloc), NumAsmToks(asmtoks.size()) {
965 initialize(C, AsmString: asmstr, AsmToks: asmtoks, Constraints: constraints, Exprs: exprs, Clobbers: clobbers);
966}
967
968static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
969 return str.copy(A: C);
970}
971
972void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
973 ArrayRef<Token> asmtoks,
974 ArrayRef<StringRef> constraints,
975 ArrayRef<Expr*> exprs,
976 ArrayRef<StringRef> clobbers) {
977 assert(NumAsmToks == asmtoks.size());
978 assert(NumClobbers == clobbers.size());
979
980 assert(exprs.size() == NumOutputs + NumInputs);
981 assert(exprs.size() == constraints.size());
982
983 AsmStr = copyIntoContext(C, str: asmstr);
984
985 Exprs = new (C) Stmt*[exprs.size()];
986 llvm::copy(Range&: exprs, Out: Exprs);
987
988 AsmToks = new (C) Token[asmtoks.size()];
989 llvm::copy(Range&: asmtoks, Out: AsmToks);
990
991 Constraints = new (C) StringRef[exprs.size()];
992 std::transform(first: constraints.begin(), last: constraints.end(), result: Constraints,
993 unary_op: [&](StringRef Constraint) {
994 return copyIntoContext(C, str: Constraint);
995 });
996
997 Clobbers = new (C) StringRef[NumClobbers];
998 // FIXME: Avoid the allocation/copy if at all possible.
999 std::transform(first: clobbers.begin(), last: clobbers.end(), result: Clobbers,
1000 unary_op: [&](StringRef Clobber) {
1001 return copyIntoContext(C, str: Clobber);
1002 });
1003}
1004
1005IfStmt::IfStmt(const ASTContext &Ctx, SourceLocation IL, IfStatementKind Kind,
1006 Stmt *Init, VarDecl *Var, Expr *Cond, SourceLocation LPL,
1007 SourceLocation RPL, Stmt *Then, SourceLocation EL, Stmt *Else)
1008 : Stmt(IfStmtClass), LParenLoc(LPL), RParenLoc(RPL) {
1009 bool HasElse = Else != nullptr;
1010 bool HasVar = Var != nullptr;
1011 bool HasInit = Init != nullptr;
1012 IfStmtBits.HasElse = HasElse;
1013 IfStmtBits.HasVar = HasVar;
1014 IfStmtBits.HasInit = HasInit;
1015
1016 setStatementKind(Kind);
1017
1018 setCond(Cond);
1019 setThen(Then);
1020 if (HasElse)
1021 setElse(Else);
1022 if (HasVar)
1023 setConditionVariable(Ctx, V: Var);
1024 if (HasInit)
1025 setInit(Init);
1026
1027 setIfLoc(IL);
1028 if (HasElse)
1029 setElseLoc(EL);
1030}
1031
1032IfStmt::IfStmt(EmptyShell Empty, bool HasElse, bool HasVar, bool HasInit)
1033 : Stmt(IfStmtClass, Empty) {
1034 IfStmtBits.HasElse = HasElse;
1035 IfStmtBits.HasVar = HasVar;
1036 IfStmtBits.HasInit = HasInit;
1037}
1038
1039IfStmt *IfStmt::Create(const ASTContext &Ctx, SourceLocation IL,
1040 IfStatementKind Kind, Stmt *Init, VarDecl *Var,
1041 Expr *Cond, SourceLocation LPL, SourceLocation RPL,
1042 Stmt *Then, SourceLocation EL, Stmt *Else) {
1043 bool HasElse = Else != nullptr;
1044 bool HasVar = Var != nullptr;
1045 bool HasInit = Init != nullptr;
1046 void *Mem = Ctx.Allocate(
1047 Size: totalSizeToAlloc<Stmt *, SourceLocation>(
1048 Counts: NumMandatoryStmtPtr + HasElse + HasVar + HasInit, Counts: HasElse),
1049 Align: alignof(IfStmt));
1050 return new (Mem)
1051 IfStmt(Ctx, IL, Kind, Init, Var, Cond, LPL, RPL, Then, EL, Else);
1052}
1053
1054IfStmt *IfStmt::CreateEmpty(const ASTContext &Ctx, bool HasElse, bool HasVar,
1055 bool HasInit) {
1056 void *Mem = Ctx.Allocate(
1057 Size: totalSizeToAlloc<Stmt *, SourceLocation>(
1058 Counts: NumMandatoryStmtPtr + HasElse + HasVar + HasInit, Counts: HasElse),
1059 Align: alignof(IfStmt));
1060 return new (Mem) IfStmt(EmptyShell(), HasElse, HasVar, HasInit);
1061}
1062
1063VarDecl *IfStmt::getConditionVariable() {
1064 auto *DS = getConditionVariableDeclStmt();
1065 if (!DS)
1066 return nullptr;
1067 return cast<VarDecl>(Val: DS->getSingleDecl());
1068}
1069
1070void IfStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1071 assert(hasVarStorage() &&
1072 "This if statement has no storage for a condition variable!");
1073
1074 if (!V) {
1075 getTrailingObjects<Stmt *>()[varOffset()] = nullptr;
1076 return;
1077 }
1078
1079 SourceRange VarRange = V->getSourceRange();
1080 getTrailingObjects<Stmt *>()[varOffset()] = new (Ctx)
1081 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1082}
1083
1084bool IfStmt::isObjCAvailabilityCheck() const {
1085 return isa<ObjCAvailabilityCheckExpr>(Val: getCond());
1086}
1087
1088std::optional<Stmt *> IfStmt::getNondiscardedCase(const ASTContext &Ctx) {
1089 if (!isConstexpr() || getCond()->isValueDependent())
1090 return std::nullopt;
1091 return !getCond()->EvaluateKnownConstInt(Ctx) ? getElse() : getThen();
1092}
1093
1094std::optional<const Stmt *>
1095IfStmt::getNondiscardedCase(const ASTContext &Ctx) const {
1096 if (std::optional<Stmt *> Result =
1097 const_cast<IfStmt *>(this)->getNondiscardedCase(Ctx))
1098 return *Result;
1099 return std::nullopt;
1100}
1101
1102ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
1103 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
1104 SourceLocation RP)
1105 : Stmt(ForStmtClass), LParenLoc(LP), RParenLoc(RP)
1106{
1107 SubExprs[INIT] = Init;
1108 setConditionVariable(C, V: condVar);
1109 SubExprs[COND] = Cond;
1110 SubExprs[INC] = Inc;
1111 SubExprs[BODY] = Body;
1112 ForStmtBits.ForLoc = FL;
1113}
1114
1115VarDecl *ForStmt::getConditionVariable() const {
1116 if (!SubExprs[CONDVAR])
1117 return nullptr;
1118
1119 auto *DS = cast<DeclStmt>(Val: SubExprs[CONDVAR]);
1120 return cast<VarDecl>(Val: DS->getSingleDecl());
1121}
1122
1123void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
1124 if (!V) {
1125 SubExprs[CONDVAR] = nullptr;
1126 return;
1127 }
1128
1129 SourceRange VarRange = V->getSourceRange();
1130 SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
1131 VarRange.getEnd());
1132}
1133
1134SwitchStmt::SwitchStmt(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
1135 Expr *Cond, SourceLocation LParenLoc,
1136 SourceLocation RParenLoc)
1137 : Stmt(SwitchStmtClass), FirstCase(nullptr), LParenLoc(LParenLoc),
1138 RParenLoc(RParenLoc) {
1139 bool HasInit = Init != nullptr;
1140 bool HasVar = Var != nullptr;
1141 SwitchStmtBits.HasInit = HasInit;
1142 SwitchStmtBits.HasVar = HasVar;
1143 SwitchStmtBits.AllEnumCasesCovered = false;
1144
1145 setCond(Cond);
1146 setBody(nullptr);
1147 if (HasInit)
1148 setInit(Init);
1149 if (HasVar)
1150 setConditionVariable(Ctx, VD: Var);
1151
1152 setSwitchLoc(SourceLocation{});
1153}
1154
1155SwitchStmt::SwitchStmt(EmptyShell Empty, bool HasInit, bool HasVar)
1156 : Stmt(SwitchStmtClass, Empty) {
1157 SwitchStmtBits.HasInit = HasInit;
1158 SwitchStmtBits.HasVar = HasVar;
1159 SwitchStmtBits.AllEnumCasesCovered = false;
1160}
1161
1162SwitchStmt *SwitchStmt::Create(const ASTContext &Ctx, Stmt *Init, VarDecl *Var,
1163 Expr *Cond, SourceLocation LParenLoc,
1164 SourceLocation RParenLoc) {
1165 bool HasInit = Init != nullptr;
1166 bool HasVar = Var != nullptr;
1167 void *Mem = Ctx.Allocate(
1168 Size: totalSizeToAlloc<Stmt *>(Counts: NumMandatoryStmtPtr + HasInit + HasVar),
1169 Align: alignof(SwitchStmt));
1170 return new (Mem) SwitchStmt(Ctx, Init, Var, Cond, LParenLoc, RParenLoc);
1171}
1172
1173SwitchStmt *SwitchStmt::CreateEmpty(const ASTContext &Ctx, bool HasInit,
1174 bool HasVar) {
1175 void *Mem = Ctx.Allocate(
1176 Size: totalSizeToAlloc<Stmt *>(Counts: NumMandatoryStmtPtr + HasInit + HasVar),
1177 Align: alignof(SwitchStmt));
1178 return new (Mem) SwitchStmt(EmptyShell(), HasInit, HasVar);
1179}
1180
1181VarDecl *SwitchStmt::getConditionVariable() {
1182 auto *DS = getConditionVariableDeclStmt();
1183 if (!DS)
1184 return nullptr;
1185 return cast<VarDecl>(Val: DS->getSingleDecl());
1186}
1187
1188void SwitchStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1189 assert(hasVarStorage() &&
1190 "This switch statement has no storage for a condition variable!");
1191
1192 if (!V) {
1193 getTrailingObjects()[varOffset()] = nullptr;
1194 return;
1195 }
1196
1197 SourceRange VarRange = V->getSourceRange();
1198 getTrailingObjects()[varOffset()] = new (Ctx)
1199 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1200}
1201
1202WhileStmt::WhileStmt(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1203 Stmt *Body, SourceLocation WL, SourceLocation LParenLoc,
1204 SourceLocation RParenLoc)
1205 : Stmt(WhileStmtClass) {
1206 bool HasVar = Var != nullptr;
1207 WhileStmtBits.HasVar = HasVar;
1208
1209 setCond(Cond);
1210 setBody(Body);
1211 if (HasVar)
1212 setConditionVariable(Ctx, V: Var);
1213
1214 setWhileLoc(WL);
1215 setLParenLoc(LParenLoc);
1216 setRParenLoc(RParenLoc);
1217}
1218
1219WhileStmt::WhileStmt(EmptyShell Empty, bool HasVar)
1220 : Stmt(WhileStmtClass, Empty) {
1221 WhileStmtBits.HasVar = HasVar;
1222}
1223
1224WhileStmt *WhileStmt::Create(const ASTContext &Ctx, VarDecl *Var, Expr *Cond,
1225 Stmt *Body, SourceLocation WL,
1226 SourceLocation LParenLoc,
1227 SourceLocation RParenLoc) {
1228 bool HasVar = Var != nullptr;
1229 void *Mem =
1230 Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: NumMandatoryStmtPtr + HasVar),
1231 Align: alignof(WhileStmt));
1232 return new (Mem) WhileStmt(Ctx, Var, Cond, Body, WL, LParenLoc, RParenLoc);
1233}
1234
1235WhileStmt *WhileStmt::CreateEmpty(const ASTContext &Ctx, bool HasVar) {
1236 void *Mem =
1237 Ctx.Allocate(Size: totalSizeToAlloc<Stmt *>(Counts: NumMandatoryStmtPtr + HasVar),
1238 Align: alignof(WhileStmt));
1239 return new (Mem) WhileStmt(EmptyShell(), HasVar);
1240}
1241
1242VarDecl *WhileStmt::getConditionVariable() {
1243 auto *DS = getConditionVariableDeclStmt();
1244 if (!DS)
1245 return nullptr;
1246 return cast<VarDecl>(Val: DS->getSingleDecl());
1247}
1248
1249void WhileStmt::setConditionVariable(const ASTContext &Ctx, VarDecl *V) {
1250 assert(hasVarStorage() &&
1251 "This while statement has no storage for a condition variable!");
1252
1253 if (!V) {
1254 getTrailingObjects()[varOffset()] = nullptr;
1255 return;
1256 }
1257
1258 SourceRange VarRange = V->getSourceRange();
1259 getTrailingObjects()[varOffset()] = new (Ctx)
1260 DeclStmt(DeclGroupRef(V), VarRange.getBegin(), VarRange.getEnd());
1261}
1262
1263// IndirectGotoStmt
1264LabelDecl *IndirectGotoStmt::getConstantTarget() {
1265 if (auto *E = dyn_cast<AddrLabelExpr>(Val: getTarget()->IgnoreParenImpCasts()))
1266 return E->getLabel();
1267 return nullptr;
1268}
1269
1270// ReturnStmt
1271ReturnStmt::ReturnStmt(SourceLocation RL, Expr *E, const VarDecl *NRVOCandidate)
1272 : Stmt(ReturnStmtClass), RetExpr(E) {
1273 bool HasNRVOCandidate = NRVOCandidate != nullptr;
1274 ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1275 if (HasNRVOCandidate)
1276 setNRVOCandidate(NRVOCandidate);
1277 setReturnLoc(RL);
1278}
1279
1280ReturnStmt::ReturnStmt(EmptyShell Empty, bool HasNRVOCandidate)
1281 : Stmt(ReturnStmtClass, Empty) {
1282 ReturnStmtBits.HasNRVOCandidate = HasNRVOCandidate;
1283}
1284
1285ReturnStmt *ReturnStmt::Create(const ASTContext &Ctx, SourceLocation RL,
1286 Expr *E, const VarDecl *NRVOCandidate) {
1287 bool HasNRVOCandidate = NRVOCandidate != nullptr;
1288 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<const VarDecl *>(Counts: HasNRVOCandidate),
1289 Align: alignof(ReturnStmt));
1290 return new (Mem) ReturnStmt(RL, E, NRVOCandidate);
1291}
1292
1293ReturnStmt *ReturnStmt::CreateEmpty(const ASTContext &Ctx,
1294 bool HasNRVOCandidate) {
1295 void *Mem = Ctx.Allocate(Size: totalSizeToAlloc<const VarDecl *>(Counts: HasNRVOCandidate),
1296 Align: alignof(ReturnStmt));
1297 return new (Mem) ReturnStmt(EmptyShell(), HasNRVOCandidate);
1298}
1299
1300// CaseStmt
1301CaseStmt *CaseStmt::Create(const ASTContext &Ctx, Expr *lhs, Expr *rhs,
1302 SourceLocation caseLoc, SourceLocation ellipsisLoc,
1303 SourceLocation colonLoc) {
1304 bool CaseStmtIsGNURange = rhs != nullptr;
1305 void *Mem = Ctx.Allocate(
1306 Size: totalSizeToAlloc<Stmt *, SourceLocation>(
1307 Counts: NumMandatoryStmtPtr + CaseStmtIsGNURange, Counts: CaseStmtIsGNURange),
1308 Align: alignof(CaseStmt));
1309 return new (Mem) CaseStmt(lhs, rhs, caseLoc, ellipsisLoc, colonLoc);
1310}
1311
1312CaseStmt *CaseStmt::CreateEmpty(const ASTContext &Ctx,
1313 bool CaseStmtIsGNURange) {
1314 void *Mem = Ctx.Allocate(
1315 Size: totalSizeToAlloc<Stmt *, SourceLocation>(
1316 Counts: NumMandatoryStmtPtr + CaseStmtIsGNURange, Counts: CaseStmtIsGNURange),
1317 Align: alignof(CaseStmt));
1318 return new (Mem) CaseStmt(EmptyShell(), CaseStmtIsGNURange);
1319}
1320
1321SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
1322 Stmt *Handler)
1323 : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
1324 Children[TRY] = TryBlock;
1325 Children[HANDLER] = Handler;
1326}
1327
1328SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
1329 SourceLocation TryLoc, Stmt *TryBlock,
1330 Stmt *Handler) {
1331 return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
1332}
1333
1334SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
1335 return dyn_cast<SEHExceptStmt>(Val: getHandler());
1336}
1337
1338SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
1339 return dyn_cast<SEHFinallyStmt>(Val: getHandler());
1340}
1341
1342SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
1343 : Stmt(SEHExceptStmtClass), Loc(Loc) {
1344 Children[FILTER_EXPR] = FilterExpr;
1345 Children[BLOCK] = Block;
1346}
1347
1348SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
1349 Expr *FilterExpr, Stmt *Block) {
1350 return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
1351}
1352
1353SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
1354 : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
1355
1356SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
1357 Stmt *Block) {
1358 return new(C)SEHFinallyStmt(Loc,Block);
1359}
1360
1361CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
1362 VarDecl *Var)
1363 : VarAndKind(Var, Kind), Loc(Loc) {
1364 switch (Kind) {
1365 case VCK_This:
1366 assert(!Var && "'this' capture cannot have a variable!");
1367 break;
1368 case VCK_ByRef:
1369 assert(Var && "capturing by reference must have a variable!");
1370 break;
1371 case VCK_ByCopy:
1372 assert(Var && "capturing by copy must have a variable!");
1373 break;
1374 case VCK_VLAType:
1375 assert(!Var &&
1376 "Variable-length array type capture cannot have a variable!");
1377 break;
1378 }
1379}
1380
1381CapturedStmt::VariableCaptureKind
1382CapturedStmt::Capture::getCaptureKind() const {
1383 return VarAndKind.getInt();
1384}
1385
1386VarDecl *CapturedStmt::Capture::getCapturedVar() const {
1387 assert((capturesVariable() || capturesVariableByCopy()) &&
1388 "No variable available for 'this' or VAT capture");
1389 return VarAndKind.getPointer();
1390}
1391
1392CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1393 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1394
1395 // Offset of the first Capture object.
1396 unsigned FirstCaptureOffset = llvm::alignTo(Value: Size, Align: alignof(Capture));
1397
1398 return reinterpret_cast<Capture *>(
1399 reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1400 + FirstCaptureOffset);
1401}
1402
1403CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1404 ArrayRef<Capture> Captures,
1405 ArrayRef<Expr *> CaptureInits,
1406 CapturedDecl *CD,
1407 RecordDecl *RD)
1408 : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1409 CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1410 assert( S && "null captured statement");
1411 assert(CD && "null captured declaration for captured statement");
1412 assert(RD && "null record declaration for captured statement");
1413
1414 // Copy initialization expressions.
1415 Stmt **Stored = getStoredStmts();
1416 for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1417 *Stored++ = CaptureInits[I];
1418
1419 // Copy the statement being captured.
1420 *Stored = S;
1421
1422 // Copy all Capture objects.
1423 Capture *Buffer = getStoredCaptures();
1424 llvm::copy(Range&: Captures, Out: Buffer);
1425}
1426
1427CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1428 : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1429 CapDeclAndKind(nullptr, CR_Default) {
1430 getStoredStmts()[NumCaptures] = nullptr;
1431
1432 // Construct default capture objects.
1433 Capture *Buffer = getStoredCaptures();
1434 for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1435 new (Buffer++) Capture();
1436}
1437
1438CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
1439 CapturedRegionKind Kind,
1440 ArrayRef<Capture> Captures,
1441 ArrayRef<Expr *> CaptureInits,
1442 CapturedDecl *CD,
1443 RecordDecl *RD) {
1444 // The layout is
1445 //
1446 // -----------------------------------------------------------
1447 // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1448 // ----------------^-------------------^----------------------
1449 // getStoredStmts() getStoredCaptures()
1450 //
1451 // where S is the statement being captured.
1452 //
1453 assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1454
1455 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1456 if (!Captures.empty()) {
1457 // Realign for the following Capture array.
1458 Size = llvm::alignTo(Value: Size, Align: alignof(Capture));
1459 Size += sizeof(Capture) * Captures.size();
1460 }
1461
1462 void *Mem = Context.Allocate(Size);
1463 return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1464}
1465
1466CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
1467 unsigned NumCaptures) {
1468 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1469 if (NumCaptures > 0) {
1470 // Realign for the following Capture array.
1471 Size = llvm::alignTo(Value: Size, Align: alignof(Capture));
1472 Size += sizeof(Capture) * NumCaptures;
1473 }
1474
1475 void *Mem = Context.Allocate(Size);
1476 return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1477}
1478
1479Stmt::child_range CapturedStmt::children() {
1480 // Children are captured field initializers.
1481 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1482}
1483
1484Stmt::const_child_range CapturedStmt::children() const {
1485 return const_child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1486}
1487
1488CapturedDecl *CapturedStmt::getCapturedDecl() {
1489 return CapDeclAndKind.getPointer();
1490}
1491
1492const CapturedDecl *CapturedStmt::getCapturedDecl() const {
1493 return CapDeclAndKind.getPointer();
1494}
1495
1496/// Set the outlined function declaration.
1497void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
1498 assert(D && "null CapturedDecl");
1499 CapDeclAndKind.setPointer(D);
1500}
1501
1502/// Retrieve the captured region kind.
1503CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
1504 return CapDeclAndKind.getInt();
1505}
1506
1507/// Set the captured region kind.
1508void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
1509 CapDeclAndKind.setInt(Kind);
1510}
1511
1512bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1513 for (const auto &I : captures()) {
1514 if (!I.capturesVariable() && !I.capturesVariableByCopy())
1515 continue;
1516 if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())
1517 return true;
1518 }
1519
1520 return false;
1521}
1522
1523const Stmt *LabelStmt::getInnermostLabeledStmt() const {
1524 const Stmt *S = getSubStmt();
1525 while (isa_and_present<LabelStmt>(Val: S))
1526 S = cast<LabelStmt>(Val: S)->getSubStmt();
1527 return S;
1528}
1529
1530const Stmt *LoopControlStmt::getNamedLoopOrSwitch() const {
1531 if (!hasLabelTarget())
1532 return nullptr;
1533 return getLabelDecl()->getStmt()->getInnermostLabeledStmt();
1534}
1535
1536DeferStmt::DeferStmt(EmptyShell Empty) : Stmt(DeferStmtClass, Empty) {}
1537DeferStmt::DeferStmt(SourceLocation DeferLoc, Stmt *Body)
1538 : Stmt(DeferStmtClass) {
1539 setDeferLoc(DeferLoc);
1540 setBody(Body);
1541}
1542
1543DeferStmt *DeferStmt::CreateEmpty(ASTContext &Context, EmptyShell Empty) {
1544 return new (Context) DeferStmt(Empty);
1545}
1546
1547DeferStmt *DeferStmt::Create(ASTContext &Context, SourceLocation DeferLoc,
1548 Stmt *Body) {
1549 return new (Context) DeferStmt(DeferLoc, Body);
1550}
1551