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/Stmt.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/AST/ExprObjC.h"
17 #include "clang/AST/StmtCXX.h"
18 #include "clang/AST/StmtObjC.h"
19 #include "clang/AST/Type.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/ASTDiagnostic.h"
22 #include "clang/Basic/TargetInfo.h"
24 using namespace clang;
26 static struct StmtClassNameTable {
30 } StmtClassInfo[Stmt::lastStmtConstant+1];
32 static StmtClassNameTable &getStmtInfoTableEntry(Stmt::StmtClass E) {
33 static bool Initialized = false;
35 return StmtClassInfo[E];
37 // Intialize the table on the first use.
39 #define ABSTRACT_STMT(STMT)
40 #define STMT(CLASS, PARENT) \
41 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Name = #CLASS; \
42 StmtClassInfo[(unsigned)Stmt::CLASS##Class].Size = sizeof(CLASS);
43 #include "clang/AST/StmtNodes.inc"
45 return StmtClassInfo[E];
48 const char *Stmt::getStmtClassName() const {
49 return getStmtInfoTableEntry((StmtClass) StmtBits.sClass).Name;
52 void Stmt::PrintStats() {
53 // Ensure the table is primed.
54 getStmtInfoTableEntry(Stmt::NullStmtClass);
57 fprintf(stderr, "*** Stmt/Expr Stats:\n");
58 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
59 if (StmtClassInfo[i].Name == 0) continue;
60 sum += StmtClassInfo[i].Counter;
62 fprintf(stderr, " %d stmts/exprs total.\n", sum);
64 for (int i = 0; i != Stmt::lastStmtConstant+1; i++) {
65 if (StmtClassInfo[i].Name == 0) continue;
66 if (StmtClassInfo[i].Counter == 0) continue;
67 fprintf(stderr, " %d %s, %d each (%d bytes)\n",
68 StmtClassInfo[i].Counter, StmtClassInfo[i].Name,
69 StmtClassInfo[i].Size,
70 StmtClassInfo[i].Counter*StmtClassInfo[i].Size);
71 sum += StmtClassInfo[i].Counter*StmtClassInfo[i].Size;
73 fprintf(stderr, "Total bytes = %d\n", sum);
76 void Stmt::addStmtClass(StmtClass s) {
77 ++getStmtInfoTableEntry(s).Counter;
80 static bool StatSwitch = false;
82 bool Stmt::CollectingStats(bool Enable) {
83 if (Enable) StatSwitch = true;
91 // These silly little functions have to be static inline to suppress
92 // unused warnings, and they have to be defined to suppress other
94 static inline good is_good(good) { return good(); }
96 typedef Stmt::child_range children_t();
97 template <class T> good implements_children(children_t T::*) {
100 static inline bad implements_children(children_t Stmt::*) {
104 typedef SourceRange getSourceRange_t() const;
105 template <class T> good implements_getSourceRange(getSourceRange_t T::*) {
108 static inline bad implements_getSourceRange(getSourceRange_t Stmt::*) {
112 #define ASSERT_IMPLEMENTS_children(type) \
113 (void) sizeof(is_good(implements_children(&type::children)))
114 #define ASSERT_IMPLEMENTS_getSourceRange(type) \
115 (void) sizeof(is_good(implements_getSourceRange(&type::getSourceRange)))
118 /// Check whether the various Stmt classes implement their member
120 static inline void check_implementations() {
121 #define ABSTRACT_STMT(type)
122 #define STMT(type, base) \
123 ASSERT_IMPLEMENTS_children(type); \
124 ASSERT_IMPLEMENTS_getSourceRange(type);
125 #include "clang/AST/StmtNodes.inc"
128 Stmt::child_range Stmt::children() {
129 switch (getStmtClass()) {
130 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
131 #define ABSTRACT_STMT(type)
132 #define STMT(type, base) \
133 case Stmt::type##Class: \
134 return static_cast<type*>(this)->children();
135 #include "clang/AST/StmtNodes.inc"
137 llvm_unreachable("unknown statement kind!");
138 return child_range();
141 SourceRange Stmt::getSourceRange() const {
142 switch (getStmtClass()) {
143 case Stmt::NoStmtClass: llvm_unreachable("statement without class");
144 #define ABSTRACT_STMT(type)
145 #define STMT(type, base) \
146 case Stmt::type##Class: \
147 return static_cast<const type*>(this)->getSourceRange();
148 #include "clang/AST/StmtNodes.inc"
150 llvm_unreachable("unknown statement kind!");
151 return SourceRange();
154 void CompoundStmt::setStmts(ASTContext &C, Stmt **Stmts, unsigned NumStmts) {
157 this->CompoundStmtBits.NumStmts = NumStmts;
159 Body = new (C) Stmt*[NumStmts];
160 memcpy(Body, Stmts, sizeof(Stmt *) * NumStmts);
163 const char *LabelStmt::getName() const {
164 return getDecl()->getIdentifier()->getNameStart();
167 // This is defined here to avoid polluting Stmt.h with importing Expr.h
168 SourceRange ReturnStmt::getSourceRange() const {
170 return SourceRange(RetLoc, RetExpr->getLocEnd());
172 return SourceRange(RetLoc);
175 bool Stmt::hasImplicitControlFlow() const {
176 switch (StmtBits.sClass) {
181 case ConditionalOperatorClass:
182 case ChooseExprClass:
187 case Stmt::BinaryOperatorClass: {
188 const BinaryOperator* B = cast<BinaryOperator>(this);
189 if (B->isLogicalOp() || B->getOpcode() == BO_Comma)
197 Expr *AsmStmt::getOutputExpr(unsigned i) {
198 return cast<Expr>(Exprs[i]);
201 /// getOutputConstraint - Return the constraint string for the specified
202 /// output operand. All output constraints are known to be non-empty (either
204 llvm::StringRef AsmStmt::getOutputConstraint(unsigned i) const {
205 return getOutputConstraintLiteral(i)->getString();
208 /// getNumPlusOperands - Return the number of output operands that have a "+"
210 unsigned AsmStmt::getNumPlusOperands() const {
212 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i)
213 if (isOutputPlusConstraint(i))
218 Expr *AsmStmt::getInputExpr(unsigned i) {
219 return cast<Expr>(Exprs[i + NumOutputs]);
222 /// getInputConstraint - Return the specified input constraint. Unlike output
223 /// constraints, these can be empty.
224 llvm::StringRef AsmStmt::getInputConstraint(unsigned i) const {
225 return getInputConstraintLiteral(i)->getString();
229 void AsmStmt::setOutputsAndInputsAndClobbers(ASTContext &C,
230 IdentifierInfo **Names,
231 StringLiteral **Constraints,
235 StringLiteral **Clobbers,
236 unsigned NumClobbers) {
237 this->NumOutputs = NumOutputs;
238 this->NumInputs = NumInputs;
239 this->NumClobbers = NumClobbers;
241 unsigned NumExprs = NumOutputs + NumInputs;
243 C.Deallocate(this->Names);
244 this->Names = new (C) IdentifierInfo*[NumExprs];
245 std::copy(Names, Names + NumExprs, this->Names);
247 C.Deallocate(this->Exprs);
248 this->Exprs = new (C) Stmt*[NumExprs];
249 std::copy(Exprs, Exprs + NumExprs, this->Exprs);
251 C.Deallocate(this->Constraints);
252 this->Constraints = new (C) StringLiteral*[NumExprs];
253 std::copy(Constraints, Constraints + NumExprs, this->Constraints);
255 C.Deallocate(this->Clobbers);
256 this->Clobbers = new (C) StringLiteral*[NumClobbers];
257 std::copy(Clobbers, Clobbers + NumClobbers, this->Clobbers);
260 /// getNamedOperand - Given a symbolic operand reference like %[foo],
261 /// translate this into a numeric value needed to reference the same operand.
262 /// This returns -1 if the operand name is invalid.
263 int AsmStmt::getNamedOperand(llvm::StringRef SymbolicName) const {
264 unsigned NumPlusOperands = 0;
266 // Check if this is an output operand.
267 for (unsigned i = 0, e = getNumOutputs(); i != e; ++i) {
268 if (getOutputName(i) == SymbolicName)
272 for (unsigned i = 0, e = getNumInputs(); i != e; ++i)
273 if (getInputName(i) == SymbolicName)
274 return getNumOutputs() + NumPlusOperands + i;
280 /// AnalyzeAsmString - Analyze the asm string of the current asm, decomposing
281 /// it into pieces. If the asm string is erroneous, emit errors and return
282 /// true, otherwise return false.
283 unsigned AsmStmt::AnalyzeAsmString(llvm::SmallVectorImpl<AsmStringPiece>&Pieces,
284 ASTContext &C, unsigned &DiagOffs) const {
285 llvm::StringRef Str = getAsmString()->getString();
286 const char *StrStart = Str.begin();
287 const char *StrEnd = Str.end();
288 const char *CurPtr = StrStart;
290 // "Simple" inline asms have no constraints or operands, just convert the asm
291 // string to escape $'s.
294 for (; CurPtr != StrEnd; ++CurPtr) {
304 Pieces.push_back(AsmStringPiece(Result));
308 // CurStringPiece - The current string that we are building up as we scan the
310 std::string CurStringPiece;
312 bool HasVariants = !C.Target.hasNoAsmVariants();
315 // Done with the string?
316 if (CurPtr == StrEnd) {
317 if (!CurStringPiece.empty())
318 Pieces.push_back(AsmStringPiece(CurStringPiece));
322 char CurChar = *CurPtr++;
324 case '$': CurStringPiece += "$$"; continue;
325 case '{': CurStringPiece += (HasVariants ? "$(" : "{"); continue;
326 case '|': CurStringPiece += (HasVariants ? "$|" : "|"); continue;
327 case '}': CurStringPiece += (HasVariants ? "$)" : "}"); continue;
331 CurStringPiece += CurChar;
335 // Escaped "%" character in asm string.
336 if (CurPtr == StrEnd) {
337 // % at end of string is invalid (no escape).
338 DiagOffs = CurPtr-StrStart-1;
339 return diag::err_asm_invalid_escape;
342 char EscapedChar = *CurPtr++;
343 if (EscapedChar == '%') { // %% -> %
344 // Escaped percentage sign.
345 CurStringPiece += '%';
349 if (EscapedChar == '=') { // %= -> Generate an unique ID.
350 CurStringPiece += "${:uid}";
354 // Otherwise, we have an operand. If we have accumulated a string so far,
355 // add it to the Pieces list.
356 if (!CurStringPiece.empty()) {
357 Pieces.push_back(AsmStringPiece(CurStringPiece));
358 CurStringPiece.clear();
361 // Handle %x4 and %x[foo] by capturing x as the modifier character.
362 char Modifier = '\0';
363 if (isalpha(EscapedChar)) {
364 Modifier = EscapedChar;
365 EscapedChar = *CurPtr++;
368 if (isdigit(EscapedChar)) {
369 // %n - Assembler operand n
373 while (CurPtr != StrEnd && isdigit(*CurPtr))
374 N = N*10 + ((*CurPtr++)-'0');
376 unsigned NumOperands =
377 getNumOutputs() + getNumPlusOperands() + getNumInputs();
378 if (N >= NumOperands) {
379 DiagOffs = CurPtr-StrStart-1;
380 return diag::err_asm_invalid_operand_number;
383 Pieces.push_back(AsmStringPiece(N, Modifier));
387 // Handle %[foo], a symbolic operand reference.
388 if (EscapedChar == '[') {
389 DiagOffs = CurPtr-StrStart-1;
392 const char *NameEnd = (const char*)memchr(CurPtr, ']', StrEnd-CurPtr);
394 return diag::err_asm_unterminated_symbolic_operand_name;
395 if (NameEnd == CurPtr)
396 return diag::err_asm_empty_symbolic_operand_name;
398 llvm::StringRef SymbolicName(CurPtr, NameEnd - CurPtr);
400 int N = getNamedOperand(SymbolicName);
402 // Verify that an operand with that name exists.
403 DiagOffs = CurPtr-StrStart;
404 return diag::err_asm_unknown_symbolic_operand_name;
406 Pieces.push_back(AsmStringPiece(N, Modifier));
412 DiagOffs = CurPtr-StrStart-1;
413 return diag::err_asm_invalid_escape;
417 QualType CXXCatchStmt::getCaughtType() const {
419 return ExceptionDecl->getType();
423 //===----------------------------------------------------------------------===//
425 //===----------------------------------------------------------------------===//
427 AsmStmt::AsmStmt(ASTContext &C, SourceLocation asmloc, bool issimple,
428 bool isvolatile, bool msasm,
429 unsigned numoutputs, unsigned numinputs,
430 IdentifierInfo **names, StringLiteral **constraints,
431 Expr **exprs, StringLiteral *asmstr, unsigned numclobbers,
432 StringLiteral **clobbers, SourceLocation rparenloc)
433 : Stmt(AsmStmtClass), AsmLoc(asmloc), RParenLoc(rparenloc), AsmStr(asmstr)
434 , IsSimple(issimple), IsVolatile(isvolatile), MSAsm(msasm)
435 , NumOutputs(numoutputs), NumInputs(numinputs), NumClobbers(numclobbers) {
437 unsigned NumExprs = NumOutputs +NumInputs;
439 Names = new (C) IdentifierInfo*[NumExprs];
440 std::copy(names, names + NumExprs, Names);
442 Exprs = new (C) Stmt*[NumExprs];
443 std::copy(exprs, exprs + NumExprs, Exprs);
445 Constraints = new (C) StringLiteral*[NumExprs];
446 std::copy(constraints, constraints + NumExprs, Constraints);
448 Clobbers = new (C) StringLiteral*[NumClobbers];
449 std::copy(clobbers, clobbers + NumClobbers, Clobbers);
452 ObjCForCollectionStmt::ObjCForCollectionStmt(Stmt *Elem, Expr *Collect,
453 Stmt *Body, SourceLocation FCL,
455 : Stmt(ObjCForCollectionStmtClass) {
456 SubExprs[ELEM] = Elem;
457 SubExprs[COLLECTION] = reinterpret_cast<Stmt*>(Collect);
458 SubExprs[BODY] = Body;
463 ObjCAtTryStmt::ObjCAtTryStmt(SourceLocation atTryLoc, Stmt *atTryStmt,
464 Stmt **CatchStmts, unsigned NumCatchStmts,
466 : Stmt(ObjCAtTryStmtClass), AtTryLoc(atTryLoc),
467 NumCatchStmts(NumCatchStmts), HasFinally(atFinallyStmt != 0)
469 Stmt **Stmts = getStmts();
470 Stmts[0] = atTryStmt;
471 for (unsigned I = 0; I != NumCatchStmts; ++I)
472 Stmts[I + 1] = CatchStmts[I];
475 Stmts[NumCatchStmts + 1] = atFinallyStmt;
478 ObjCAtTryStmt *ObjCAtTryStmt::Create(ASTContext &Context,
479 SourceLocation atTryLoc,
482 unsigned NumCatchStmts,
483 Stmt *atFinallyStmt) {
484 unsigned Size = sizeof(ObjCAtTryStmt) +
485 (1 + NumCatchStmts + (atFinallyStmt != 0)) * sizeof(Stmt *);
486 void *Mem = Context.Allocate(Size, llvm::alignOf<ObjCAtTryStmt>());
487 return new (Mem) ObjCAtTryStmt(atTryLoc, atTryStmt, CatchStmts, NumCatchStmts,
491 ObjCAtTryStmt *ObjCAtTryStmt::CreateEmpty(ASTContext &Context,
492 unsigned NumCatchStmts,
494 unsigned Size = sizeof(ObjCAtTryStmt) +
495 (1 + NumCatchStmts + HasFinally) * sizeof(Stmt *);
496 void *Mem = Context.Allocate(Size, llvm::alignOf<ObjCAtTryStmt>());
497 return new (Mem) ObjCAtTryStmt(EmptyShell(), NumCatchStmts, HasFinally);
500 SourceRange ObjCAtTryStmt::getSourceRange() const {
501 SourceLocation EndLoc;
503 EndLoc = getFinallyStmt()->getLocEnd();
504 else if (NumCatchStmts)
505 EndLoc = getCatchStmt(NumCatchStmts - 1)->getLocEnd();
507 EndLoc = getTryBody()->getLocEnd();
509 return SourceRange(AtTryLoc, EndLoc);
512 CXXTryStmt *CXXTryStmt::Create(ASTContext &C, SourceLocation tryLoc,
513 Stmt *tryBlock, Stmt **handlers,
514 unsigned numHandlers) {
515 std::size_t Size = sizeof(CXXTryStmt);
516 Size += ((numHandlers + 1) * sizeof(Stmt));
518 void *Mem = C.Allocate(Size, llvm::alignOf<CXXTryStmt>());
519 return new (Mem) CXXTryStmt(tryLoc, tryBlock, handlers, numHandlers);
522 CXXTryStmt *CXXTryStmt::Create(ASTContext &C, EmptyShell Empty,
523 unsigned numHandlers) {
524 std::size_t Size = sizeof(CXXTryStmt);
525 Size += ((numHandlers + 1) * sizeof(Stmt));
527 void *Mem = C.Allocate(Size, llvm::alignOf<CXXTryStmt>());
528 return new (Mem) CXXTryStmt(Empty, numHandlers);
531 CXXTryStmt::CXXTryStmt(SourceLocation tryLoc, Stmt *tryBlock,
532 Stmt **handlers, unsigned numHandlers)
533 : Stmt(CXXTryStmtClass), TryLoc(tryLoc), NumHandlers(numHandlers) {
534 Stmt **Stmts = reinterpret_cast<Stmt **>(this + 1);
536 std::copy(handlers, handlers + NumHandlers, Stmts + 1);
539 IfStmt::IfStmt(ASTContext &C, SourceLocation IL, VarDecl *var, Expr *cond,
540 Stmt *then, SourceLocation EL, Stmt *elsev)
541 : Stmt(IfStmtClass), IfLoc(IL), ElseLoc(EL)
543 setConditionVariable(C, var);
544 SubExprs[COND] = reinterpret_cast<Stmt*>(cond);
545 SubExprs[THEN] = then;
546 SubExprs[ELSE] = elsev;
549 VarDecl *IfStmt::getConditionVariable() const {
553 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
554 return cast<VarDecl>(DS->getSingleDecl());
557 void IfStmt::setConditionVariable(ASTContext &C, VarDecl *V) {
563 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V),
564 V->getSourceRange().getBegin(),
565 V->getSourceRange().getEnd());
568 ForStmt::ForStmt(ASTContext &C, Stmt *Init, Expr *Cond, VarDecl *condVar,
569 Expr *Inc, Stmt *Body, SourceLocation FL, SourceLocation LP,
571 : Stmt(ForStmtClass), ForLoc(FL), LParenLoc(LP), RParenLoc(RP)
573 SubExprs[INIT] = Init;
574 setConditionVariable(C, condVar);
575 SubExprs[COND] = reinterpret_cast<Stmt*>(Cond);
576 SubExprs[INC] = reinterpret_cast<Stmt*>(Inc);
577 SubExprs[BODY] = Body;
580 VarDecl *ForStmt::getConditionVariable() const {
581 if (!SubExprs[CONDVAR])
584 DeclStmt *DS = cast<DeclStmt>(SubExprs[CONDVAR]);
585 return cast<VarDecl>(DS->getSingleDecl());
588 void ForStmt::setConditionVariable(ASTContext &C, VarDecl *V) {
590 SubExprs[CONDVAR] = 0;
594 SubExprs[CONDVAR] = new (C) DeclStmt(DeclGroupRef(V),
595 V->getSourceRange().getBegin(),
596 V->getSourceRange().getEnd());
599 SwitchStmt::SwitchStmt(ASTContext &C, VarDecl *Var, Expr *cond)
600 : Stmt(SwitchStmtClass), FirstCase(0), AllEnumCasesCovered(0)
602 setConditionVariable(C, Var);
603 SubExprs[COND] = reinterpret_cast<Stmt*>(cond);
604 SubExprs[BODY] = NULL;
607 VarDecl *SwitchStmt::getConditionVariable() const {
611 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
612 return cast<VarDecl>(DS->getSingleDecl());
615 void SwitchStmt::setConditionVariable(ASTContext &C, VarDecl *V) {
621 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V),
622 V->getSourceRange().getBegin(),
623 V->getSourceRange().getEnd());
626 Stmt *SwitchCase::getSubStmt() {
627 if (isa<CaseStmt>(this)) return cast<CaseStmt>(this)->getSubStmt();
628 return cast<DefaultStmt>(this)->getSubStmt();
631 WhileStmt::WhileStmt(ASTContext &C, VarDecl *Var, Expr *cond, Stmt *body,
633 : Stmt(WhileStmtClass)
635 setConditionVariable(C, Var);
636 SubExprs[COND] = reinterpret_cast<Stmt*>(cond);
637 SubExprs[BODY] = body;
641 VarDecl *WhileStmt::getConditionVariable() const {
645 DeclStmt *DS = cast<DeclStmt>(SubExprs[VAR]);
646 return cast<VarDecl>(DS->getSingleDecl());
649 void WhileStmt::setConditionVariable(ASTContext &C, VarDecl *V) {
655 SubExprs[VAR] = new (C) DeclStmt(DeclGroupRef(V),
656 V->getSourceRange().getBegin(),
657 V->getSourceRange().getEnd());
661 LabelDecl *IndirectGotoStmt::getConstantTarget() {
662 if (AddrLabelExpr *E =
663 dyn_cast<AddrLabelExpr>(getTarget()->IgnoreParenImpCasts()))
664 return E->getLabel();
669 const Expr* ReturnStmt::getRetValue() const {
670 return cast_or_null<Expr>(RetExpr);
672 Expr* ReturnStmt::getRetValue() {
673 return cast_or_null<Expr>(RetExpr);