blob: 93ee6f449dc9a5358df8b756d989cba968549da5 [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 Kremenek08176a52007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
22#include "llvm/Config/config.h"
Ted Kremenek97f75312007-08-21 21:42:03 +000023#include <iostream>
24#include <iomanip>
25#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000026#include <sstream>
27
Ted Kremenek97f75312007-08-21 21:42:03 +000028using namespace clang;
29
30namespace {
31
Ted Kremenekd6e50602007-08-23 21:26:19 +000032// SaveAndRestore - A utility class that uses RIIA to save and restore
33// the value of a variable.
34template<typename T>
35struct SaveAndRestore {
36 SaveAndRestore(T& x) : X(x), old_value(x) {}
37 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000038 T get() { return old_value; }
39
Ted Kremenekd6e50602007-08-23 21:26:19 +000040 T& X;
41 T old_value;
42};
Ted Kremenek97f75312007-08-21 21:42:03 +000043
44/// CFGBuilder - This class is implements CFG construction from an AST.
45/// The builder is stateful: an instance of the builder should be used to only
46/// construct a single CFG.
47///
48/// Example usage:
49///
50/// CFGBuilder builder;
51/// CFG* cfg = builder.BuildAST(stmt1);
52///
Ted Kremenek95e854d2007-08-21 22:06:14 +000053/// CFG construction is done via a recursive walk of an AST.
54/// We actually parse the AST in reverse order so that the successor
55/// of a basic block is constructed prior to its predecessor. This
56/// allows us to nicely capture implicit fall-throughs without extra
57/// basic blocks.
58///
59class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000060 CFG* cfg;
61 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000062 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000063 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000064 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000065 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000066
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 Kremenek14594572007-09-05 20:02:05 +000083 SwitchTerminatedBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000084 // Create an empty CFG.
85 cfg = new CFG();
86 }
87
88 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000089
Ted Kremenek73543912007-08-23 21:42:29 +000090 // buildCFG - Used by external clients to construct the CFG.
91 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000092
Ted Kremenek73543912007-08-23 21:42:29 +000093 // Visitors to walk an AST and construct the CFG. Called by
94 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000095
Ted Kremenek73543912007-08-23 21:42:29 +000096 CFGBlock* VisitStmt(Stmt* Statement);
97 CFGBlock* VisitNullStmt(NullStmt* Statement);
98 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
99 CFGBlock* VisitIfStmt(IfStmt* I);
100 CFGBlock* VisitReturnStmt(ReturnStmt* R);
101 CFGBlock* VisitLabelStmt(LabelStmt* L);
102 CFGBlock* VisitGotoStmt(GotoStmt* G);
103 CFGBlock* VisitForStmt(ForStmt* F);
104 CFGBlock* VisitWhileStmt(WhileStmt* W);
105 CFGBlock* VisitDoStmt(DoStmt* D);
106 CFGBlock* VisitContinueStmt(ContinueStmt* C);
107 CFGBlock* VisitBreakStmt(BreakStmt* B);
108 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
109 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000110 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000111
Ted Kremenek73543912007-08-23 21:42:29 +0000112private:
113 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000114 CFGBlock* addStmt(Stmt* S);
115 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
116 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000117 CFGBlock* WalkAST_VisitVarDecl(VarDecl* D);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000118 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenek73543912007-08-23 21:42:29 +0000119 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000120
Ted Kremenek97f75312007-08-21 21:42:03 +0000121};
Ted Kremenek73543912007-08-23 21:42:29 +0000122
123/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
124/// represent an arbitrary statement. Examples include a single expression
125/// or a function body (compound statement). The ownership of the returned
126/// CFG is transferred to the caller. If CFG construction fails, this method
127/// returns NULL.
128CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000129 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000130 if (!Statement) return NULL;
131
132 // Create an empty block that will serve as the exit block for the CFG.
133 // Since this is the first block added to the CFG, it will be implicitly
134 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000135 Succ = createBlock();
136 assert (Succ == &cfg->getExit());
137 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000138
139 // Visit the statements and create the CFG.
140 if (CFGBlock* B = Visit(Statement)) {
141 // Finalize the last constructed block. This usually involves
142 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000143 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000144
145 // Backpatch the gotos whose label -> block mappings we didn't know
146 // when we encountered them.
147 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
148 E = BackpatchBlocks.end(); I != E; ++I ) {
149
150 CFGBlock* B = *I;
151 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
152 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
153
154 // If there is no target for the goto, then we are looking at an
155 // incomplete AST. Handle this by not registering a successor.
156 if (LI == LabelMap.end()) continue;
157
158 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000159 }
Ted Kremenek73543912007-08-23 21:42:29 +0000160
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000161 // Add successors to the Indirect Goto Dispatch block (if we have one).
162 if (CFGBlock* B = cfg->getIndirectGotoBlock())
163 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
164 E = AddressTakenLabels.end(); I != E; ++I ) {
165
166 // Lookup the target block.
167 LabelMapTy::iterator LI = LabelMap.find(*I);
168
169 // If there is no target block that contains label, then we are looking
170 // at an incomplete AST. Handle this by not registering a successor.
171 if (LI == LabelMap.end()) continue;
172
173 B->addSuccessor(LI->second);
174 }
175
176 // Create an empty entry block that has no predecessors.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000177 if (B->pred_size() > 0) {
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000178 Succ = B;
179 cfg->setEntry(createBlock());
180 }
181 else cfg->setEntry(B);
182
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000183 // NULL out cfg so that repeated calls to the builder will fail and that
184 // the ownership of the constructed CFG is passed to the caller.
Ted Kremenek73543912007-08-23 21:42:29 +0000185 CFG* t = cfg;
186 cfg = NULL;
187 return t;
188 }
189 else return NULL;
190}
191
192/// createBlock - Used to lazily create blocks that are connected
193/// to the current (global) succcessor.
194CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000195 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000196 if (add_successor && Succ) B->addSuccessor(Succ);
197 return B;
198}
199
200/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000201/// we must reverse the statements because they have been inserted
202/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000203void CFGBuilder::FinishBlock(CFGBlock* B) {
204 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000205 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000206}
207
Ted Kremenek65cfa562007-08-27 21:27:44 +0000208/// addStmt - Used to add statements/expressions to the current CFGBlock
209/// "Block". This method calls WalkAST on the passed statement to see if it
210/// contains any short-circuit expressions. If so, it recursively creates
211/// the necessary blocks for such expressions. It returns the "topmost" block
212/// of the created blocks, or the original value of "Block" when this method
213/// was called if no additional blocks are created.
214CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000215 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-08-27 21:27:44 +0000216 return WalkAST(S,true);
217}
218
219/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000220/// add extra blocks for ternary operators, &&, and ||. We also
221/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek65cfa562007-08-27 21:27:44 +0000222CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
223 switch (S->getStmtClass()) {
224 case Stmt::ConditionalOperatorClass: {
225 ConditionalOperator* C = cast<ConditionalOperator>(S);
226
227 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
228 ConfluenceBlock->appendStmt(C);
229 FinishBlock(ConfluenceBlock);
230
231 Succ = ConfluenceBlock;
232 Block = NULL;
233 CFGBlock* LHSBlock = Visit(C->getLHS());
234
235 Succ = ConfluenceBlock;
236 Block = NULL;
237 CFGBlock* RHSBlock = Visit(C->getRHS());
238
239 Block = createBlock(false);
240 Block->addSuccessor(LHSBlock);
241 Block->addSuccessor(RHSBlock);
242 Block->setTerminator(C);
243 return addStmt(C->getCond());
244 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000245
246 case Stmt::ChooseExprClass: {
247 ChooseExpr* C = cast<ChooseExpr>(S);
248
249 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
250 ConfluenceBlock->appendStmt(C);
251 FinishBlock(ConfluenceBlock);
252
253 Succ = ConfluenceBlock;
254 Block = NULL;
255 CFGBlock* LHSBlock = Visit(C->getLHS());
256
257 Succ = ConfluenceBlock;
258 Block = NULL;
259 CFGBlock* RHSBlock = Visit(C->getRHS());
260
261 Block = createBlock(false);
262 Block->addSuccessor(LHSBlock);
263 Block->addSuccessor(RHSBlock);
264 Block->setTerminator(C);
265 return addStmt(C->getCond());
266 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000267
Ted Kremeneke822b622007-08-28 18:14:37 +0000268 case Stmt::DeclStmtClass:
269 if (VarDecl* V = dyn_cast<VarDecl>(cast<DeclStmt>(S)->getDecl())) {
270 Block->appendStmt(S);
271 return WalkAST_VisitVarDecl(V);
272 }
273 else return Block;
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000274
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000275 case Stmt::AddrLabelExprClass: {
276 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
277 AddressTakenLabels.insert(A->getLabel());
278
279 if (AlwaysAddStmt) Block->appendStmt(S);
280 return Block;
281 }
282
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000283 case Stmt::StmtExprClass:
284 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000285
Ted Kremenekcfaae762007-08-27 21:54:41 +0000286 case Stmt::BinaryOperatorClass: {
287 BinaryOperator* B = cast<BinaryOperator>(S);
288
289 if (B->isLogicalOp()) { // && or ||
290 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
291 ConfluenceBlock->appendStmt(B);
292 FinishBlock(ConfluenceBlock);
293
294 // create the block evaluating the LHS
295 CFGBlock* LHSBlock = createBlock(false);
296 LHSBlock->addSuccessor(ConfluenceBlock);
297 LHSBlock->setTerminator(B);
298
299 // create the block evaluating the RHS
300 Succ = ConfluenceBlock;
301 Block = NULL;
302 CFGBlock* RHSBlock = Visit(B->getRHS());
303 LHSBlock->addSuccessor(RHSBlock);
304
305 // Generate the blocks for evaluating the LHS.
306 Block = LHSBlock;
307 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000308 }
309 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
310 Block->appendStmt(B);
311 addStmt(B->getRHS());
312 return addStmt(B->getLHS());
Ted Kremenekcfaae762007-08-27 21:54:41 +0000313 }
314
315 // Fall through to the default case.
316 }
317
Ted Kremenek65cfa562007-08-27 21:27:44 +0000318 default:
319 if (AlwaysAddStmt) Block->appendStmt(S);
320 return WalkAST_VisitChildren(S);
321 };
322}
323
Ted Kremeneke822b622007-08-28 18:14:37 +0000324/// WalkAST_VisitVarDecl - Utility method to handle VarDecls contained in
325/// DeclStmts. Because the initialization code for declarations can
326/// contain arbitrary expressions, we must linearize declarations
327/// to handle arbitrary control-flow induced by those expressions.
328CFGBlock* CFGBuilder::WalkAST_VisitVarDecl(VarDecl* V) {
329 // We actually must parse the LAST declaration in a chain of
330 // declarations first, because we are building the CFG in reverse
331 // order.
332 if (Decl* D = V->getNextDeclarator())
333 if (VarDecl* Next = cast<VarDecl>(D))
334 Block = WalkAST_VisitVarDecl(Next);
335
336 if (Expr* E = V->getInit())
337 return addStmt(E);
338
339 assert (Block);
340 return Block;
341}
342
Ted Kremenek65cfa562007-08-27 21:27:44 +0000343/// WalkAST_VisitChildren - Utility method to call WalkAST on the
344/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000345CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000346 CFGBlock* B = Block;
347 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
348 I != E; ++I)
349 B = WalkAST(*I);
350
351 return B;
352}
353
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000354/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
355/// expressions (a GCC extension).
356CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
357 Block->appendStmt(S);
358 return VisitCompoundStmt(S->getSubStmt());
359}
360
Ted Kremenek73543912007-08-23 21:42:29 +0000361/// VisitStmt - Handle statements with no branching control flow.
362CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
363 // We cannot assume that we are in the middle of a basic block, since
364 // the CFG might only be constructed for this single statement. If
365 // we have no current basic block, just create one lazily.
366 if (!Block) Block = createBlock();
367
368 // Simply add the statement to the current block. We actually
369 // insert statements in reverse order; this order is reversed later
370 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000371 addStmt(Statement);
372
Ted Kremenek73543912007-08-23 21:42:29 +0000373 return Block;
374}
375
376CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
377 return Block;
378}
379
380CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
381 // The value returned from this function is the last created CFGBlock
382 // that represents the "entry" point for the translated AST node.
383 CFGBlock* LastBlock;
384
385 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
386 E = C->body_rend(); I != E; ++I )
387 // Add the statement to the current block.
388 if (!(LastBlock=Visit(*I)))
389 return NULL;
390
391 return LastBlock;
392}
393
394CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
395 // We may see an if statement in the middle of a basic block, or
396 // it may be the first statement we are processing. In either case,
397 // we create a new basic block. First, we create the blocks for
398 // the then...else statements, and then we create the block containing
399 // the if statement. If we were in the middle of a block, we
400 // stop processing that block and reverse its statements. That block
401 // is then the implicit successor for the "then" and "else" clauses.
402
403 // The block we were proccessing is now finished. Make it the
404 // successor block.
405 if (Block) {
406 Succ = Block;
407 FinishBlock(Block);
408 }
409
410 // Process the false branch. NULL out Block so that the recursive
411 // call to Visit will create a new basic block.
412 // Null out Block so that all successor
413 CFGBlock* ElseBlock = Succ;
414
415 if (Stmt* Else = I->getElse()) {
416 SaveAndRestore<CFGBlock*> sv(Succ);
417
418 // NULL out Block so that the recursive call to Visit will
419 // create a new basic block.
420 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000421 ElseBlock = Visit(Else);
422
423 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
424 ElseBlock = sv.get();
425 else if (Block)
426 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000427 }
428
429 // Process the true branch. NULL out Block so that the recursive
430 // call to Visit will create a new basic block.
431 // Null out Block so that all successor
432 CFGBlock* ThenBlock;
433 {
434 Stmt* Then = I->getThen();
435 assert (Then);
436 SaveAndRestore<CFGBlock*> sv(Succ);
437 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000438 ThenBlock = Visit(Then);
439
440 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
441 ThenBlock = sv.get();
442 else if (Block)
443 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000444 }
445
446 // Now create a new block containing the if statement.
447 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000448
449 // Set the terminator of the new block to the If statement.
450 Block->setTerminator(I);
451
452 // Now add the successors.
453 Block->addSuccessor(ThenBlock);
454 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000455
456 // Add the condition as the last statement in the new block. This
457 // may create new blocks as the condition may contain control-flow. Any
458 // newly created blocks will be pointed to be "Block".
459 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000460}
461
462CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
463 // If we were in the middle of a block we stop processing that block
464 // and reverse its statements.
465 //
466 // NOTE: If a "return" appears in the middle of a block, this means
467 // that the code afterwards is DEAD (unreachable). We still
468 // keep a basic block for that code; a simple "mark-and-sweep"
469 // from the entry block will be able to report such dead
470 // blocks.
471 if (Block) FinishBlock(Block);
472
473 // Create the new block.
474 Block = createBlock(false);
475
476 // The Exit block is the only successor.
477 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000478
479 // Add the return statement to the block. This may create new blocks
480 // if R contains control-flow (short-circuit operations).
481 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000482}
483
484CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
485 // Get the block of the labeled statement. Add it to our map.
486 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000487
488 if (!LabelBlock) // This can happen when the body is empty, i.e.
489 LabelBlock=createBlock(); // scopes that only contains NullStmts.
490
Ted Kremenek73543912007-08-23 21:42:29 +0000491 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
492 LabelMap[ L ] = LabelBlock;
493
494 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000495 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000496 // label (and we have already processed the substatement) there is no
497 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000498 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000499 FinishBlock(LabelBlock);
500
501 // We set Block to NULL to allow lazy creation of a new block
502 // (if necessary);
503 Block = NULL;
504
505 // This block is now the implicit successor of other blocks.
506 Succ = LabelBlock;
507
508 return LabelBlock;
509}
510
511CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
512 // Goto is a control-flow statement. Thus we stop processing the
513 // current block and create a new one.
514 if (Block) FinishBlock(Block);
515 Block = createBlock(false);
516 Block->setTerminator(G);
517
518 // If we already know the mapping to the label block add the
519 // successor now.
520 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
521
522 if (I == LabelMap.end())
523 // We will need to backpatch this block later.
524 BackpatchBlocks.push_back(Block);
525 else
526 Block->addSuccessor(I->second);
527
528 return Block;
529}
530
531CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
532 // "for" is a control-flow statement. Thus we stop processing the
533 // current block.
534
535 CFGBlock* LoopSuccessor = NULL;
536
537 if (Block) {
538 FinishBlock(Block);
539 LoopSuccessor = Block;
540 }
541 else LoopSuccessor = Succ;
542
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000543 // Because of short-circuit evaluation, the condition of the loop
544 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
545 // blocks that evaluate the condition.
546 CFGBlock* ExitConditionBlock = createBlock(false);
547 CFGBlock* EntryConditionBlock = ExitConditionBlock;
548
549 // Set the terminator for the "exit" condition block.
550 ExitConditionBlock->setTerminator(F);
551
552 // Now add the actual condition to the condition block. Because the
553 // condition itself may contain control-flow, new blocks may be created.
554 if (Stmt* C = F->getCond()) {
555 Block = ExitConditionBlock;
556 EntryConditionBlock = addStmt(C);
557 if (Block) FinishBlock(EntryConditionBlock);
558 }
Ted Kremenek73543912007-08-23 21:42:29 +0000559
560 // The condition block is the implicit successor for the loop body as
561 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000562 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000563
564 // Now create the loop body.
565 {
566 assert (F->getBody());
567
568 // Save the current values for Block, Succ, and continue and break targets
569 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
570 save_continue(ContinueTargetBlock),
571 save_break(BreakTargetBlock);
572
573 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000574 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000575
576 // All breaks should go to the code following the loop.
577 BreakTargetBlock = LoopSuccessor;
578
Ted Kremenek390b9762007-08-30 18:39:40 +0000579 // Create a new block to contain the (bottom) of the loop body.
580 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000581
582 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000583 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000584
585 // Now populate the body block, and in the process create new blocks
586 // as we walk the body of the loop.
587 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000588
589 if (!BodyBlock)
590 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
591 else if (Block)
592 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000593
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000594 // This new body block is a successor to our "exit" condition block.
595 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000596 }
597
598 // Link up the condition block with the code that follows the loop.
599 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000600 ExitConditionBlock->addSuccessor(LoopSuccessor);
601
Ted Kremenek73543912007-08-23 21:42:29 +0000602 // If the loop contains initialization, create a new block for those
603 // statements. This block can also contain statements that precede
604 // the loop.
605 if (Stmt* I = F->getInit()) {
606 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000607 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000608 }
609 else {
610 // There is no loop initialization. We are thus basically a while
611 // loop. NULL out Block to force lazy block construction.
612 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000613 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000614 }
615}
616
617CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
618 // "while" is a control-flow statement. Thus we stop processing the
619 // current block.
620
621 CFGBlock* LoopSuccessor = NULL;
622
623 if (Block) {
624 FinishBlock(Block);
625 LoopSuccessor = Block;
626 }
627 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000628
629 // Because of short-circuit evaluation, the condition of the loop
630 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
631 // blocks that evaluate the condition.
632 CFGBlock* ExitConditionBlock = createBlock(false);
633 CFGBlock* EntryConditionBlock = ExitConditionBlock;
634
635 // Set the terminator for the "exit" condition block.
636 ExitConditionBlock->setTerminator(W);
637
638 // Now add the actual condition to the condition block. Because the
639 // condition itself may contain control-flow, new blocks may be created.
640 // Thus we update "Succ" after adding the condition.
641 if (Stmt* C = W->getCond()) {
642 Block = ExitConditionBlock;
643 EntryConditionBlock = addStmt(C);
644 if (Block) FinishBlock(EntryConditionBlock);
645 }
Ted Kremenek73543912007-08-23 21:42:29 +0000646
647 // The condition block is the implicit successor for the loop body as
648 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000649 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000650
651 // Process the loop body.
652 {
653 assert (W->getBody());
654
655 // Save the current values for Block, Succ, and continue and break targets
656 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
657 save_continue(ContinueTargetBlock),
658 save_break(BreakTargetBlock);
659
660 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000661 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000662
663 // All breaks should go to the code following the loop.
664 BreakTargetBlock = LoopSuccessor;
665
666 // NULL out Block to force lazy instantiation of blocks for the body.
667 Block = NULL;
668
669 // Create the body. The returned block is the entry to the loop body.
670 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000671
672 if (!BodyBlock)
673 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
674 else if (Block)
675 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000676
677 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000678 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000679 }
680
681 // Link up the condition block with the code that follows the loop.
682 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000683 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000684
685 // There can be no more statements in the condition block
686 // since we loop back to this block. NULL out Block to force
687 // lazy creation of another block.
688 Block = NULL;
689
690 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000691 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000692}
693
694CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
695 // "do...while" is a control-flow statement. Thus we stop processing the
696 // current block.
697
698 CFGBlock* LoopSuccessor = NULL;
699
700 if (Block) {
701 FinishBlock(Block);
702 LoopSuccessor = Block;
703 }
704 else LoopSuccessor = Succ;
705
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000706 // Because of short-circuit evaluation, the condition of the loop
707 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
708 // blocks that evaluate the condition.
709 CFGBlock* ExitConditionBlock = createBlock(false);
710 CFGBlock* EntryConditionBlock = ExitConditionBlock;
711
712 // Set the terminator for the "exit" condition block.
713 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000714
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000715 // Now add the actual condition to the condition block. Because the
716 // condition itself may contain control-flow, new blocks may be created.
717 if (Stmt* C = D->getCond()) {
718 Block = ExitConditionBlock;
719 EntryConditionBlock = addStmt(C);
720 if (Block) FinishBlock(EntryConditionBlock);
721 }
Ted Kremenek73543912007-08-23 21:42:29 +0000722
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000723 // The condition block is the implicit successor for the loop body as
724 // well as any code above the loop.
725 Succ = EntryConditionBlock;
726
727
Ted Kremenek73543912007-08-23 21:42:29 +0000728 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000729 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000730 {
731 assert (D->getBody());
732
733 // Save the current values for Block, Succ, and continue and break targets
734 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
735 save_continue(ContinueTargetBlock),
736 save_break(BreakTargetBlock);
737
738 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000739 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000740
741 // All breaks should go to the code following the loop.
742 BreakTargetBlock = LoopSuccessor;
743
744 // NULL out Block to force lazy instantiation of blocks for the body.
745 Block = NULL;
746
747 // Create the body. The returned block is the entry to the loop body.
748 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000749
Ted Kremenek390b9762007-08-30 18:39:40 +0000750 if (!BodyBlock)
751 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
752 else if (Block)
753 FinishBlock(BodyBlock);
754
Ted Kremenek73543912007-08-23 21:42:29 +0000755 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000756 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000757 }
758
759 // Link up the condition block with the code that follows the loop.
760 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000761 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000762
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000763 // There can be no more statements in the body block(s)
764 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000765 // lazy creation of another block.
766 Block = NULL;
767
768 // Return the loop body, which is the dominating block for the loop.
769 return BodyBlock;
770}
771
772CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
773 // "continue" is a control-flow statement. Thus we stop processing the
774 // current block.
775 if (Block) FinishBlock(Block);
776
777 // Now create a new block that ends with the continue statement.
778 Block = createBlock(false);
779 Block->setTerminator(C);
780
781 // If there is no target for the continue, then we are looking at an
782 // incomplete AST. Handle this by not registering a successor.
783 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
784
785 return Block;
786}
787
788CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
789 // "break" is a control-flow statement. Thus we stop processing the
790 // current block.
791 if (Block) FinishBlock(Block);
792
793 // Now create a new block that ends with the continue statement.
794 Block = createBlock(false);
795 Block->setTerminator(B);
796
797 // If there is no target for the break, then we are looking at an
798 // incomplete AST. Handle this by not registering a successor.
799 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
800
801 return Block;
802}
803
804CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
805 // "switch" is a control-flow statement. Thus we stop processing the
806 // current block.
807 CFGBlock* SwitchSuccessor = NULL;
808
809 if (Block) {
810 FinishBlock(Block);
811 SwitchSuccessor = Block;
812 }
813 else SwitchSuccessor = Succ;
814
815 // Save the current "switch" context.
816 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
817 save_break(BreakTargetBlock);
818
819 // Create a new block that will contain the switch statement.
820 SwitchTerminatedBlock = createBlock(false);
821
Ted Kremenek73543912007-08-23 21:42:29 +0000822 // Now process the switch body. The code after the switch is the implicit
823 // successor.
824 Succ = SwitchSuccessor;
825 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000826
827 // When visiting the body, the case statements should automatically get
828 // linked up to the switch. We also don't keep a pointer to the body,
829 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000830 assert (S->getBody() && "switch must contain a non-NULL body");
831 Block = NULL;
832 CFGBlock *BodyBlock = Visit(S->getBody());
833 if (Block) FinishBlock(BodyBlock);
834
835 // Add the terminator and condition in the switch block.
836 SwitchTerminatedBlock->setTerminator(S);
837 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000838 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000839 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000840}
841
842CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
843 // A SwitchCase is either a "default" or "case" statement. We handle
844 // both in the same way. They are essentially labels, so they are the
845 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000846
847 if (S->getSubStmt()) Visit(S->getSubStmt());
848 CFGBlock* CaseBlock = Block;
849 if (!CaseBlock) CaseBlock = createBlock();
850
Ted Kremenekec055e12007-08-29 23:20:49 +0000851 // Cases/Default statements partition block, so this is the top of
852 // the basic block we were processing (the case/default is the label).
853 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000854 FinishBlock(CaseBlock);
855
856 // Add this block to the list of successors for the block with the
857 // switch statement.
858 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
859
860 // We set Block to NULL to allow lazy creation of a new block (if necessary)
861 Block = NULL;
862
863 // This block is now the implicit successor of other blocks.
864 Succ = CaseBlock;
865
866 return CaseBlock;
867}
868
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000869CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
870 // Lazily create the indirect-goto dispatch block if there isn't one
871 // already.
872 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
873
874 if (!IBlock) {
875 IBlock = createBlock(false);
876 cfg->setIndirectGotoBlock(IBlock);
877 }
878
879 // IndirectGoto is a control-flow statement. Thus we stop processing the
880 // current block and create a new one.
881 if (Block) FinishBlock(Block);
882 Block = createBlock(false);
883 Block->setTerminator(I);
884 Block->addSuccessor(IBlock);
885 return addStmt(I->getTarget());
886}
887
Ted Kremenek73543912007-08-23 21:42:29 +0000888
Ted Kremenekd6e50602007-08-23 21:26:19 +0000889} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000890
891/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
892/// block has no successors or predecessors. If this is the first block
893/// created in the CFG, it is automatically set to be the Entry and Exit
894/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +0000895CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000896 bool first_block = begin() == end();
897
898 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +0000899 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +0000900
901 // If this is the first block, set it as the Entry and Exit.
902 if (first_block) Entry = Exit = &front();
903
904 // Return the block.
905 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000906}
907
Ted Kremenek4db5b452007-08-23 16:51:22 +0000908/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
909/// CFG is returned to the caller.
910CFG* CFG::buildCFG(Stmt* Statement) {
911 CFGBuilder Builder;
912 return Builder.buildCFG(Statement);
913}
914
915/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000916void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
917
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000918
919//===----------------------------------------------------------------------===//
920// CFG pretty printing
921//===----------------------------------------------------------------------===//
922
Ted Kremenekd8313202007-08-22 18:22:34 +0000923namespace {
924
Ted Kremenek86afc042007-08-31 22:26:13 +0000925class StmtPrinterHelper : public PrinterHelper {
926
Ted Kremenek08176a52007-08-31 21:30:12 +0000927 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
928 StmtMapTy StmtMap;
929 signed CurrentBlock;
930 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +0000931
Ted Kremenek73543912007-08-23 21:42:29 +0000932public:
Ted Kremenek86afc042007-08-31 22:26:13 +0000933
Ted Kremenek08176a52007-08-31 21:30:12 +0000934 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
935 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
936 unsigned j = 1;
937 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
938 BI != BEnd; ++BI, ++j )
939 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
940 }
941 }
942
943 virtual ~StmtPrinterHelper() {}
944
945 void setBlockID(signed i) { CurrentBlock = i; }
946 void setStmtID(unsigned i) { CurrentStmt = i; }
947
Ted Kremenek86afc042007-08-31 22:26:13 +0000948 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
949
950 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek08176a52007-08-31 21:30:12 +0000951
952 if (I == StmtMap.end())
953 return false;
954
955 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
956 && I->second.second == CurrentStmt)
957 return false;
958
Ted Kremenek86afc042007-08-31 22:26:13 +0000959 OS << "[B" << I->second.first << "." << I->second.second << "]";
960 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +0000961 }
962};
963
964class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek621e1592007-08-31 21:49:40 +0000965 void >
966{
Ted Kremenek08176a52007-08-31 21:30:12 +0000967 std::ostream& OS;
968 StmtPrinterHelper* Helper;
969public:
970 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
971 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +0000972
973 void VisitIfStmt(IfStmt* I) {
974 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +0000975 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +0000976 OS << "\n";
977 }
978
979 // Default case.
Ted Kremenek621e1592007-08-31 21:49:40 +0000980 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +0000981
982 void VisitForStmt(ForStmt* F) {
983 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +0000984 if (F->getInit()) OS << "...";
985 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +0000986 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +0000987 OS << "; ";
988 if (F->getInc()) OS << "...";
Ted Kremenek73543912007-08-23 21:42:29 +0000989 OS << ")\n";
990 }
991
992 void VisitWhileStmt(WhileStmt* W) {
993 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +0000994 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +0000995 OS << "\n";
996 }
997
998 void VisitDoStmt(DoStmt* D) {
999 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001000 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001001 OS << '\n';
1002 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001003
Ted Kremenek65cfa562007-08-27 21:27:44 +00001004 void VisitSwitchStmt(SwitchStmt* S) {
1005 OS << "switch ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001006 S->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001007 OS << '\n';
1008 }
1009
Ted Kremenek621e1592007-08-31 21:49:40 +00001010 void VisitConditionalOperator(ConditionalOperator* C) {
1011 C->getCond()->printPretty(OS,Helper);
1012 OS << " ? ... : ...\n";
1013 }
1014
Ted Kremenek2025cc92007-08-31 22:29:13 +00001015 void VisitChooseExpr(ChooseExpr* C) {
1016 OS << "__builtin_choose_expr( ";
1017 C->getCond()->printPretty(OS,Helper);
1018 OS << " )\n";
1019 }
1020
Ted Kremenek86afc042007-08-31 22:26:13 +00001021 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1022 OS << "goto *";
1023 I->getTarget()->printPretty(OS,Helper);
1024 OS << '\n';
1025 }
1026
Ted Kremenek621e1592007-08-31 21:49:40 +00001027 void VisitBinaryOperator(BinaryOperator* B) {
1028 if (!B->isLogicalOp()) {
1029 VisitExpr(B);
1030 return;
1031 }
1032
1033 B->getLHS()->printPretty(OS,Helper);
1034
1035 switch (B->getOpcode()) {
1036 case BinaryOperator::LOr:
1037 OS << " || ...\n";
1038 return;
1039 case BinaryOperator::LAnd:
1040 OS << " && ...\n";
1041 return;
1042 default:
1043 assert(false && "Invalid logical operator.");
1044 }
1045 }
1046
Ted Kremenekcfaae762007-08-27 21:54:41 +00001047 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001048 E->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001049 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +00001050 }
Ted Kremenek73543912007-08-23 21:42:29 +00001051};
Ted Kremenek08176a52007-08-31 21:30:12 +00001052
1053
Ted Kremenek86afc042007-08-31 22:26:13 +00001054void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1055 if (Helper) {
1056 // special printing for statement-expressions.
1057 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1058 CompoundStmt* Sub = SE->getSubStmt();
1059
1060 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001061 OS << "({ ... ; ";
Ted Kremenek86afc042007-08-31 22:26:13 +00001062 Helper->handledStmt(*SE->getSubStmt()->child_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001063 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001064 return;
1065 }
1066 }
1067
1068 // special printing for comma expressions.
1069 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1070 if (B->getOpcode() == BinaryOperator::Comma) {
1071 OS << "... , ";
1072 Helper->handledStmt(B->getRHS(),OS);
1073 OS << '\n';
1074 return;
1075 }
1076 }
1077 }
1078
1079 S->printPretty(OS, Helper);
1080
1081 // Expressions need a newline.
1082 if (isa<Expr>(S)) OS << '\n';
1083}
1084
Ted Kremenek08176a52007-08-31 21:30:12 +00001085void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1086 StmtPrinterHelper* Helper, bool print_edges) {
1087
1088 if (Helper) Helper->setBlockID(B.getBlockID());
1089
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001090 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001091 OS << "\n [ B" << B.getBlockID();
1092
1093 if (&B == &cfg->getEntry())
1094 OS << " (ENTRY) ]\n";
1095 else if (&B == &cfg->getExit())
1096 OS << " (EXIT) ]\n";
1097 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001098 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001099 else
1100 OS << " ]\n";
1101
Ted Kremenekec055e12007-08-29 23:20:49 +00001102 // Print the label of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001103 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1104
1105 if (print_edges)
1106 OS << " ";
1107
Ted Kremenekec055e12007-08-29 23:20:49 +00001108 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1109 OS << L->getName();
1110 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1111 OS << "case ";
1112 C->getLHS()->printPretty(OS);
1113 if (C->getRHS()) {
1114 OS << " ... ";
1115 C->getRHS()->printPretty(OS);
1116 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001117 }
1118 else if (DefaultStmt* D = dyn_cast<DefaultStmt>(D))
Ted Kremenekec055e12007-08-29 23:20:49 +00001119 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001120 else
1121 assert(false && "Invalid label statement in CFGBlock.");
1122
Ted Kremenekec055e12007-08-29 23:20:49 +00001123 OS << ":\n";
1124 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001125
Ted Kremenek97f75312007-08-21 21:42:03 +00001126 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001127 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001128
1129 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1130 I != E ; ++I, ++j ) {
1131
Ted Kremenekec055e12007-08-29 23:20:49 +00001132 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001133 if (print_edges)
1134 OS << " ";
1135
1136 OS << std::setw(3) << j << ": ";
1137
1138 if (Helper)
1139 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001140
1141 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001142 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001143
Ted Kremenekec055e12007-08-29 23:20:49 +00001144 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001145 if (B.getTerminator()) {
1146 if (print_edges)
1147 OS << " ";
1148
Ted Kremenekec055e12007-08-29 23:20:49 +00001149 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001150
1151 if (Helper) Helper->setBlockID(-1);
1152
1153 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1154 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001155 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001156
Ted Kremenekec055e12007-08-29 23:20:49 +00001157 if (print_edges) {
1158 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001159 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001160 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001161
Ted Kremenek08176a52007-08-31 21:30:12 +00001162 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1163 I != E; ++I, ++i) {
1164
1165 if (i == 8 || (i-8) == 0)
1166 OS << "\n ";
1167
Ted Kremenekec055e12007-08-29 23:20:49 +00001168 OS << " B" << (*I)->getBlockID();
1169 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001170
1171 OS << '\n';
1172
1173 // Print the successors of this block.
1174 OS << " Successors (" << B.succ_size() << "):";
1175 i = 0;
1176
1177 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1178 I != E; ++I, ++i) {
1179
1180 if (i == 8 || (i-8) % 10 == 0)
1181 OS << "\n ";
1182
1183 OS << " B" << (*I)->getBlockID();
1184 }
1185
Ted Kremenekec055e12007-08-29 23:20:49 +00001186 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001187 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001188}
1189
1190} // end anonymous namespace
1191
1192/// dump - A simple pretty printer of a CFG that outputs to stderr.
1193void CFG::dump() const { print(std::cerr); }
1194
1195/// print - A simple pretty printer of a CFG that outputs to an ostream.
1196void CFG::print(std::ostream& OS) const {
1197
1198 StmtPrinterHelper Helper(this);
1199
1200 // Print the entry block.
1201 print_block(OS, this, getEntry(), &Helper, true);
1202
1203 // Iterate through the CFGBlocks and print them one by one.
1204 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1205 // Skip the entry block, because we already printed it.
1206 if (&(*I) == &getEntry() || &(*I) == &getExit())
1207 continue;
1208
1209 print_block(OS, this, *I, &Helper, true);
1210 }
1211
1212 // Print the exit block.
1213 print_block(OS, this, getExit(), &Helper, true);
1214}
1215
1216/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1217void CFGBlock::dump(const CFG* cfg) const { print(std::cerr, cfg); }
1218
1219/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1220/// Generally this will only be called from CFG::print.
1221void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1222 StmtPrinterHelper Helper(cfg);
1223 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001224}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001225
1226//===----------------------------------------------------------------------===//
1227// CFG Graphviz Visualization
1228//===----------------------------------------------------------------------===//
1229
Ted Kremenek08176a52007-08-31 21:30:12 +00001230
1231#ifndef NDEBUG
1232namespace {
1233 StmtPrinterHelper* GraphHelper;
1234}
1235#endif
1236
1237void CFG::viewCFG() const {
1238#ifndef NDEBUG
1239 StmtPrinterHelper H(this);
1240 GraphHelper = &H;
1241 llvm::ViewGraph(this,"CFG");
1242 GraphHelper = NULL;
1243#else
1244 std::cerr << "CFG::viewCFG is only available in debug builds on "
1245 << "systems with Graphviz or gv!" << std::endl;
1246#endif
1247}
1248
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001249namespace llvm {
1250template<>
1251struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1252 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1253
1254 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001255 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001256 std::string OutStr = Out.str();
1257
1258 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1259
1260 // Process string output to make it nicer...
1261 for (unsigned i = 0; i != OutStr.length(); ++i)
1262 if (OutStr[i] == '\n') { // Left justify
1263 OutStr[i] = '\\';
1264 OutStr.insert(OutStr.begin()+i+1, 'l');
1265 }
1266
1267 return OutStr;
1268 }
1269};
1270} // end namespace llvm