blob: 014dc861de707b01fd2d41ddeb7dffc0ac912127 [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) {
216 assert (Block);
217 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 Kremenek666a6af2007-08-28 16:18:58 +0000246
Ted Kremeneke822b622007-08-28 18:14:37 +0000247 case Stmt::DeclStmtClass:
248 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
249 Block->appendStmt(S);
250 return WalkAST_VisitVarDecl(V);
251 }
252 else return Block;
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000253
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000254 case Stmt::AddrLabelExprClass: {
255 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
256 AddressTakenLabels.insert(A->getLabel());
257
258 if (AlwaysAddStmt) Block->appendStmt(S);
259 return Block;
260 }
261
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000262 case Stmt::StmtExprClass:
263 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000264
Ted Kremenekcfaae762007-08-27 21:54:41 +0000265 case Stmt::BinaryOperatorClass: {
266 BinaryOperator* B = cast<BinaryOperator>(S);
267
268 if (B->isLogicalOp()) { // && or ||
269 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
270 ConfluenceBlock->appendStmt(B);
271 FinishBlock(ConfluenceBlock);
272
273 // create the block evaluating the LHS
274 CFGBlock* LHSBlock = createBlock(false);
275 LHSBlock->addSuccessor(ConfluenceBlock);
276 LHSBlock->setTerminator(B);
277
278 // create the block evaluating the RHS
279 Succ = ConfluenceBlock;
280 Block = NULL;
281 CFGBlock* RHSBlock = Visit(B->getRHS());
282 LHSBlock->addSuccessor(RHSBlock);
283
284 // Generate the blocks for evaluating the LHS.
285 Block = LHSBlock;
286 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000287 }
288 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
289 Block->appendStmt(B);
290 addStmt(B->getRHS());
291 return addStmt(B->getLHS());
Ted Kremenekcfaae762007-08-27 21:54:41 +0000292 }
293
294 // Fall through to the default case.
295 }
296
Ted Kremenek65cfa562007-08-27 21:27:44 +0000297 default:
298 if (AlwaysAddStmt) Block->appendStmt(S);
299 return WalkAST_VisitChildren(S);
300 };
301}
302
Ted Kremeneke822b622007-08-28 18:14:37 +0000303/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
304/// DeclStmts. Because the initialization code for declarations can
305/// contain arbitrary expressions, we must linearize declarations
306/// to handle arbitrary control-flow induced by those expressions.
307CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
308 // We actually must parse the LAST declaration in a chain of
309 // declarations first, because we are building the CFG in reverse
310 // order.
311 if (Decl* D = V->getNextDeclarator())
312 if (VarDecl* Next = cast<VarDecl>(D))
313 Block = WalkAST_VisitVarDecl(Next);
314
315 if (Expr* E = V->getInit())
316 return addStmt(E);
317
318 assert (Block);
319 return Block;
320}
321
Ted Kremenek65cfa562007-08-27 21:27:44 +0000322/// WalkAST_VisitChildren - Utility method to call WalkAST on the
323/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000324CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000325 CFGBlock* B = Block;
326 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
327 I != E; ++I)
328 B = WalkAST(*I);
329
330 return B;
331}
332
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000333/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
334/// expressions (a GCC extension).
335CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
336 Block->appendStmt(S);
337 return VisitCompoundStmt(S->getSubStmt());
338}
339
Ted Kremenek73543912007-08-23 21:42:29 +0000340/// VisitStmt - Handle statements with no branching control flow.
341CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
342 // We cannot assume that we are in the middle of a basic block, since
343 // the CFG might only be constructed for this single statement. If
344 // we have no current basic block, just create one lazily.
345 if (!Block) Block = createBlock();
346
347 // Simply add the statement to the current block. We actually
348 // insert statements in reverse order; this order is reversed later
349 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000350 addStmt(Statement);
351
Ted Kremenek73543912007-08-23 21:42:29 +0000352 return Block;
353}
354
355CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
356 return Block;
357}
358
359CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
360 // The value returned from this function is the last created CFGBlock
361 // that represents the "entry" point for the translated AST node.
362 CFGBlock* LastBlock;
363
364 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
365 E = C->body_rend(); I != E; ++I )
366 // Add the statement to the current block.
367 if (!(LastBlock=Visit(*I)))
368 return NULL;
369
370 return LastBlock;
371}
372
373CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
374 // We may see an if statement in the middle of a basic block, or
375 // it may be the first statement we are processing. In either case,
376 // we create a new basic block. First, we create the blocks for
377 // the then...else statements, and then we create the block containing
378 // the if statement. If we were in the middle of a block, we
379 // stop processing that block and reverse its statements. That block
380 // is then the implicit successor for the "then" and "else" clauses.
381
382 // The block we were proccessing is now finished. Make it the
383 // successor block.
384 if (Block) {
385 Succ = Block;
386 FinishBlock(Block);
387 }
388
389 // Process the false branch. NULL out Block so that the recursive
390 // call to Visit will create a new basic block.
391 // Null out Block so that all successor
392 CFGBlock* ElseBlock = Succ;
393
394 if (Stmt* Else = I->getElse()) {
395 SaveAndRestore<CFGBlock*> sv(Succ);
396
397 // NULL out Block so that the recursive call to Visit will
398 // create a new basic block.
399 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000400 ElseBlock = Visit(Else);
401
402 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
403 ElseBlock = sv.get();
404 else if (Block)
405 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000406 }
407
408 // Process the true branch. NULL out Block so that the recursive
409 // call to Visit will create a new basic block.
410 // Null out Block so that all successor
411 CFGBlock* ThenBlock;
412 {
413 Stmt* Then = I->getThen();
414 assert (Then);
415 SaveAndRestore<CFGBlock*> sv(Succ);
416 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000417 ThenBlock = Visit(Then);
418
419 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
420 ThenBlock = sv.get();
421 else if (Block)
422 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000423 }
424
425 // Now create a new block containing the if statement.
426 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000427
428 // Set the terminator of the new block to the If statement.
429 Block->setTerminator(I);
430
431 // Now add the successors.
432 Block->addSuccessor(ThenBlock);
433 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000434
435 // Add the condition as the last statement in the new block. This
436 // may create new blocks as the condition may contain control-flow. Any
437 // newly created blocks will be pointed to be "Block".
438 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000439}
440
441CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
442 // If we were in the middle of a block we stop processing that block
443 // and reverse its statements.
444 //
445 // NOTE: If a "return" appears in the middle of a block, this means
446 // that the code afterwards is DEAD (unreachable). We still
447 // keep a basic block for that code; a simple "mark-and-sweep"
448 // from the entry block will be able to report such dead
449 // blocks.
450 if (Block) FinishBlock(Block);
451
452 // Create the new block.
453 Block = createBlock(false);
454
455 // The Exit block is the only successor.
456 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000457
458 // Add the return statement to the block. This may create new blocks
459 // if R contains control-flow (short-circuit operations).
460 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000461}
462
463CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
464 // Get the block of the labeled statement. Add it to our map.
465 CFGBlock* LabelBlock = Visit(L->getSubStmt());
466 assert (LabelBlock);
467
468 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
469 LabelMap[ L ] = LabelBlock;
470
471 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000472 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000473 // label (and we have already processed the substatement) there is no
474 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000475 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000476 FinishBlock(LabelBlock);
477
478 // We set Block to NULL to allow lazy creation of a new block
479 // (if necessary);
480 Block = NULL;
481
482 // This block is now the implicit successor of other blocks.
483 Succ = LabelBlock;
484
485 return LabelBlock;
486}
487
488CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
489 // Goto is a control-flow statement. Thus we stop processing the
490 // current block and create a new one.
491 if (Block) FinishBlock(Block);
492 Block = createBlock(false);
493 Block->setTerminator(G);
494
495 // If we already know the mapping to the label block add the
496 // successor now.
497 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
498
499 if (I == LabelMap.end())
500 // We will need to backpatch this block later.
501 BackpatchBlocks.push_back(Block);
502 else
503 Block->addSuccessor(I->second);
504
505 return Block;
506}
507
508CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
509 // "for" is a control-flow statement. Thus we stop processing the
510 // current block.
511
512 CFGBlock* LoopSuccessor = NULL;
513
514 if (Block) {
515 FinishBlock(Block);
516 LoopSuccessor = Block;
517 }
518 else LoopSuccessor = Succ;
519
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000520 // Because of short-circuit evaluation, the condition of the loop
521 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
522 // blocks that evaluate the condition.
523 CFGBlock* ExitConditionBlock = createBlock(false);
524 CFGBlock* EntryConditionBlock = ExitConditionBlock;
525
526 // Set the terminator for the "exit" condition block.
527 ExitConditionBlock->setTerminator(F);
528
529 // Now add the actual condition to the condition block. Because the
530 // condition itself may contain control-flow, new blocks may be created.
531 if (Stmt* C = F->getCond()) {
532 Block = ExitConditionBlock;
533 EntryConditionBlock = addStmt(C);
534 if (Block) FinishBlock(EntryConditionBlock);
535 }
Ted Kremenek73543912007-08-23 21:42:29 +0000536
537 // The condition block is the implicit successor for the loop body as
538 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000539 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000540
541 // Now create the loop body.
542 {
543 assert (F->getBody());
544
545 // Save the current values for Block, Succ, and continue and break targets
546 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
547 save_continue(ContinueTargetBlock),
548 save_break(BreakTargetBlock);
549
550 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000551 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000552
553 // All breaks should go to the code following the loop.
554 BreakTargetBlock = LoopSuccessor;
555
556 // Create a new block to contain the (bottom) of the loop body.
557 Block = createBlock();
558
559 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000560 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000561
562 // Now populate the body block, and in the process create new blocks
563 // as we walk the body of the loop.
564 CFGBlock* BodyBlock = Visit(F->getBody());
565 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000566 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000567
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000568 // This new body block is a successor to our "exit" condition block.
569 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000570 }
571
572 // Link up the condition block with the code that follows the loop.
573 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000574 ExitConditionBlock->addSuccessor(LoopSuccessor);
575
Ted Kremenek73543912007-08-23 21:42:29 +0000576 // If the loop contains initialization, create a new block for those
577 // statements. This block can also contain statements that precede
578 // the loop.
579 if (Stmt* I = F->getInit()) {
580 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000581 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000582 }
583 else {
584 // There is no loop initialization. We are thus basically a while
585 // loop. NULL out Block to force lazy block construction.
586 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000587 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000588 }
589}
590
591CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
592 // "while" is a control-flow statement. Thus we stop processing the
593 // current block.
594
595 CFGBlock* LoopSuccessor = NULL;
596
597 if (Block) {
598 FinishBlock(Block);
599 LoopSuccessor = Block;
600 }
601 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000602
603 // Because of short-circuit evaluation, the condition of the loop
604 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
605 // blocks that evaluate the condition.
606 CFGBlock* ExitConditionBlock = createBlock(false);
607 CFGBlock* EntryConditionBlock = ExitConditionBlock;
608
609 // Set the terminator for the "exit" condition block.
610 ExitConditionBlock->setTerminator(W);
611
612 // Now add the actual condition to the condition block. Because the
613 // condition itself may contain control-flow, new blocks may be created.
614 // Thus we update "Succ" after adding the condition.
615 if (Stmt* C = W->getCond()) {
616 Block = ExitConditionBlock;
617 EntryConditionBlock = addStmt(C);
618 if (Block) FinishBlock(EntryConditionBlock);
619 }
Ted Kremenek73543912007-08-23 21:42:29 +0000620
621 // The condition block is the implicit successor for the loop body as
622 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000623 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000624
625 // Process the loop body.
626 {
627 assert (W->getBody());
628
629 // Save the current values for Block, Succ, and continue and break targets
630 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
631 save_continue(ContinueTargetBlock),
632 save_break(BreakTargetBlock);
633
634 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000635 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000636
637 // All breaks should go to the code following the loop.
638 BreakTargetBlock = LoopSuccessor;
639
640 // NULL out Block to force lazy instantiation of blocks for the body.
641 Block = NULL;
642
643 // Create the body. The returned block is the entry to the loop body.
644 CFGBlock* BodyBlock = Visit(W->getBody());
645 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000646 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000647
648 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000649 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000650 }
651
652 // Link up the condition block with the code that follows the loop.
653 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000654 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000655
656 // There can be no more statements in the condition block
657 // since we loop back to this block. NULL out Block to force
658 // lazy creation of another block.
659 Block = NULL;
660
661 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000662 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000663}
664
665CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
666 // "do...while" is a control-flow statement. Thus we stop processing the
667 // current block.
668
669 CFGBlock* LoopSuccessor = NULL;
670
671 if (Block) {
672 FinishBlock(Block);
673 LoopSuccessor = Block;
674 }
675 else LoopSuccessor = Succ;
676
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000677 // Because of short-circuit evaluation, the condition of the loop
678 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
679 // blocks that evaluate the condition.
680 CFGBlock* ExitConditionBlock = createBlock(false);
681 CFGBlock* EntryConditionBlock = ExitConditionBlock;
682
683 // Set the terminator for the "exit" condition block.
684 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000685
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000686 // Now add the actual condition to the condition block. Because the
687 // condition itself may contain control-flow, new blocks may be created.
688 if (Stmt* C = D->getCond()) {
689 Block = ExitConditionBlock;
690 EntryConditionBlock = addStmt(C);
691 if (Block) FinishBlock(EntryConditionBlock);
692 }
Ted Kremenek73543912007-08-23 21:42:29 +0000693
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000694 // The condition block is the implicit successor for the loop body as
695 // well as any code above the loop.
696 Succ = EntryConditionBlock;
697
698
Ted Kremenek73543912007-08-23 21:42:29 +0000699 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000700 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000701 {
702 assert (D->getBody());
703
704 // Save the current values for Block, Succ, and continue and break targets
705 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
706 save_continue(ContinueTargetBlock),
707 save_break(BreakTargetBlock);
708
709 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000710 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000711
712 // All breaks should go to the code following the loop.
713 BreakTargetBlock = LoopSuccessor;
714
715 // NULL out Block to force lazy instantiation of blocks for the body.
716 Block = NULL;
717
718 // Create the body. The returned block is the entry to the loop body.
719 BodyBlock = Visit(D->getBody());
720 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000721 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000722
723 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000724 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000725 }
726
727 // Link up the condition block with the code that follows the loop.
728 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000729 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000730
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000731 // There can be no more statements in the body block(s)
732 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000733 // lazy creation of another block.
734 Block = NULL;
735
736 // Return the loop body, which is the dominating block for the loop.
737 return BodyBlock;
738}
739
740CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
741 // "continue" is a control-flow statement. Thus we stop processing the
742 // current block.
743 if (Block) FinishBlock(Block);
744
745 // Now create a new block that ends with the continue statement.
746 Block = createBlock(false);
747 Block->setTerminator(C);
748
749 // If there is no target for the continue, then we are looking at an
750 // incomplete AST. Handle this by not registering a successor.
751 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
752
753 return Block;
754}
755
756CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
757 // "break" is a control-flow statement. Thus we stop processing the
758 // current block.
759 if (Block) FinishBlock(Block);
760
761 // Now create a new block that ends with the continue statement.
762 Block = createBlock(false);
763 Block->setTerminator(B);
764
765 // If there is no target for the break, then we are looking at an
766 // incomplete AST. Handle this by not registering a successor.
767 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
768
769 return Block;
770}
771
772CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
773 // "switch" is a control-flow statement. Thus we stop processing the
774 // current block.
775 CFGBlock* SwitchSuccessor = NULL;
776
777 if (Block) {
778 FinishBlock(Block);
779 SwitchSuccessor = Block;
780 }
781 else SwitchSuccessor = Succ;
782
783 // Save the current "switch" context.
784 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
785 save_break(BreakTargetBlock);
786
787 // Create a new block that will contain the switch statement.
788 SwitchTerminatedBlock = createBlock(false);
789
Ted Kremenek73543912007-08-23 21:42:29 +0000790 // Now process the switch body. The code after the switch is the implicit
791 // successor.
792 Succ = SwitchSuccessor;
793 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000794
795 // When visiting the body, the case statements should automatically get
796 // linked up to the switch. We also don't keep a pointer to the body,
797 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000798 assert (S->getBody() && "switch must contain a non-NULL body");
799 Block = NULL;
800 CFGBlock *BodyBlock = Visit(S->getBody());
801 if (Block) FinishBlock(BodyBlock);
802
803 // Add the terminator and condition in the switch block.
804 SwitchTerminatedBlock->setTerminator(S);
805 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000806 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000807 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000808}
809
810CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
811 // A SwitchCase is either a "default" or "case" statement. We handle
812 // both in the same way. They are essentially labels, so they are the
813 // first statement in a block.
814 CFGBlock* CaseBlock = Visit(S->getSubStmt());
815 assert (CaseBlock);
816
Ted Kremenekec055e12007-08-29 23:20:49 +0000817 // Cases/Default statements partition block, so this is the top of
818 // the basic block we were processing (the case/default is the label).
819 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000820 FinishBlock(CaseBlock);
821
822 // Add this block to the list of successors for the block with the
823 // switch statement.
824 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
825
826 // We set Block to NULL to allow lazy creation of a new block (if necessary)
827 Block = NULL;
828
829 // This block is now the implicit successor of other blocks.
830 Succ = CaseBlock;
831
832 return CaseBlock;
833}
834
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000835CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
836 // Lazily create the indirect-goto dispatch block if there isn't one
837 // already.
838 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
839
840 if (!IBlock) {
841 IBlock = createBlock(false);
842 cfg->setIndirectGotoBlock(IBlock);
843 }
844
845 // IndirectGoto is a control-flow statement. Thus we stop processing the
846 // current block and create a new one.
847 if (Block) FinishBlock(Block);
848 Block = createBlock(false);
849 Block->setTerminator(I);
850 Block->addSuccessor(IBlock);
851 return addStmt(I->getTarget());
852}
853
Ted Kremenek73543912007-08-23 21:42:29 +0000854
Ted Kremenekd6e50602007-08-23 21:26:19 +0000855} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000856
857/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
858/// block has no successors or predecessors. If this is the first block
859/// created in the CFG, it is automatically set to be the Entry and Exit
860/// of the CFG.
861CFGBlock* CFG::createBlock(unsigned blockID) {
862 bool first_block = begin() == end();
863
864 // Create the block.
865 Blocks.push_front(CFGBlock(blockID));
866
867 // If this is the first block, set it as the Entry and Exit.
868 if (first_block) Entry = Exit = &front();
869
870 // Return the block.
871 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000872}
873
Ted Kremenek4db5b452007-08-23 16:51:22 +0000874/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
875/// CFG is returned to the caller.
876CFG* CFG::buildCFG(Stmt* Statement) {
877 CFGBuilder Builder;
878 return Builder.buildCFG(Statement);
879}
880
881/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000882void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
883
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000884
885//===----------------------------------------------------------------------===//
886// CFG pretty printing
887//===----------------------------------------------------------------------===//
888
Ted Kremenek4db5b452007-08-23 16:51:22 +0000889/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000890void CFG::dump() const { print(std::cerr); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000891
Ted Kremenek4db5b452007-08-23 16:51:22 +0000892/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000893void CFG::print(std::ostream& OS) const {
894
895 // Print the entry block.
896 getEntry().print(OS,this);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000897
Ted Kremenek4db5b452007-08-23 16:51:22 +0000898 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000899 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000900 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000901 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000902 I->print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000903 }
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000904
905 // Print the exit block.
906 getExit().print(OS,this);
Ted Kremenek97f75312007-08-21 21:42:03 +0000907}
908
Ted Kremenekd8313202007-08-22 18:22:34 +0000909namespace {
910
Ted Kremenek73543912007-08-23 21:42:29 +0000911class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
912 void > {
913 std::ostream& OS;
914public:
915 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
916
917 void VisitIfStmt(IfStmt* I) {
918 OS << "if ";
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000919 I->getCond()->printPretty(OS);
Ted Kremenek73543912007-08-23 21:42:29 +0000920 OS << "\n";
921 }
922
923 // Default case.
924 void VisitStmt(Stmt* S) { S->printPretty(OS); }
925
926 void VisitForStmt(ForStmt* F) {
927 OS << "for (" ;
928 if (Stmt* I = F->getInit()) I->printPretty(OS);
929 OS << " ; ";
930 if (Stmt* C = F->getCond()) C->printPretty(OS);
931 OS << " ; ";
932 if (Stmt* I = F->getInc()) I->printPretty(OS);
933 OS << ")\n";
934 }
935
936 void VisitWhileStmt(WhileStmt* W) {
937 OS << "while " ;
938 if (Stmt* C = W->getCond()) C->printPretty(OS);
939 OS << "\n";
940 }
941
942 void VisitDoStmt(DoStmt* D) {
943 OS << "do ... while ";
944 if (Stmt* C = D->getCond()) C->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000945 OS << '\n';
946 }
947
948 void VisitSwitchStmt(SwitchStmt* S) {
949 OS << "switch ";
950 S->getCond()->printPretty(OS);
951 OS << '\n';
952 }
953
Ted Kremenekcfaae762007-08-27 21:54:41 +0000954 void VisitExpr(Expr* E) {
955 E->printPretty(OS);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000956 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +0000957 }
Ted Kremenek73543912007-08-23 21:42:29 +0000958};
959} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000960
Ted Kremenek4db5b452007-08-23 16:51:22 +0000961/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000962void CFGBlock::dump(const CFG* cfg) const { print(std::cerr,cfg); }
Ted Kremenek97f75312007-08-21 21:42:03 +0000963
Ted Kremenek4db5b452007-08-23 16:51:22 +0000964/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
965/// Generally this will only be called from CFG::print.
Ted Kremenekec055e12007-08-29 23:20:49 +0000966void CFGBlock::print(std::ostream& OS, const CFG* cfg, bool print_edges) const {
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000967
968 // Print the header.
969 OS << "\n [ B" << getBlockID();
970 if (this == &cfg->getEntry()) { OS << " (ENTRY) ]\n"; }
971 else if (this == &cfg->getExit()) { OS << " (EXIT) ]\n"; }
972 else if (this == cfg->getIndirectGotoBlock()) {
973 OS << " (INDIRECT GOTO DISPATCH) ]\n";
974 }
975 else OS << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000976
Ted Kremenekec055e12007-08-29 23:20:49 +0000977 // Print the label of this block.
978 if (Stmt* S = const_cast<Stmt*>(getLabel())) {
979 if (print_edges) OS << " ";
980 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
981 OS << L->getName();
982 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
983 OS << "case ";
984 C->getLHS()->printPretty(OS);
985 if (C->getRHS()) {
986 OS << " ... ";
987 C->getRHS()->printPretty(OS);
988 }
989 }
990 else if (DefaultStmt* D = dyn_cast<DefaultStmt>(D)) {
991 OS << "default";
992 }
993 else assert(false && "Invalid label statement in CFGBlock.");
994
995 OS << ":\n";
996 }
997
Ted Kremenek97f75312007-08-21 21:42:03 +0000998 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +0000999 unsigned j = 1;
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001000 for (const_iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001001 // Print the statement # in the basic block and the statement itself.
1002 if (print_edges) OS << " ";
1003 OS << std::setw(3) << j << ": ";
1004 (*I)->printPretty(OS);
1005
Ted Kremenekc5de2222007-08-21 23:26:17 +00001006 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +00001007 if (isa<Expr>(*I)) OS << '\n';
1008 }
Ted Kremenek97f75312007-08-21 21:42:03 +00001009
Ted Kremenekec055e12007-08-29 23:20:49 +00001010 // Print the terminator of this block.
1011 if (getTerminator()) {
1012 if (print_edges) OS << " ";
1013 OS << " T: ";
1014 CFGBlockTerminatorPrint(OS).Visit(const_cast<Stmt*>(getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001015 }
1016
Ted Kremenekec055e12007-08-29 23:20:49 +00001017 if (print_edges) {
1018 // Print the predecessors of this block.
1019 OS << " Predecessors (" << pred_size() << "):";
1020 unsigned i = 0;
1021 for (const_pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i) {
1022 if (i == 8 || (i-8) == 0) {
1023 OS << "\n ";
1024 }
1025 OS << " B" << (*I)->getBlockID();
Ted Kremenek97f75312007-08-21 21:42:03 +00001026 }
Ted Kremenekec055e12007-08-29 23:20:49 +00001027 OS << '\n';
1028
1029 // Print the successors of this block.
1030 OS << " Successors (" << succ_size() << "):";
1031 i = 0;
1032 for (const_succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i) {
1033 if (i == 8 || (i-8) % 10 == 0) {
1034 OS << "\n ";
1035 }
1036 OS << " B" << (*I)->getBlockID();
1037 }
1038 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001039 }
Ted Kremenek4db5b452007-08-23 16:51:22 +00001040}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001041
1042//===----------------------------------------------------------------------===//
1043// CFG Graphviz Visualization
1044//===----------------------------------------------------------------------===//
1045
1046namespace llvm {
1047template<>
1048struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1049 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1050
1051 std::ostringstream Out;
Ted Kremenekec055e12007-08-29 23:20:49 +00001052 Node->print(Out,Graph,false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001053 std::string OutStr = Out.str();
1054
1055 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1056
1057 // Process string output to make it nicer...
1058 for (unsigned i = 0; i != OutStr.length(); ++i)
1059 if (OutStr[i] == '\n') { // Left justify
1060 OutStr[i] = '\\';
1061 OutStr.insert(OutStr.begin()+i+1, 'l');
1062 }
1063
1064 return OutStr;
1065 }
1066};
1067} // end namespace llvm
1068
1069void CFG::viewCFG() const {
1070#ifndef NDEBUG
1071 llvm::ViewGraph(this,"CFG");
1072#else
1073 std::cerr << "CFG::viewCFG is only available in debug builds on "
1074 << "systems with Graphviz or gv!" << std::endl;
1075#endif
1076}