blob: 89d7af99657d7dfcad07e218601c61445ea36824 [file] [log] [blame]
Ted Kremenek97f75312007-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 Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
21#include "llvm/Config/config.h"
Ted Kremenek97f75312007-08-21 21:42:03 +000022#include <iostream>
23#include <iomanip>
24#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000025#include <sstream>
26
Ted Kremenek97f75312007-08-21 21:42:03 +000027using namespace clang;
28
29namespace {
30
Ted Kremenekd6e50602007-08-23 21:26:19 +000031// SaveAndRestore - A utility class that uses RIIA to save and restore
32// the value of a variable.
33template<typename T>
34struct SaveAndRestore {
35 SaveAndRestore(T& x) : X(x), old_value(x) {}
36 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000037 T get() { return old_value; }
38
Ted Kremenekd6e50602007-08-23 21:26:19 +000039 T& X;
40 T old_value;
41};
Ted Kremenek97f75312007-08-21 21:42:03 +000042
43/// CFGBuilder - This class is implements CFG construction from an AST.
44/// The builder is stateful: an instance of the builder should be used to only
45/// construct a single CFG.
46///
47/// Example usage:
48///
49/// CFGBuilder builder;
50/// CFG* cfg = builder.BuildAST(stmt1);
51///
Ted Kremenek95e854d2007-08-21 22:06:14 +000052/// CFG construction is done via a recursive walk of an AST.
53/// We actually parse the AST in reverse order so that the successor
54/// of a basic block is constructed prior to its predecessor. This
55/// allows us to nicely capture implicit fall-throughs without extra
56/// basic blocks.
57///
58class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000059 CFG* cfg;
60 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000061 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000062 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000063 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000064 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000065 unsigned NumBlocks;
66
Ted Kremenek0edd3a92007-08-28 19:26:49 +000067 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000068 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
69 LabelMapTy LabelMap;
70
Ted Kremenek0edd3a92007-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 Kremenekf5392b72007-08-22 15:40:58 +000073 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000074 BackpatchBlocksTy BackpatchBlocks;
75
Ted Kremenek0edd3a92007-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 Kremenek97f75312007-08-21 21:42:03 +000080public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000081 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000082 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremeneke809ebf2007-08-23 18:43:24 +000083 SwitchTerminatedBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000084 NumBlocks(0) {
85 // Create an empty CFG.
86 cfg = new CFG();
87 }
88
89 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000090
Ted Kremenek73543912007-08-23 21:42:29 +000091 // buildCFG - Used by external clients to construct the CFG.
92 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000093
Ted Kremenek73543912007-08-23 21:42:29 +000094 // Visitors to walk an AST and construct the CFG. Called by
95 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000096
Ted Kremenek73543912007-08-23 21:42:29 +000097 CFGBlock* VisitStmt(Stmt* Statement);
98 CFGBlock* VisitNullStmt(NullStmt* Statement);
99 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
100 CFGBlock* VisitIfStmt(IfStmt* I);
101 CFGBlock* VisitReturnStmt(ReturnStmt* R);
102 CFGBlock* VisitLabelStmt(LabelStmt* L);
103 CFGBlock* VisitGotoStmt(GotoStmt* G);
104 CFGBlock* VisitForStmt(ForStmt* F);
105 CFGBlock* VisitWhileStmt(WhileStmt* W);
106 CFGBlock* VisitDoStmt(DoStmt* D);
107 CFGBlock* VisitContinueStmt(ContinueStmt* C);
108 CFGBlock* VisitBreakStmt(BreakStmt* B);
109 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
110 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000111 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000112
Ted Kremenek73543912007-08-23 21:42:29 +0000113private:
114 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000115 CFGBlock* addStmt(Stmt* S);
116 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
117 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000118 CFGBlock* WalkAST_VisitVarDecl(VarDecl* D);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000119 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenek73543912007-08-23 21:42:29 +0000120 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000121
Ted Kremenek97f75312007-08-21 21:42:03 +0000122};
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000130 assert (cfg);
Ted Kremenek73543912007-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 Kremenekcfee50c2007-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 Kremenek73543912007-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 Kremenekcfee50c2007-08-27 19:46:09 +0000144 if (Block) FinishBlock(B);
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000160 }
Ted Kremenek73543912007-08-23 21:42:29 +0000161
Ted Kremenek0edd3a92007-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 Kremenekcfee50c2007-08-27 19:46:09 +0000178 if (B->pred_size() > 0) {
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000179 Succ = B;
180 cfg->setEntry(createBlock());
181 }
182 else cfg->setEntry(B);
183
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000184 // NULL out cfg so that repeated calls to the builder will fail and that
185 // the ownership of the constructed CFG is passed to the caller.
Ted Kremenek73543912007-08-23 21:42:29 +0000186 CFG* t = cfg;
187 cfg = NULL;
188 return t;
189 }
190 else return NULL;
191}
192
193/// createBlock - Used to lazily create blocks that are connected
194/// to the current (global) succcessor.
195CFGBlock* CFGBuilder::createBlock(bool add_successor) {
196 CFGBlock* B = cfg->createBlock(NumBlocks++);
197 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 Kremenekcfee50c2007-08-27 19:46:09 +0000202/// we must reverse the statements because they have been inserted
203/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000204void CFGBuilder::FinishBlock(CFGBlock* B) {
205 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000206 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000207}
208
Ted Kremenek65cfa562007-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 Kremenek390b9762007-08-30 18:39:40 +0000216 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-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 Kremeneke822b622007-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 Kremenek65cfa562007-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());
235
236 Succ = ConfluenceBlock;
237 Block = NULL;
238 CFGBlock* RHSBlock = Visit(C->getRHS());
239
240 Block = createBlock(false);
241 Block->addSuccessor(LHSBlock);
242 Block->addSuccessor(RHSBlock);
243 Block->setTerminator(C);
244 return addStmt(C->getCond());
245 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000246
247 case Stmt::ChooseExprClass: {
248 ChooseExpr* C = cast<ChooseExpr>(S);
249
250 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
251 ConfluenceBlock->appendStmt(C);
252 FinishBlock(ConfluenceBlock);
253
254 Succ = ConfluenceBlock;
255 Block = NULL;
256 CFGBlock* LHSBlock = Visit(C->getLHS());
257
258 Succ = ConfluenceBlock;
259 Block = NULL;
260 CFGBlock* RHSBlock = Visit(C->getRHS());
261
262 Block = createBlock(false);
263 Block->addSuccessor(LHSBlock);
264 Block->addSuccessor(RHSBlock);
265 Block->setTerminator(C);
266 return addStmt(C->getCond());
267 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000268
Ted Kremeneke822b622007-08-28 18:14:37 +0000269 case Stmt::DeclStmtClass:
270 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
271 Block->appendStmt(S);
272 return WalkAST_VisitVarDecl(V);
273 }
274 else return Block;
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000275
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000276 case Stmt::AddrLabelExprClass: {
277 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
278 AddressTakenLabels.insert(A->getLabel());
279
280 if (AlwaysAddStmt) Block->appendStmt(S);
281 return Block;
282 }
283
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000284 case Stmt::StmtExprClass:
285 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000286
Ted Kremenekcfaae762007-08-27 21:54:41 +0000287 case Stmt::BinaryOperatorClass: {
288 BinaryOperator* B = cast<BinaryOperator>(S);
289
290 if (B->isLogicalOp()) { // && or ||
291 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
292 ConfluenceBlock->appendStmt(B);
293 FinishBlock(ConfluenceBlock);
294
295 // create the block evaluating the LHS
296 CFGBlock* LHSBlock = createBlock(false);
297 LHSBlock->addSuccessor(ConfluenceBlock);
298 LHSBlock->setTerminator(B);
299
300 // create the block evaluating the RHS
301 Succ = ConfluenceBlock;
302 Block = NULL;
303 CFGBlock* RHSBlock = Visit(B->getRHS());
304 LHSBlock->addSuccessor(RHSBlock);
305
306 // Generate the blocks for evaluating the LHS.
307 Block = LHSBlock;
308 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000309 }
310 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
311 Block->appendStmt(B);
312 addStmt(B->getRHS());
313 return addStmt(B->getLHS());
Ted Kremenekcfaae762007-08-27 21:54:41 +0000314 }
315
316 // Fall through to the default case.
317 }
318
Ted Kremenek65cfa562007-08-27 21:27:44 +0000319 default:
320 if (AlwaysAddStmt) Block->appendStmt(S);
321 return WalkAST_VisitChildren(S);
322 };
323}
324
Ted Kremeneke822b622007-08-28 18:14:37 +0000325/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
326/// DeclStmts. Because the initialization code for declarations can
327/// contain arbitrary expressions, we must linearize declarations
328/// to handle arbitrary control-flow induced by those expressions.
329CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
330 // We actually must parse the LAST declaration in a chain of
331 // declarations first, because we are building the CFG in reverse
332 // order.
333 if (Decl* D = V->getNextDeclarator())
334 if (VarDecl* Next = cast<VarDecl>(D))
335 Block = WalkAST_VisitVarDecl(Next);
336
337 if (Expr* E = V->getInit())
338 return addStmt(E);
339
340 assert (Block);
341 return Block;
342}
343
Ted Kremenek65cfa562007-08-27 21:27:44 +0000344/// WalkAST_VisitChildren - Utility method to call WalkAST on the
345/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000346CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000347 CFGBlock* B = Block;
348 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
349 I != E; ++I)
350 B = WalkAST(*I);
351
352 return B;
353}
354
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000355/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
356/// expressions (a GCC extension).
357CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
358 Block->appendStmt(S);
359 return VisitCompoundStmt(S->getSubStmt());
360}
361
Ted Kremenek73543912007-08-23 21:42:29 +0000362/// VisitStmt - Handle statements with no branching control flow.
363CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
364 // We cannot assume that we are in the middle of a basic block, since
365 // the CFG might only be constructed for this single statement. If
366 // we have no current basic block, just create one lazily.
367 if (!Block) Block = createBlock();
368
369 // Simply add the statement to the current block. We actually
370 // insert statements in reverse order; this order is reversed later
371 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000372 addStmt(Statement);
373
Ted Kremenek73543912007-08-23 21:42:29 +0000374 return Block;
375}
376
377CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
378 return Block;
379}
380
381CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
382 // The value returned from this function is the last created CFGBlock
383 // that represents the "entry" point for the translated AST node.
384 CFGBlock* LastBlock;
385
386 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
387 E = C->body_rend(); I != E; ++I )
388 // Add the statement to the current block.
389 if (!(LastBlock=Visit(*I)))
390 return NULL;
391
392 return LastBlock;
393}
394
395CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
396 // We may see an if statement in the middle of a basic block, or
397 // it may be the first statement we are processing. In either case,
398 // we create a new basic block. First, we create the blocks for
399 // the then...else statements, and then we create the block containing
400 // the if statement. If we were in the middle of a block, we
401 // stop processing that block and reverse its statements. That block
402 // is then the implicit successor for the "then" and "else" clauses.
403
404 // The block we were proccessing is now finished. Make it the
405 // successor block.
406 if (Block) {
407 Succ = Block;
408 FinishBlock(Block);
409 }
410
411 // Process the false branch. NULL out Block so that the recursive
412 // call to Visit will create a new basic block.
413 // Null out Block so that all successor
414 CFGBlock* ElseBlock = Succ;
415
416 if (Stmt* Else = I->getElse()) {
417 SaveAndRestore<CFGBlock*> sv(Succ);
418
419 // NULL out Block so that the recursive call to Visit will
420 // create a new basic block.
421 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000422 ElseBlock = Visit(Else);
423
424 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
425 ElseBlock = sv.get();
426 else if (Block)
427 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000428 }
429
430 // Process the true branch. NULL out Block so that the recursive
431 // call to Visit will create a new basic block.
432 // Null out Block so that all successor
433 CFGBlock* ThenBlock;
434 {
435 Stmt* Then = I->getThen();
436 assert (Then);
437 SaveAndRestore<CFGBlock*> sv(Succ);
438 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000439 ThenBlock = Visit(Then);
440
441 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
442 ThenBlock = sv.get();
443 else if (Block)
444 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000445 }
446
447 // Now create a new block containing the if statement.
448 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000449
450 // Set the terminator of the new block to the If statement.
451 Block->setTerminator(I);
452
453 // Now add the successors.
454 Block->addSuccessor(ThenBlock);
455 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000456
457 // Add the condition as the last statement in the new block. This
458 // may create new blocks as the condition may contain control-flow. Any
459 // newly created blocks will be pointed to be "Block".
460 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000461}
462
463CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
464 // If we were in the middle of a block we stop processing that block
465 // and reverse its statements.
466 //
467 // NOTE: If a "return" appears in the middle of a block, this means
468 // that the code afterwards is DEAD (unreachable). We still
469 // keep a basic block for that code; a simple "mark-and-sweep"
470 // from the entry block will be able to report such dead
471 // blocks.
472 if (Block) FinishBlock(Block);
473
474 // Create the new block.
475 Block = createBlock(false);
476
477 // The Exit block is the only successor.
478 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000479
480 // Add the return statement to the block. This may create new blocks
481 // if R contains control-flow (short-circuit operations).
482 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000483}
484
485CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
486 // Get the block of the labeled statement. Add it to our map.
487 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000488
489 if (!LabelBlock) // This can happen when the body is empty, i.e.
490 LabelBlock=createBlock(); // scopes that only contains NullStmts.
491
Ted Kremenek73543912007-08-23 21:42:29 +0000492 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
493 LabelMap[ L ] = LabelBlock;
494
495 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000496 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000497 // label (and we have already processed the substatement) there is no
498 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000499 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000500 FinishBlock(LabelBlock);
501
502 // We set Block to NULL to allow lazy creation of a new block
503 // (if necessary);
504 Block = NULL;
505
506 // This block is now the implicit successor of other blocks.
507 Succ = LabelBlock;
508
509 return LabelBlock;
510}
511
512CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
513 // Goto is a control-flow statement. Thus we stop processing the
514 // current block and create a new one.
515 if (Block) FinishBlock(Block);
516 Block = createBlock(false);
517 Block->setTerminator(G);
518
519 // If we already know the mapping to the label block add the
520 // successor now.
521 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
522
523 if (I == LabelMap.end())
524 // We will need to backpatch this block later.
525 BackpatchBlocks.push_back(Block);
526 else
527 Block->addSuccessor(I->second);
528
529 return Block;
530}
531
532CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
533 // "for" is a control-flow statement. Thus we stop processing the
534 // current block.
535
536 CFGBlock* LoopSuccessor = NULL;
537
538 if (Block) {
539 FinishBlock(Block);
540 LoopSuccessor = Block;
541 }
542 else LoopSuccessor = Succ;
543
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000544 // Because of short-circuit evaluation, the condition of the loop
545 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
546 // blocks that evaluate the condition.
547 CFGBlock* ExitConditionBlock = createBlock(false);
548 CFGBlock* EntryConditionBlock = ExitConditionBlock;
549
550 // Set the terminator for the "exit" condition block.
551 ExitConditionBlock->setTerminator(F);
552
553 // Now add the actual condition to the condition block. Because the
554 // condition itself may contain control-flow, new blocks may be created.
555 if (Stmt* C = F->getCond()) {
556 Block = ExitConditionBlock;
557 EntryConditionBlock = addStmt(C);
558 if (Block) FinishBlock(EntryConditionBlock);
559 }
Ted Kremenek73543912007-08-23 21:42:29 +0000560
561 // The condition block is the implicit successor for the loop body as
562 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000563 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000564
565 // Now create the loop body.
566 {
567 assert (F->getBody());
568
569 // Save the current values for Block, Succ, and continue and break targets
570 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
571 save_continue(ContinueTargetBlock),
572 save_break(BreakTargetBlock);
573
574 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000575 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000576
577 // All breaks should go to the code following the loop.
578 BreakTargetBlock = LoopSuccessor;
579
Ted Kremenek390b9762007-08-30 18:39:40 +0000580 // Create a new block to contain the (bottom) of the loop body.
581 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000582
583 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000584 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000585
586 // Now populate the body block, and in the process create new blocks
587 // as we walk the body of the loop.
588 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000589
590 if (!BodyBlock)
591 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
592 else if (Block)
593 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000594
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000595 // This new body block is a successor to our "exit" condition block.
596 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000597 }
598
599 // Link up the condition block with the code that follows the loop.
600 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000601 ExitConditionBlock->addSuccessor(LoopSuccessor);
602
Ted Kremenek73543912007-08-23 21:42:29 +0000603 // If the loop contains initialization, create a new block for those
604 // statements. This block can also contain statements that precede
605 // the loop.
606 if (Stmt* I = F->getInit()) {
607 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000608 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000609 }
610 else {
611 // There is no loop initialization. We are thus basically a while
612 // loop. NULL out Block to force lazy block construction.
613 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000614 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000615 }
616}
617
618CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
619 // "while" is a control-flow statement. Thus we stop processing the
620 // current block.
621
622 CFGBlock* LoopSuccessor = NULL;
623
624 if (Block) {
625 FinishBlock(Block);
626 LoopSuccessor = Block;
627 }
628 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000629
630 // Because of short-circuit evaluation, the condition of the loop
631 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
632 // blocks that evaluate the condition.
633 CFGBlock* ExitConditionBlock = createBlock(false);
634 CFGBlock* EntryConditionBlock = ExitConditionBlock;
635
636 // Set the terminator for the "exit" condition block.
637 ExitConditionBlock->setTerminator(W);
638
639 // Now add the actual condition to the condition block. Because the
640 // condition itself may contain control-flow, new blocks may be created.
641 // Thus we update "Succ" after adding the condition.
642 if (Stmt* C = W->getCond()) {
643 Block = ExitConditionBlock;
644 EntryConditionBlock = addStmt(C);
645 if (Block) FinishBlock(EntryConditionBlock);
646 }
Ted Kremenek73543912007-08-23 21:42:29 +0000647
648 // The condition block is the implicit successor for the loop body as
649 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000650 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000651
652 // Process the loop body.
653 {
654 assert (W->getBody());
655
656 // Save the current values for Block, Succ, and continue and break targets
657 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
658 save_continue(ContinueTargetBlock),
659 save_break(BreakTargetBlock);
660
661 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000662 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000663
664 // All breaks should go to the code following the loop.
665 BreakTargetBlock = LoopSuccessor;
666
667 // NULL out Block to force lazy instantiation of blocks for the body.
668 Block = NULL;
669
670 // Create the body. The returned block is the entry to the loop body.
671 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000672
673 if (!BodyBlock)
674 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
675 else if (Block)
676 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000677
678 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000679 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000680 }
681
682 // Link up the condition block with the code that follows the loop.
683 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000684 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000685
686 // There can be no more statements in the condition block
687 // since we loop back to this block. NULL out Block to force
688 // lazy creation of another block.
689 Block = NULL;
690
691 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000692 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000693}
694
695CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
696 // "do...while" is a control-flow statement. Thus we stop processing the
697 // current block.
698
699 CFGBlock* LoopSuccessor = NULL;
700
701 if (Block) {
702 FinishBlock(Block);
703 LoopSuccessor = Block;
704 }
705 else LoopSuccessor = Succ;
706
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000707 // Because of short-circuit evaluation, the condition of the loop
708 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
709 // blocks that evaluate the condition.
710 CFGBlock* ExitConditionBlock = createBlock(false);
711 CFGBlock* EntryConditionBlock = ExitConditionBlock;
712
713 // Set the terminator for the "exit" condition block.
714 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000715
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000716 // Now add the actual condition to the condition block. Because the
717 // condition itself may contain control-flow, new blocks may be created.
718 if (Stmt* C = D->getCond()) {
719 Block = ExitConditionBlock;
720 EntryConditionBlock = addStmt(C);
721 if (Block) FinishBlock(EntryConditionBlock);
722 }
Ted Kremenek73543912007-08-23 21:42:29 +0000723
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000724 // The condition block is the implicit successor for the loop body as
725 // well as any code above the loop.
726 Succ = EntryConditionBlock;
727
728
Ted Kremenek73543912007-08-23 21:42:29 +0000729 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000730 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000731 {
732 assert (D->getBody());
733
734 // Save the current values for Block, Succ, and continue and break targets
735 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
736 save_continue(ContinueTargetBlock),
737 save_break(BreakTargetBlock);
738
739 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000740 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000741
742 // All breaks should go to the code following the loop.
743 BreakTargetBlock = LoopSuccessor;
744
745 // NULL out Block to force lazy instantiation of blocks for the body.
746 Block = NULL;
747
748 // Create the body. The returned block is the entry to the loop body.
749 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000750
Ted Kremenek390b9762007-08-30 18:39:40 +0000751 if (!BodyBlock)
752 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
753 else if (Block)
754 FinishBlock(BodyBlock);
755
Ted Kremenek73543912007-08-23 21:42:29 +0000756 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000757 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000758 }
759
760 // Link up the condition block with the code that follows the loop.
761 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000762 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000763
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000764 // There can be no more statements in the body block(s)
765 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000766 // lazy creation of another block.
767 Block = NULL;
768
769 // Return the loop body, which is the dominating block for the loop.
770 return BodyBlock;
771}
772
773CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
774 // "continue" is a control-flow statement. Thus we stop processing the
775 // current block.
776 if (Block) FinishBlock(Block);
777
778 // Now create a new block that ends with the continue statement.
779 Block = createBlock(false);
780 Block->setTerminator(C);
781
782 // If there is no target for the continue, then we are looking at an
783 // incomplete AST. Handle this by not registering a successor.
784 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
785
786 return Block;
787}
788
789CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
790 // "break" 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(B);
797
798 // If there is no target for the break, then we are looking at an
799 // incomplete AST. Handle this by not registering a successor.
800 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
801
802 return Block;
803}
804
805CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
806 // "switch" is a control-flow statement. Thus we stop processing the
807 // current block.
808 CFGBlock* SwitchSuccessor = NULL;
809
810 if (Block) {
811 FinishBlock(Block);
812 SwitchSuccessor = Block;
813 }
814 else SwitchSuccessor = Succ;
815
816 // Save the current "switch" context.
817 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
818 save_break(BreakTargetBlock);
819
820 // Create a new block that will contain the switch statement.
821 SwitchTerminatedBlock = createBlock(false);
822
Ted Kremenek73543912007-08-23 21:42:29 +0000823 // Now process the switch body. The code after the switch is the implicit
824 // successor.
825 Succ = SwitchSuccessor;
826 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000827
828 // When visiting the body, the case statements should automatically get
829 // linked up to the switch. We also don't keep a pointer to the body,
830 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000831 assert (S->getBody() && "switch must contain a non-NULL body");
832 Block = NULL;
833 CFGBlock *BodyBlock = Visit(S->getBody());
834 if (Block) FinishBlock(BodyBlock);
835
836 // Add the terminator and condition in the switch block.
837 SwitchTerminatedBlock->setTerminator(S);
838 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000839 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000840 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000841}
842
843CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
844 // A SwitchCase is either a "default" or "case" statement. We handle
845 // both in the same way. They are essentially labels, so they are the
846 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000847
848 if (S->getSubStmt()) Visit(S->getSubStmt());
849 CFGBlock* CaseBlock = Block;
850 if (!CaseBlock) CaseBlock = createBlock();
851
Ted Kremenekec055e12007-08-29 23:20:49 +0000852 // Cases/Default statements partition block, so this is the top of
853 // the basic block we were processing (the case/default is the label).
854 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000855 FinishBlock(CaseBlock);
856
857 // Add this block to the list of successors for the block with the
858 // switch statement.
859 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
860
861 // We set Block to NULL to allow lazy creation of a new block (if necessary)
862 Block = NULL;
863
864 // This block is now the implicit successor of other blocks.
865 Succ = CaseBlock;
866
867 return CaseBlock;
868}
869
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000870CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
871 // Lazily create the indirect-goto dispatch block if there isn't one
872 // already.
873 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
874
875 if (!IBlock) {
876 IBlock = createBlock(false);
877 cfg->setIndirectGotoBlock(IBlock);
878 }
879
880 // IndirectGoto is a control-flow statement. Thus we stop processing the
881 // current block and create a new one.
882 if (Block) FinishBlock(Block);
883 Block = createBlock(false);
884 Block->setTerminator(I);
885 Block->addSuccessor(IBlock);
886 return addStmt(I->getTarget());
887}
888
Ted Kremenek73543912007-08-23 21:42:29 +0000889
Ted Kremenekd6e50602007-08-23 21:26:19 +0000890} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000891
892/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
893/// block has no successors or predecessors. If this is the first block
894/// created in the CFG, it is automatically set to be the Entry and Exit
895/// of the CFG.
896CFGBlock* CFG::createBlock(unsigned blockID) {
897 bool first_block = begin() == end();
898
899 // Create the block.
900 Blocks.push_front(CFGBlock(blockID));
901
902 // If this is the first block, set it as the Entry and Exit.
903 if (first_block) Entry = Exit = &front();
904
905 // Return the block.
906 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000907}
908
Ted Kremenek4db5b452007-08-23 16:51:22 +0000909/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
910/// CFG is returned to the caller.
911CFG* CFG::buildCFG(Stmt* Statement) {
912 CFGBuilder Builder;
913 return Builder.buildCFG(Statement);
914}
915
916/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000917void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
918
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000919
920//===----------------------------------------------------------------------===//
921// CFG pretty printing
922//===----------------------------------------------------------------------===//
923
Ted Kremenek4db5b452007-08-23 16:51:22 +0000924/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000925void CFG::dump() const { print(std::cerr); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000926
Ted Kremenek4db5b452007-08-23 16:51:22 +0000927/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000928void CFG::print(std::ostream& OS) const {
929
930 // Print the entry block.
931 getEntry().print(OS,this);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000932
Ted Kremenek4db5b452007-08-23 16:51:22 +0000933 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000934 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000935 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000936 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000937 I->print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000938 }
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000939
940 // Print the exit block.
941 getExit().print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000942}
943
Ted Kremenekd8313202007-08-22 18:22:34 +0000944namespace {
945
Ted Kremenek73543912007-08-23 21:42:29 +0000946class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
947 void > {
948 std::ostream& OS;
949public:
950 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
951
952 void VisitIfStmt(IfStmt* I) {
953 OS << "if ";
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000954 I->getCond()->printPretty(OS);
Ted Kremenek73543912007-08-23 21:42:29 +0000955 OS << "\n";
956 }
957
958 // Default case.
959 void VisitStmt(Stmt* S) { S->printPretty(OS); }
960
961 void VisitForStmt(ForStmt* F) {
962 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +0000963 if (F->getInit()) OS << "...";
964 OS << "; ";
Ted Kremenek73543912007-08-23 21:42:29 +0000965 if (Stmt* C = F->getCond()) C->printPretty(OS);
Ted Kremenek23a1d662007-08-30 21:28:02 +0000966 OS << "; ";
967 if (F->getInc()) OS << "...";
Ted Kremenek73543912007-08-23 21:42:29 +0000968 OS << ")\n";
969 }
970
971 void VisitWhileStmt(WhileStmt* W) {
972 OS << "while " ;
973 if (Stmt* C = W->getCond()) C->printPretty(OS);
974 OS << "\n";
975 }
976
977 void VisitDoStmt(DoStmt* D) {
978 OS << "do ... while ";
979 if (Stmt* C = D->getCond()) C->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000980 OS << '\n';
981 }
982
983 void VisitSwitchStmt(SwitchStmt* S) {
984 OS << "switch ";
985 S->getCond()->printPretty(OS);
986 OS << '\n';
987 }
988
Ted Kremenekcfaae762007-08-27 21:54:41 +0000989 void VisitExpr(Expr* E) {
990 E->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000991 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +0000992 }
Ted Kremenek73543912007-08-23 21:42:29 +0000993};
994} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000995
Ted Kremenek4db5b452007-08-23 16:51:22 +0000996/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000997void CFGBlock::dump(const CFG* cfg) const { print(std::cerr,cfg); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000998
Ted Kremenek4db5b452007-08-23 16:51:22 +0000999/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1000/// Generally this will only be called from CFG::print.
Ted Kremenekec055e12007-08-29 23:20:49 +00001001void CFGBlock::print(std::ostream& OS, const CFG* cfg, bool print_edges) const {
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001002
1003 // Print the header.
1004 OS << "\n [ B" << getBlockID();
1005 if (this == &cfg->getEntry()) { OS << " (ENTRY) ]\n"; }
1006 else if (this == &cfg->getExit()) { OS << " (EXIT) ]\n"; }
1007 else if (this == cfg->getIndirectGotoBlock()) {
1008 OS << " (INDIRECT GOTO DISPATCH) ]\n";
1009 }
1010 else OS << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +00001011
Ted Kremenekec055e12007-08-29 23:20:49 +00001012 // Print the label of this block.
1013 if (Stmt* S = const_cast<Stmt*>(getLabel())) {
1014 if (print_edges) OS << " ";
1015 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1016 OS << L->getName();
1017 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1018 OS << "case ";
1019 C->getLHS()->printPretty(OS);
1020 if (C->getRHS()) {
1021 OS << " ... ";
1022 C->getRHS()->printPretty(OS);
1023 }
1024 }
1025 else if (DefaultStmt* D = dyn_cast<DefaultStmt>(D)) {
1026 OS << "default";
1027 }
1028 else assert(false && "Invalid label statement in CFGBlock.");
1029
1030 OS << ":\n";
1031 }
1032
Ted Kremenek97f75312007-08-21 21:42:03 +00001033 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001034 unsigned j = 1;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001035 for (const_iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001036 // Print the statement # in the basic block and the statement itself.
1037 if (print_edges) OS << " ";
1038 OS << std::setw(3) << j << ": ";
1039 (*I)->printPretty(OS);
1040
Ted Kremenekc5de2222007-08-21 23:26:17 +00001041 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +00001042 if (isa<Expr>(*I)) OS << '\n';
1043 }
Ted Kremenek97f75312007-08-21 21:42:03 +00001044
Ted Kremenekec055e12007-08-29 23:20:49 +00001045 // Print the terminator of this block.
1046 if (getTerminator()) {
1047 if (print_edges) OS << " ";
1048 OS << " T: ";
1049 CFGBlockTerminatorPrint(OS).Visit(const_cast<Stmt*>(getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001050 }
1051
Ted Kremenekec055e12007-08-29 23:20:49 +00001052 if (print_edges) {
1053 // Print the predecessors of this block.
1054 OS << " Predecessors (" << pred_size() << "):";
1055 unsigned i = 0;
1056 for (const_pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i) {
1057 if (i == 8 || (i-8) == 0) {
1058 OS << "\n ";
1059 }
1060 OS << " B" << (*I)->getBlockID();
Ted Kremenek97f75312007-08-21 21:42:03 +00001061 }
Ted Kremenekec055e12007-08-29 23:20:49 +00001062 OS << '\n';
1063
1064 // Print the successors of this block.
1065 OS << " Successors (" << succ_size() << "):";
1066 i = 0;
1067 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i) {
1068 if (i == 8 || (i-8) % 10 == 0) {
1069 OS << "\n ";
1070 }
1071 OS << " B" << (*I)->getBlockID();
1072 }
1073 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001074 }
Ted Kremenek4db5b452007-08-23 16:51:22 +00001075}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001076
1077//===----------------------------------------------------------------------===//
1078// CFG Graphviz Visualization
1079//===----------------------------------------------------------------------===//
1080
1081namespace llvm {
1082template<>
1083struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1084 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1085
1086 std::ostringstream Out;
Ted Kremenekec055e12007-08-29 23:20:49 +00001087 Node->print(Out,Graph,false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001088 std::string OutStr = Out.str();
1089
1090 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1091
1092 // Process string output to make it nicer...
1093 for (unsigned i = 0; i != OutStr.length(); ++i)
1094 if (OutStr[i] == '\n') { // Left justify
1095 OutStr[i] = '\\';
1096 OutStr.insert(OutStr.begin()+i+1, 'l');
1097 }
1098
1099 return OutStr;
1100 }
1101};
1102} // end namespace llvm
1103
1104void CFG::viewCFG() const {
1105#ifndef NDEBUG
1106 llvm::ViewGraph(this,"CFG");
1107#else
1108 std::cerr << "CFG::viewCFG is only available in debug builds on "
1109 << "systems with Graphviz or gv!" << std::endl;
1110#endif
1111}