blob: d3087c2f87da9b1581fb7e5fe4ec364514cb9e9e [file] [log] [blame]
Ted Kremenekfddd5182007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenekfddd5182007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
Ted Kremenekc310e932007-08-21 22:06:14 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000017#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000021#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000022#include "llvm/Support/Compiler.h"
Ted Kremenek274f4332008-04-28 18:00:46 +000023#include <llvm/Support/Allocator.h>
Ted Kremeneka95d3752008-09-13 05:16:45 +000024#include <llvm/Support/Format.h>
Ted Kremenek83c01da2008-01-11 00:40:29 +000025
Ted Kremenekfddd5182007-08-21 21:42:03 +000026using namespace clang;
27
28namespace {
29
Ted Kremenekbefef2f2007-08-23 21:26:19 +000030// SaveAndRestore - A utility class that uses RIIA to save and restore
31// the value of a variable.
32template<typename T>
Ted Kremenek6fa9b882008-01-08 18:15:10 +000033struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekbefef2f2007-08-23 21:26:19 +000034 SaveAndRestore(T& x) : X(x), old_value(x) {}
35 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000036 T get() { return old_value; }
37
Ted Kremenekbefef2f2007-08-23 21:26:19 +000038 T& X;
39 T old_value;
40};
Ted Kremenekfddd5182007-08-21 21:42:03 +000041
Douglas Gregor4afa39d2009-01-20 01:17:11 +000042static SourceLocation GetEndLoc(Decl* D) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +000043 if (VarDecl* VD = dyn_cast<VarDecl>(D))
44 if (Expr* Ex = VD->getInit())
45 return Ex->getSourceRange().getEnd();
46
47 return D->getLocation();
48}
49
Ted Kremeneka34ea072008-08-04 22:51:42 +000050/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenekfddd5182007-08-21 21:42:03 +000051/// The builder is stateful: an instance of the builder should be used to only
52/// construct a single CFG.
53///
54/// Example usage:
55///
56/// CFGBuilder builder;
57/// CFG* cfg = builder.BuildAST(stmt1);
58///
Ted Kremenekc310e932007-08-21 22:06:14 +000059/// CFG construction is done via a recursive walk of an AST.
60/// We actually parse the AST in reverse order so that the successor
61/// of a basic block is constructed prior to its predecessor. This
62/// allows us to nicely capture implicit fall-throughs without extra
63/// basic blocks.
64///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000065class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000066 CFG* cfg;
67 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000068 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000069 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000070 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000071 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000072 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000073
Ted Kremenek19bb3562007-08-28 19:26:49 +000074 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000075 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
76 LabelMapTy LabelMap;
77
Ted Kremenek19bb3562007-08-28 19:26:49 +000078 // A list of blocks that end with a "goto" that must be backpatched to
79 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000080 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000081 BackpatchBlocksTy BackpatchBlocks;
82
Ted Kremenek19bb3562007-08-28 19:26:49 +000083 // A list of labels whose address has been taken (for indirect gotos).
84 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
85 LabelSetTy AddressTakenLabels;
86
Ted Kremenekfddd5182007-08-21 21:42:03 +000087public:
Ted Kremenek026473c2007-08-23 16:51:22 +000088 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000089 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000090 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000091 // Create an empty CFG.
92 cfg = new CFG();
93 }
94
95 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000096
Ted Kremenekd4fdee32007-08-23 21:42:29 +000097 // buildCFG - Used by external clients to construct the CFG.
98 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000099
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000100 // Visitors to walk an AST and construct the CFG. Called by
101 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000102
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000103 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000104 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek514de5a2008-11-11 17:10:00 +0000105 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
106 CFGBlock* VisitContinueStmt(ContinueStmt* C);
Ted Kremenek295222c2008-02-13 21:46:34 +0000107 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek514de5a2008-11-11 17:10:00 +0000108 CFGBlock* VisitDoStmt(DoStmt* D);
109 CFGBlock* VisitForStmt(ForStmt* F);
110 CFGBlock* VisitGotoStmt(GotoStmt* G);
111 CFGBlock* VisitIfStmt(IfStmt* I);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000112 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek514de5a2008-11-11 17:10:00 +0000113 CFGBlock* VisitLabelStmt(LabelStmt* L);
114 CFGBlock* VisitNullStmt(NullStmt* Statement);
115 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S);
116 CFGBlock* VisitReturnStmt(ReturnStmt* R);
117 CFGBlock* VisitStmt(Stmt* Statement);
118 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
119 CFGBlock* VisitWhileStmt(WhileStmt* W);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000120
Ted Kremenek4102af92008-03-13 03:04:22 +0000121 // FIXME: Add support for ObjC-specific control-flow structures.
122
Ted Kremenek274f4332008-04-28 18:00:46 +0000123 // NYS == Not Yet Supported
124 CFGBlock* NYS() {
Ted Kremenek4102af92008-03-13 03:04:22 +0000125 badCFG = true;
126 return Block;
127 }
128
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000129 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S);
130 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) {
131 // FIXME: For now we pretend that @catch and the code it contains
132 // does not exit.
133 return Block;
134 }
135
Ted Kremenek2fda5042008-12-09 20:20:09 +0000136 // FIXME: This is not completely supported. We basically @throw like
137 // a 'return'.
138 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S);
Ted Kremenek274f4332008-04-28 18:00:46 +0000139
Ted Kremenekb3b0b362009-05-02 01:49:13 +0000140 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S);
Ted Kremenek4102af92008-03-13 03:04:22 +0000141
Ted Kremenek00c0a302008-09-26 18:17:07 +0000142 // Blocks.
143 CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); }
144 CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); }
145
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000146private:
147 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000148 CFGBlock* addStmt(Stmt* Terminator);
149 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
150 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000151 CFGBlock* WalkAST_VisitDeclSubExpr(Decl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000152 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000153 bool FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000154
Ted Kremenek4102af92008-03-13 03:04:22 +0000155 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000156};
Ted Kremenek610a09e2008-09-26 22:58:57 +0000157
Douglas Gregor898574e2008-12-05 23:32:09 +0000158// FIXME: Add support for dependent-sized array types in C++?
159// Does it even make sense to build a CFG for an uninstantiated template?
Ted Kremenek610a09e2008-09-26 22:58:57 +0000160static VariableArrayType* FindVA(Type* t) {
161 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
162 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
163 if (vat->getSizeExpr())
164 return vat;
165
166 t = vt->getElementType().getTypePtr();
167 }
168
169 return 0;
170}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000171
172/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
173/// represent an arbitrary statement. Examples include a single expression
174/// or a function body (compound statement). The ownership of the returned
175/// CFG is transferred to the caller. If CFG construction fails, this method
176/// returns NULL.
177CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000178 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000179 if (!Statement) return NULL;
180
Ted Kremenek4102af92008-03-13 03:04:22 +0000181 badCFG = false;
182
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000183 // Create an empty block that will serve as the exit block for the CFG.
184 // Since this is the first block added to the CFG, it will be implicitly
185 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000186 Succ = createBlock();
187 assert (Succ == &cfg->getExit());
188 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000189
190 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000191 CFGBlock* B = Visit(Statement);
192 if (!B) B = Succ;
193
194 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000195 // Finalize the last constructed block. This usually involves
196 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000197 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000198
199 // Backpatch the gotos whose label -> block mappings we didn't know
200 // when we encountered them.
201 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
202 E = BackpatchBlocks.end(); I != E; ++I ) {
203
204 CFGBlock* B = *I;
205 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
206 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
207
208 // If there is no target for the goto, then we are looking at an
209 // incomplete AST. Handle this by not registering a successor.
210 if (LI == LabelMap.end()) continue;
211
212 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000213 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000214
Ted Kremenek19bb3562007-08-28 19:26:49 +0000215 // Add successors to the Indirect Goto Dispatch block (if we have one).
216 if (CFGBlock* B = cfg->getIndirectGotoBlock())
217 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
218 E = AddressTakenLabels.end(); I != E; ++I ) {
219
220 // Lookup the target block.
221 LabelMapTy::iterator LI = LabelMap.find(*I);
222
223 // If there is no target block that contains label, then we are looking
224 // at an incomplete AST. Handle this by not registering a successor.
225 if (LI == LabelMap.end()) continue;
226
227 B->addSuccessor(LI->second);
228 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000229
Ted Kremenek94b33162007-09-17 16:18:02 +0000230 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000231 }
232
233 // Create an empty entry block that has no predecessors.
234 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000235
Ted Kremenek4102af92008-03-13 03:04:22 +0000236 if (badCFG) {
237 delete cfg;
238 cfg = NULL;
239 return NULL;
240 }
241
Ted Kremenek322f58d2007-09-26 21:23:31 +0000242 // NULL out cfg so that repeated calls to the builder will fail and that
243 // the ownership of the constructed CFG is passed to the caller.
244 CFG* t = cfg;
245 cfg = NULL;
246 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000247}
248
249/// createBlock - Used to lazily create blocks that are connected
250/// to the current (global) succcessor.
251CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000252 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000253 if (add_successor && Succ) B->addSuccessor(Succ);
254 return B;
255}
256
257/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000258/// we must reverse the statements because they have been inserted
259/// in reverse order.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000260bool CFGBuilder::FinishBlock(CFGBlock* B) {
261 if (badCFG)
262 return false;
263
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000264 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000265 B->reverseStmts();
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000266 return true;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000267}
268
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000269/// addStmt - Used to add statements/expressions to the current CFGBlock
270/// "Block". This method calls WalkAST on the passed statement to see if it
271/// contains any short-circuit expressions. If so, it recursively creates
272/// the necessary blocks for such expressions. It returns the "topmost" block
273/// of the created blocks, or the original value of "Block" when this method
274/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000275CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000276 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000277 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000278}
279
280/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000281/// add extra blocks for ternary operators, &&, and ||. We also
282/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000283CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
284 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000285 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000286 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000287
288 // Create the confluence block that will "merge" the results
289 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000290 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
291 ConfluenceBlock->appendStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000292 if (!FinishBlock(ConfluenceBlock))
293 return 0;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000294
295 // Create a block for the LHS expression if there is an LHS expression.
296 // A GCC extension allows LHS to be NULL, causing the condition to
297 // be the value that is returned instead.
298 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000299 Succ = ConfluenceBlock;
300 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000301 CFGBlock* LHSBlock = NULL;
302 if (C->getLHS()) {
303 LHSBlock = Visit(C->getLHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000304 if (!FinishBlock(LHSBlock))
305 return 0;
306 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000307 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000308
Ted Kremenekecc04c92007-11-26 18:20:26 +0000309 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000310 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000311 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000312 if (!FinishBlock(RHSBlock))
313 return 0;
314
Ted Kremenekecc04c92007-11-26 18:20:26 +0000315 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000316 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000317
318 if (LHSBlock)
319 Block->addSuccessor(LHSBlock);
320 else {
321 // If we have no LHS expression, add the ConfluenceBlock as a direct
322 // successor for the block containing the condition. Moreover,
323 // we need to reverse the order of the predecessors in the
324 // ConfluenceBlock because the RHSBlock will have been added to
325 // the succcessors already, and we want the first predecessor to the
326 // the block containing the expression for the case when the ternary
327 // expression evaluates to true.
328 Block->addSuccessor(ConfluenceBlock);
329 assert (ConfluenceBlock->pred_size() == 2);
330 std::reverse(ConfluenceBlock->pred_begin(),
331 ConfluenceBlock->pred_end());
332 }
333
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000334 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000335
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000336 Block->setTerminator(C);
337 return addStmt(C->getCond());
338 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000339
340 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000341 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000342
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000343 CFGBlock* ConfluenceBlock = Block ? Block : createBlock();
Ted Kremenek49a436d2007-08-31 17:03:41 +0000344 ConfluenceBlock->appendStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000345 if (!FinishBlock(ConfluenceBlock))
346 return 0;
Ted Kremenek49a436d2007-08-31 17:03:41 +0000347
348 Succ = ConfluenceBlock;
349 Block = NULL;
350 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000351 if (!FinishBlock(LHSBlock))
352 return 0;
Ted Kremenekf50ec102007-09-11 21:29:43 +0000353
Ted Kremenek49a436d2007-08-31 17:03:41 +0000354 Succ = ConfluenceBlock;
355 Block = NULL;
356 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000357 if (!FinishBlock(RHSBlock))
358 return 0;
Ted Kremenek49a436d2007-08-31 17:03:41 +0000359
360 Block = createBlock(false);
361 Block->addSuccessor(LHSBlock);
362 Block->addSuccessor(RHSBlock);
363 Block->setTerminator(C);
364 return addStmt(C->getCond());
365 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000366
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000367 case Stmt::DeclStmtClass: {
Ted Kremenek53061c82008-10-06 20:56:19 +0000368 DeclStmt *DS = cast<DeclStmt>(Terminator);
Chris Lattner7e24e822009-03-28 06:33:19 +0000369 if (DS->isSingleDecl()) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000370 Block->appendStmt(Terminator);
Chris Lattner7e24e822009-03-28 06:33:19 +0000371 return WalkAST_VisitDeclSubExpr(DS->getSingleDecl());
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000372 }
Chris Lattner7e24e822009-03-28 06:33:19 +0000373
Chris Lattner7e24e822009-03-28 06:33:19 +0000374 CFGBlock* B = 0;
Ted Kremenek53061c82008-10-06 20:56:19 +0000375
Chris Lattner7e24e822009-03-28 06:33:19 +0000376 // FIXME: Add a reverse iterator for DeclStmt to avoid this
377 // extra copy.
Chris Lattnere66a8cf2009-03-28 06:53:40 +0000378 typedef llvm::SmallVector<Decl*,10> BufTy;
379 BufTy Buf(DS->decl_begin(), DS->decl_end());
Chris Lattner7e24e822009-03-28 06:33:19 +0000380
381 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
382 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
383 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
384 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Ted Kremenek53061c82008-10-06 20:56:19 +0000385
Chris Lattner7e24e822009-03-28 06:33:19 +0000386 // Allocate the DeclStmt using the BumpPtrAllocator. It will
387 // get automatically freed with the CFG.
388 DeclGroupRef DG(*I);
389 Decl* D = *I;
390 void* Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
391
Chris Lattnere66a8cf2009-03-28 06:53:40 +0000392 DeclStmt* DS = new (Mem) DeclStmt(DG, D->getLocation(), GetEndLoc(D));
Chris Lattner7e24e822009-03-28 06:33:19 +0000393
394 // Append the fake DeclStmt to block.
395 Block->appendStmt(DS);
396 B = WalkAST_VisitDeclSubExpr(D);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000397 }
Chris Lattner7e24e822009-03-28 06:33:19 +0000398 return B;
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000399 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000400
Ted Kremenek19bb3562007-08-28 19:26:49 +0000401 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000402 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000403 AddressTakenLabels.insert(A->getLabel());
404
Ted Kremenek411cdee2008-04-16 21:10:48 +0000405 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000406 return Block;
407 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000408
Ted Kremenek15c27a82007-08-28 18:30:10 +0000409 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000410 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000411
Sebastian Redl05189992008-11-11 17:56:53 +0000412 case Stmt::SizeOfAlignOfExprClass: {
413 SizeOfAlignOfExpr* E = cast<SizeOfAlignOfExpr>(Terminator);
Ted Kremenek610a09e2008-09-26 22:58:57 +0000414
415 // VLA types have expressions that must be evaluated.
Sebastian Redl05189992008-11-11 17:56:53 +0000416 if (E->isArgumentType()) {
417 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
418 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
419 addStmt(VA->getSizeExpr());
420 }
421 // Expressions in sizeof/alignof are not evaluated and thus have no
422 // control flow.
423 else
424 Block->appendStmt(Terminator);
Ted Kremenek610a09e2008-09-26 22:58:57 +0000425
426 return Block;
427 }
428
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000429 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000430 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000431
432 if (B->isLogicalOp()) { // && or ||
433 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
434 ConfluenceBlock->appendStmt(B);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000435 if (!FinishBlock(ConfluenceBlock))
436 return 0;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000437
438 // create the block evaluating the LHS
439 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000440 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000441
442 // create the block evaluating the RHS
443 Succ = ConfluenceBlock;
444 Block = NULL;
445 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000446 if (!FinishBlock(RHSBlock))
447 return 0;
Ted Kremenekafe54332007-12-21 19:49:00 +0000448
449 // Now link the LHSBlock with RHSBlock.
450 if (B->getOpcode() == BinaryOperator::LOr) {
451 LHSBlock->addSuccessor(ConfluenceBlock);
452 LHSBlock->addSuccessor(RHSBlock);
453 }
454 else {
455 assert (B->getOpcode() == BinaryOperator::LAnd);
456 LHSBlock->addSuccessor(RHSBlock);
457 LHSBlock->addSuccessor(ConfluenceBlock);
458 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000459
460 // Generate the blocks for evaluating the LHS.
461 Block = LHSBlock;
462 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000463 }
464 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
465 Block->appendStmt(B);
466 addStmt(B->getRHS());
467 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000468 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000469
470 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000471 }
Ted Kremenek00c0a302008-09-26 18:17:07 +0000472
473 // Blocks: No support for blocks ... yet
474 case Stmt::BlockExprClass:
475 case Stmt::BlockDeclRefExprClass:
476 return NYS();
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000477
478 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000479 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000480
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000481 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000482 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000483 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000484
Ted Kremenek411cdee2008-04-16 21:10:48 +0000485 if (AlwaysAddStmt) Block->appendStmt(Terminator);
486 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000487}
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000488
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000489/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
490/// for initializers in Decls.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000491CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(Decl* D) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000492 VarDecl* VD = dyn_cast<VarDecl>(D);
493
494 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000495 return Block;
496
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000497 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000498
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000499 if (Init) {
Mike Stump54cc43f2009-02-26 08:00:25 +0000500 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000501 switch (Init->getStmtClass()) {
502 case Stmt::IntegerLiteralClass:
503 case Stmt::CharacterLiteralClass:
504 case Stmt::StringLiteralClass:
505 break;
506 default:
507 Block = addStmt(Init);
508 }
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000509 }
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000510
511 // If the type of VD is a VLA, then we must process its size expressions.
512 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
513 VA = FindVA(VA->getElementType().getTypePtr()))
514 Block = addStmt(VA->getSizeExpr());
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000515
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000516 return Block;
517}
518
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000519/// WalkAST_VisitChildren - Utility method to call WalkAST on the
520/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000521CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000522 CFGBlock* B = Block;
Mike Stump54cc43f2009-02-26 08:00:25 +0000523 for (Stmt::child_iterator I = Terminator->child_begin(),
524 E = Terminator->child_end();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000525 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000526 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000527
528 return B;
529}
530
Ted Kremenek15c27a82007-08-28 18:30:10 +0000531/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
532/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000533CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
534 Block->appendStmt(Terminator);
535 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000536}
537
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000538/// VisitStmt - Handle statements with no branching control flow.
539CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
540 // We cannot assume that we are in the middle of a basic block, since
541 // the CFG might only be constructed for this single statement. If
542 // we have no current basic block, just create one lazily.
543 if (!Block) Block = createBlock();
544
545 // Simply add the statement to the current block. We actually
546 // insert statements in reverse order; this order is reversed later
547 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000548 addStmt(Statement);
549
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000550 return Block;
551}
552
553CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
554 return Block;
555}
556
557CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000558
559 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000560
Ted Kremenekd34066c2008-02-26 00:22:58 +0000561 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
562 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000563 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000564 }
565
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000566 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000567}
568
569CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
570 // We may see an if statement in the middle of a basic block, or
571 // it may be the first statement we are processing. In either case,
572 // we create a new basic block. First, we create the blocks for
573 // the then...else statements, and then we create the block containing
574 // the if statement. If we were in the middle of a block, we
575 // stop processing that block and reverse its statements. That block
576 // is then the implicit successor for the "then" and "else" clauses.
577
578 // The block we were proccessing is now finished. Make it the
579 // successor block.
580 if (Block) {
581 Succ = Block;
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000582 if (!FinishBlock(Block))
583 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000584 }
585
586 // Process the false branch. NULL out Block so that the recursive
587 // call to Visit will create a new basic block.
588 // Null out Block so that all successor
589 CFGBlock* ElseBlock = Succ;
590
591 if (Stmt* Else = I->getElse()) {
592 SaveAndRestore<CFGBlock*> sv(Succ);
593
594 // NULL out Block so that the recursive call to Visit will
595 // create a new basic block.
596 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000597 ElseBlock = Visit(Else);
598
599 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
600 ElseBlock = sv.get();
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000601 else if (Block) {
602 if (!FinishBlock(ElseBlock))
603 return 0;
604 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000605 }
606
607 // Process the true branch. NULL out Block so that the recursive
608 // call to Visit will create a new basic block.
609 // Null out Block so that all successor
610 CFGBlock* ThenBlock;
611 {
612 Stmt* Then = I->getThen();
613 assert (Then);
614 SaveAndRestore<CFGBlock*> sv(Succ);
615 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000616 ThenBlock = Visit(Then);
617
Ted Kremenekdbdf7942009-04-01 03:52:47 +0000618 if (!ThenBlock) {
619 // We can reach here if the "then" body has all NullStmts.
620 // Create an empty block so we can distinguish between true and false
621 // branches in path-sensitive analyses.
622 ThenBlock = createBlock(false);
623 ThenBlock->addSuccessor(sv.get());
624 }
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000625 else if (Block) {
626 if (!FinishBlock(ThenBlock))
627 return 0;
628 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000629 }
630
631 // Now create a new block containing the if statement.
632 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000633
634 // Set the terminator of the new block to the If statement.
635 Block->setTerminator(I);
636
637 // Now add the successors.
638 Block->addSuccessor(ThenBlock);
639 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000640
641 // Add the condition as the last statement in the new block. This
642 // may create new blocks as the condition may contain control-flow. Any
643 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000644 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000645}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000646
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000647
648CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
649 // If we were in the middle of a block we stop processing that block
650 // and reverse its statements.
651 //
652 // NOTE: If a "return" appears in the middle of a block, this means
653 // that the code afterwards is DEAD (unreachable). We still
654 // keep a basic block for that code; a simple "mark-and-sweep"
655 // from the entry block will be able to report such dead
656 // blocks.
657 if (Block) FinishBlock(Block);
658
659 // Create the new block.
660 Block = createBlock(false);
661
662 // The Exit block is the only successor.
663 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000664
665 // Add the return statement to the block. This may create new blocks
666 // if R contains control-flow (short-circuit operations).
667 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000668}
669
670CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
671 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000672 Visit(L->getSubStmt());
673 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000674
675 if (!LabelBlock) // This can happen when the body is empty, i.e.
676 LabelBlock=createBlock(); // scopes that only contains NullStmts.
677
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000678 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
679 LabelMap[ L ] = LabelBlock;
680
681 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000682 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000683 // label (and we have already processed the substatement) there is no
684 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000685 LabelBlock->setLabel(L);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000686 if (!FinishBlock(LabelBlock))
687 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000688
689 // We set Block to NULL to allow lazy creation of a new block
690 // (if necessary);
691 Block = NULL;
692
693 // This block is now the implicit successor of other blocks.
694 Succ = LabelBlock;
695
696 return LabelBlock;
697}
698
699CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
700 // Goto is a control-flow statement. Thus we stop processing the
701 // current block and create a new one.
702 if (Block) FinishBlock(Block);
703 Block = createBlock(false);
704 Block->setTerminator(G);
705
706 // If we already know the mapping to the label block add the
707 // successor now.
708 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
709
710 if (I == LabelMap.end())
711 // We will need to backpatch this block later.
712 BackpatchBlocks.push_back(Block);
713 else
714 Block->addSuccessor(I->second);
715
716 return Block;
717}
718
719CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
720 // "for" is a control-flow statement. Thus we stop processing the
721 // current block.
722
723 CFGBlock* LoopSuccessor = NULL;
724
725 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000726 if (!FinishBlock(Block))
727 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000728 LoopSuccessor = Block;
729 }
730 else LoopSuccessor = Succ;
731
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000732 // Because of short-circuit evaluation, the condition of the loop
733 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
734 // blocks that evaluate the condition.
735 CFGBlock* ExitConditionBlock = createBlock(false);
736 CFGBlock* EntryConditionBlock = ExitConditionBlock;
737
738 // Set the terminator for the "exit" condition block.
739 ExitConditionBlock->setTerminator(F);
740
741 // Now add the actual condition to the condition block. Because the
742 // condition itself may contain control-flow, new blocks may be created.
743 if (Stmt* C = F->getCond()) {
744 Block = ExitConditionBlock;
745 EntryConditionBlock = addStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000746 if (Block) {
747 if (!FinishBlock(EntryConditionBlock))
748 return 0;
749 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000750 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000751
752 // The condition block is the implicit successor for the loop body as
753 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000754 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000755
756 // Now create the loop body.
757 {
758 assert (F->getBody());
759
760 // Save the current values for Block, Succ, and continue and break targets
761 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
762 save_continue(ContinueTargetBlock),
763 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000764
Ted Kremenekaf603f72007-08-30 18:39:40 +0000765 // Create a new block to contain the (bottom) of the loop body.
766 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000767
Ted Kremeneke9334502008-09-04 21:48:47 +0000768 if (Stmt* I = F->getInc()) {
769 // Generate increment code in its own basic block. This is the target
770 // of continue statements.
Ted Kremenekd0172432008-11-24 20:50:24 +0000771 Succ = Visit(I);
Ted Kremeneke9334502008-09-04 21:48:47 +0000772 }
773 else {
Ted Kremenek3575f842009-04-28 00:51:56 +0000774 // No increment code. Create a special, empty, block that is used as
775 // the target block for "looping back" to the start of the loop.
776 assert(Succ == EntryConditionBlock);
777 Succ = createBlock();
Ted Kremeneke9334502008-09-04 21:48:47 +0000778 }
779
Ted Kremenek3575f842009-04-28 00:51:56 +0000780 // Finish up the increment (or empty) block if it hasn't been already.
781 if (Block) {
782 assert(Block == Succ);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000783 if (!FinishBlock(Block))
784 return 0;
Ted Kremenek3575f842009-04-28 00:51:56 +0000785 Block = 0;
786 }
787
788 ContinueTargetBlock = Succ;
789
790 // The starting block for the loop increment is the block that should
791 // represent the 'loop target' for looping back to the start of the loop.
792 ContinueTargetBlock->setLoopTarget(F);
793
Ted Kremeneke9334502008-09-04 21:48:47 +0000794 // All breaks should go to the code following the loop.
795 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000796
797 // Now populate the body block, and in the process create new blocks
798 // as we walk the body of the loop.
799 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000800
801 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000802 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000803 else if (Block) {
804 if (!FinishBlock(BodyBlock))
805 return 0;
806 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000807
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000808 // This new body block is a successor to our "exit" condition block.
809 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000810 }
811
812 // Link up the condition block with the code that follows the loop.
813 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000814 ExitConditionBlock->addSuccessor(LoopSuccessor);
815
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000816 // If the loop contains initialization, create a new block for those
817 // statements. This block can also contain statements that precede
818 // the loop.
819 if (Stmt* I = F->getInit()) {
820 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000821 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000822 }
823 else {
824 // There is no loop initialization. We are thus basically a while
825 // loop. NULL out Block to force lazy block construction.
826 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000827 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000828 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000829 }
830}
831
Ted Kremenek514de5a2008-11-11 17:10:00 +0000832CFGBlock* CFGBuilder::VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
833 // Objective-C fast enumeration 'for' statements:
834 // http://developer.apple.com/documentation/Cocoa/Conceptual/ObjectiveC
835 //
836 // for ( Type newVariable in collection_expression ) { statements }
837 //
838 // becomes:
839 //
840 // prologue:
841 // 1. collection_expression
842 // T. jump to loop_entry
843 // loop_entry:
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000844 // 1. side-effects of element expression
Ted Kremenek514de5a2008-11-11 17:10:00 +0000845 // 1. ObjCForCollectionStmt [performs binding to newVariable]
846 // T. ObjCForCollectionStmt TB, FB [jumps to TB if newVariable != nil]
847 // TB:
848 // statements
849 // T. jump to loop_entry
850 // FB:
851 // what comes after
852 //
853 // and
854 //
855 // Type existingItem;
856 // for ( existingItem in expression ) { statements }
857 //
858 // becomes:
859 //
860 // the same with newVariable replaced with existingItem; the binding
861 // works the same except that for one ObjCForCollectionStmt::getElement()
862 // returns a DeclStmt and the other returns a DeclRefExpr.
863 //
864
865 CFGBlock* LoopSuccessor = 0;
866
867 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000868 if (!FinishBlock(Block))
869 return 0;
Ted Kremenek514de5a2008-11-11 17:10:00 +0000870 LoopSuccessor = Block;
871 Block = 0;
872 }
873 else LoopSuccessor = Succ;
874
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000875 // Build the condition blocks.
876 CFGBlock* ExitConditionBlock = createBlock(false);
877 CFGBlock* EntryConditionBlock = ExitConditionBlock;
878
879 // Set the terminator for the "exit" condition block.
880 ExitConditionBlock->setTerminator(S);
881
882 // The last statement in the block should be the ObjCForCollectionStmt,
883 // which performs the actual binding to 'element' and determines if there
884 // are any more items in the collection.
885 ExitConditionBlock->appendStmt(S);
886 Block = ExitConditionBlock;
887
888 // Walk the 'element' expression to see if there are any side-effects. We
889 // generate new blocks as necesary. We DON'T add the statement by default
890 // to the CFG unless it contains control-flow.
891 EntryConditionBlock = WalkAST(S->getElement(), false);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000892 if (Block) {
893 if (!FinishBlock(EntryConditionBlock))
894 return 0;
895 Block = 0;
896 }
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000897
898 // The condition block is the implicit successor for the loop body as
899 // well as any code above the loop.
900 Succ = EntryConditionBlock;
Ted Kremenek514de5a2008-11-11 17:10:00 +0000901
902 // Now create the true branch.
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000903 {
904 // Save the current values for Succ, continue and break targets.
905 SaveAndRestore<CFGBlock*> save_Succ(Succ),
906 save_continue(ContinueTargetBlock), save_break(BreakTargetBlock);
907
908 BreakTargetBlock = LoopSuccessor;
909 ContinueTargetBlock = EntryConditionBlock;
910
911 CFGBlock* BodyBlock = Visit(S->getBody());
912
913 if (!BodyBlock)
914 BodyBlock = EntryConditionBlock; // can happen for "for (X in Y) ;"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000915 else if (Block) {
916 if (!FinishBlock(BodyBlock))
917 return 0;
918 }
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000919
920 // This new body block is a successor to our "exit" condition block.
921 ExitConditionBlock->addSuccessor(BodyBlock);
922 }
Ted Kremenekfc335522008-11-13 06:36:45 +0000923
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000924 // Link up the condition block with the code that follows the loop.
925 // (the false branch).
926 ExitConditionBlock->addSuccessor(LoopSuccessor);
927
Ted Kremenek514de5a2008-11-11 17:10:00 +0000928 // Now create a prologue block to contain the collection expression.
Ted Kremenek4cb3a852008-11-14 01:57:41 +0000929 Block = createBlock();
Ted Kremenek514de5a2008-11-11 17:10:00 +0000930 return addStmt(S->getCollection());
931}
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000932
Ted Kremenekb3b0b362009-05-02 01:49:13 +0000933CFGBlock* CFGBuilder::VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S) {
934 // FIXME: Add locking 'primitives' to CFG for @synchronized.
935
936 // Inline the body.
Ted Kremenekda5348e2009-05-05 23:11:51 +0000937 CFGBlock *SyncBlock = Visit(S->getSynchBody());
938
939 // The sync body starts its own basic block. This makes it a little easier
940 // for diagnostic clients.
941 if (SyncBlock) {
942 if (!FinishBlock(SyncBlock))
943 return 0;
944
945 Block = 0;
946 }
947
948 Succ = SyncBlock;
Ted Kremenekb3b0b362009-05-02 01:49:13 +0000949
950 // Inline the sync expression.
951 return Visit(S->getSynchExpr());
952}
953
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000954CFGBlock* CFGBuilder::VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
Ted Kremenek90658ec2009-04-07 04:26:02 +0000955 return NYS();
Ted Kremeneke31c0d22009-03-30 22:29:21 +0000956}
Ted Kremenek514de5a2008-11-11 17:10:00 +0000957
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000958CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
959 // "while" is a control-flow statement. Thus we stop processing the
960 // current block.
961
962 CFGBlock* LoopSuccessor = NULL;
963
964 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000965 if (!FinishBlock(Block))
966 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000967 LoopSuccessor = Block;
968 }
969 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000970
971 // Because of short-circuit evaluation, the condition of the loop
972 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
973 // blocks that evaluate the condition.
974 CFGBlock* ExitConditionBlock = createBlock(false);
975 CFGBlock* EntryConditionBlock = ExitConditionBlock;
976
977 // Set the terminator for the "exit" condition block.
978 ExitConditionBlock->setTerminator(W);
979
980 // Now add the actual condition to the condition block. Because the
981 // condition itself may contain control-flow, new blocks may be created.
982 // Thus we update "Succ" after adding the condition.
983 if (Stmt* C = W->getCond()) {
984 Block = ExitConditionBlock;
985 EntryConditionBlock = addStmt(C);
Ted Kremenekf6e85412009-04-28 03:09:44 +0000986 assert(Block == EntryConditionBlock);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +0000987 if (Block) {
988 if (!FinishBlock(EntryConditionBlock))
989 return 0;
990 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000991 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000992
993 // The condition block is the implicit successor for the loop body as
994 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000995 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000996
997 // Process the loop body.
998 {
Ted Kremenekf6e85412009-04-28 03:09:44 +0000999 assert(W->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001000
1001 // Save the current values for Block, Succ, and continue and break targets
1002 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1003 save_continue(ContinueTargetBlock),
1004 save_break(BreakTargetBlock);
Ted Kremenekf6e85412009-04-28 03:09:44 +00001005
1006 // Create an empty block to represent the transition block for looping
1007 // back to the head of the loop.
1008 Block = 0;
1009 assert(Succ == EntryConditionBlock);
1010 Succ = createBlock();
1011 Succ->setLoopTarget(W);
1012 ContinueTargetBlock = Succ;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001013
1014 // All breaks should go to the code following the loop.
1015 BreakTargetBlock = LoopSuccessor;
1016
1017 // NULL out Block to force lazy instantiation of blocks for the body.
1018 Block = NULL;
1019
1020 // Create the body. The returned block is the entry to the loop body.
1021 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +00001022
1023 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +00001024 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001025 else if (Block) {
1026 if (!FinishBlock(BodyBlock))
1027 return 0;
1028 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001029
1030 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001031 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001032 }
1033
1034 // Link up the condition block with the code that follows the loop.
1035 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001036 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001037
1038 // There can be no more statements in the condition block
1039 // since we loop back to this block. NULL out Block to force
1040 // lazy creation of another block.
1041 Block = NULL;
1042
1043 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +00001044 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001045 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001046}
Ted Kremenek2fda5042008-12-09 20:20:09 +00001047
1048CFGBlock* CFGBuilder::VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) {
1049 // FIXME: This isn't complete. We basically treat @throw like a return
1050 // statement.
1051
1052 // If we were in the middle of a block we stop processing that block
1053 // and reverse its statements.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001054 if (Block) {
1055 if (!FinishBlock(Block))
1056 return 0;
1057 }
Ted Kremenek2fda5042008-12-09 20:20:09 +00001058
1059 // Create the new block.
1060 Block = createBlock(false);
1061
1062 // The Exit block is the only successor.
1063 Block->addSuccessor(&cfg->getExit());
1064
1065 // Add the statement to the block. This may create new blocks
1066 // if S contains control-flow (short-circuit operations).
1067 return addStmt(S);
1068}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001069
1070CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
1071 // "do...while" is a control-flow statement. Thus we stop processing the
1072 // current block.
1073
1074 CFGBlock* LoopSuccessor = NULL;
1075
1076 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001077 if (!FinishBlock(Block))
1078 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001079 LoopSuccessor = Block;
1080 }
1081 else LoopSuccessor = Succ;
1082
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001083 // Because of short-circuit evaluation, the condition of the loop
1084 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
1085 // blocks that evaluate the condition.
1086 CFGBlock* ExitConditionBlock = createBlock(false);
1087 CFGBlock* EntryConditionBlock = ExitConditionBlock;
1088
1089 // Set the terminator for the "exit" condition block.
1090 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001091
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001092 // Now add the actual condition to the condition block. Because the
1093 // condition itself may contain control-flow, new blocks may be created.
1094 if (Stmt* C = D->getCond()) {
1095 Block = ExitConditionBlock;
1096 EntryConditionBlock = addStmt(C);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001097 if (Block) {
1098 if (!FinishBlock(EntryConditionBlock))
1099 return 0;
1100 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001101 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001102
Ted Kremenek54827132008-02-27 07:20:00 +00001103 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001104 Succ = EntryConditionBlock;
1105
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001106 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001107 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001108 {
1109 assert (D->getBody());
1110
1111 // Save the current values for Block, Succ, and continue and break targets
1112 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
1113 save_continue(ContinueTargetBlock),
1114 save_break(BreakTargetBlock);
1115
1116 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001117 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001118
1119 // All breaks should go to the code following the loop.
1120 BreakTargetBlock = LoopSuccessor;
1121
1122 // NULL out Block to force lazy instantiation of blocks for the body.
1123 Block = NULL;
1124
1125 // Create the body. The returned block is the entry to the loop body.
1126 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001127
Ted Kremenekaf603f72007-08-30 18:39:40 +00001128 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +00001129 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001130 else if (Block) {
1131 if (!FinishBlock(BodyBlock))
1132 return 0;
1133 }
Ted Kremenekaf603f72007-08-30 18:39:40 +00001134
Ted Kremenek8f08c9d2009-04-28 04:22:00 +00001135 // Add an intermediate block between the BodyBlock and the
1136 // ExitConditionBlock to represent the "loop back" transition.
1137 // Create an empty block to represent the transition block for looping
1138 // back to the head of the loop.
1139 // FIXME: Can we do this more efficiently without adding another block?
1140 Block = NULL;
1141 Succ = BodyBlock;
1142 CFGBlock *LoopBackBlock = createBlock();
1143 LoopBackBlock->setLoopTarget(D);
1144
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001145 // Add the loop body entry as a successor to the condition.
Ted Kremenek8f08c9d2009-04-28 04:22:00 +00001146 ExitConditionBlock->addSuccessor(LoopBackBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001147 }
1148
1149 // Link up the condition block with the code that follows the loop.
1150 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001151 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001152
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001153 // There can be no more statements in the body block(s)
1154 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001155 // lazy creation of another block.
1156 Block = NULL;
1157
1158 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +00001159 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001160 return BodyBlock;
1161}
1162
1163CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
1164 // "continue" is a control-flow statement. Thus we stop processing the
1165 // current block.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001166 if (Block) {
1167 if (!FinishBlock(Block))
1168 return 0;
1169 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001170
1171 // Now create a new block that ends with the continue statement.
1172 Block = createBlock(false);
1173 Block->setTerminator(C);
1174
1175 // If there is no target for the continue, then we are looking at an
Ted Kremenek235c5ed2009-04-07 18:53:24 +00001176 // incomplete AST. This means the CFG cannot be constructed.
1177 if (ContinueTargetBlock)
1178 Block->addSuccessor(ContinueTargetBlock);
1179 else
1180 badCFG = true;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001181
1182 return Block;
1183}
1184
1185CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
1186 // "break" is a control-flow statement. Thus we stop processing the
1187 // current block.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001188 if (Block) {
1189 if (!FinishBlock(Block))
1190 return 0;
1191 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001192
1193 // Now create a new block that ends with the continue statement.
1194 Block = createBlock(false);
1195 Block->setTerminator(B);
1196
1197 // If there is no target for the break, then we are looking at an
Ted Kremenek235c5ed2009-04-07 18:53:24 +00001198 // incomplete AST. This means that the CFG cannot be constructed.
1199 if (BreakTargetBlock)
1200 Block->addSuccessor(BreakTargetBlock);
1201 else
1202 badCFG = true;
1203
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001204
1205 return Block;
1206}
1207
Ted Kremenek411cdee2008-04-16 21:10:48 +00001208CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001209 // "switch" is a control-flow statement. Thus we stop processing the
1210 // current block.
1211 CFGBlock* SwitchSuccessor = NULL;
1212
1213 if (Block) {
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001214 if (!FinishBlock(Block))
1215 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001216 SwitchSuccessor = Block;
1217 }
1218 else SwitchSuccessor = Succ;
1219
1220 // Save the current "switch" context.
1221 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001222 save_break(BreakTargetBlock),
1223 save_default(DefaultCaseBlock);
1224
1225 // Set the "default" case to be the block after the switch statement.
1226 // If the switch statement contains a "default:", this value will
1227 // be overwritten with the block for that code.
1228 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +00001229
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001230 // Create a new block that will contain the switch statement.
1231 SwitchTerminatedBlock = createBlock(false);
1232
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001233 // Now process the switch body. The code after the switch is the implicit
1234 // successor.
1235 Succ = SwitchSuccessor;
1236 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001237
1238 // When visiting the body, the case statements should automatically get
1239 // linked up to the switch. We also don't keep a pointer to the body,
1240 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001241 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001242 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001243 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001244 if (Block) {
1245 if (!FinishBlock(BodyBlock))
1246 return 0;
1247 }
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001248
Ted Kremenek295222c2008-02-13 21:46:34 +00001249 // If we have no "default:" case, the default transition is to the
1250 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001251 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001252
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001253 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001254 SwitchTerminatedBlock->setTerminator(Terminator);
1255 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001256 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001257
Ted Kremenek411cdee2008-04-16 21:10:48 +00001258 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001259}
1260
Ted Kremenek411cdee2008-04-16 21:10:48 +00001261CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001262 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001263 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001264
Ted Kremenek411cdee2008-04-16 21:10:48 +00001265 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001266 CFGBlock* CaseBlock = Block;
1267 if (!CaseBlock) CaseBlock = createBlock();
1268
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001269 // Cases statements partition blocks, so this is the top of
1270 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001271 CaseBlock->setLabel(Terminator);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001272 if (!FinishBlock(CaseBlock))
1273 return 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001274
1275 // Add this block to the list of successors for the block with the
1276 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001277 assert (SwitchTerminatedBlock);
1278 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001279
1280 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1281 Block = NULL;
1282
1283 // This block is now the implicit successor of other blocks.
1284 Succ = CaseBlock;
1285
Ted Kremenek2677ea82008-03-15 07:45:02 +00001286 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001287}
Ted Kremenek295222c2008-02-13 21:46:34 +00001288
Ted Kremenek411cdee2008-04-16 21:10:48 +00001289CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1290 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001291 DefaultCaseBlock = Block;
1292 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1293
1294 // Default statements partition blocks, so this is the top of
1295 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001296 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001297 if (!FinishBlock(DefaultCaseBlock))
1298 return 0;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001299
1300 // Unlike case statements, we don't add the default block to the
1301 // successors for the switch statement immediately. This is done
1302 // when we finish processing the switch statement. This allows for
1303 // the default case (including a fall-through to the code after the
1304 // switch statement) to always be the last successor of a switch-terminated
1305 // block.
1306
1307 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1308 Block = NULL;
1309
1310 // This block is now the implicit successor of other blocks.
1311 Succ = DefaultCaseBlock;
1312
1313 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001314}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001315
Ted Kremenek19bb3562007-08-28 19:26:49 +00001316CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1317 // Lazily create the indirect-goto dispatch block if there isn't one
1318 // already.
1319 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1320
1321 if (!IBlock) {
1322 IBlock = createBlock(false);
1323 cfg->setIndirectGotoBlock(IBlock);
1324 }
1325
1326 // IndirectGoto is a control-flow statement. Thus we stop processing the
1327 // current block and create a new one.
Ted Kremenek4e8df2e2009-05-02 00:13:27 +00001328 if (Block) {
1329 if (!FinishBlock(Block))
1330 return 0;
1331 }
Ted Kremenek19bb3562007-08-28 19:26:49 +00001332 Block = createBlock(false);
1333 Block->setTerminator(I);
1334 Block->addSuccessor(IBlock);
1335 return addStmt(I->getTarget());
1336}
1337
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001338
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001339} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001340
1341/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1342/// block has no successors or predecessors. If this is the first block
1343/// created in the CFG, it is automatically set to be the Entry and Exit
1344/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001345CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001346 bool first_block = begin() == end();
1347
1348 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001349 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001350
1351 // If this is the first block, set it as the Entry and Exit.
1352 if (first_block) Entry = Exit = &front();
1353
1354 // Return the block.
1355 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001356}
1357
Ted Kremenek026473c2007-08-23 16:51:22 +00001358/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1359/// CFG is returned to the caller.
1360CFG* CFG::buildCFG(Stmt* Statement) {
1361 CFGBuilder Builder;
1362 return Builder.buildCFG(Statement);
1363}
1364
1365/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001366void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1367
Ted Kremenek63f58872007-10-01 19:33:33 +00001368//===----------------------------------------------------------------------===//
1369// CFG: Queries for BlkExprs.
1370//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001371
Ted Kremenek63f58872007-10-01 19:33:33 +00001372namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001373 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001374}
1375
Ted Kremenek411cdee2008-04-16 21:10:48 +00001376static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1377 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001378 return;
1379
Ted Kremenek411cdee2008-04-16 21:10:48 +00001380 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001381 if (!*I) continue;
1382
1383 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1384 if (B->isAssignmentOp()) Set.insert(B);
1385
1386 FindSubExprAssignments(*I, Set);
1387 }
1388}
1389
Ted Kremenek63f58872007-10-01 19:33:33 +00001390static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1391 BlkExprMapTy* M = new BlkExprMapTy();
1392
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001393 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001394 // only assignments that we want to *possibly* register as a block-level
1395 // expression. Basically, if an assignment occurs both in a subexpression
1396 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001397 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1398
Ted Kremenek63f58872007-10-01 19:33:33 +00001399 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1400 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001401 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001402
Ted Kremenek411cdee2008-04-16 21:10:48 +00001403 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1404
1405 // Iterate over the statements again on identify the Expr* and Stmt* at
1406 // the block-level that are block-level expressions.
1407
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001408 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001409 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001410
Ted Kremenek411cdee2008-04-16 21:10:48 +00001411 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001412 // Assignment expressions that are not nested within another
1413 // expression are really "statements" whose value is never
1414 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001415 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001416 continue;
1417 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001418 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001419 // Special handling for statement expressions. The last statement
1420 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001421 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001422 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001423 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001424 (*M)[C->body_back()] = x;
1425 }
1426 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001427
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001428 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001429 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001430 }
1431
Ted Kremenek411cdee2008-04-16 21:10:48 +00001432 // Look at terminators. The condition is a block-level expression.
1433
Ted Kremenek390e48b2008-11-12 21:11:49 +00001434 Stmt* S = I->getTerminatorCondition();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001435
Ted Kremenek390e48b2008-11-12 21:11:49 +00001436 if (S && M->find(S) == M->end()) {
Ted Kremenek411cdee2008-04-16 21:10:48 +00001437 unsigned x = M->size();
Ted Kremenek390e48b2008-11-12 21:11:49 +00001438 (*M)[S] = x;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001439 }
1440 }
1441
Ted Kremenek63f58872007-10-01 19:33:33 +00001442 return M;
1443}
1444
Ted Kremenek86946742008-01-17 20:48:37 +00001445CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1446 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001447 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1448
1449 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001450 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001451
1452 if (I == M->end()) return CFG::BlkExprNumTy();
1453 else return CFG::BlkExprNumTy(I->second);
1454}
1455
1456unsigned CFG::getNumBlkExprs() {
1457 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1458 return M->size();
1459 else {
1460 // We assume callers interested in the number of BlkExprs will want
1461 // the map constructed if it doesn't already exist.
1462 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1463 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1464 }
1465}
1466
Ted Kremenek274f4332008-04-28 18:00:46 +00001467//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001468// Cleanup: CFG dstor.
1469//===----------------------------------------------------------------------===//
1470
Ted Kremenek63f58872007-10-01 19:33:33 +00001471CFG::~CFG() {
1472 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1473}
1474
Ted Kremenek7dba8602007-08-29 21:56:09 +00001475//===----------------------------------------------------------------------===//
1476// CFG pretty printing
1477//===----------------------------------------------------------------------===//
1478
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001479namespace {
1480
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001481class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001482
Ted Kremenek42a509f2007-08-31 21:30:12 +00001483 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1484 StmtMapTy StmtMap;
1485 signed CurrentBlock;
1486 unsigned CurrentStmt;
Chris Lattnere4f21422009-06-30 01:26:17 +00001487 const LangOptions &LangOpts;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001488public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001489
Chris Lattnere4f21422009-06-30 01:26:17 +00001490 StmtPrinterHelper(const CFG* cfg, const LangOptions &LO)
1491 : CurrentBlock(0), CurrentStmt(0), LangOpts(LO) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001492 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1493 unsigned j = 1;
1494 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1495 BI != BEnd; ++BI, ++j )
1496 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1497 }
1498 }
1499
1500 virtual ~StmtPrinterHelper() {}
1501
Chris Lattnere4f21422009-06-30 01:26:17 +00001502 const LangOptions &getLangOpts() const { return LangOpts; }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001503 void setBlockID(signed i) { CurrentBlock = i; }
1504 void setStmtID(unsigned i) { CurrentStmt = i; }
1505
Ted Kremeneka95d3752008-09-13 05:16:45 +00001506 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001507
Ted Kremenek411cdee2008-04-16 21:10:48 +00001508 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001509
1510 if (I == StmtMap.end())
1511 return false;
1512
1513 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1514 && I->second.second == CurrentStmt)
1515 return false;
1516
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001517 OS << "[B" << I->second.first << "." << I->second.second << "]";
1518 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001519 }
1520};
Chris Lattnere4f21422009-06-30 01:26:17 +00001521} // end anonymous namespace
Ted Kremenek42a509f2007-08-31 21:30:12 +00001522
Chris Lattnere4f21422009-06-30 01:26:17 +00001523
1524namespace {
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001525class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1526 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1527
Ted Kremeneka95d3752008-09-13 05:16:45 +00001528 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001529 StmtPrinterHelper* Helper;
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001530 PrintingPolicy Policy;
1531
Ted Kremenek42a509f2007-08-31 21:30:12 +00001532public:
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001533 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper,
Chris Lattnere4f21422009-06-30 01:26:17 +00001534 const PrintingPolicy &Policy)
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001535 : OS(os), Helper(helper), Policy(Policy) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001536
1537 void VisitIfStmt(IfStmt* I) {
1538 OS << "if ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001539 I->getCond()->printPretty(OS,Helper,Policy);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001540 }
1541
1542 // Default case.
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001543 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS, Helper, Policy); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001544
1545 void VisitForStmt(ForStmt* F) {
1546 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001547 if (F->getInit()) OS << "...";
1548 OS << "; ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001549 if (Stmt* C = F->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek535bb202007-08-30 21:28:02 +00001550 OS << "; ";
1551 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001552 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001553 }
1554
1555 void VisitWhileStmt(WhileStmt* W) {
1556 OS << "while " ;
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001557 if (Stmt* C = W->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001558 }
1559
1560 void VisitDoStmt(DoStmt* D) {
1561 OS << "do ... while ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001562 if (Stmt* C = D->getCond()) C->printPretty(OS, Helper, Policy);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001563 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001564
Ted Kremenek411cdee2008-04-16 21:10:48 +00001565 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001566 OS << "switch ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001567 Terminator->getCond()->printPretty(OS, Helper, Policy);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001568 }
1569
Ted Kremenek805e9a82007-08-31 21:49:40 +00001570 void VisitConditionalOperator(ConditionalOperator* C) {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001571 C->getCond()->printPretty(OS, Helper, Policy);
Ted Kremeneka2925852008-01-30 23:02:42 +00001572 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001573 }
1574
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001575 void VisitChooseExpr(ChooseExpr* C) {
1576 OS << "__builtin_choose_expr( ";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001577 C->getCond()->printPretty(OS, Helper, Policy);
Ted Kremeneka2925852008-01-30 23:02:42 +00001578 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001579 }
1580
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001581 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1582 OS << "goto *";
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001583 I->getTarget()->printPretty(OS, Helper, Policy);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001584 }
1585
Ted Kremenek805e9a82007-08-31 21:49:40 +00001586 void VisitBinaryOperator(BinaryOperator* B) {
1587 if (!B->isLogicalOp()) {
1588 VisitExpr(B);
1589 return;
1590 }
1591
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001592 B->getLHS()->printPretty(OS, Helper, Policy);
Ted Kremenek805e9a82007-08-31 21:49:40 +00001593
1594 switch (B->getOpcode()) {
1595 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001596 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001597 return;
1598 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001599 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001600 return;
1601 default:
1602 assert(false && "Invalid logical operator.");
1603 }
1604 }
1605
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001606 void VisitExpr(Expr* E) {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001607 E->printPretty(OS, Helper, Policy);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001608 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001609};
Chris Lattnere4f21422009-06-30 01:26:17 +00001610} // end anonymous namespace
1611
Ted Kremenek42a509f2007-08-31 21:30:12 +00001612
Chris Lattnere4f21422009-06-30 01:26:17 +00001613static void print_stmt(llvm::raw_ostream &OS, StmtPrinterHelper* Helper,
1614 Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001615 if (Helper) {
1616 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001617 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001618 CompoundStmt* Sub = SE->getSubStmt();
1619
1620 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001621 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001622 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001623 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001624 return;
1625 }
1626 }
1627
1628 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001629 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001630 if (B->getOpcode() == BinaryOperator::Comma) {
1631 OS << "... , ";
1632 Helper->handledStmt(B->getRHS(),OS);
1633 OS << '\n';
1634 return;
1635 }
1636 }
1637 }
1638
Chris Lattnere4f21422009-06-30 01:26:17 +00001639 Terminator->printPretty(OS, Helper, PrintingPolicy(Helper->getLangOpts()));
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001640
1641 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001642 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001643}
1644
Chris Lattnere4f21422009-06-30 01:26:17 +00001645static void print_block(llvm::raw_ostream& OS, const CFG* cfg,
1646 const CFGBlock& B,
1647 StmtPrinterHelper* Helper, bool print_edges) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001648
1649 if (Helper) Helper->setBlockID(B.getBlockID());
1650
Ted Kremenek7dba8602007-08-29 21:56:09 +00001651 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001652 OS << "\n [ B" << B.getBlockID();
1653
1654 if (&B == &cfg->getEntry())
1655 OS << " (ENTRY) ]\n";
1656 else if (&B == &cfg->getExit())
1657 OS << " (EXIT) ]\n";
1658 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001659 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001660 else
1661 OS << " ]\n";
1662
Ted Kremenek9cffe732007-08-29 23:20:49 +00001663 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001664 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001665
1666 if (print_edges)
1667 OS << " ";
1668
Ted Kremenek411cdee2008-04-16 21:10:48 +00001669 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001670 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001671 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001672 OS << "case ";
Chris Lattnere4f21422009-06-30 01:26:17 +00001673 C->getLHS()->printPretty(OS, Helper,
1674 PrintingPolicy(Helper->getLangOpts()));
Ted Kremenek9cffe732007-08-29 23:20:49 +00001675 if (C->getRHS()) {
1676 OS << " ... ";
Chris Lattnere4f21422009-06-30 01:26:17 +00001677 C->getRHS()->printPretty(OS, Helper,
1678 PrintingPolicy(Helper->getLangOpts()));
Ted Kremenek9cffe732007-08-29 23:20:49 +00001679 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001680 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001681 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001682 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001683 else
1684 assert(false && "Invalid label statement in CFGBlock.");
1685
Ted Kremenek9cffe732007-08-29 23:20:49 +00001686 OS << ":\n";
1687 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001688
Ted Kremenekfddd5182007-08-21 21:42:03 +00001689 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001690 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001691
1692 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1693 I != E ; ++I, ++j ) {
1694
Ted Kremenek9cffe732007-08-29 23:20:49 +00001695 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001696 if (print_edges)
1697 OS << " ";
1698
Ted Kremeneka95d3752008-09-13 05:16:45 +00001699 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001700
1701 if (Helper)
1702 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001703
1704 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001705 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001706
Ted Kremenek9cffe732007-08-29 23:20:49 +00001707 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001708 if (B.getTerminator()) {
1709 if (print_edges)
1710 OS << " ";
1711
Ted Kremenek9cffe732007-08-29 23:20:49 +00001712 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001713
1714 if (Helper) Helper->setBlockID(-1);
1715
Chris Lattnere4f21422009-06-30 01:26:17 +00001716 CFGBlockTerminatorPrint TPrinter(OS, Helper,
1717 PrintingPolicy(Helper->getLangOpts()));
Ted Kremenek42a509f2007-08-31 21:30:12 +00001718 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001719 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001720 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001721
Ted Kremenek9cffe732007-08-29 23:20:49 +00001722 if (print_edges) {
1723 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001724 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001725 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001726
Ted Kremenek42a509f2007-08-31 21:30:12 +00001727 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1728 I != E; ++I, ++i) {
1729
1730 if (i == 8 || (i-8) == 0)
1731 OS << "\n ";
1732
Ted Kremenek9cffe732007-08-29 23:20:49 +00001733 OS << " B" << (*I)->getBlockID();
1734 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001735
1736 OS << '\n';
1737
1738 // Print the successors of this block.
1739 OS << " Successors (" << B.succ_size() << "):";
1740 i = 0;
1741
1742 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1743 I != E; ++I, ++i) {
1744
1745 if (i == 8 || (i-8) % 10 == 0)
1746 OS << "\n ";
1747
1748 OS << " B" << (*I)->getBlockID();
1749 }
1750
Ted Kremenek9cffe732007-08-29 23:20:49 +00001751 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001752 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001753}
1754
Ted Kremenek42a509f2007-08-31 21:30:12 +00001755
1756/// dump - A simple pretty printer of a CFG that outputs to stderr.
Chris Lattnere4f21422009-06-30 01:26:17 +00001757void CFG::dump(const LangOptions &LO) const { print(llvm::errs(), LO); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001758
1759/// print - A simple pretty printer of a CFG that outputs to an ostream.
Chris Lattnere4f21422009-06-30 01:26:17 +00001760void CFG::print(llvm::raw_ostream &OS, const LangOptions &LO) const {
1761 StmtPrinterHelper Helper(this, LO);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001762
1763 // Print the entry block.
1764 print_block(OS, this, getEntry(), &Helper, true);
1765
1766 // Iterate through the CFGBlocks and print them one by one.
1767 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1768 // Skip the entry block, because we already printed it.
1769 if (&(*I) == &getEntry() || &(*I) == &getExit())
1770 continue;
1771
1772 print_block(OS, this, *I, &Helper, true);
1773 }
1774
1775 // Print the exit block.
1776 print_block(OS, this, getExit(), &Helper, true);
Ted Kremenekd0172432008-11-24 20:50:24 +00001777 OS.flush();
Ted Kremenek42a509f2007-08-31 21:30:12 +00001778}
1779
1780/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Chris Lattnere4f21422009-06-30 01:26:17 +00001781void CFGBlock::dump(const CFG* cfg, const LangOptions &LO) const {
1782 print(llvm::errs(), cfg, LO);
1783}
Ted Kremenek42a509f2007-08-31 21:30:12 +00001784
1785/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1786/// Generally this will only be called from CFG::print.
Chris Lattnere4f21422009-06-30 01:26:17 +00001787void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg,
1788 const LangOptions &LO) const {
1789 StmtPrinterHelper Helper(cfg, LO);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001790 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001791}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001792
Ted Kremeneka2925852008-01-30 23:02:42 +00001793/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Chris Lattnere4f21422009-06-30 01:26:17 +00001794void CFGBlock::printTerminator(llvm::raw_ostream &OS,
1795 const LangOptions &LO) const {
1796 CFGBlockTerminatorPrint TPrinter(OS, NULL, PrintingPolicy(LO));
Ted Kremeneka2925852008-01-30 23:02:42 +00001797 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1798}
1799
Ted Kremenek390e48b2008-11-12 21:11:49 +00001800Stmt* CFGBlock::getTerminatorCondition() {
Ted Kremenek411cdee2008-04-16 21:10:48 +00001801
1802 if (!Terminator)
1803 return NULL;
1804
1805 Expr* E = NULL;
1806
1807 switch (Terminator->getStmtClass()) {
1808 default:
1809 break;
1810
1811 case Stmt::ForStmtClass:
1812 E = cast<ForStmt>(Terminator)->getCond();
1813 break;
1814
1815 case Stmt::WhileStmtClass:
1816 E = cast<WhileStmt>(Terminator)->getCond();
1817 break;
1818
1819 case Stmt::DoStmtClass:
1820 E = cast<DoStmt>(Terminator)->getCond();
1821 break;
1822
1823 case Stmt::IfStmtClass:
1824 E = cast<IfStmt>(Terminator)->getCond();
1825 break;
1826
1827 case Stmt::ChooseExprClass:
1828 E = cast<ChooseExpr>(Terminator)->getCond();
1829 break;
1830
1831 case Stmt::IndirectGotoStmtClass:
1832 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1833 break;
1834
1835 case Stmt::SwitchStmtClass:
1836 E = cast<SwitchStmt>(Terminator)->getCond();
1837 break;
1838
1839 case Stmt::ConditionalOperatorClass:
1840 E = cast<ConditionalOperator>(Terminator)->getCond();
1841 break;
1842
1843 case Stmt::BinaryOperatorClass: // '&&' and '||'
1844 E = cast<BinaryOperator>(Terminator)->getLHS();
Ted Kremenek390e48b2008-11-12 21:11:49 +00001845 break;
1846
1847 case Stmt::ObjCForCollectionStmtClass:
1848 return Terminator;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001849 }
1850
1851 return E ? E->IgnoreParens() : NULL;
1852}
1853
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001854bool CFGBlock::hasBinaryBranchTerminator() const {
1855
1856 if (!Terminator)
1857 return false;
1858
1859 Expr* E = NULL;
1860
1861 switch (Terminator->getStmtClass()) {
1862 default:
1863 return false;
1864
1865 case Stmt::ForStmtClass:
1866 case Stmt::WhileStmtClass:
1867 case Stmt::DoStmtClass:
1868 case Stmt::IfStmtClass:
1869 case Stmt::ChooseExprClass:
1870 case Stmt::ConditionalOperatorClass:
1871 case Stmt::BinaryOperatorClass:
1872 return true;
1873 }
1874
1875 return E ? E->IgnoreParens() : NULL;
1876}
1877
Ted Kremeneka2925852008-01-30 23:02:42 +00001878
Ted Kremenek7dba8602007-08-29 21:56:09 +00001879//===----------------------------------------------------------------------===//
1880// CFG Graphviz Visualization
1881//===----------------------------------------------------------------------===//
1882
Ted Kremenek42a509f2007-08-31 21:30:12 +00001883
1884#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001885static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001886#endif
1887
Chris Lattnere4f21422009-06-30 01:26:17 +00001888void CFG::viewCFG(const LangOptions &LO) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001889#ifndef NDEBUG
Chris Lattnere4f21422009-06-30 01:26:17 +00001890 StmtPrinterHelper H(this, LO);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001891 GraphHelper = &H;
1892 llvm::ViewGraph(this,"CFG");
1893 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001894#endif
1895}
1896
Ted Kremenek7dba8602007-08-29 21:56:09 +00001897namespace llvm {
1898template<>
1899struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
Owen Anderson02995ce2009-06-24 17:37:55 +00001900 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph,
1901 bool ShortNames) {
Ted Kremenek7dba8602007-08-29 21:56:09 +00001902
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001903#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001904 std::string OutSStr;
1905 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001906 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001907 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001908
1909 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1910
1911 // Process string output to make it nicer...
1912 for (unsigned i = 0; i != OutStr.length(); ++i)
1913 if (OutStr[i] == '\n') { // Left justify
1914 OutStr[i] = '\\';
1915 OutStr.insert(OutStr.begin()+i+1, 'l');
1916 }
1917
1918 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001919#else
1920 return "";
1921#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001922 }
1923};
1924} // end namespace llvm