1 //===- Stmt.cpp - Statement AST Node Implementation -----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Stmt class and statement subclasses.
12 //===----------------------------------------------------------------------===//
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/ASTDiagnostic.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/AST/DeclGroup.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/AST/ExprOpenMP.h"
21 #include "clang/AST/Stmt.h"
22 #include "clang/AST/StmtCXX.h"
23 #include "clang/AST/StmtObjC.h"
24 #include "clang/AST/StmtOpenMP.h"
25 #include "clang/AST/Type.h"
26 #include "clang/Basic/CharInfo.h"
27 #include "clang/Basic/LLVM.h"
28 #include "clang/Basic/SourceLocation.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "clang/Lex/Token.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/raw_ostream.h"
45 using namespace clang;
47 static struct StmtClassNameTable {
51 } StmtClassInfo[Stmt::lastStmtConstant+1];
53 static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
54 static bool Initialized = false;
56 return StmtClassInfo[E];
58 // Intialize the table on the first use.
60 #define ABSTRACT_STMT(STMT)
61 #define STMT(CLASS, PARENT) \
62 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
63 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
64 #include "clang/AST/StmtNodes.inc"
66 return StmtClassInfo[E];
69 void *Stmt::operator new(size_t bytes, const ASTContext& C,
71 return ::operator new(bytes, C, alignment);
74 const char *Stmt::getStmtClassName() const {
75 return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
78 void Stmt::PrintStats() {
79 // Ensure the table is primed.
80 getStmtInfoTableEntry(Stmt::NullStmtClass);
83 llvm::errs() << "\n*** Stmt/Expr Stats:\n";
84 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
85 if (StmtClassInfo[i].Name == nullptr) continue;
86 sum += StmtClassInfo[i].Counter;
88 llvm::errs() << " " << sum << " stmts/exprs total.\n";
90 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
91 if (StmtClassInfo[i].Name == nullptr) continue;
92 if (StmtClassInfo[i].Counter == 0) continue;
93 llvm::errs() << " " << StmtClassInfo[i].Counter << " "
94 << StmtClassInfo[i].Name << ", " << StmtClassInfo[i].Size
95 << " each (" << StmtClassInfo[i].Counter*StmtClassInfo[i].Size
97 sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
100 llvm::errs() << "Total bytes = " << sum << "\n";
103 void Stmt::addStmtClass(StmtClass s) {
104 ++getStmtInfoTableEntry(s).Counter;
107 bool Stmt::StatisticsEnabled = false;
108 void Stmt::EnableStatistics() {
109 StatisticsEnabled = true;
112 Stmt *Stmt::IgnoreImplicit() {
115 if (auto *ewc = dyn_cast<ExprWithCleanups>(s))
116 s = ewc->getSubExpr();
118 if (auto *mte = dyn_cast<MaterializeTemporaryExpr>(s))
119 s = mte->GetTemporaryExpr();
121 if (auto *bte = dyn_cast<CXXBindTemporaryExpr>(s))
122 s = bte->getSubExpr();
124 while (auto *ice = dyn_cast<ImplicitCastExpr>(s))
125 s = ice->getSubExpr();
130 /// \brief Skip no-op (attributed, compound) container stmts and skip captured
131 /// stmt at the top, if \a IgnoreCaptured is true.
132 Stmt *Stmt::IgnoreContainers(bool IgnoreCaptured) {
135 if (auto CapS = dyn_cast_or_null<CapturedStmt>(S))
136 S = CapS->getCapturedStmt();
138 if (auto AS = dyn_cast_or_null<AttributedStmt>(S))
139 S = AS->getSubStmt();
140 else if (auto CS = dyn_cast_or_null<CompoundStmt>(S)) {
150 /// \brief Strip off all label-like statements.
152 /// This will strip off label statements, case statements, attributed
153 /// statements and default statements recursively.
154 const Stmt *Stmt::stripLabelLikeStatements() const {
155 const Stmt *S = this;
157 if (const LabelStmt *LS = dyn_cast<LabelStmt>(S))
158 S = LS->getSubStmt();
159 else if (const SwitchCase *SC = dyn_cast<SwitchCase>(S))
160 S = SC->getSubStmt();
161 else if (const AttributedStmt *AS = dyn_cast<AttributedStmt>(S))
162 S = AS->getSubStmt();
173 // These silly little functions have to be static inline to suppress
174 // unused warnings, and they have to be defined to suppress other
176 static inline good is_good(good) { return good(); }
178 typedef Stmt::child_range children_t();
179 template <class T> good implements_children(children_t T::*) {
182 LLVM_ATTRIBUTE_UNUSED
183 static inline bad implements_children(children_t Stmt::*) {
187 typedef SourceLocation getLocStart_t() const;
188 template <class T> good implements_getLocStart(getLocStart_t T::*) {
191 LLVM_ATTRIBUTE_UNUSED
192 static inline bad implements_getLocStart(getLocStart_t Stmt::*) {
196 typedef SourceLocation getLocEnd_t() const;
197 template <class T> good implements_getLocEnd(getLocEnd_t T::*) {
200 LLVM_ATTRIBUTE_UNUSED
201 static inline bad implements_getLocEnd(getLocEnd_t Stmt::*) {
205 #define ASSERT_IMPLEMENTS_children(type) \
206 (void) is_good(implements_children(&type::children))
207 #define ASSERT_IMPLEMENTS_getLocStart(type) \
208 (void) is_good(implements_getLocStart(&type::getLocStart))
209 #define ASSERT_IMPLEMENTS_getLocEnd(type) \
210 (void) is_good(implements_getLocEnd(&type::getLocEnd))
214 /// Check whether the various Stmt classes implement their member
216 LLVM_ATTRIBUTE_UNUSED
217 static inline void check_implementations() {
218 #define ABSTRACT_STMT(type)
219 #define STMT(type, base) \
220 ASSERT_IMPLEMENTS_children(type); \
221 ASSERT_IMPLEMENTS_getLocStart(type); \
222 ASSERT_IMPLEMENTS_getLocEnd(type);
223 #include "clang/AST/StmtNodes.inc"
226 Stmt::child_range Stmt::children() {
227 switch (getStmtClass()) {
228 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
229 #define ABSTRACT_STMT(type)
230 #define STMT(type, base) \
231 case Stmt::type##Class: \
232 return static_cast<type*>(this)->children();
233 #include "clang/AST/StmtNodes.inc"
235 llvm_unreachable("unknown statement kind!");
238 // Amusing macro metaprogramming hack: check whether a class provides
239 // a more specific implementation of getSourceRange.
241 // See also Expr.cpp:getExprLoc().
244 /// This implementation is used when a class provides a custom
245 /// implementation of getSourceRange.
246 template <class S, class T>
247 SourceRange getSourceRangeImpl(const Stmt *stmt,
248 SourceRange (T::*v)() const) {
249 return static_cast<const S*>(stmt)->getSourceRange();
252 /// This implementation is used when a class doesn't provide a custom
253 /// implementation of getSourceRange. Overload resolution should pick it over
254 /// the implementation above because it's more specialized according to
255 /// function template partial ordering.
257 SourceRange getSourceRangeImpl(const Stmt *stmt,
258 SourceRange (Stmt::*v)() const) {
259 return SourceRange(static_cast<const S*>(stmt)->getLocStart(),
260 static_cast<const S*>(stmt)->getLocEnd());
265 SourceRange Stmt::getSourceRange() const {
266 switch (getStmtClass()) {
267 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
268 #define ABSTRACT_STMT(type)
269 #define STMT(type, base) \
270 case Stmt::type##Class: \
271 return getSourceRangeImpl<type>(this, &type::getSourceRange);
272 #include "clang/AST/StmtNodes.inc"
274 llvm_unreachable("unknown statement kind!");
277 SourceLocation Stmt::getLocStart() const {
278 // llvm::errs() << "getLocStart() for " << getStmtClassName() << "\n";
279 switch (getStmtClass()) {
280 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
281 #define ABSTRACT_STMT(type)
282 #define STMT(type, base) \
283 case Stmt::type##Class: \
284 return static_cast<const type*>(this)->getLocStart();
285 #include "clang/AST/StmtNodes.inc"
287 llvm_unreachable("unknown statement kind");
290 SourceLocation Stmt::getLocEnd() const {
291 switch (getStmtClass()) {
292 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
293 #define ABSTRACT_STMT(type)
294 #define STMT(type, base) \
295 case Stmt::type##Class: \
296 return static_cast<const type*>(this)->getLocEnd();
297 #include "clang/AST/StmtNodes.inc"
299 llvm_unreachable("unknown statement kind");
302 CompoundStmt::CompoundStmt(ArrayRef<Stmt *> Stmts, SourceLocation LB,
304 : Stmt(CompoundStmtClass), LBraceLoc(LB), RBraceLoc(RB) {
305 CompoundStmtBits.NumStmts = Stmts.size();
309 void CompoundStmt::setStmts(ArrayRef<Stmt *> Stmts) {
310 assert(CompoundStmtBits.NumStmts == Stmts.size() &&
311 "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
313 std::copy(Stmts.begin(), Stmts.end(), body_begin());
316 CompoundStmt *CompoundStmt::Create(const ASTContext &C, ArrayRef<Stmt *> Stmts,
317 SourceLocation LB, SourceLocation RB) {
319 C.Allocate(totalSizeToAlloc<Stmt *>(Stmts.size()), alignof(CompoundStmt));
320 return new (Mem) CompoundStmt(Stmts, LB, RB);
323 CompoundStmt *CompoundStmt::CreateEmpty(const ASTContext &C,
326 C.Allocate(totalSizeToAlloc<Stmt *>(NumStmts), alignof(CompoundStmt));
327 CompoundStmt *New = new (Mem) CompoundStmt(EmptyShell());
328 New->CompoundStmtBits.NumStmts = NumStmts;
332 const char *LabelStmt::getName() const {
333 return getDecl()->getIdentifier()->getNameStart();
336 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
337 ArrayRef<const Attr*> Attrs,
339 assert(!Attrs.empty() && "Attrs should not be empty");
340 void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(Attrs.size()),
341 alignof(AttributedStmt));
342 return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
345 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
347 assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
348 void *Mem = C.Allocate(totalSizeToAlloc<const Attr *>(NumAttrs),
349 alignof(AttributedStmt));
350 return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
353 std::string AsmStmt::generateAsmString(const ASTContext &C) const {
354 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
355 return gccAsmStmt->generateAsmString(C);
356 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
357 return msAsmStmt->generateAsmString(C);
358 llvm_unreachable("unknown asm statement kind!");
361 StringRef AsmStmt::getOutputConstraint(unsigned i) const {
362 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
363 return gccAsmStmt->getOutputConstraint(i);
364 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
365 return msAsmStmt->getOutputConstraint(i);
366 llvm_unreachable("unknown asm statement kind!");
369 const Expr *AsmStmt::getOutputExpr(unsigned i) const {
370 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
371 return gccAsmStmt->getOutputExpr(i);
372 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
373 return msAsmStmt->getOutputExpr(i);
374 llvm_unreachable("unknown asm statement kind!");
377 StringRef AsmStmt::getInputConstraint(unsigned i) const {
378 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
379 return gccAsmStmt->getInputConstraint(i);
380 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
381 return msAsmStmt->getInputConstraint(i);
382 llvm_unreachable("unknown asm statement kind!");
385 const Expr *AsmStmt::getInputExpr(unsigned i) const {
386 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
387 return gccAsmStmt->getInputExpr(i);
388 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
389 return msAsmStmt->getInputExpr(i);
390 llvm_unreachable("unknown asm statement kind!");
393 StringRef AsmStmt::getClobber(unsigned i) const {
394 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
395 return gccAsmStmt->getClobber(i);
396 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
397 return msAsmStmt->getClobber(i);
398 llvm_unreachable("unknown asm statement kind!");
401 /// getNumPlusOperands - Return the number of output operands that have a "+"
403 unsigned AsmStmt::getNumPlusOperands() const {
405 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
406 if (isOutputPlusConstraint(i))
411 char GCCAsmStmt::AsmStringPiece::getModifier() const {
412 assert(isOperand() && "Only Operands can have modifiers.");
413 return isLetter(Str[0]) ? Str[0] : '\0';
416 StringRef GCCAsmStmt::getClobber(unsigned i) const {
417 return getClobberStringLiteral(i)->getString();
420 Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
421 return cast<Expr>(Exprs[i]);
424 /// getOutputConstraint - Return the constraint string for the specified
425 /// output operand. All output constraints are known to be non-empty (either
427 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const {
428 return getOutputConstraintLiteral(i)->getString();
431 Expr *GCCAsmStmt::getInputExpr(unsigned i) {
432 return cast<Expr>(Exprs[i + NumOutputs]);
435 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
436 Exprs[i + NumOutputs] = E;
439 /// getInputConstraint - Return the specified input constraint. Unlike output
440 /// constraints, these can be empty.
441 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const {
442 return getInputConstraintLiteral(i)->getString();
445 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C,
446 IdentifierInfo **Names,
447 StringLiteral **Constraints,
451 StringLiteral **Clobbers,
452 unsigned NumClobbers) {
453 this->NumOutputs = NumOutputs;
454 this->NumInputs = NumInputs;
455 this->NumClobbers = NumClobbers;
457 unsigned NumExprs = NumOutputs + NumInputs;
459 C.Deallocate(this->Names);
460 this->Names = new (C) IdentifierInfo*[NumExprs];
461 std::copy(Names, Names + NumExprs, this->Names);
463 C.Deallocate(this->Exprs);
464 this->Exprs = new (C) Stmt*[NumExprs];
465 std::copy(Exprs, Exprs + NumExprs, this->Exprs);
467 C.Deallocate(this->Constraints);
468 this->Constraints = new (C) StringLiteral*[NumExprs];
469 std::copy(Constraints, Constraints + NumExprs, this->Constraints);
471 C.Deallocate(this->Clobbers);
472 this->Clobbers = new (C) StringLiteral*[NumClobbers];
473 std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
476 /// getNamedOperand - Given a symbolic operand reference like %[foo],
477 /// translate this into a numeric value needed to reference the same operand.
478 /// This returns -1 if the operand name is invalid.
479 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
480 unsigned NumPlusOperands = 0;
482 // Check if this is an output operand.
483 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
484 if (getOutputName(i) == SymbolicName)
488 for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
489 if (getInputName(i) == SymbolicName)
490 return getNumOutputs() + NumPlusOperands + i;
496 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
497 /// it into pieces. If the asm string is erroneous, emit errors and return
498 /// true, otherwise return false.
499 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
500 const ASTContext &C, unsigned &DiagOffs) const {
501 StringRef Str = getAsmString()->getString();
502 const char *StrStart = Str.begin();
503 const char *StrEnd = Str.end();
504 const char *CurPtr = StrStart;
506 // "Simple" inline asms have no constraints or operands, just convert the asm
507 // string to escape $'s.
510 for (; CurPtr != StrEnd; ++CurPtr) {
520 Pieces.push_back(AsmStringPiece(Result));
524 // CurStringPiece - The current string that we are building up as we scan the
526 std::string CurStringPiece;
528 bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
530 unsigned LastAsmStringToken = 0;
531 unsigned LastAsmStringOffset = 0;
534 // Done with the string?
535 if (CurPtr == StrEnd) {
536 if (!CurStringPiece.empty())
537 Pieces.push_back(AsmStringPiece(CurStringPiece));
541 char CurChar = *CurPtr++;
543 case '$': CurStringPiece += "$$"; continue;
544 case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
545 case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
546 case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
550 CurStringPiece += CurChar;
554 // Escaped "%" character in asm string.
555 if (CurPtr == StrEnd) {
556 // % at end of string is invalid (no escape).
557 DiagOffs = CurPtr-StrStart-1;
558 return diag::err_asm_invalid_escape;
560 // Handle escaped char and continue looping over the asm string.
561 char EscapedChar = *CurPtr++;
562 switch (EscapedChar) {
568 CurStringPiece += EscapedChar;
570 case '=': // %= -> Generate a unique ID.
571 CurStringPiece += "${:uid}";
575 // Otherwise, we have an operand. If we have accumulated a string so far,
576 // add it to the Pieces list.
577 if (!CurStringPiece.empty()) {
578 Pieces.push_back(AsmStringPiece(CurStringPiece));
579 CurStringPiece.clear();
582 // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
583 // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
585 const char *Begin = CurPtr - 1; // Points to the character following '%'.
586 const char *Percent = Begin - 1; // Points to '%'.
588 if (isLetter(EscapedChar)) {
589 if (CurPtr == StrEnd) { // Premature end.
590 DiagOffs = CurPtr-StrStart-1;
591 return diag::err_asm_invalid_escape;
593 EscapedChar = *CurPtr++;
596 const TargetInfo &TI = C.getTargetInfo();
597 const SourceManager &SM = C.getSourceManager();
598 const LangOptions &LO = C.getLangOpts();
600 // Handle operands that don't have asmSymbolicName (e.g., %x4).
601 if (isDigit(EscapedChar)) {
602 // %n - Assembler operand n
606 while (CurPtr != StrEnd && isDigit(*CurPtr))
607 N = N*10 + ((*CurPtr++)-'0');
609 unsigned NumOperands =
610 getNumOutputs() + getNumPlusOperands() + getNumInputs();
611 if (N >= NumOperands) {
612 DiagOffs = CurPtr-StrStart-1;
613 return diag::err_asm_invalid_operand_number;
616 // Str contains "x4" (Operand without the leading %).
617 std::string Str(Begin, CurPtr - Begin);
619 // (BeginLoc, EndLoc) represents the range of the operand we are currently
620 // processing. Unlike Str, the range includes the leading '%'.
621 SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
622 Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
623 &LastAsmStringOffset);
624 SourceLocation EndLoc = getAsmString()->getLocationOfByte(
625 CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
626 &LastAsmStringOffset);
628 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
632 // Handle operands that have asmSymbolicName (e.g., %x[foo]).
633 if (EscapedChar == '[') {
634 DiagOffs = CurPtr-StrStart-1;
637 const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
638 if (NameEnd == nullptr)
639 return diag::err_asm_unterminated_symbolic_operand_name;
640 if (NameEnd == CurPtr)
641 return diag::err_asm_empty_symbolic_operand_name;
643 StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
645 int N = getNamedOperand(SymbolicName);
647 // Verify that an operand with that name exists.
648 DiagOffs = CurPtr-StrStart;
649 return diag::err_asm_unknown_symbolic_operand_name;
652 // Str contains "x[foo]" (Operand without the leading %).
653 std::string Str(Begin, NameEnd + 1 - Begin);
655 // (BeginLoc, EndLoc) represents the range of the operand we are currently
656 // processing. Unlike Str, the range includes the leading '%'.
657 SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
658 Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
659 &LastAsmStringOffset);
660 SourceLocation EndLoc = getAsmString()->getLocationOfByte(
661 NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
662 &LastAsmStringOffset);
664 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
670 DiagOffs = CurPtr-StrStart-1;
671 return diag::err_asm_invalid_escape;
675 /// Assemble final IR asm string (GCC-style).
676 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
677 // Analyze the asm string to decompose it into its pieces. We know that Sema
678 // has already done this, so it is guaranteed to be successful.
679 SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
681 AnalyzeAsmString(Pieces, C, DiagOffs);
683 std::string AsmString;
684 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
685 if (Pieces[i].isString())
686 AsmString += Pieces[i].getString();
687 else if (Pieces[i].getModifier() == '\0')
688 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
690 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
691 Pieces[i].getModifier() + '}';
696 /// Assemble final IR asm string (MS-style).
697 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
698 // FIXME: This needs to be translated into the IR string representation.
702 Expr *MSAsmStmt::getOutputExpr(unsigned i) {
703 return cast<Expr>(Exprs[i]);
706 Expr *MSAsmStmt::getInputExpr(unsigned i) {
707 return cast<Expr>(Exprs[i + NumOutputs]);
710 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
711 Exprs[i + NumOutputs] = E;
714 //===----------------------------------------------------------------------===//
716 //===----------------------------------------------------------------------===//
718 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
719 bool issimple, bool isvolatile, unsigned numoutputs,
720 unsigned numinputs, IdentifierInfo **names,
721 StringLiteral **constraints, Expr **exprs,
722 StringLiteral *asmstr, unsigned numclobbers,
723 StringLiteral **clobbers, SourceLocation rparenloc)
724 : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
725 numinputs, numclobbers), RParenLoc(rparenloc), AsmStr(asmstr) {
726 unsigned NumExprs = NumOutputs + NumInputs;
728 Names = new (C) IdentifierInfo*[NumExprs];
729 std::copy(names, names + NumExprs, Names);
731 Exprs = new (C) Stmt*[NumExprs];
732 std::copy(exprs, exprs + NumExprs, Exprs);
734 Constraints = new (C) StringLiteral*[NumExprs];
735 std::copy(constraints, constraints + NumExprs, Constraints);
737 Clobbers = new (C) StringLiteral*[NumClobbers];
738 std::copy(clobbers, clobbers + NumClobbers, Clobbers);
741 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
742 SourceLocation lbraceloc, bool issimple, bool isvolatile,
743 ArrayRef<Token> asmtoks, unsigned numoutputs,
745 ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
746 StringRef asmstr, ArrayRef<StringRef> clobbers,
747 SourceLocation endloc)
748 : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
749 numinputs, clobbers.size()), LBraceLoc(lbraceloc),
750 EndLoc(endloc), NumAsmToks(asmtoks.size()) {
751 initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
754 static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
758 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
759 ArrayRef<Token> asmtoks,
760 ArrayRef<StringRef> constraints,
761 ArrayRef<Expr*> exprs,
762 ArrayRef<StringRef> clobbers) {
763 assert(NumAsmToks == asmtoks.size());
764 assert(NumClobbers == clobbers.size());
766 assert(exprs.size() == NumOutputs + NumInputs);
767 assert(exprs.size() == constraints.size());
769 AsmStr = copyIntoContext(C, asmstr);
771 Exprs = new (C) Stmt*[exprs.size()];
772 std::copy(exprs.begin(), exprs.end(), Exprs);
774 AsmToks = new (C) Token[asmtoks.size()];
775 std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
777 Constraints = new (C) StringRef[exprs.size()];
778 std::transform(constraints.begin(), constraints.end(), Constraints,
779 [&](StringRef Constraint) {
780 return copyIntoContext(C, Constraint);
783 Clobbers = new (C) StringRef[NumClobbers];
784 // FIXME: Avoid the allocation/copy if at all possible.
785 std::transform(clobbers.begin(), clobbers.end(), Clobbers,
786 [&](StringRef Clobber) {
787 return copyIntoContext(C, Clobber);
791 IfStmt::IfStmt(const ASTContext &C, SourceLocation IL, bool IsConstexpr,
792 Stmt *init, VarDecl *var, Expr *cond, Stmt *then,
793 SourceLocation EL, Stmt *elsev)
794 : Stmt(IfStmtClass), IfLoc(IL), ElseLoc(EL) {
795 setConstexpr(IsConstexpr);
796 setConditionVariable(C, var);
797 SubExprs[INIT] = init;
798 SubExprs[COND] = cond;
799 SubExprs[THEN] = then;
800 SubExprs[ELSE] = elsev;
803 VarDecl *IfStmt::getConditionVariable() const {
807 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
808 return cast<VarDecl>(DS->getSingleDecl());
811 void IfStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
813 SubExprs[VAR] = nullptr;
817 SourceRange VarRange = V->getSourceRange();
818 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
822 bool IfStmt::isObjCAvailabilityCheck() const {
823 return isa<ObjCAvailabilityCheckExpr>(SubExprs[COND]);
826 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
827 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
829 : Stmt(ForStmtClass), ForLoc(FL), LParenLoc(LP), RParenLoc(RP)
831 SubExprs[INIT] = Init;
832 setConditionVariable(C, condVar);
833 SubExprs[COND] = Cond;
835 SubExprs[BODY] = Body;
838 VarDecl *ForStmt::getConditionVariable() const {
839 if (!SubExprs[CONDVAR])
842 DeclStmt *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
843 return cast<VarDecl>(DS->getSingleDecl());
846 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
848 SubExprs[CONDVAR] = nullptr;
852 SourceRange VarRange = V->getSourceRange();
853 SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
857 SwitchStmt::SwitchStmt(const ASTContext &C, Stmt *init, VarDecl *Var,
859 : Stmt(SwitchStmtClass), FirstCase(nullptr, false) {
860 setConditionVariable(C, Var);
861 SubExprs[INIT] = init;
862 SubExprs[COND] = cond;
863 SubExprs[BODY] = nullptr;
866 VarDecl *SwitchStmt::getConditionVariable() const {
870 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
871 return cast<VarDecl>(DS->getSingleDecl());
874 void SwitchStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
876 SubExprs[VAR] = nullptr;
880 SourceRange VarRange = V->getSourceRange();
881 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
885 Stmt *SwitchCase::getSubStmt() {
886 if (isa<CaseStmt>(this))
887 return cast<CaseStmt>(this)->getSubStmt();
888 return cast<DefaultStmt>(this)->getSubStmt();
891 WhileStmt::WhileStmt(const ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,
893 : Stmt(WhileStmtClass) {
894 setConditionVariable(C, Var);
895 SubExprs[COND] = cond;
896 SubExprs[BODY] = body;
900 VarDecl *WhileStmt::getConditionVariable() const {
904 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
905 return cast<VarDecl>(DS->getSingleDecl());
908 void WhileStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
910 SubExprs[VAR] = nullptr;
914 SourceRange VarRange = V->getSourceRange();
915 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
920 LabelDecl *IndirectGotoStmt::getConstantTarget() {
921 if (AddrLabelExpr *E =
922 dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
923 return E->getLabel();
928 const Expr* ReturnStmt::getRetValue() const {
929 return cast_or_null<Expr>(RetExpr);
931 Expr* ReturnStmt::getRetValue() {
932 return cast_or_null<Expr>(RetExpr);
935 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
937 : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
938 Children[TRY] = TryBlock;
939 Children[HANDLER] = Handler;
942 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
943 SourceLocation TryLoc, Stmt *TryBlock,
945 return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
948 SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
949 return dyn_cast<SEHExceptStmt>(getHandler());
952 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
953 return dyn_cast<SEHFinallyStmt>(getHandler());
956 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
957 : Stmt(SEHExceptStmtClass), Loc(Loc) {
958 Children[FILTER_EXPR] = FilterExpr;
959 Children[BLOCK] = Block;
962 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
963 Expr *FilterExpr, Stmt *Block) {
964 return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
967 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
968 : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
970 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
972 return new(C)SEHFinallyStmt(Loc,Block);
975 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
977 : VarAndKind(Var, Kind), Loc(Loc) {
980 assert(!Var && "'this' capture cannot have a variable!");
983 assert(Var && "capturing by reference must have a variable!");
986 assert(Var && "capturing by copy must have a variable!");
988 (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() &&
990 ->castAs<ReferenceType>()
992 ->isScalarType())) &&
993 "captures by copy are expected to have a scalar type!");
997 "Variable-length array type capture cannot have a variable!");
1002 CapturedStmt::VariableCaptureKind
1003 CapturedStmt::Capture::getCaptureKind() const {
1004 return VarAndKind.getInt();
1007 VarDecl *CapturedStmt::Capture::getCapturedVar() const {
1008 assert((capturesVariable() || capturesVariableByCopy()) &&
1009 "No variable available for 'this' or VAT capture");
1010 return VarAndKind.getPointer();
1013 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1014 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1016 // Offset of the first Capture object.
1017 unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
1019 return reinterpret_cast<Capture *>(
1020 reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1021 + FirstCaptureOffset);
1024 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1025 ArrayRef<Capture> Captures,
1026 ArrayRef<Expr *> CaptureInits,
1029 : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1030 CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1031 assert( S && "null captured statement");
1032 assert(CD && "null captured declaration for captured statement");
1033 assert(RD && "null record declaration for captured statement");
1035 // Copy initialization expressions.
1036 Stmt **Stored = getStoredStmts();
1037 for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1038 *Stored++ = CaptureInits[I];
1040 // Copy the statement being captured.
1043 // Copy all Capture objects.
1044 Capture *Buffer = getStoredCaptures();
1045 std::copy(Captures.begin(), Captures.end(), Buffer);
1048 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1049 : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1050 CapDeclAndKind(nullptr, CR_Default) {
1051 getStoredStmts()[NumCaptures] = nullptr;
1054 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
1055 CapturedRegionKind Kind,
1056 ArrayRef<Capture> Captures,
1057 ArrayRef<Expr *> CaptureInits,
1062 // -----------------------------------------------------------
1063 // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1064 // ----------------^-------------------^----------------------
1065 // getStoredStmts() getStoredCaptures()
1067 // where S is the statement being captured.
1069 assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1071 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1072 if (!Captures.empty()) {
1073 // Realign for the following Capture array.
1074 Size = llvm::alignTo(Size, alignof(Capture));
1075 Size += sizeof(Capture) * Captures.size();
1078 void *Mem = Context.Allocate(Size);
1079 return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1082 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
1083 unsigned NumCaptures) {
1084 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1085 if (NumCaptures > 0) {
1086 // Realign for the following Capture array.
1087 Size = llvm::alignTo(Size, alignof(Capture));
1088 Size += sizeof(Capture) * NumCaptures;
1091 void *Mem = Context.Allocate(Size);
1092 return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1095 Stmt::child_range CapturedStmt::children() {
1096 // Children are captured field initializers.
1097 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1100 CapturedDecl *CapturedStmt::getCapturedDecl() {
1101 return CapDeclAndKind.getPointer();
1104 const CapturedDecl *CapturedStmt::getCapturedDecl() const {
1105 return CapDeclAndKind.getPointer();
1108 /// \brief Set the outlined function declaration.
1109 void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
1110 assert(D && "null CapturedDecl");
1111 CapDeclAndKind.setPointer(D);
1114 /// \brief Retrieve the captured region kind.
1115 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
1116 return CapDeclAndKind.getInt();
1119 /// \brief Set the captured region kind.
1120 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
1121 CapDeclAndKind.setInt(Kind);
1124 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1125 for (const auto &I : captures()) {
1126 if (!I.capturesVariable() && !I.capturesVariableByCopy())
1128 if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())