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(const ASTContext &C, ArrayRef<Stmt*> Stmts,
303 SourceLocation LB, SourceLocation RB)
304 : Stmt(CompoundStmtClass), LBraceLoc(LB), RBraceLoc(RB) {
305 CompoundStmtBits.NumStmts = Stmts.size();
306 assert(CompoundStmtBits.NumStmts == Stmts.size() &&
307 "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
314 Body = new (C) Stmt*[Stmts.size()];
315 std::copy(Stmts.begin(), Stmts.end(), Body);
318 void CompoundStmt::setStmts(const ASTContext &C, ArrayRef<Stmt *> Stmts) {
321 CompoundStmtBits.NumStmts = Stmts.size();
322 assert(CompoundStmtBits.NumStmts == Stmts.size() &&
323 "NumStmts doesn't fit in bits of CompoundStmtBits.NumStmts!");
325 Body = new (C) Stmt*[Stmts.size()];
326 std::copy(Stmts.begin(), Stmts.end(), Body);
329 const char *LabelStmt::getName() const {
330 return getDecl()->getIdentifier()->getNameStart();
333 AttributedStmt *AttributedStmt::Create(const ASTContext &C, SourceLocation Loc,
334 ArrayRef<const Attr*> Attrs,
336 assert(!Attrs.empty() && "Attrs should not be empty");
337 void *Mem = C.Allocate(sizeof(AttributedStmt) + sizeof(Attr *) * Attrs.size(),
338 alignof(AttributedStmt));
339 return new (Mem) AttributedStmt(Loc, Attrs, SubStmt);
342 AttributedStmt *AttributedStmt::CreateEmpty(const ASTContext &C,
344 assert(NumAttrs > 0 && "NumAttrs should be greater than zero");
345 void *Mem = C.Allocate(sizeof(AttributedStmt) + sizeof(Attr *) * NumAttrs,
346 alignof(AttributedStmt));
347 return new (Mem) AttributedStmt(EmptyShell(), NumAttrs);
350 std::string AsmStmt::generateAsmString(const ASTContext &C) const {
351 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
352 return gccAsmStmt->generateAsmString(C);
353 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
354 return msAsmStmt->generateAsmString(C);
355 llvm_unreachable("unknown asm statement kind!");
358 StringRef AsmStmt::getOutputConstraint(unsigned i) const {
359 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
360 return gccAsmStmt->getOutputConstraint(i);
361 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
362 return msAsmStmt->getOutputConstraint(i);
363 llvm_unreachable("unknown asm statement kind!");
366 const Expr *AsmStmt::getOutputExpr(unsigned i) const {
367 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
368 return gccAsmStmt->getOutputExpr(i);
369 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
370 return msAsmStmt->getOutputExpr(i);
371 llvm_unreachable("unknown asm statement kind!");
374 StringRef AsmStmt::getInputConstraint(unsigned i) const {
375 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
376 return gccAsmStmt->getInputConstraint(i);
377 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
378 return msAsmStmt->getInputConstraint(i);
379 llvm_unreachable("unknown asm statement kind!");
382 const Expr *AsmStmt::getInputExpr(unsigned i) const {
383 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
384 return gccAsmStmt->getInputExpr(i);
385 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
386 return msAsmStmt->getInputExpr(i);
387 llvm_unreachable("unknown asm statement kind!");
390 StringRef AsmStmt::getClobber(unsigned i) const {
391 if (const GCCAsmStmt *gccAsmStmt = dyn_cast<GCCAsmStmt>(this))
392 return gccAsmStmt->getClobber(i);
393 if (const MSAsmStmt *msAsmStmt = dyn_cast<MSAsmStmt>(this))
394 return msAsmStmt->getClobber(i);
395 llvm_unreachable("unknown asm statement kind!");
398 /// getNumPlusOperands - Return the number of output operands that have a "+"
400 unsigned AsmStmt::getNumPlusOperands() const {
402 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
403 if (isOutputPlusConstraint(i))
408 char GCCAsmStmt::AsmStringPiece::getModifier() const {
409 assert(isOperand() && "Only Operands can have modifiers.");
410 return isLetter(Str[0]) ? Str[0] : '\0';
413 StringRef GCCAsmStmt::getClobber(unsigned i) const {
414 return getClobberStringLiteral(i)->getString();
417 Expr *GCCAsmStmt::getOutputExpr(unsigned i) {
418 return cast<Expr>(Exprs[i]);
421 /// getOutputConstraint - Return the constraint string for the specified
422 /// output operand. All output constraints are known to be non-empty (either
424 StringRef GCCAsmStmt::getOutputConstraint(unsigned i) const {
425 return getOutputConstraintLiteral(i)->getString();
428 Expr *GCCAsmStmt::getInputExpr(unsigned i) {
429 return cast<Expr>(Exprs[i + NumOutputs]);
432 void GCCAsmStmt::setInputExpr(unsigned i, Expr *E) {
433 Exprs[i + NumOutputs] = E;
436 /// getInputConstraint - Return the specified input constraint. Unlike output
437 /// constraints, these can be empty.
438 StringRef GCCAsmStmt::getInputConstraint(unsigned i) const {
439 return getInputConstraintLiteral(i)->getString();
442 void GCCAsmStmt::setOutputsAndInputsAndClobbers(const ASTContext &C,
443 IdentifierInfo **Names,
444 StringLiteral **Constraints,
448 StringLiteral **Clobbers,
449 unsigned NumClobbers) {
450 this->NumOutputs = NumOutputs;
451 this->NumInputs = NumInputs;
452 this->NumClobbers = NumClobbers;
454 unsigned NumExprs = NumOutputs + NumInputs;
456 C.Deallocate(this->Names);
457 this->Names = new (C) IdentifierInfo*[NumExprs];
458 std::copy(Names, Names + NumExprs, this->Names);
460 C.Deallocate(this->Exprs);
461 this->Exprs = new (C) Stmt*[NumExprs];
462 std::copy(Exprs, Exprs + NumExprs, this->Exprs);
464 C.Deallocate(this->Constraints);
465 this->Constraints = new (C) StringLiteral*[NumExprs];
466 std::copy(Constraints, Constraints + NumExprs, this->Constraints);
468 C.Deallocate(this->Clobbers);
469 this->Clobbers = new (C) StringLiteral*[NumClobbers];
470 std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
473 /// getNamedOperand - Given a symbolic operand reference like %[foo],
474 /// translate this into a numeric value needed to reference the same operand.
475 /// This returns -1 if the operand name is invalid.
476 int GCCAsmStmt::getNamedOperand(StringRef SymbolicName) const {
477 unsigned NumPlusOperands = 0;
479 // Check if this is an output operand.
480 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
481 if (getOutputName(i) == SymbolicName)
485 for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
486 if (getInputName(i) == SymbolicName)
487 return getNumOutputs() + NumPlusOperands + i;
493 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
494 /// it into pieces. If the asm string is erroneous, emit errors and return
495 /// true, otherwise return false.
496 unsigned GCCAsmStmt::AnalyzeAsmString(SmallVectorImpl<AsmStringPiece>&Pieces,
497 const ASTContext &C, unsigned &DiagOffs) const {
498 StringRef Str = getAsmString()->getString();
499 const char *StrStart = Str.begin();
500 const char *StrEnd = Str.end();
501 const char *CurPtr = StrStart;
503 // "Simple" inline asms have no constraints or operands, just convert the asm
504 // string to escape $'s.
507 for (; CurPtr != StrEnd; ++CurPtr) {
517 Pieces.push_back(AsmStringPiece(Result));
521 // CurStringPiece - The current string that we are building up as we scan the
523 std::string CurStringPiece;
525 bool HasVariants = !C.getTargetInfo().hasNoAsmVariants();
527 unsigned LastAsmStringToken = 0;
528 unsigned LastAsmStringOffset = 0;
531 // Done with the string?
532 if (CurPtr == StrEnd) {
533 if (!CurStringPiece.empty())
534 Pieces.push_back(AsmStringPiece(CurStringPiece));
538 char CurChar = *CurPtr++;
540 case '$': CurStringPiece += "$$"; continue;
541 case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
542 case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
543 case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
547 CurStringPiece += CurChar;
551 // Escaped "%" character in asm string.
552 if (CurPtr == StrEnd) {
553 // % at end of string is invalid (no escape).
554 DiagOffs = CurPtr-StrStart-1;
555 return diag::err_asm_invalid_escape;
557 // Handle escaped char and continue looping over the asm string.
558 char EscapedChar = *CurPtr++;
559 switch (EscapedChar) {
565 CurStringPiece += EscapedChar;
567 case '=': // %= -> Generate a unique ID.
568 CurStringPiece += "${:uid}";
572 // Otherwise, we have an operand. If we have accumulated a string so far,
573 // add it to the Pieces list.
574 if (!CurStringPiece.empty()) {
575 Pieces.push_back(AsmStringPiece(CurStringPiece));
576 CurStringPiece.clear();
579 // Handle operands that have asmSymbolicName (e.g., %x[foo]) and those that
580 // don't (e.g., %x4). 'x' following the '%' is the constraint modifier.
582 const char *Begin = CurPtr - 1; // Points to the character following '%'.
583 const char *Percent = Begin - 1; // Points to '%'.
585 if (isLetter(EscapedChar)) {
586 if (CurPtr == StrEnd) { // Premature end.
587 DiagOffs = CurPtr-StrStart-1;
588 return diag::err_asm_invalid_escape;
590 EscapedChar = *CurPtr++;
593 const TargetInfo &TI = C.getTargetInfo();
594 const SourceManager &SM = C.getSourceManager();
595 const LangOptions &LO = C.getLangOpts();
597 // Handle operands that don't have asmSymbolicName (e.g., %x4).
598 if (isDigit(EscapedChar)) {
599 // %n - Assembler operand n
603 while (CurPtr != StrEnd && isDigit(*CurPtr))
604 N = N*10 + ((*CurPtr++)-'0');
606 unsigned NumOperands =
607 getNumOutputs() + getNumPlusOperands() + getNumInputs();
608 if (N >= NumOperands) {
609 DiagOffs = CurPtr-StrStart-1;
610 return diag::err_asm_invalid_operand_number;
613 // Str contains "x4" (Operand without the leading %).
614 std::string Str(Begin, CurPtr - Begin);
616 // (BeginLoc, EndLoc) represents the range of the operand we are currently
617 // processing. Unlike Str, the range includes the leading '%'.
618 SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
619 Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
620 &LastAsmStringOffset);
621 SourceLocation EndLoc = getAsmString()->getLocationOfByte(
622 CurPtr - StrStart, SM, LO, TI, &LastAsmStringToken,
623 &LastAsmStringOffset);
625 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
629 // Handle operands that have asmSymbolicName (e.g., %x[foo]).
630 if (EscapedChar == '[') {
631 DiagOffs = CurPtr-StrStart-1;
634 const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
635 if (NameEnd == nullptr)
636 return diag::err_asm_unterminated_symbolic_operand_name;
637 if (NameEnd == CurPtr)
638 return diag::err_asm_empty_symbolic_operand_name;
640 StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
642 int N = getNamedOperand(SymbolicName);
644 // Verify that an operand with that name exists.
645 DiagOffs = CurPtr-StrStart;
646 return diag::err_asm_unknown_symbolic_operand_name;
649 // Str contains "x[foo]" (Operand without the leading %).
650 std::string Str(Begin, NameEnd + 1 - Begin);
652 // (BeginLoc, EndLoc) represents the range of the operand we are currently
653 // processing. Unlike Str, the range includes the leading '%'.
654 SourceLocation BeginLoc = getAsmString()->getLocationOfByte(
655 Percent - StrStart, SM, LO, TI, &LastAsmStringToken,
656 &LastAsmStringOffset);
657 SourceLocation EndLoc = getAsmString()->getLocationOfByte(
658 NameEnd + 1 - StrStart, SM, LO, TI, &LastAsmStringToken,
659 &LastAsmStringOffset);
661 Pieces.emplace_back(N, std::move(Str), BeginLoc, EndLoc);
667 DiagOffs = CurPtr-StrStart-1;
668 return diag::err_asm_invalid_escape;
672 /// Assemble final IR asm string (GCC-style).
673 std::string GCCAsmStmt::generateAsmString(const ASTContext &C) const {
674 // Analyze the asm string to decompose it into its pieces. We know that Sema
675 // has already done this, so it is guaranteed to be successful.
676 SmallVector<GCCAsmStmt::AsmStringPiece, 4> Pieces;
678 AnalyzeAsmString(Pieces, C, DiagOffs);
680 std::string AsmString;
681 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
682 if (Pieces[i].isString())
683 AsmString += Pieces[i].getString();
684 else if (Pieces[i].getModifier() == '\0')
685 AsmString += '$' + llvm::utostr(Pieces[i].getOperandNo());
687 AsmString += "${" + llvm::utostr(Pieces[i].getOperandNo()) + ':' +
688 Pieces[i].getModifier() + '}';
693 /// Assemble final IR asm string (MS-style).
694 std::string MSAsmStmt::generateAsmString(const ASTContext &C) const {
695 // FIXME: This needs to be translated into the IR string representation.
699 Expr *MSAsmStmt::getOutputExpr(unsigned i) {
700 return cast<Expr>(Exprs[i]);
703 Expr *MSAsmStmt::getInputExpr(unsigned i) {
704 return cast<Expr>(Exprs[i + NumOutputs]);
707 void MSAsmStmt::setInputExpr(unsigned i, Expr *E) {
708 Exprs[i + NumOutputs] = E;
711 //===----------------------------------------------------------------------===//
713 //===----------------------------------------------------------------------===//
715 GCCAsmStmt::GCCAsmStmt(const ASTContext &C, SourceLocation asmloc,
716 bool issimple, bool isvolatile, unsigned numoutputs,
717 unsigned numinputs, IdentifierInfo **names,
718 StringLiteral **constraints, Expr **exprs,
719 StringLiteral *asmstr, unsigned numclobbers,
720 StringLiteral **clobbers, SourceLocation rparenloc)
721 : AsmStmt(GCCAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
722 numinputs, numclobbers), RParenLoc(rparenloc), AsmStr(asmstr) {
723 unsigned NumExprs = NumOutputs + NumInputs;
725 Names = new (C) IdentifierInfo*[NumExprs];
726 std::copy(names, names + NumExprs, Names);
728 Exprs = new (C) Stmt*[NumExprs];
729 std::copy(exprs, exprs + NumExprs, Exprs);
731 Constraints = new (C) StringLiteral*[NumExprs];
732 std::copy(constraints, constraints + NumExprs, Constraints);
734 Clobbers = new (C) StringLiteral*[NumClobbers];
735 std::copy(clobbers, clobbers + NumClobbers, Clobbers);
738 MSAsmStmt::MSAsmStmt(const ASTContext &C, SourceLocation asmloc,
739 SourceLocation lbraceloc, bool issimple, bool isvolatile,
740 ArrayRef<Token> asmtoks, unsigned numoutputs,
742 ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
743 StringRef asmstr, ArrayRef<StringRef> clobbers,
744 SourceLocation endloc)
745 : AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
746 numinputs, clobbers.size()), LBraceLoc(lbraceloc),
747 EndLoc(endloc), NumAsmToks(asmtoks.size()) {
748 initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
751 static StringRef copyIntoContext(const ASTContext &C, StringRef str) {
755 void MSAsmStmt::initialize(const ASTContext &C, StringRef asmstr,
756 ArrayRef<Token> asmtoks,
757 ArrayRef<StringRef> constraints,
758 ArrayRef<Expr*> exprs,
759 ArrayRef<StringRef> clobbers) {
760 assert(NumAsmToks == asmtoks.size());
761 assert(NumClobbers == clobbers.size());
763 assert(exprs.size() == NumOutputs + NumInputs);
764 assert(exprs.size() == constraints.size());
766 AsmStr = copyIntoContext(C, asmstr);
768 Exprs = new (C) Stmt*[exprs.size()];
769 std::copy(exprs.begin(), exprs.end(), Exprs);
771 AsmToks = new (C) Token[asmtoks.size()];
772 std::copy(asmtoks.begin(), asmtoks.end(), AsmToks);
774 Constraints = new (C) StringRef[exprs.size()];
775 std::transform(constraints.begin(), constraints.end(), Constraints,
776 [&](StringRef Constraint) {
777 return copyIntoContext(C, Constraint);
780 Clobbers = new (C) StringRef[NumClobbers];
781 // FIXME: Avoid the allocation/copy if at all possible.
782 std::transform(clobbers.begin(), clobbers.end(), Clobbers,
783 [&](StringRef Clobber) {
784 return copyIntoContext(C, Clobber);
788 IfStmt::IfStmt(const ASTContext &C, SourceLocation IL, bool IsConstexpr,
789 Stmt *init, VarDecl *var, Expr *cond, Stmt *then,
790 SourceLocation EL, Stmt *elsev)
791 : Stmt(IfStmtClass), IfLoc(IL), ElseLoc(EL) {
792 setConstexpr(IsConstexpr);
793 setConditionVariable(C, var);
794 SubExprs[INIT] = init;
795 SubExprs[COND] = cond;
796 SubExprs[THEN] = then;
797 SubExprs[ELSE] = elsev;
800 VarDecl *IfStmt::getConditionVariable() const {
804 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
805 return cast<VarDecl>(DS->getSingleDecl());
808 void IfStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
810 SubExprs[VAR] = nullptr;
814 SourceRange VarRange = V->getSourceRange();
815 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
819 bool IfStmt::isObjCAvailabilityCheck() const {
820 return isa<ObjCAvailabilityCheckExpr>(SubExprs[COND]);
823 ForStmt::ForStmt(const ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
824 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
826 : Stmt(ForStmtClass), ForLoc(FL), LParenLoc(LP), RParenLoc(RP)
828 SubExprs[INIT] = Init;
829 setConditionVariable(C, condVar);
830 SubExprs[COND] = Cond;
832 SubExprs[BODY] = Body;
835 VarDecl *ForStmt::getConditionVariable() const {
836 if (!SubExprs[CONDVAR])
839 DeclStmt *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
840 return cast<VarDecl>(DS->getSingleDecl());
843 void ForStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
845 SubExprs[CONDVAR] = nullptr;
849 SourceRange VarRange = V->getSourceRange();
850 SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
854 SwitchStmt::SwitchStmt(const ASTContext &C, Stmt *init, VarDecl *Var,
856 : Stmt(SwitchStmtClass), FirstCase(nullptr, false) {
857 setConditionVariable(C, Var);
858 SubExprs[INIT] = init;
859 SubExprs[COND] = cond;
860 SubExprs[BODY] = nullptr;
863 VarDecl *SwitchStmt::getConditionVariable() const {
867 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
868 return cast<VarDecl>(DS->getSingleDecl());
871 void SwitchStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
873 SubExprs[VAR] = nullptr;
877 SourceRange VarRange = V->getSourceRange();
878 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
882 Stmt *SwitchCase::getSubStmt() {
883 if (isa<CaseStmt>(this))
884 return cast<CaseStmt>(this)->getSubStmt();
885 return cast<DefaultStmt>(this)->getSubStmt();
888 WhileStmt::WhileStmt(const ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,
890 : Stmt(WhileStmtClass) {
891 setConditionVariable(C, Var);
892 SubExprs[COND] = cond;
893 SubExprs[BODY] = body;
897 VarDecl *WhileStmt::getConditionVariable() const {
901 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
902 return cast<VarDecl>(DS->getSingleDecl());
905 void WhileStmt::setConditionVariable(const ASTContext &C, VarDecl *V) {
907 SubExprs[VAR] = nullptr;
911 SourceRange VarRange = V->getSourceRange();
912 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V), VarRange.getBegin(),
917 LabelDecl *IndirectGotoStmt::getConstantTarget() {
918 if (AddrLabelExpr *E =
919 dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
920 return E->getLabel();
925 const Expr* ReturnStmt::getRetValue() const {
926 return cast_or_null<Expr>(RetExpr);
928 Expr* ReturnStmt::getRetValue() {
929 return cast_or_null<Expr>(RetExpr);
932 SEHTryStmt::SEHTryStmt(bool IsCXXTry, SourceLocation TryLoc, Stmt *TryBlock,
934 : Stmt(SEHTryStmtClass), IsCXXTry(IsCXXTry), TryLoc(TryLoc) {
935 Children[TRY] = TryBlock;
936 Children[HANDLER] = Handler;
939 SEHTryStmt* SEHTryStmt::Create(const ASTContext &C, bool IsCXXTry,
940 SourceLocation TryLoc, Stmt *TryBlock,
942 return new(C) SEHTryStmt(IsCXXTry,TryLoc,TryBlock,Handler);
945 SEHExceptStmt* SEHTryStmt::getExceptHandler() const {
946 return dyn_cast<SEHExceptStmt>(getHandler());
949 SEHFinallyStmt* SEHTryStmt::getFinallyHandler() const {
950 return dyn_cast<SEHFinallyStmt>(getHandler());
953 SEHExceptStmt::SEHExceptStmt(SourceLocation Loc, Expr *FilterExpr, Stmt *Block)
954 : Stmt(SEHExceptStmtClass), Loc(Loc) {
955 Children[FILTER_EXPR] = FilterExpr;
956 Children[BLOCK] = Block;
959 SEHExceptStmt* SEHExceptStmt::Create(const ASTContext &C, SourceLocation Loc,
960 Expr *FilterExpr, Stmt *Block) {
961 return new(C) SEHExceptStmt(Loc,FilterExpr,Block);
964 SEHFinallyStmt::SEHFinallyStmt(SourceLocation Loc, Stmt *Block)
965 : Stmt(SEHFinallyStmtClass), Loc(Loc), Block(Block) {}
967 SEHFinallyStmt* SEHFinallyStmt::Create(const ASTContext &C, SourceLocation Loc,
969 return new(C)SEHFinallyStmt(Loc,Block);
972 CapturedStmt::Capture::Capture(SourceLocation Loc, VariableCaptureKind Kind,
974 : VarAndKind(Var, Kind), Loc(Loc) {
977 assert(!Var && "'this' capture cannot have a variable!");
980 assert(Var && "capturing by reference must have a variable!");
983 assert(Var && "capturing by copy must have a variable!");
985 (Var->getType()->isScalarType() || (Var->getType()->isReferenceType() &&
987 ->castAs<ReferenceType>()
989 ->isScalarType())) &&
990 "captures by copy are expected to have a scalar type!");
994 "Variable-length array type capture cannot have a variable!");
999 CapturedStmt::VariableCaptureKind
1000 CapturedStmt::Capture::getCaptureKind() const {
1001 return VarAndKind.getInt();
1004 VarDecl *CapturedStmt::Capture::getCapturedVar() const {
1005 assert((capturesVariable() || capturesVariableByCopy()) &&
1006 "No variable available for 'this' or VAT capture");
1007 return VarAndKind.getPointer();
1010 CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
1011 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1013 // Offset of the first Capture object.
1014 unsigned FirstCaptureOffset = llvm::alignTo(Size, alignof(Capture));
1016 return reinterpret_cast<Capture *>(
1017 reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
1018 + FirstCaptureOffset);
1021 CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
1022 ArrayRef<Capture> Captures,
1023 ArrayRef<Expr *> CaptureInits,
1026 : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
1027 CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
1028 assert( S && "null captured statement");
1029 assert(CD && "null captured declaration for captured statement");
1030 assert(RD && "null record declaration for captured statement");
1032 // Copy initialization expressions.
1033 Stmt **Stored = getStoredStmts();
1034 for (unsigned I = 0, N = NumCaptures; I != N; ++I)
1035 *Stored++ = CaptureInits[I];
1037 // Copy the statement being captured.
1040 // Copy all Capture objects.
1041 Capture *Buffer = getStoredCaptures();
1042 std::copy(Captures.begin(), Captures.end(), Buffer);
1045 CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
1046 : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
1047 CapDeclAndKind(nullptr, CR_Default) {
1048 getStoredStmts()[NumCaptures] = nullptr;
1051 CapturedStmt *CapturedStmt::Create(const ASTContext &Context, Stmt *S,
1052 CapturedRegionKind Kind,
1053 ArrayRef<Capture> Captures,
1054 ArrayRef<Expr *> CaptureInits,
1059 // -----------------------------------------------------------
1060 // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
1061 // ----------------^-------------------^----------------------
1062 // getStoredStmts() getStoredCaptures()
1064 // where S is the statement being captured.
1066 assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
1068 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
1069 if (!Captures.empty()) {
1070 // Realign for the following Capture array.
1071 Size = llvm::alignTo(Size, alignof(Capture));
1072 Size += sizeof(Capture) * Captures.size();
1075 void *Mem = Context.Allocate(Size);
1076 return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
1079 CapturedStmt *CapturedStmt::CreateDeserialized(const ASTContext &Context,
1080 unsigned NumCaptures) {
1081 unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
1082 if (NumCaptures > 0) {
1083 // Realign for the following Capture array.
1084 Size = llvm::alignTo(Size, alignof(Capture));
1085 Size += sizeof(Capture) * NumCaptures;
1088 void *Mem = Context.Allocate(Size);
1089 return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
1092 Stmt::child_range CapturedStmt::children() {
1093 // Children are captured field initializers.
1094 return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
1097 CapturedDecl *CapturedStmt::getCapturedDecl() {
1098 return CapDeclAndKind.getPointer();
1101 const CapturedDecl *CapturedStmt::getCapturedDecl() const {
1102 return CapDeclAndKind.getPointer();
1105 /// \brief Set the outlined function declaration.
1106 void CapturedStmt::setCapturedDecl(CapturedDecl *D) {
1107 assert(D && "null CapturedDecl");
1108 CapDeclAndKind.setPointer(D);
1111 /// \brief Retrieve the captured region kind.
1112 CapturedRegionKind CapturedStmt::getCapturedRegionKind() const {
1113 return CapDeclAndKind.getInt();
1116 /// \brief Set the captured region kind.
1117 void CapturedStmt::setCapturedRegionKind(CapturedRegionKind Kind) {
1118 CapDeclAndKind.setInt(Kind);
1121 bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
1122 for (const auto &I : captures()) {
1123 if (!I.capturesVariable() && !I.capturesVariableByCopy())
1125 if (I.getCapturedVar()->getCanonicalDecl() == Var->getCanonicalDecl())