blob: e1c1a7474c3daa2326f84677f26e75eeb168511d [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//
5// This file was developed by Ted Kremenek and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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"
16#include "clang/AST/Expr.h"
Ted Kremenekc310e932007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
22#include "llvm/Config/config.h"
Ted Kremenekfddd5182007-08-21 21:42:03 +000023#include <iostream>
24#include <iomanip>
25#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000026#include <sstream>
27
Ted Kremenekfddd5182007-08-21 21:42:03 +000028using namespace clang;
29
30namespace {
31
Ted Kremenekbefef2f2007-08-23 21:26:19 +000032// SaveAndRestore - A utility class that uses RIIA to save and restore
33// the value of a variable.
34template<typename T>
35struct SaveAndRestore {
36 SaveAndRestore(T& x) : X(x), old_value(x) {}
37 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000038 T get() { return old_value; }
39
Ted Kremenekbefef2f2007-08-23 21:26:19 +000040 T& X;
41 T old_value;
42};
Ted Kremenekfddd5182007-08-21 21:42:03 +000043
44/// CFGBuilder - This class is implements CFG construction from an AST.
45/// The builder is stateful: an instance of the builder should be used to only
46/// construct a single CFG.
47///
48/// Example usage:
49///
50/// CFGBuilder builder;
51/// CFG* cfg = builder.BuildAST(stmt1);
52///
Ted Kremenekc310e932007-08-21 22:06:14 +000053/// CFG construction is done via a recursive walk of an AST.
54/// We actually parse the AST in reverse order so that the successor
55/// of a basic block is constructed prior to its predecessor. This
56/// allows us to nicely capture implicit fall-throughs without extra
57/// basic blocks.
58///
59class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000060 CFG* cfg;
61 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000062 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000063 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000064 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000065 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000066
Ted Kremenek19bb3562007-08-28 19:26:49 +000067 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000068 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
69 LabelMapTy LabelMap;
70
Ted Kremenek19bb3562007-08-28 19:26:49 +000071 // A list of blocks that end with a "goto" that must be backpatched to
72 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000073 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000074 BackpatchBlocksTy BackpatchBlocks;
75
Ted Kremenek19bb3562007-08-28 19:26:49 +000076 // A list of labels whose address has been taken (for indirect gotos).
77 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
78 LabelSetTy AddressTakenLabels;
79
Ted Kremenekfddd5182007-08-21 21:42:03 +000080public:
Ted Kremenek026473c2007-08-23 16:51:22 +000081 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000082 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek94382522007-09-05 20:02:05 +000083 SwitchTerminatedBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000084 // Create an empty CFG.
85 cfg = new CFG();
86 }
87
88 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000089
Ted Kremenekd4fdee32007-08-23 21:42:29 +000090 // buildCFG - Used by external clients to construct the CFG.
91 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000092
Ted Kremenekd4fdee32007-08-23 21:42:29 +000093 // Visitors to walk an AST and construct the CFG. Called by
94 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000095
Ted Kremenekd4fdee32007-08-23 21:42:29 +000096 CFGBlock* VisitStmt(Stmt* Statement);
97 CFGBlock* VisitNullStmt(NullStmt* Statement);
98 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
99 CFGBlock* VisitIfStmt(IfStmt* I);
100 CFGBlock* VisitReturnStmt(ReturnStmt* R);
101 CFGBlock* VisitLabelStmt(LabelStmt* L);
102 CFGBlock* VisitGotoStmt(GotoStmt* G);
103 CFGBlock* VisitForStmt(ForStmt* F);
104 CFGBlock* VisitWhileStmt(WhileStmt* W);
105 CFGBlock* VisitDoStmt(DoStmt* D);
106 CFGBlock* VisitContinueStmt(ContinueStmt* C);
107 CFGBlock* VisitBreakStmt(BreakStmt* B);
108 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
109 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000110 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000111
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000112private:
113 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000114 CFGBlock* addStmt(Stmt* S);
115 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
116 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000117 CFGBlock* WalkAST_VisitVarDecl(VarDecl* D);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000118 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekf50ec102007-09-11 21:29:43 +0000119 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000120 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000121
Ted Kremenekfddd5182007-08-21 21:42:03 +0000122};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000123
124/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
125/// represent an arbitrary statement. Examples include a single expression
126/// or a function body (compound statement). The ownership of the returned
127/// CFG is transferred to the caller. If CFG construction fails, this method
128/// returns NULL.
129CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000130 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000131 if (!Statement) return NULL;
132
133 // Create an empty block that will serve as the exit block for the CFG.
134 // Since this is the first block added to the CFG, it will be implicitly
135 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000136 Succ = createBlock();
137 assert (Succ == &cfg->getExit());
138 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000139
140 // Visit the statements and create the CFG.
141 if (CFGBlock* B = Visit(Statement)) {
142 // Finalize the last constructed block. This usually involves
143 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000144 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000145
146 // Backpatch the gotos whose label -> block mappings we didn't know
147 // when we encountered them.
148 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
149 E = BackpatchBlocks.end(); I != E; ++I ) {
150
151 CFGBlock* B = *I;
152 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
153 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
154
155 // If there is no target for the goto, then we are looking at an
156 // incomplete AST. Handle this by not registering a successor.
157 if (LI == LabelMap.end()) continue;
158
159 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000160 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000161
Ted Kremenek19bb3562007-08-28 19:26:49 +0000162 // Add successors to the Indirect Goto Dispatch block (if we have one).
163 if (CFGBlock* B = cfg->getIndirectGotoBlock())
164 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
165 E = AddressTakenLabels.end(); I != E; ++I ) {
166
167 // Lookup the target block.
168 LabelMapTy::iterator LI = LabelMap.find(*I);
169
170 // If there is no target block that contains label, then we are looking
171 // at an incomplete AST. Handle this by not registering a successor.
172 if (LI == LabelMap.end()) continue;
173
174 B->addSuccessor(LI->second);
175 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000176
Ted Kremenek94b33162007-09-17 16:18:02 +0000177 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000178 }
179
180 // Create an empty entry block that has no predecessors.
181 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000182
Ted Kremenek322f58d2007-09-26 21:23:31 +0000183 // NULL out cfg so that repeated calls to the builder will fail and that
184 // the ownership of the constructed CFG is passed to the caller.
185 CFG* t = cfg;
186 cfg = NULL;
187 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000188}
189
190/// createBlock - Used to lazily create blocks that are connected
191/// to the current (global) succcessor.
192CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000193 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000194 if (add_successor && Succ) B->addSuccessor(Succ);
195 return B;
196}
197
198/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000199/// we must reverse the statements because they have been inserted
200/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000201void CFGBuilder::FinishBlock(CFGBlock* B) {
202 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000203 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000204}
205
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000206/// addStmt - Used to add statements/expressions to the current CFGBlock
207/// "Block". This method calls WalkAST on the passed statement to see if it
208/// contains any short-circuit expressions. If so, it recursively creates
209/// the necessary blocks for such expressions. It returns the "topmost" block
210/// of the created blocks, or the original value of "Block" when this method
211/// was called if no additional blocks are created.
212CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000213 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000214 return WalkAST(S,true);
215}
216
217/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000218/// add extra blocks for ternary operators, &&, and ||. We also
219/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000220CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
221 switch (S->getStmtClass()) {
222 case Stmt::ConditionalOperatorClass: {
223 ConditionalOperator* C = cast<ConditionalOperator>(S);
224
225 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
226 ConfluenceBlock->appendStmt(C);
227 FinishBlock(ConfluenceBlock);
228
229 Succ = ConfluenceBlock;
230 Block = NULL;
231 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000232 FinishBlock(LHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000233
234 Succ = ConfluenceBlock;
235 Block = NULL;
236 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000237 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000238
239 Block = createBlock(false);
240 Block->addSuccessor(LHSBlock);
241 Block->addSuccessor(RHSBlock);
242 Block->setTerminator(C);
243 return addStmt(C->getCond());
244 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000245
246 case Stmt::ChooseExprClass: {
247 ChooseExpr* C = cast<ChooseExpr>(S);
248
249 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
250 ConfluenceBlock->appendStmt(C);
251 FinishBlock(ConfluenceBlock);
252
253 Succ = ConfluenceBlock;
254 Block = NULL;
255 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000256 FinishBlock(LHSBlock);
257
Ted Kremenek49a436d2007-08-31 17:03:41 +0000258 Succ = ConfluenceBlock;
259 Block = NULL;
260 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000261 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000262
263 Block = createBlock(false);
264 Block->addSuccessor(LHSBlock);
265 Block->addSuccessor(RHSBlock);
266 Block->setTerminator(C);
267 return addStmt(C->getCond());
268 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000269
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000270 case Stmt::DeclStmtClass:
271 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
272 Block->appendStmt(S);
273 return WalkAST_VisitVarDecl(V);
274 }
275 else return Block;
Ted Kremenek15c27a82007-08-28 18:30:10 +0000276
Ted Kremenek19bb3562007-08-28 19:26:49 +0000277 case Stmt::AddrLabelExprClass: {
278 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
279 AddressTakenLabels.insert(A->getLabel());
280
281 if (AlwaysAddStmt) Block->appendStmt(S);
282 return Block;
283 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000284
285 case Stmt::CallExprClass:
286 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000287
Ted Kremenek15c27a82007-08-28 18:30:10 +0000288 case Stmt::StmtExprClass:
289 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000290
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000291 case Stmt::BinaryOperatorClass: {
292 BinaryOperator* B = cast<BinaryOperator>(S);
293
294 if (B->isLogicalOp()) { // && or ||
295 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
296 ConfluenceBlock->appendStmt(B);
297 FinishBlock(ConfluenceBlock);
298
299 // create the block evaluating the LHS
300 CFGBlock* LHSBlock = createBlock(false);
301 LHSBlock->addSuccessor(ConfluenceBlock);
302 LHSBlock->setTerminator(B);
303
304 // create the block evaluating the RHS
305 Succ = ConfluenceBlock;
306 Block = NULL;
307 CFGBlock* RHSBlock = Visit(B->getRHS());
308 LHSBlock->addSuccessor(RHSBlock);
309
310 // Generate the blocks for evaluating the LHS.
311 Block = LHSBlock;
312 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000313 }
314 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
315 Block->appendStmt(B);
316 addStmt(B->getRHS());
317 return addStmt(B->getLHS());
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000318 }
319
320 // Fall through to the default case.
321 }
322
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000323 default:
324 if (AlwaysAddStmt) Block->appendStmt(S);
325 return WalkAST_VisitChildren(S);
326 };
327}
328
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000329/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
330/// DeclStmts. Because the initialization code for declarations can
331/// contain arbitrary expressions, we must linearize declarations
332/// to handle arbitrary control-flow induced by those expressions.
333CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
334 // We actually must parse the LAST declaration in a chain of
335 // declarations first, because we are building the CFG in reverse
336 // order.
337 if (Decl* D = V->getNextDeclarator())
338 if (VarDecl* Next = cast<VarDecl>(D))
339 Block = WalkAST_VisitVarDecl(Next);
340
341 if (Expr* E = V->getInit())
342 return addStmt(E);
343
344 assert (Block);
345 return Block;
346}
347
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000348/// WalkAST_VisitChildren - Utility method to call WalkAST on the
349/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000350CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000351 CFGBlock* B = Block;
352 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
353 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000354 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000355
356 return B;
357}
358
Ted Kremenek15c27a82007-08-28 18:30:10 +0000359/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
360/// expressions (a GCC extension).
361CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
362 Block->appendStmt(S);
363 return VisitCompoundStmt(S->getSubStmt());
364}
365
Ted Kremenekf50ec102007-09-11 21:29:43 +0000366/// WalkAST_VisitCallExpr - Utility method to handle function calls that
367/// are nested in expressions. The idea is that each function call should
368/// appear as a distinct statement in the CFGBlock.
369CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
370 Block->appendStmt(C);
371 return WalkAST_VisitChildren(C);
372}
373
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000374/// VisitStmt - Handle statements with no branching control flow.
375CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
376 // We cannot assume that we are in the middle of a basic block, since
377 // the CFG might only be constructed for this single statement. If
378 // we have no current basic block, just create one lazily.
379 if (!Block) Block = createBlock();
380
381 // Simply add the statement to the current block. We actually
382 // insert statements in reverse order; this order is reversed later
383 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000384 addStmt(Statement);
385
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000386 return Block;
387}
388
389CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
390 return Block;
391}
392
393CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
394 // The value returned from this function is the last created CFGBlock
395 // that represents the "entry" point for the translated AST node.
Chris Lattner271f1a62007-09-27 15:15:46 +0000396 CFGBlock* LastBlock = 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000397
398 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
399 E = C->body_rend(); I != E; ++I )
400 // Add the statement to the current block.
401 if (!(LastBlock=Visit(*I)))
402 return NULL;
403
404 return LastBlock;
405}
406
407CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
408 // We may see an if statement in the middle of a basic block, or
409 // it may be the first statement we are processing. In either case,
410 // we create a new basic block. First, we create the blocks for
411 // the then...else statements, and then we create the block containing
412 // the if statement. If we were in the middle of a block, we
413 // stop processing that block and reverse its statements. That block
414 // is then the implicit successor for the "then" and "else" clauses.
415
416 // The block we were proccessing is now finished. Make it the
417 // successor block.
418 if (Block) {
419 Succ = Block;
420 FinishBlock(Block);
421 }
422
423 // Process the false branch. NULL out Block so that the recursive
424 // call to Visit will create a new basic block.
425 // Null out Block so that all successor
426 CFGBlock* ElseBlock = Succ;
427
428 if (Stmt* Else = I->getElse()) {
429 SaveAndRestore<CFGBlock*> sv(Succ);
430
431 // NULL out Block so that the recursive call to Visit will
432 // create a new basic block.
433 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000434 ElseBlock = Visit(Else);
435
436 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
437 ElseBlock = sv.get();
438 else if (Block)
439 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000440 }
441
442 // Process the true branch. NULL out Block so that the recursive
443 // call to Visit will create a new basic block.
444 // Null out Block so that all successor
445 CFGBlock* ThenBlock;
446 {
447 Stmt* Then = I->getThen();
448 assert (Then);
449 SaveAndRestore<CFGBlock*> sv(Succ);
450 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000451 ThenBlock = Visit(Then);
452
453 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
454 ThenBlock = sv.get();
455 else if (Block)
456 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000457 }
458
459 // Now create a new block containing the if statement.
460 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000461
462 // Set the terminator of the new block to the If statement.
463 Block->setTerminator(I);
464
465 // Now add the successors.
466 Block->addSuccessor(ThenBlock);
467 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000468
469 // Add the condition as the last statement in the new block. This
470 // may create new blocks as the condition may contain control-flow. Any
471 // newly created blocks will be pointed to be "Block".
472 return addStmt(I->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000473}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000474
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000475
476CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
477 // If we were in the middle of a block we stop processing that block
478 // and reverse its statements.
479 //
480 // NOTE: If a "return" appears in the middle of a block, this means
481 // that the code afterwards is DEAD (unreachable). We still
482 // keep a basic block for that code; a simple "mark-and-sweep"
483 // from the entry block will be able to report such dead
484 // blocks.
485 if (Block) FinishBlock(Block);
486
487 // Create the new block.
488 Block = createBlock(false);
489
490 // The Exit block is the only successor.
491 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000492
493 // Add the return statement to the block. This may create new blocks
494 // if R contains control-flow (short-circuit operations).
495 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000496}
497
498CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
499 // Get the block of the labeled statement. Add it to our map.
500 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000501
502 if (!LabelBlock) // This can happen when the body is empty, i.e.
503 LabelBlock=createBlock(); // scopes that only contains NullStmts.
504
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000505 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
506 LabelMap[ L ] = LabelBlock;
507
508 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000509 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000510 // label (and we have already processed the substatement) there is no
511 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000512 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000513 FinishBlock(LabelBlock);
514
515 // We set Block to NULL to allow lazy creation of a new block
516 // (if necessary);
517 Block = NULL;
518
519 // This block is now the implicit successor of other blocks.
520 Succ = LabelBlock;
521
522 return LabelBlock;
523}
524
525CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
526 // Goto is a control-flow statement. Thus we stop processing the
527 // current block and create a new one.
528 if (Block) FinishBlock(Block);
529 Block = createBlock(false);
530 Block->setTerminator(G);
531
532 // If we already know the mapping to the label block add the
533 // successor now.
534 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
535
536 if (I == LabelMap.end())
537 // We will need to backpatch this block later.
538 BackpatchBlocks.push_back(Block);
539 else
540 Block->addSuccessor(I->second);
541
542 return Block;
543}
544
545CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
546 // "for" is a control-flow statement. Thus we stop processing the
547 // current block.
548
549 CFGBlock* LoopSuccessor = NULL;
550
551 if (Block) {
552 FinishBlock(Block);
553 LoopSuccessor = Block;
554 }
555 else LoopSuccessor = Succ;
556
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000557 // Because of short-circuit evaluation, the condition of the loop
558 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
559 // blocks that evaluate the condition.
560 CFGBlock* ExitConditionBlock = createBlock(false);
561 CFGBlock* EntryConditionBlock = ExitConditionBlock;
562
563 // Set the terminator for the "exit" condition block.
564 ExitConditionBlock->setTerminator(F);
565
566 // Now add the actual condition to the condition block. Because the
567 // condition itself may contain control-flow, new blocks may be created.
568 if (Stmt* C = F->getCond()) {
569 Block = ExitConditionBlock;
570 EntryConditionBlock = addStmt(C);
571 if (Block) FinishBlock(EntryConditionBlock);
572 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000573
574 // The condition block is the implicit successor for the loop body as
575 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000576 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000577
578 // Now create the loop body.
579 {
580 assert (F->getBody());
581
582 // Save the current values for Block, Succ, and continue and break targets
583 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
584 save_continue(ContinueTargetBlock),
585 save_break(BreakTargetBlock);
586
587 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000588 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000589
590 // All breaks should go to the code following the loop.
591 BreakTargetBlock = LoopSuccessor;
592
Ted Kremenekaf603f72007-08-30 18:39:40 +0000593 // Create a new block to contain the (bottom) of the loop body.
594 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000595
596 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000597 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000598
599 // Now populate the body block, and in the process create new blocks
600 // as we walk the body of the loop.
601 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000602
603 if (!BodyBlock)
604 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
605 else if (Block)
606 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000607
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000608 // This new body block is a successor to our "exit" condition block.
609 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000610 }
611
612 // Link up the condition block with the code that follows the loop.
613 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000614 ExitConditionBlock->addSuccessor(LoopSuccessor);
615
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000616 // If the loop contains initialization, create a new block for those
617 // statements. This block can also contain statements that precede
618 // the loop.
619 if (Stmt* I = F->getInit()) {
620 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000621 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000622 }
623 else {
624 // There is no loop initialization. We are thus basically a while
625 // loop. NULL out Block to force lazy block construction.
626 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000627 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000628 }
629}
630
631CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
632 // "while" is a control-flow statement. Thus we stop processing the
633 // current block.
634
635 CFGBlock* LoopSuccessor = NULL;
636
637 if (Block) {
638 FinishBlock(Block);
639 LoopSuccessor = Block;
640 }
641 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000642
643 // Because of short-circuit evaluation, the condition of the loop
644 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
645 // blocks that evaluate the condition.
646 CFGBlock* ExitConditionBlock = createBlock(false);
647 CFGBlock* EntryConditionBlock = ExitConditionBlock;
648
649 // Set the terminator for the "exit" condition block.
650 ExitConditionBlock->setTerminator(W);
651
652 // Now add the actual condition to the condition block. Because the
653 // condition itself may contain control-flow, new blocks may be created.
654 // Thus we update "Succ" after adding the condition.
655 if (Stmt* C = W->getCond()) {
656 Block = ExitConditionBlock;
657 EntryConditionBlock = addStmt(C);
658 if (Block) FinishBlock(EntryConditionBlock);
659 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000660
661 // The condition block is the implicit successor for the loop body as
662 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000663 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000664
665 // Process the loop body.
666 {
667 assert (W->getBody());
668
669 // Save the current values for Block, Succ, and continue and break targets
670 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
671 save_continue(ContinueTargetBlock),
672 save_break(BreakTargetBlock);
673
674 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000675 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000676
677 // All breaks should go to the code following the loop.
678 BreakTargetBlock = LoopSuccessor;
679
680 // NULL out Block to force lazy instantiation of blocks for the body.
681 Block = NULL;
682
683 // Create the body. The returned block is the entry to the loop body.
684 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000685
686 if (!BodyBlock)
687 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
688 else if (Block)
689 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000690
691 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000692 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000693 }
694
695 // Link up the condition block with the code that follows the loop.
696 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000697 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000698
699 // There can be no more statements in the condition block
700 // since we loop back to this block. NULL out Block to force
701 // lazy creation of another block.
702 Block = NULL;
703
704 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000705 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000706}
707
708CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
709 // "do...while" is a control-flow statement. Thus we stop processing the
710 // current block.
711
712 CFGBlock* LoopSuccessor = NULL;
713
714 if (Block) {
715 FinishBlock(Block);
716 LoopSuccessor = Block;
717 }
718 else LoopSuccessor = Succ;
719
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000720 // Because of short-circuit evaluation, the condition of the loop
721 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
722 // blocks that evaluate the condition.
723 CFGBlock* ExitConditionBlock = createBlock(false);
724 CFGBlock* EntryConditionBlock = ExitConditionBlock;
725
726 // Set the terminator for the "exit" condition block.
727 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000728
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000729 // Now add the actual condition to the condition block. Because the
730 // condition itself may contain control-flow, new blocks may be created.
731 if (Stmt* C = D->getCond()) {
732 Block = ExitConditionBlock;
733 EntryConditionBlock = addStmt(C);
734 if (Block) FinishBlock(EntryConditionBlock);
735 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000736
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000737 // The condition block is the implicit successor for the loop body as
738 // well as any code above the loop.
739 Succ = EntryConditionBlock;
740
741
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000742 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000743 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000744 {
745 assert (D->getBody());
746
747 // Save the current values for Block, Succ, and continue and break targets
748 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
749 save_continue(ContinueTargetBlock),
750 save_break(BreakTargetBlock);
751
752 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000753 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000754
755 // All breaks should go to the code following the loop.
756 BreakTargetBlock = LoopSuccessor;
757
758 // NULL out Block to force lazy instantiation of blocks for the body.
759 Block = NULL;
760
761 // Create the body. The returned block is the entry to the loop body.
762 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000763
Ted Kremenekaf603f72007-08-30 18:39:40 +0000764 if (!BodyBlock)
765 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
766 else if (Block)
767 FinishBlock(BodyBlock);
768
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000769 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000770 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000771 }
772
773 // Link up the condition block with the code that follows the loop.
774 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000775 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000776
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000777 // There can be no more statements in the body block(s)
778 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000779 // lazy creation of another block.
780 Block = NULL;
781
782 // Return the loop body, which is the dominating block for the loop.
783 return BodyBlock;
784}
785
786CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
787 // "continue" is a control-flow statement. Thus we stop processing the
788 // current block.
789 if (Block) FinishBlock(Block);
790
791 // Now create a new block that ends with the continue statement.
792 Block = createBlock(false);
793 Block->setTerminator(C);
794
795 // If there is no target for the continue, then we are looking at an
796 // incomplete AST. Handle this by not registering a successor.
797 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
798
799 return Block;
800}
801
802CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
803 // "break" is a control-flow statement. Thus we stop processing the
804 // current block.
805 if (Block) FinishBlock(Block);
806
807 // Now create a new block that ends with the continue statement.
808 Block = createBlock(false);
809 Block->setTerminator(B);
810
811 // If there is no target for the break, then we are looking at an
812 // incomplete AST. Handle this by not registering a successor.
813 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
814
815 return Block;
816}
817
818CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
819 // "switch" is a control-flow statement. Thus we stop processing the
820 // current block.
821 CFGBlock* SwitchSuccessor = NULL;
822
823 if (Block) {
824 FinishBlock(Block);
825 SwitchSuccessor = Block;
826 }
827 else SwitchSuccessor = Succ;
828
829 // Save the current "switch" context.
830 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
831 save_break(BreakTargetBlock);
832
833 // Create a new block that will contain the switch statement.
834 SwitchTerminatedBlock = createBlock(false);
835
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000836 // Now process the switch body. The code after the switch is the implicit
837 // successor.
838 Succ = SwitchSuccessor;
839 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000840
841 // When visiting the body, the case statements should automatically get
842 // linked up to the switch. We also don't keep a pointer to the body,
843 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000844 assert (S->getBody() && "switch must contain a non-NULL body");
845 Block = NULL;
846 CFGBlock *BodyBlock = Visit(S->getBody());
847 if (Block) FinishBlock(BodyBlock);
848
849 // Add the terminator and condition in the switch block.
850 SwitchTerminatedBlock->setTerminator(S);
851 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000852 Block = SwitchTerminatedBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000853 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000854}
855
856CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
857 // A SwitchCase is either a "default" or "case" statement. We handle
858 // both in the same way. They are essentially labels, so they are the
859 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000860
861 if (S->getSubStmt()) Visit(S->getSubStmt());
862 CFGBlock* CaseBlock = Block;
863 if (!CaseBlock) CaseBlock = createBlock();
864
Ted Kremenek9cffe732007-08-29 23:20:49 +0000865 // Cases/Default statements partition block, so this is the top of
866 // the basic block we were processing (the case/default is the label).
867 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000868 FinishBlock(CaseBlock);
869
870 // Add this block to the list of successors for the block with the
871 // switch statement.
872 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
873
874 // We set Block to NULL to allow lazy creation of a new block (if necessary)
875 Block = NULL;
876
877 // This block is now the implicit successor of other blocks.
878 Succ = CaseBlock;
879
880 return CaseBlock;
881}
882
Ted Kremenek19bb3562007-08-28 19:26:49 +0000883CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
884 // Lazily create the indirect-goto dispatch block if there isn't one
885 // already.
886 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
887
888 if (!IBlock) {
889 IBlock = createBlock(false);
890 cfg->setIndirectGotoBlock(IBlock);
891 }
892
893 // IndirectGoto is a control-flow statement. Thus we stop processing the
894 // current block and create a new one.
895 if (Block) FinishBlock(Block);
896 Block = createBlock(false);
897 Block->setTerminator(I);
898 Block->addSuccessor(IBlock);
899 return addStmt(I->getTarget());
900}
901
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000902
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000903} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000904
905/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
906/// block has no successors or predecessors. If this is the first block
907/// created in the CFG, it is automatically set to be the Entry and Exit
908/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000909CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000910 bool first_block = begin() == end();
911
912 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +0000913 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +0000914
915 // If this is the first block, set it as the Entry and Exit.
916 if (first_block) Entry = Exit = &front();
917
918 // Return the block.
919 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +0000920}
921
Ted Kremenek026473c2007-08-23 16:51:22 +0000922/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
923/// CFG is returned to the caller.
924CFG* CFG::buildCFG(Stmt* Statement) {
925 CFGBuilder Builder;
926 return Builder.buildCFG(Statement);
927}
928
929/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +0000930void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
931
Ted Kremenek7dba8602007-08-29 21:56:09 +0000932
933//===----------------------------------------------------------------------===//
934// CFG pretty printing
935//===----------------------------------------------------------------------===//
936
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000937namespace {
938
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000939class StmtPrinterHelper : public PrinterHelper {
940
Ted Kremenek42a509f2007-08-31 21:30:12 +0000941 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
942 StmtMapTy StmtMap;
943 signed CurrentBlock;
944 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000945
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000946public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000947
Ted Kremenek42a509f2007-08-31 21:30:12 +0000948 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
949 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
950 unsigned j = 1;
951 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
952 BI != BEnd; ++BI, ++j )
953 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
954 }
955 }
956
957 virtual ~StmtPrinterHelper() {}
958
959 void setBlockID(signed i) { CurrentBlock = i; }
960 void setStmtID(unsigned i) { CurrentStmt = i; }
961
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000962 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
963
964 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +0000965
966 if (I == StmtMap.end())
967 return false;
968
969 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
970 && I->second.second == CurrentStmt)
971 return false;
972
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000973 OS << "[B" << I->second.first << "." << I->second.second << "]";
974 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +0000975 }
976};
977
978class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek805e9a82007-08-31 21:49:40 +0000979 void >
980{
Ted Kremenek42a509f2007-08-31 21:30:12 +0000981 std::ostream& OS;
982 StmtPrinterHelper* Helper;
983public:
984 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
985 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000986
987 void VisitIfStmt(IfStmt* I) {
988 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +0000989 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000990 OS << "\n";
991 }
992
993 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +0000994 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000995
996 void VisitForStmt(ForStmt* F) {
997 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +0000998 if (F->getInit()) OS << "...";
999 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001000 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001001 OS << "; ";
1002 if (F->getInc()) OS << "...";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001003 OS << ")\n";
1004 }
1005
1006 void VisitWhileStmt(WhileStmt* W) {
1007 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001008 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001009 OS << "\n";
1010 }
1011
1012 void VisitDoStmt(DoStmt* D) {
1013 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001014 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001015 OS << '\n';
1016 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001017
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001018 void VisitSwitchStmt(SwitchStmt* S) {
1019 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001020 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001021 OS << '\n';
1022 }
1023
Ted Kremenek805e9a82007-08-31 21:49:40 +00001024 void VisitConditionalOperator(ConditionalOperator* C) {
1025 C->getCond()->printPretty(OS,Helper);
1026 OS << " ? ... : ...\n";
1027 }
1028
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001029 void VisitChooseExpr(ChooseExpr* C) {
1030 OS << "__builtin_choose_expr( ";
1031 C->getCond()->printPretty(OS,Helper);
1032 OS << " )\n";
1033 }
1034
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001035 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1036 OS << "goto *";
1037 I->getTarget()->printPretty(OS,Helper);
1038 OS << '\n';
1039 }
1040
Ted Kremenek805e9a82007-08-31 21:49:40 +00001041 void VisitBinaryOperator(BinaryOperator* B) {
1042 if (!B->isLogicalOp()) {
1043 VisitExpr(B);
1044 return;
1045 }
1046
1047 B->getLHS()->printPretty(OS,Helper);
1048
1049 switch (B->getOpcode()) {
1050 case BinaryOperator::LOr:
1051 OS << " || ...\n";
1052 return;
1053 case BinaryOperator::LAnd:
1054 OS << " && ...\n";
1055 return;
1056 default:
1057 assert(false && "Invalid logical operator.");
1058 }
1059 }
1060
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001061 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001062 E->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001063 OS << '\n';
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001064 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001065};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001066
1067
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001068void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1069 if (Helper) {
1070 // special printing for statement-expressions.
1071 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1072 CompoundStmt* Sub = SE->getSubStmt();
1073
1074 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001075 OS << "({ ... ; ";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001076 Helper->handledStmt(*SE->getSubStmt()->child_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001077 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001078 return;
1079 }
1080 }
1081
1082 // special printing for comma expressions.
1083 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1084 if (B->getOpcode() == BinaryOperator::Comma) {
1085 OS << "... , ";
1086 Helper->handledStmt(B->getRHS(),OS);
1087 OS << '\n';
1088 return;
1089 }
1090 }
1091 }
1092
1093 S->printPretty(OS, Helper);
1094
1095 // Expressions need a newline.
1096 if (isa<Expr>(S)) OS << '\n';
1097}
1098
Ted Kremenek42a509f2007-08-31 21:30:12 +00001099void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1100 StmtPrinterHelper* Helper, bool print_edges) {
1101
1102 if (Helper) Helper->setBlockID(B.getBlockID());
1103
Ted Kremenek7dba8602007-08-29 21:56:09 +00001104 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001105 OS << "\n [ B" << B.getBlockID();
1106
1107 if (&B == &cfg->getEntry())
1108 OS << " (ENTRY) ]\n";
1109 else if (&B == &cfg->getExit())
1110 OS << " (EXIT) ]\n";
1111 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001112 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001113 else
1114 OS << " ]\n";
1115
Ted Kremenek9cffe732007-08-29 23:20:49 +00001116 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001117 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1118
1119 if (print_edges)
1120 OS << " ";
1121
Ted Kremenek9cffe732007-08-29 23:20:49 +00001122 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1123 OS << L->getName();
1124 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1125 OS << "case ";
1126 C->getLHS()->printPretty(OS);
1127 if (C->getRHS()) {
1128 OS << " ... ";
1129 C->getRHS()->printPretty(OS);
1130 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001131 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001132 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001133 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001134 else
1135 assert(false && "Invalid label statement in CFGBlock.");
1136
Ted Kremenek9cffe732007-08-29 23:20:49 +00001137 OS << ":\n";
1138 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001139
Ted Kremenekfddd5182007-08-21 21:42:03 +00001140 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001141 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001142
1143 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1144 I != E ; ++I, ++j ) {
1145
Ted Kremenek9cffe732007-08-29 23:20:49 +00001146 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001147 if (print_edges)
1148 OS << " ";
1149
1150 OS << std::setw(3) << j << ": ";
1151
1152 if (Helper)
1153 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001154
1155 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001156 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001157
Ted Kremenek9cffe732007-08-29 23:20:49 +00001158 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001159 if (B.getTerminator()) {
1160 if (print_edges)
1161 OS << " ";
1162
Ted Kremenek9cffe732007-08-29 23:20:49 +00001163 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001164
1165 if (Helper) Helper->setBlockID(-1);
1166
1167 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1168 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenekfddd5182007-08-21 21:42:03 +00001169 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001170
Ted Kremenek9cffe732007-08-29 23:20:49 +00001171 if (print_edges) {
1172 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001173 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001174 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001175
Ted Kremenek42a509f2007-08-31 21:30:12 +00001176 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1177 I != E; ++I, ++i) {
1178
1179 if (i == 8 || (i-8) == 0)
1180 OS << "\n ";
1181
Ted Kremenek9cffe732007-08-29 23:20:49 +00001182 OS << " B" << (*I)->getBlockID();
1183 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001184
1185 OS << '\n';
1186
1187 // Print the successors of this block.
1188 OS << " Successors (" << B.succ_size() << "):";
1189 i = 0;
1190
1191 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1192 I != E; ++I, ++i) {
1193
1194 if (i == 8 || (i-8) % 10 == 0)
1195 OS << "\n ";
1196
1197 OS << " B" << (*I)->getBlockID();
1198 }
1199
Ted Kremenek9cffe732007-08-29 23:20:49 +00001200 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001201 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001202}
1203
1204} // end anonymous namespace
1205
1206/// dump - A simple pretty printer of a CFG that outputs to stderr.
1207void CFG::dump() const { print(std::cerr); }
1208
1209/// print - A simple pretty printer of a CFG that outputs to an ostream.
1210void CFG::print(std::ostream& OS) const {
1211
1212 StmtPrinterHelper Helper(this);
1213
1214 // Print the entry block.
1215 print_block(OS, this, getEntry(), &Helper, true);
1216
1217 // Iterate through the CFGBlocks and print them one by one.
1218 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1219 // Skip the entry block, because we already printed it.
1220 if (&(*I) == &getEntry() || &(*I) == &getExit())
1221 continue;
1222
1223 print_block(OS, this, *I, &Helper, true);
1224 }
1225
1226 // Print the exit block.
1227 print_block(OS, this, getExit(), &Helper, true);
1228}
1229
1230/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1231void CFGBlock::dump(const CFG* cfg) const { print(std::cerr, cfg); }
1232
1233/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1234/// Generally this will only be called from CFG::print.
1235void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1236 StmtPrinterHelper Helper(cfg);
1237 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001238}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001239
Ted Kremenek155383b2007-09-11 22:08:24 +00001240/// hasImplicitControlFlow - Returns true if a given expression is
1241/// is represented within a CFG as having a designated "statement slot"
1242bool CFG::hasImplicitControlFlow(const Stmt* S) {
1243 switch (S->getStmtClass()) {
1244 default:
1245 return false;
1246
1247 case Stmt::CallExprClass:
1248 case Stmt::ConditionalOperatorClass:
1249 case Stmt::ChooseExprClass:
1250 case Stmt::StmtExprClass:
1251 case Stmt::DeclStmtClass:
1252 return true;
1253
1254 case Stmt::BinaryOperatorClass: {
1255 const BinaryOperator* B = cast<BinaryOperator>(S);
1256 if (B->isLogicalOp() || B->getOpcode() == BinaryOperator::Comma)
1257 return true;
1258 else
1259 return false;
1260 }
1261 }
1262}
1263
Ted Kremenek7dba8602007-08-29 21:56:09 +00001264//===----------------------------------------------------------------------===//
1265// CFG Graphviz Visualization
1266//===----------------------------------------------------------------------===//
1267
Ted Kremenek42a509f2007-08-31 21:30:12 +00001268
1269#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001270static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001271#endif
1272
1273void CFG::viewCFG() const {
1274#ifndef NDEBUG
1275 StmtPrinterHelper H(this);
1276 GraphHelper = &H;
1277 llvm::ViewGraph(this,"CFG");
1278 GraphHelper = NULL;
1279#else
1280 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001281 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001282#endif
1283}
1284
Ted Kremenek7dba8602007-08-29 21:56:09 +00001285namespace llvm {
1286template<>
1287struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1288 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1289
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001290#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001291 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001292 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001293 std::string OutStr = Out.str();
1294
1295 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1296
1297 // Process string output to make it nicer...
1298 for (unsigned i = 0; i != OutStr.length(); ++i)
1299 if (OutStr[i] == '\n') { // Left justify
1300 OutStr[i] = '\\';
1301 OutStr.insert(OutStr.begin()+i+1, 'l');
1302 }
1303
1304 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001305#else
1306 return "";
1307#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001308 }
1309};
1310} // end namespace llvm