blob: 42b27d23ab36badaaef7b717feb9c39795fe3d2c [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 }
176
177 // Create an empty entry block that has no predecessors.
Ted Kremenek94b33162007-09-17 16:18:02 +0000178 Succ = B;
179 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000180
Ted Kremenek19bb3562007-08-28 19:26:49 +0000181 // NULL out cfg so that repeated calls to the builder will fail and that
182 // the ownership of the constructed CFG is passed to the caller.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000183 CFG* t = cfg;
184 cfg = NULL;
185 return t;
186 }
Ted Kremenek94b33162007-09-17 16:18:02 +0000187 else {
188 assert (false && "CFG construction failed.");
189 return NULL;
190 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000191}
192
193/// createBlock - Used to lazily create blocks that are connected
194/// to the current (global) succcessor.
195CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000196 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000197 if (add_successor && Succ) B->addSuccessor(Succ);
198 return B;
199}
200
201/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000202/// we must reverse the statements because they have been inserted
203/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000204void CFGBuilder::FinishBlock(CFGBlock* B) {
205 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000206 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000207}
208
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000209/// addStmt - Used to add statements/expressions to the current CFGBlock
210/// "Block". This method calls WalkAST on the passed statement to see if it
211/// contains any short-circuit expressions. If so, it recursively creates
212/// the necessary blocks for such expressions. It returns the "topmost" block
213/// of the created blocks, or the original value of "Block" when this method
214/// was called if no additional blocks are created.
215CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000216 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000217 return WalkAST(S,true);
218}
219
220/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000221/// add extra blocks for ternary operators, &&, and ||. We also
222/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000223CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
224 switch (S->getStmtClass()) {
225 case Stmt::ConditionalOperatorClass: {
226 ConditionalOperator* C = cast<ConditionalOperator>(S);
227
228 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
229 ConfluenceBlock->appendStmt(C);
230 FinishBlock(ConfluenceBlock);
231
232 Succ = ConfluenceBlock;
233 Block = NULL;
234 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000235 FinishBlock(LHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000236
237 Succ = ConfluenceBlock;
238 Block = NULL;
239 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000240 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000241
242 Block = createBlock(false);
243 Block->addSuccessor(LHSBlock);
244 Block->addSuccessor(RHSBlock);
245 Block->setTerminator(C);
246 return addStmt(C->getCond());
247 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000248
249 case Stmt::ChooseExprClass: {
250 ChooseExpr* C = cast<ChooseExpr>(S);
251
252 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
253 ConfluenceBlock->appendStmt(C);
254 FinishBlock(ConfluenceBlock);
255
256 Succ = ConfluenceBlock;
257 Block = NULL;
258 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000259 FinishBlock(LHSBlock);
260
Ted Kremenek49a436d2007-08-31 17:03:41 +0000261 Succ = ConfluenceBlock;
262 Block = NULL;
263 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000264 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000265
266 Block = createBlock(false);
267 Block->addSuccessor(LHSBlock);
268 Block->addSuccessor(RHSBlock);
269 Block->setTerminator(C);
270 return addStmt(C->getCond());
271 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000272
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000273 case Stmt::DeclStmtClass:
274 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
275 Block->appendStmt(S);
276 return WalkAST_VisitVarDecl(V);
277 }
278 else return Block;
Ted Kremenek15c27a82007-08-28 18:30:10 +0000279
Ted Kremenek19bb3562007-08-28 19:26:49 +0000280 case Stmt::AddrLabelExprClass: {
281 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
282 AddressTakenLabels.insert(A->getLabel());
283
284 if (AlwaysAddStmt) Block->appendStmt(S);
285 return Block;
286 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000287
288 case Stmt::CallExprClass:
289 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000290
Ted Kremenek15c27a82007-08-28 18:30:10 +0000291 case Stmt::StmtExprClass:
292 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000293
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000294 case Stmt::BinaryOperatorClass: {
295 BinaryOperator* B = cast<BinaryOperator>(S);
296
297 if (B->isLogicalOp()) { // && or ||
298 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
299 ConfluenceBlock->appendStmt(B);
300 FinishBlock(ConfluenceBlock);
301
302 // create the block evaluating the LHS
303 CFGBlock* LHSBlock = createBlock(false);
304 LHSBlock->addSuccessor(ConfluenceBlock);
305 LHSBlock->setTerminator(B);
306
307 // create the block evaluating the RHS
308 Succ = ConfluenceBlock;
309 Block = NULL;
310 CFGBlock* RHSBlock = Visit(B->getRHS());
311 LHSBlock->addSuccessor(RHSBlock);
312
313 // Generate the blocks for evaluating the LHS.
314 Block = LHSBlock;
315 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000316 }
317 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
318 Block->appendStmt(B);
319 addStmt(B->getRHS());
320 return addStmt(B->getLHS());
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000321 }
322
323 // Fall through to the default case.
324 }
325
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000326 default:
327 if (AlwaysAddStmt) Block->appendStmt(S);
328 return WalkAST_VisitChildren(S);
329 };
330}
331
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000332/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
333/// DeclStmts. Because the initialization code for declarations can
334/// contain arbitrary expressions, we must linearize declarations
335/// to handle arbitrary control-flow induced by those expressions.
336CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
337 // We actually must parse the LAST declaration in a chain of
338 // declarations first, because we are building the CFG in reverse
339 // order.
340 if (Decl* D = V->getNextDeclarator())
341 if (VarDecl* Next = cast<VarDecl>(D))
342 Block = WalkAST_VisitVarDecl(Next);
343
344 if (Expr* E = V->getInit())
345 return addStmt(E);
346
347 assert (Block);
348 return Block;
349}
350
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000351/// WalkAST_VisitChildren - Utility method to call WalkAST on the
352/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000353CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000354 CFGBlock* B = Block;
355 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
356 I != E; ++I)
357 B = WalkAST(*I);
358
359 return B;
360}
361
Ted Kremenek15c27a82007-08-28 18:30:10 +0000362/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
363/// expressions (a GCC extension).
364CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
365 Block->appendStmt(S);
366 return VisitCompoundStmt(S->getSubStmt());
367}
368
Ted Kremenekf50ec102007-09-11 21:29:43 +0000369/// WalkAST_VisitCallExpr - Utility method to handle function calls that
370/// are nested in expressions. The idea is that each function call should
371/// appear as a distinct statement in the CFGBlock.
372CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
373 Block->appendStmt(C);
374 return WalkAST_VisitChildren(C);
375}
376
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000377/// VisitStmt - Handle statements with no branching control flow.
378CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
379 // We cannot assume that we are in the middle of a basic block, since
380 // the CFG might only be constructed for this single statement. If
381 // we have no current basic block, just create one lazily.
382 if (!Block) Block = createBlock();
383
384 // Simply add the statement to the current block. We actually
385 // insert statements in reverse order; this order is reversed later
386 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000387 addStmt(Statement);
388
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000389 return Block;
390}
391
392CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
393 return Block;
394}
395
396CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
397 // The value returned from this function is the last created CFGBlock
398 // that represents the "entry" point for the translated AST node.
399 CFGBlock* LastBlock;
400
401 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
402 E = C->body_rend(); I != E; ++I )
403 // Add the statement to the current block.
404 if (!(LastBlock=Visit(*I)))
405 return NULL;
406
407 return LastBlock;
408}
409
410CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
411 // We may see an if statement in the middle of a basic block, or
412 // it may be the first statement we are processing. In either case,
413 // we create a new basic block. First, we create the blocks for
414 // the then...else statements, and then we create the block containing
415 // the if statement. If we were in the middle of a block, we
416 // stop processing that block and reverse its statements. That block
417 // is then the implicit successor for the "then" and "else" clauses.
418
419 // The block we were proccessing is now finished. Make it the
420 // successor block.
421 if (Block) {
422 Succ = Block;
423 FinishBlock(Block);
424 }
425
426 // Process the false branch. NULL out Block so that the recursive
427 // call to Visit will create a new basic block.
428 // Null out Block so that all successor
429 CFGBlock* ElseBlock = Succ;
430
431 if (Stmt* Else = I->getElse()) {
432 SaveAndRestore<CFGBlock*> sv(Succ);
433
434 // NULL out Block so that the recursive call to Visit will
435 // create a new basic block.
436 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000437 ElseBlock = Visit(Else);
438
439 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
440 ElseBlock = sv.get();
441 else if (Block)
442 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000443 }
444
445 // Process the true branch. NULL out Block so that the recursive
446 // call to Visit will create a new basic block.
447 // Null out Block so that all successor
448 CFGBlock* ThenBlock;
449 {
450 Stmt* Then = I->getThen();
451 assert (Then);
452 SaveAndRestore<CFGBlock*> sv(Succ);
453 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000454 ThenBlock = Visit(Then);
455
456 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
457 ThenBlock = sv.get();
458 else if (Block)
459 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000460 }
461
462 // Now create a new block containing the if statement.
463 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000464
465 // Set the terminator of the new block to the If statement.
466 Block->setTerminator(I);
467
468 // Now add the successors.
469 Block->addSuccessor(ThenBlock);
470 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000471
472 // Add the condition as the last statement in the new block. This
473 // may create new blocks as the condition may contain control-flow. Any
474 // newly created blocks will be pointed to be "Block".
475 return addStmt(I->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000476}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000477
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000478
479CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
480 // If we were in the middle of a block we stop processing that block
481 // and reverse its statements.
482 //
483 // NOTE: If a "return" appears in the middle of a block, this means
484 // that the code afterwards is DEAD (unreachable). We still
485 // keep a basic block for that code; a simple "mark-and-sweep"
486 // from the entry block will be able to report such dead
487 // blocks.
488 if (Block) FinishBlock(Block);
489
490 // Create the new block.
491 Block = createBlock(false);
492
493 // The Exit block is the only successor.
494 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000495
496 // Add the return statement to the block. This may create new blocks
497 // if R contains control-flow (short-circuit operations).
498 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000499}
500
501CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
502 // Get the block of the labeled statement. Add it to our map.
503 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000504
505 if (!LabelBlock) // This can happen when the body is empty, i.e.
506 LabelBlock=createBlock(); // scopes that only contains NullStmts.
507
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000508 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
509 LabelMap[ L ] = LabelBlock;
510
511 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000512 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000513 // label (and we have already processed the substatement) there is no
514 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000515 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000516 FinishBlock(LabelBlock);
517
518 // We set Block to NULL to allow lazy creation of a new block
519 // (if necessary);
520 Block = NULL;
521
522 // This block is now the implicit successor of other blocks.
523 Succ = LabelBlock;
524
525 return LabelBlock;
526}
527
528CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
529 // Goto is a control-flow statement. Thus we stop processing the
530 // current block and create a new one.
531 if (Block) FinishBlock(Block);
532 Block = createBlock(false);
533 Block->setTerminator(G);
534
535 // If we already know the mapping to the label block add the
536 // successor now.
537 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
538
539 if (I == LabelMap.end())
540 // We will need to backpatch this block later.
541 BackpatchBlocks.push_back(Block);
542 else
543 Block->addSuccessor(I->second);
544
545 return Block;
546}
547
548CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
549 // "for" is a control-flow statement. Thus we stop processing the
550 // current block.
551
552 CFGBlock* LoopSuccessor = NULL;
553
554 if (Block) {
555 FinishBlock(Block);
556 LoopSuccessor = Block;
557 }
558 else LoopSuccessor = Succ;
559
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000560 // Because of short-circuit evaluation, the condition of the loop
561 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
562 // blocks that evaluate the condition.
563 CFGBlock* ExitConditionBlock = createBlock(false);
564 CFGBlock* EntryConditionBlock = ExitConditionBlock;
565
566 // Set the terminator for the "exit" condition block.
567 ExitConditionBlock->setTerminator(F);
568
569 // Now add the actual condition to the condition block. Because the
570 // condition itself may contain control-flow, new blocks may be created.
571 if (Stmt* C = F->getCond()) {
572 Block = ExitConditionBlock;
573 EntryConditionBlock = addStmt(C);
574 if (Block) FinishBlock(EntryConditionBlock);
575 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000576
577 // The condition block is the implicit successor for the loop body as
578 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000579 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000580
581 // Now create the loop body.
582 {
583 assert (F->getBody());
584
585 // Save the current values for Block, Succ, and continue and break targets
586 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
587 save_continue(ContinueTargetBlock),
588 save_break(BreakTargetBlock);
589
590 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000591 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000592
593 // All breaks should go to the code following the loop.
594 BreakTargetBlock = LoopSuccessor;
595
Ted Kremenekaf603f72007-08-30 18:39:40 +0000596 // Create a new block to contain the (bottom) of the loop body.
597 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000598
599 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000600 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000601
602 // Now populate the body block, and in the process create new blocks
603 // as we walk the body of the loop.
604 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000605
606 if (!BodyBlock)
607 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
608 else if (Block)
609 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000610
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000611 // This new body block is a successor to our "exit" condition block.
612 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000613 }
614
615 // Link up the condition block with the code that follows the loop.
616 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000617 ExitConditionBlock->addSuccessor(LoopSuccessor);
618
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000619 // If the loop contains initialization, create a new block for those
620 // statements. This block can also contain statements that precede
621 // the loop.
622 if (Stmt* I = F->getInit()) {
623 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000624 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000625 }
626 else {
627 // There is no loop initialization. We are thus basically a while
628 // loop. NULL out Block to force lazy block construction.
629 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000630 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000631 }
632}
633
634CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
635 // "while" is a control-flow statement. Thus we stop processing the
636 // current block.
637
638 CFGBlock* LoopSuccessor = NULL;
639
640 if (Block) {
641 FinishBlock(Block);
642 LoopSuccessor = Block;
643 }
644 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000645
646 // Because of short-circuit evaluation, the condition of the loop
647 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
648 // blocks that evaluate the condition.
649 CFGBlock* ExitConditionBlock = createBlock(false);
650 CFGBlock* EntryConditionBlock = ExitConditionBlock;
651
652 // Set the terminator for the "exit" condition block.
653 ExitConditionBlock->setTerminator(W);
654
655 // Now add the actual condition to the condition block. Because the
656 // condition itself may contain control-flow, new blocks may be created.
657 // Thus we update "Succ" after adding the condition.
658 if (Stmt* C = W->getCond()) {
659 Block = ExitConditionBlock;
660 EntryConditionBlock = addStmt(C);
661 if (Block) FinishBlock(EntryConditionBlock);
662 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000663
664 // The condition block is the implicit successor for the loop body as
665 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000666 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000667
668 // Process the loop body.
669 {
670 assert (W->getBody());
671
672 // Save the current values for Block, Succ, and continue and break targets
673 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
674 save_continue(ContinueTargetBlock),
675 save_break(BreakTargetBlock);
676
677 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000678 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000679
680 // All breaks should go to the code following the loop.
681 BreakTargetBlock = LoopSuccessor;
682
683 // NULL out Block to force lazy instantiation of blocks for the body.
684 Block = NULL;
685
686 // Create the body. The returned block is the entry to the loop body.
687 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000688
689 if (!BodyBlock)
690 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
691 else if (Block)
692 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000693
694 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000695 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000696 }
697
698 // Link up the condition block with the code that follows the loop.
699 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000700 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000701
702 // There can be no more statements in the condition block
703 // since we loop back to this block. NULL out Block to force
704 // lazy creation of another block.
705 Block = NULL;
706
707 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000708 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000709}
710
711CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
712 // "do...while" is a control-flow statement. Thus we stop processing the
713 // current block.
714
715 CFGBlock* LoopSuccessor = NULL;
716
717 if (Block) {
718 FinishBlock(Block);
719 LoopSuccessor = Block;
720 }
721 else LoopSuccessor = Succ;
722
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000723 // Because of short-circuit evaluation, the condition of the loop
724 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
725 // blocks that evaluate the condition.
726 CFGBlock* ExitConditionBlock = createBlock(false);
727 CFGBlock* EntryConditionBlock = ExitConditionBlock;
728
729 // Set the terminator for the "exit" condition block.
730 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000731
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000732 // Now add the actual condition to the condition block. Because the
733 // condition itself may contain control-flow, new blocks may be created.
734 if (Stmt* C = D->getCond()) {
735 Block = ExitConditionBlock;
736 EntryConditionBlock = addStmt(C);
737 if (Block) FinishBlock(EntryConditionBlock);
738 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000739
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000740 // The condition block is the implicit successor for the loop body as
741 // well as any code above the loop.
742 Succ = EntryConditionBlock;
743
744
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000745 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000746 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000747 {
748 assert (D->getBody());
749
750 // Save the current values for Block, Succ, and continue and break targets
751 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
752 save_continue(ContinueTargetBlock),
753 save_break(BreakTargetBlock);
754
755 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000756 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000757
758 // All breaks should go to the code following the loop.
759 BreakTargetBlock = LoopSuccessor;
760
761 // NULL out Block to force lazy instantiation of blocks for the body.
762 Block = NULL;
763
764 // Create the body. The returned block is the entry to the loop body.
765 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000766
Ted Kremenekaf603f72007-08-30 18:39:40 +0000767 if (!BodyBlock)
768 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
769 else if (Block)
770 FinishBlock(BodyBlock);
771
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000772 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000773 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000774 }
775
776 // Link up the condition block with the code that follows the loop.
777 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000778 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000779
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000780 // There can be no more statements in the body block(s)
781 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000782 // lazy creation of another block.
783 Block = NULL;
784
785 // Return the loop body, which is the dominating block for the loop.
786 return BodyBlock;
787}
788
789CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
790 // "continue" is a control-flow statement. Thus we stop processing the
791 // current block.
792 if (Block) FinishBlock(Block);
793
794 // Now create a new block that ends with the continue statement.
795 Block = createBlock(false);
796 Block->setTerminator(C);
797
798 // If there is no target for the continue, then we are looking at an
799 // incomplete AST. Handle this by not registering a successor.
800 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
801
802 return Block;
803}
804
805CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
806 // "break" is a control-flow statement. Thus we stop processing the
807 // current block.
808 if (Block) FinishBlock(Block);
809
810 // Now create a new block that ends with the continue statement.
811 Block = createBlock(false);
812 Block->setTerminator(B);
813
814 // If there is no target for the break, then we are looking at an
815 // incomplete AST. Handle this by not registering a successor.
816 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
817
818 return Block;
819}
820
821CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
822 // "switch" is a control-flow statement. Thus we stop processing the
823 // current block.
824 CFGBlock* SwitchSuccessor = NULL;
825
826 if (Block) {
827 FinishBlock(Block);
828 SwitchSuccessor = Block;
829 }
830 else SwitchSuccessor = Succ;
831
832 // Save the current "switch" context.
833 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
834 save_break(BreakTargetBlock);
835
836 // Create a new block that will contain the switch statement.
837 SwitchTerminatedBlock = createBlock(false);
838
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000839 // Now process the switch body. The code after the switch is the implicit
840 // successor.
841 Succ = SwitchSuccessor;
842 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000843
844 // When visiting the body, the case statements should automatically get
845 // linked up to the switch. We also don't keep a pointer to the body,
846 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000847 assert (S->getBody() && "switch must contain a non-NULL body");
848 Block = NULL;
849 CFGBlock *BodyBlock = Visit(S->getBody());
850 if (Block) FinishBlock(BodyBlock);
851
852 // Add the terminator and condition in the switch block.
853 SwitchTerminatedBlock->setTerminator(S);
854 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000855 Block = SwitchTerminatedBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000856 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000857}
858
859CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
860 // A SwitchCase is either a "default" or "case" statement. We handle
861 // both in the same way. They are essentially labels, so they are the
862 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000863
864 if (S->getSubStmt()) Visit(S->getSubStmt());
865 CFGBlock* CaseBlock = Block;
866 if (!CaseBlock) CaseBlock = createBlock();
867
Ted Kremenek9cffe732007-08-29 23:20:49 +0000868 // Cases/Default statements partition block, so this is the top of
869 // the basic block we were processing (the case/default is the label).
870 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000871 FinishBlock(CaseBlock);
872
873 // Add this block to the list of successors for the block with the
874 // switch statement.
875 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
876
877 // We set Block to NULL to allow lazy creation of a new block (if necessary)
878 Block = NULL;
879
880 // This block is now the implicit successor of other blocks.
881 Succ = CaseBlock;
882
883 return CaseBlock;
884}
885
Ted Kremenek19bb3562007-08-28 19:26:49 +0000886CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
887 // Lazily create the indirect-goto dispatch block if there isn't one
888 // already.
889 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
890
891 if (!IBlock) {
892 IBlock = createBlock(false);
893 cfg->setIndirectGotoBlock(IBlock);
894 }
895
896 // IndirectGoto is a control-flow statement. Thus we stop processing the
897 // current block and create a new one.
898 if (Block) FinishBlock(Block);
899 Block = createBlock(false);
900 Block->setTerminator(I);
901 Block->addSuccessor(IBlock);
902 return addStmt(I->getTarget());
903}
904
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000905
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000906} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000907
908/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
909/// block has no successors or predecessors. If this is the first block
910/// created in the CFG, it is automatically set to be the Entry and Exit
911/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000912CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000913 bool first_block = begin() == end();
914
915 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +0000916 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +0000917
918 // If this is the first block, set it as the Entry and Exit.
919 if (first_block) Entry = Exit = &front();
920
921 // Return the block.
922 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +0000923}
924
Ted Kremenek026473c2007-08-23 16:51:22 +0000925/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
926/// CFG is returned to the caller.
927CFG* CFG::buildCFG(Stmt* Statement) {
928 CFGBuilder Builder;
929 return Builder.buildCFG(Statement);
930}
931
932/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +0000933void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
934
Ted Kremenek7dba8602007-08-29 21:56:09 +0000935
936//===----------------------------------------------------------------------===//
937// CFG pretty printing
938//===----------------------------------------------------------------------===//
939
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000940namespace {
941
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000942class StmtPrinterHelper : public PrinterHelper {
943
Ted Kremenek42a509f2007-08-31 21:30:12 +0000944 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
945 StmtMapTy StmtMap;
946 signed CurrentBlock;
947 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000948
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000949public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000950
Ted Kremenek42a509f2007-08-31 21:30:12 +0000951 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
952 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
953 unsigned j = 1;
954 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
955 BI != BEnd; ++BI, ++j )
956 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
957 }
958 }
959
960 virtual ~StmtPrinterHelper() {}
961
962 void setBlockID(signed i) { CurrentBlock = i; }
963 void setStmtID(unsigned i) { CurrentStmt = i; }
964
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000965 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
966
967 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +0000968
969 if (I == StmtMap.end())
970 return false;
971
972 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
973 && I->second.second == CurrentStmt)
974 return false;
975
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000976 OS << "[B" << I->second.first << "." << I->second.second << "]";
977 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +0000978 }
979};
980
981class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek805e9a82007-08-31 21:49:40 +0000982 void >
983{
Ted Kremenek42a509f2007-08-31 21:30:12 +0000984 std::ostream& OS;
985 StmtPrinterHelper* Helper;
986public:
987 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
988 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000989
990 void VisitIfStmt(IfStmt* I) {
991 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +0000992 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000993 OS << "\n";
994 }
995
996 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +0000997 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000998
999 void VisitForStmt(ForStmt* F) {
1000 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001001 if (F->getInit()) OS << "...";
1002 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001003 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001004 OS << "; ";
1005 if (F->getInc()) OS << "...";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001006 OS << ")\n";
1007 }
1008
1009 void VisitWhileStmt(WhileStmt* W) {
1010 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001011 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001012 OS << "\n";
1013 }
1014
1015 void VisitDoStmt(DoStmt* D) {
1016 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001017 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001018 OS << '\n';
1019 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001020
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001021 void VisitSwitchStmt(SwitchStmt* S) {
1022 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001023 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001024 OS << '\n';
1025 }
1026
Ted Kremenek805e9a82007-08-31 21:49:40 +00001027 void VisitConditionalOperator(ConditionalOperator* C) {
1028 C->getCond()->printPretty(OS,Helper);
1029 OS << " ? ... : ...\n";
1030 }
1031
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001032 void VisitChooseExpr(ChooseExpr* C) {
1033 OS << "__builtin_choose_expr( ";
1034 C->getCond()->printPretty(OS,Helper);
1035 OS << " )\n";
1036 }
1037
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001038 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1039 OS << "goto *";
1040 I->getTarget()->printPretty(OS,Helper);
1041 OS << '\n';
1042 }
1043
Ted Kremenek805e9a82007-08-31 21:49:40 +00001044 void VisitBinaryOperator(BinaryOperator* B) {
1045 if (!B->isLogicalOp()) {
1046 VisitExpr(B);
1047 return;
1048 }
1049
1050 B->getLHS()->printPretty(OS,Helper);
1051
1052 switch (B->getOpcode()) {
1053 case BinaryOperator::LOr:
1054 OS << " || ...\n";
1055 return;
1056 case BinaryOperator::LAnd:
1057 OS << " && ...\n";
1058 return;
1059 default:
1060 assert(false && "Invalid logical operator.");
1061 }
1062 }
1063
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001064 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001065 E->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001066 OS << '\n';
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001067 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001068};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001069
1070
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001071void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1072 if (Helper) {
1073 // special printing for statement-expressions.
1074 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1075 CompoundStmt* Sub = SE->getSubStmt();
1076
1077 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001078 OS << "({ ... ; ";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001079 Helper->handledStmt(*SE->getSubStmt()->child_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001080 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001081 return;
1082 }
1083 }
1084
1085 // special printing for comma expressions.
1086 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1087 if (B->getOpcode() == BinaryOperator::Comma) {
1088 OS << "... , ";
1089 Helper->handledStmt(B->getRHS(),OS);
1090 OS << '\n';
1091 return;
1092 }
1093 }
1094 }
1095
1096 S->printPretty(OS, Helper);
1097
1098 // Expressions need a newline.
1099 if (isa<Expr>(S)) OS << '\n';
1100}
1101
Ted Kremenek42a509f2007-08-31 21:30:12 +00001102void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1103 StmtPrinterHelper* Helper, bool print_edges) {
1104
1105 if (Helper) Helper->setBlockID(B.getBlockID());
1106
Ted Kremenek7dba8602007-08-29 21:56:09 +00001107 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001108 OS << "\n [ B" << B.getBlockID();
1109
1110 if (&B == &cfg->getEntry())
1111 OS << " (ENTRY) ]\n";
1112 else if (&B == &cfg->getExit())
1113 OS << " (EXIT) ]\n";
1114 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001115 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001116 else
1117 OS << " ]\n";
1118
Ted Kremenek9cffe732007-08-29 23:20:49 +00001119 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001120 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1121
1122 if (print_edges)
1123 OS << " ";
1124
Ted Kremenek9cffe732007-08-29 23:20:49 +00001125 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1126 OS << L->getName();
1127 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1128 OS << "case ";
1129 C->getLHS()->printPretty(OS);
1130 if (C->getRHS()) {
1131 OS << " ... ";
1132 C->getRHS()->printPretty(OS);
1133 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001134 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001135 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001136 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001137 else
1138 assert(false && "Invalid label statement in CFGBlock.");
1139
Ted Kremenek9cffe732007-08-29 23:20:49 +00001140 OS << ":\n";
1141 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001142
Ted Kremenekfddd5182007-08-21 21:42:03 +00001143 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001144 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001145
1146 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1147 I != E ; ++I, ++j ) {
1148
Ted Kremenek9cffe732007-08-29 23:20:49 +00001149 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001150 if (print_edges)
1151 OS << " ";
1152
1153 OS << std::setw(3) << j << ": ";
1154
1155 if (Helper)
1156 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001157
1158 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001159 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001160
Ted Kremenek9cffe732007-08-29 23:20:49 +00001161 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001162 if (B.getTerminator()) {
1163 if (print_edges)
1164 OS << " ";
1165
Ted Kremenek9cffe732007-08-29 23:20:49 +00001166 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001167
1168 if (Helper) Helper->setBlockID(-1);
1169
1170 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1171 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenekfddd5182007-08-21 21:42:03 +00001172 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001173
Ted Kremenek9cffe732007-08-29 23:20:49 +00001174 if (print_edges) {
1175 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001176 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001177 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001178
Ted Kremenek42a509f2007-08-31 21:30:12 +00001179 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1180 I != E; ++I, ++i) {
1181
1182 if (i == 8 || (i-8) == 0)
1183 OS << "\n ";
1184
Ted Kremenek9cffe732007-08-29 23:20:49 +00001185 OS << " B" << (*I)->getBlockID();
1186 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001187
1188 OS << '\n';
1189
1190 // Print the successors of this block.
1191 OS << " Successors (" << B.succ_size() << "):";
1192 i = 0;
1193
1194 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1195 I != E; ++I, ++i) {
1196
1197 if (i == 8 || (i-8) % 10 == 0)
1198 OS << "\n ";
1199
1200 OS << " B" << (*I)->getBlockID();
1201 }
1202
Ted Kremenek9cffe732007-08-29 23:20:49 +00001203 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001204 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001205}
1206
1207} // end anonymous namespace
1208
1209/// dump - A simple pretty printer of a CFG that outputs to stderr.
1210void CFG::dump() const { print(std::cerr); }
1211
1212/// print - A simple pretty printer of a CFG that outputs to an ostream.
1213void CFG::print(std::ostream& OS) const {
1214
1215 StmtPrinterHelper Helper(this);
1216
1217 // Print the entry block.
1218 print_block(OS, this, getEntry(), &Helper, true);
1219
1220 // Iterate through the CFGBlocks and print them one by one.
1221 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1222 // Skip the entry block, because we already printed it.
1223 if (&(*I) == &getEntry() || &(*I) == &getExit())
1224 continue;
1225
1226 print_block(OS, this, *I, &Helper, true);
1227 }
1228
1229 // Print the exit block.
1230 print_block(OS, this, getExit(), &Helper, true);
1231}
1232
1233/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1234void CFGBlock::dump(const CFG* cfg) const { print(std::cerr, cfg); }
1235
1236/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1237/// Generally this will only be called from CFG::print.
1238void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1239 StmtPrinterHelper Helper(cfg);
1240 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001241}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001242
Ted Kremenek155383b2007-09-11 22:08:24 +00001243/// hasImplicitControlFlow - Returns true if a given expression is
1244/// is represented within a CFG as having a designated "statement slot"
1245bool CFG::hasImplicitControlFlow(const Stmt* S) {
1246 switch (S->getStmtClass()) {
1247 default:
1248 return false;
1249
1250 case Stmt::CallExprClass:
1251 case Stmt::ConditionalOperatorClass:
1252 case Stmt::ChooseExprClass:
1253 case Stmt::StmtExprClass:
1254 case Stmt::DeclStmtClass:
1255 return true;
1256
1257 case Stmt::BinaryOperatorClass: {
1258 const BinaryOperator* B = cast<BinaryOperator>(S);
1259 if (B->isLogicalOp() || B->getOpcode() == BinaryOperator::Comma)
1260 return true;
1261 else
1262 return false;
1263 }
1264 }
1265}
1266
Ted Kremenek7dba8602007-08-29 21:56:09 +00001267//===----------------------------------------------------------------------===//
1268// CFG Graphviz Visualization
1269//===----------------------------------------------------------------------===//
1270
Ted Kremenek42a509f2007-08-31 21:30:12 +00001271
1272#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001273static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001274#endif
1275
1276void CFG::viewCFG() const {
1277#ifndef NDEBUG
1278 StmtPrinterHelper H(this);
1279 GraphHelper = &H;
1280 llvm::ViewGraph(this,"CFG");
1281 GraphHelper = NULL;
1282#else
1283 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001284 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001285#endif
1286}
1287
Ted Kremenek7dba8602007-08-29 21:56:09 +00001288namespace llvm {
1289template<>
1290struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1291 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1292
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001293#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001294 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001295 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001296 std::string OutStr = Out.str();
1297
1298 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1299
1300 // Process string output to make it nicer...
1301 for (unsigned i = 0; i != OutStr.length(); ++i)
1302 if (OutStr[i] == '\n') { // Left justify
1303 OutStr[i] = '\\';
1304 OutStr.insert(OutStr.begin()+i+1, 'l');
1305 }
1306
1307 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001308#else
1309 return "";
1310#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001311 }
1312};
1313} // end namespace llvm