blob: eb39fdfc01d19538c126b1f7ab0e0b0d4c90216e [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//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek97f75312007-08-21 21:42:03 +00007//
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"
Ted Kremenek56c939e2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek5ee98a72008-01-11 00:40:29 +000024#include <set>
Ted Kremenek97f75312007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000027#include <sstream>
28
Ted Kremenek5ee98a72008-01-11 00:40:29 +000029
Ted Kremenek97f75312007-08-21 21:42:03 +000030using namespace clang;
31
32namespace {
33
Ted Kremenekd6e50602007-08-23 21:26:19 +000034// SaveAndRestore - A utility class that uses RIIA to save and restore
35// the value of a variable.
36template<typename T>
Ted Kremenek98cee3a2008-01-08 18:15:10 +000037struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000038 SaveAndRestore(T& x) : X(x), old_value(x) {}
39 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000040 T get() { return old_value; }
41
Ted Kremenekd6e50602007-08-23 21:26:19 +000042 T& X;
43 T old_value;
44};
Ted Kremenek97f75312007-08-21 21:42:03 +000045
46/// CFGBuilder - This class is implements CFG construction from an AST.
47/// The builder is stateful: an instance of the builder should be used to only
48/// construct a single CFG.
49///
50/// Example usage:
51///
52/// CFGBuilder builder;
53/// CFG* cfg = builder.BuildAST(stmt1);
54///
Ted Kremenek95e854d2007-08-21 22:06:14 +000055/// CFG construction is done via a recursive walk of an AST.
56/// We actually parse the AST in reverse order so that the successor
57/// of a basic block is constructed prior to its predecessor. This
58/// allows us to nicely capture implicit fall-throughs without extra
59/// basic blocks.
60///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000061class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000062 CFG* cfg;
63 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000064 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000065 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000066 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000067 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +000068 bool SwitchHasDefaultCase;
Ted Kremenek97f75312007-08-21 21:42:03 +000069
Ted Kremenek0edd3a92007-08-28 19:26:49 +000070 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000071 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
72 LabelMapTy LabelMap;
73
Ted Kremenek0edd3a92007-08-28 19:26:49 +000074 // A list of blocks that end with a "goto" that must be backpatched to
75 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000076 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000077 BackpatchBlocksTy BackpatchBlocks;
78
Ted Kremenek0edd3a92007-08-28 19:26:49 +000079 // A list of labels whose address has been taken (for indirect gotos).
80 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
81 LabelSetTy AddressTakenLabels;
82
Ted Kremenek97f75312007-08-21 21:42:03 +000083public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000084 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000085 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek14594572007-09-05 20:02:05 +000086 SwitchTerminatedBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000087 // Create an empty CFG.
88 cfg = new CFG();
89 }
90
91 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000092
Ted Kremenek73543912007-08-23 21:42:29 +000093 // buildCFG - Used by external clients to construct the CFG.
94 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000095
Ted Kremenek73543912007-08-23 21:42:29 +000096 // Visitors to walk an AST and construct the CFG. Called by
97 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000098
Ted Kremenek73543912007-08-23 21:42:29 +000099 CFGBlock* VisitStmt(Stmt* Statement);
100 CFGBlock* VisitNullStmt(NullStmt* Statement);
101 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
102 CFGBlock* VisitIfStmt(IfStmt* I);
103 CFGBlock* VisitReturnStmt(ReturnStmt* R);
104 CFGBlock* VisitLabelStmt(LabelStmt* L);
105 CFGBlock* VisitGotoStmt(GotoStmt* G);
106 CFGBlock* VisitForStmt(ForStmt* F);
107 CFGBlock* VisitWhileStmt(WhileStmt* W);
108 CFGBlock* VisitDoStmt(DoStmt* D);
109 CFGBlock* VisitContinueStmt(ContinueStmt* C);
110 CFGBlock* VisitBreakStmt(BreakStmt* B);
111 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
112 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000113 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000114 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000115
Ted Kremenek73543912007-08-23 21:42:29 +0000116private:
117 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000118 CFGBlock* addStmt(Stmt* S);
119 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
120 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000121 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000122 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekd11620d2007-09-11 21:29:43 +0000123 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenek73543912007-08-23 21:42:29 +0000124 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000125
Ted Kremenek97f75312007-08-21 21:42:03 +0000126};
Ted Kremenek73543912007-08-23 21:42:29 +0000127
128/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
129/// represent an arbitrary statement. Examples include a single expression
130/// or a function body (compound statement). The ownership of the returned
131/// CFG is transferred to the caller. If CFG construction fails, this method
132/// returns NULL.
133CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000134 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000135 if (!Statement) return NULL;
136
137 // Create an empty block that will serve as the exit block for the CFG.
138 // Since this is the first block added to the CFG, it will be implicitly
139 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000140 Succ = createBlock();
141 assert (Succ == &cfg->getExit());
142 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000143
144 // Visit the statements and create the CFG.
145 if (CFGBlock* B = Visit(Statement)) {
146 // Finalize the last constructed block. This usually involves
147 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000148 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000149
150 // Backpatch the gotos whose label -> block mappings we didn't know
151 // when we encountered them.
152 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
153 E = BackpatchBlocks.end(); I != E; ++I ) {
154
155 CFGBlock* B = *I;
156 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
157 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
158
159 // If there is no target for the goto, then we are looking at an
160 // incomplete AST. Handle this by not registering a successor.
161 if (LI == LabelMap.end()) continue;
162
163 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000164 }
Ted Kremenek73543912007-08-23 21:42:29 +0000165
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000166 // Add successors to the Indirect Goto Dispatch block (if we have one).
167 if (CFGBlock* B = cfg->getIndirectGotoBlock())
168 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
169 E = AddressTakenLabels.end(); I != E; ++I ) {
170
171 // Lookup the target block.
172 LabelMapTy::iterator LI = LabelMap.find(*I);
173
174 // If there is no target block that contains label, then we are looking
175 // at an incomplete AST. Handle this by not registering a successor.
176 if (LI == LabelMap.end()) continue;
177
178 B->addSuccessor(LI->second);
179 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000180
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000181 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000182 }
183
184 // Create an empty entry block that has no predecessors.
185 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000186
Ted Kremenek680fcb82007-09-26 21:23:31 +0000187 // NULL out cfg so that repeated calls to the builder will fail and that
188 // the ownership of the constructed CFG is passed to the caller.
189 CFG* t = cfg;
190 cfg = NULL;
191 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000192}
193
194/// createBlock - Used to lazily create blocks that are connected
195/// to the current (global) succcessor.
196CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000197 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000198 if (add_successor && Succ) B->addSuccessor(Succ);
199 return B;
200}
201
202/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000203/// we must reverse the statements because they have been inserted
204/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000205void CFGBuilder::FinishBlock(CFGBlock* B) {
206 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000207 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000208}
209
Ted Kremenek65cfa562007-08-27 21:27:44 +0000210/// addStmt - Used to add statements/expressions to the current CFGBlock
211/// "Block". This method calls WalkAST on the passed statement to see if it
212/// contains any short-circuit expressions. If so, it recursively creates
213/// the necessary blocks for such expressions. It returns the "topmost" block
214/// of the created blocks, or the original value of "Block" when this method
215/// was called if no additional blocks are created.
216CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000217 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-08-27 21:27:44 +0000218 return WalkAST(S,true);
219}
220
221/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000222/// add extra blocks for ternary operators, &&, and ||. We also
223/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek65cfa562007-08-27 21:27:44 +0000224CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
225 switch (S->getStmtClass()) {
226 case Stmt::ConditionalOperatorClass: {
227 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000228
229 // Create the confluence block that will "merge" the results
230 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000231 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
232 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000233 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000234
235 // Create a block for the LHS expression if there is an LHS expression.
236 // A GCC extension allows LHS to be NULL, causing the condition to
237 // be the value that is returned instead.
238 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000239 Succ = ConfluenceBlock;
240 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000241 CFGBlock* LHSBlock = NULL;
242 if (C->getLHS()) {
243 LHSBlock = Visit(C->getLHS());
244 FinishBlock(LHSBlock);
245 Block = NULL;
246 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000247
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000248 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000249 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000250 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000251 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000252
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000253 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000254 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000255
256 if (LHSBlock)
257 Block->addSuccessor(LHSBlock);
258 else {
259 // If we have no LHS expression, add the ConfluenceBlock as a direct
260 // successor for the block containing the condition. Moreover,
261 // we need to reverse the order of the predecessors in the
262 // ConfluenceBlock because the RHSBlock will have been added to
263 // the succcessors already, and we want the first predecessor to the
264 // the block containing the expression for the case when the ternary
265 // expression evaluates to true.
266 Block->addSuccessor(ConfluenceBlock);
267 assert (ConfluenceBlock->pred_size() == 2);
268 std::reverse(ConfluenceBlock->pred_begin(),
269 ConfluenceBlock->pred_end());
270 }
271
Ted Kremenek65cfa562007-08-27 21:27:44 +0000272 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000273
Ted Kremenek65cfa562007-08-27 21:27:44 +0000274 Block->setTerminator(C);
275 return addStmt(C->getCond());
276 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000277
278 case Stmt::ChooseExprClass: {
279 ChooseExpr* C = cast<ChooseExpr>(S);
280
281 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
282 ConfluenceBlock->appendStmt(C);
283 FinishBlock(ConfluenceBlock);
284
285 Succ = ConfluenceBlock;
286 Block = NULL;
287 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000288 FinishBlock(LHSBlock);
289
Ted Kremenek7f788422007-08-31 17:03:41 +0000290 Succ = ConfluenceBlock;
291 Block = NULL;
292 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000293 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000294
295 Block = createBlock(false);
296 Block->addSuccessor(LHSBlock);
297 Block->addSuccessor(RHSBlock);
298 Block->setTerminator(C);
299 return addStmt(C->getCond());
300 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000301
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000302 case Stmt::DeclStmtClass: {
303 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
304 Block->appendStmt(S);
305
306 StmtIterator I(D);
307 return WalkAST_VisitDeclSubExprs(I);
308 }
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000309
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000310 case Stmt::AddrLabelExprClass: {
311 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
312 AddressTakenLabels.insert(A->getLabel());
313
314 if (AlwaysAddStmt) Block->appendStmt(S);
315 return Block;
316 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000317
318 case Stmt::CallExprClass:
319 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000320
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000321 case Stmt::StmtExprClass:
322 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000323
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000324 case Stmt::UnaryOperatorClass: {
325 UnaryOperator* U = cast<UnaryOperator>(S);
326
327 // sizeof(expressions). For such expressions,
328 // the subexpression is not really evaluated, so
329 // we don't care about control-flow within the sizeof.
330 if (U->getOpcode() == UnaryOperator::SizeOf) {
331 Block->appendStmt(S);
332 return Block;
333 }
334
335 break;
336 }
337
Ted Kremenekcfaae762007-08-27 21:54:41 +0000338 case Stmt::BinaryOperatorClass: {
339 BinaryOperator* B = cast<BinaryOperator>(S);
340
341 if (B->isLogicalOp()) { // && or ||
342 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
343 ConfluenceBlock->appendStmt(B);
344 FinishBlock(ConfluenceBlock);
345
346 // create the block evaluating the LHS
347 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000348 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000349
350 // create the block evaluating the RHS
351 Succ = ConfluenceBlock;
352 Block = NULL;
353 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000354
355 // Now link the LHSBlock with RHSBlock.
356 if (B->getOpcode() == BinaryOperator::LOr) {
357 LHSBlock->addSuccessor(ConfluenceBlock);
358 LHSBlock->addSuccessor(RHSBlock);
359 }
360 else {
361 assert (B->getOpcode() == BinaryOperator::LAnd);
362 LHSBlock->addSuccessor(RHSBlock);
363 LHSBlock->addSuccessor(ConfluenceBlock);
364 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000365
366 // Generate the blocks for evaluating the LHS.
367 Block = LHSBlock;
368 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000369 }
370 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
371 Block->appendStmt(B);
372 addStmt(B->getRHS());
373 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000374 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000375
376 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000377 }
378
Ted Kremenek65cfa562007-08-27 21:27:44 +0000379 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000380 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000381 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000382
383 if (AlwaysAddStmt) Block->appendStmt(S);
384 return WalkAST_VisitChildren(S);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000385}
386
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000387/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
388/// DeclStmts. Because the initialization code (and sometimes the
389/// the type declarations) for DeclStmts can contain arbitrary expressions,
390/// we must linearize declarations to handle arbitrary control-flow induced by
391/// those expressions.
392CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000393 if (I == StmtIterator())
394 return Block;
395
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000396 Stmt* S = *I;
397 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000398 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000399
400 Block = addStmt(S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000401 return Block;
402}
403
Ted Kremenek65cfa562007-08-27 21:27:44 +0000404/// WalkAST_VisitChildren - Utility method to call WalkAST on the
405/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000406CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000407 CFGBlock* B = Block;
408 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
409 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000410 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000411
412 return B;
413}
414
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000415/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
416/// expressions (a GCC extension).
417CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
418 Block->appendStmt(S);
419 return VisitCompoundStmt(S->getSubStmt());
420}
421
Ted Kremenekd11620d2007-09-11 21:29:43 +0000422/// WalkAST_VisitCallExpr - Utility method to handle function calls that
423/// are nested in expressions. The idea is that each function call should
424/// appear as a distinct statement in the CFGBlock.
425CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
426 Block->appendStmt(C);
427 return WalkAST_VisitChildren(C);
428}
429
Ted Kremenek73543912007-08-23 21:42:29 +0000430/// VisitStmt - Handle statements with no branching control flow.
431CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
432 // We cannot assume that we are in the middle of a basic block, since
433 // the CFG might only be constructed for this single statement. If
434 // we have no current basic block, just create one lazily.
435 if (!Block) Block = createBlock();
436
437 // Simply add the statement to the current block. We actually
438 // insert statements in reverse order; this order is reversed later
439 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000440 addStmt(Statement);
441
Ted Kremenek73543912007-08-23 21:42:29 +0000442 return Block;
443}
444
445CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
446 return Block;
447}
448
449CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
450 // The value returned from this function is the last created CFGBlock
451 // that represents the "entry" point for the translated AST node.
Chris Lattner265c8172007-09-27 15:15:46 +0000452 CFGBlock* LastBlock = 0;
Ted Kremenek73543912007-08-23 21:42:29 +0000453
454 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
455 E = C->body_rend(); I != E; ++I )
456 // Add the statement to the current block.
457 if (!(LastBlock=Visit(*I)))
458 return NULL;
459
460 return LastBlock;
461}
462
463CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
464 // We may see an if statement in the middle of a basic block, or
465 // it may be the first statement we are processing. In either case,
466 // we create a new basic block. First, we create the blocks for
467 // the then...else statements, and then we create the block containing
468 // the if statement. If we were in the middle of a block, we
469 // stop processing that block and reverse its statements. That block
470 // is then the implicit successor for the "then" and "else" clauses.
471
472 // The block we were proccessing is now finished. Make it the
473 // successor block.
474 if (Block) {
475 Succ = Block;
476 FinishBlock(Block);
477 }
478
479 // Process the false branch. NULL out Block so that the recursive
480 // call to Visit will create a new basic block.
481 // Null out Block so that all successor
482 CFGBlock* ElseBlock = Succ;
483
484 if (Stmt* Else = I->getElse()) {
485 SaveAndRestore<CFGBlock*> sv(Succ);
486
487 // NULL out Block so that the recursive call to Visit will
488 // create a new basic block.
489 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000490 ElseBlock = Visit(Else);
491
492 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
493 ElseBlock = sv.get();
494 else if (Block)
495 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000496 }
497
498 // Process the true branch. NULL out Block so that the recursive
499 // call to Visit will create a new basic block.
500 // Null out Block so that all successor
501 CFGBlock* ThenBlock;
502 {
503 Stmt* Then = I->getThen();
504 assert (Then);
505 SaveAndRestore<CFGBlock*> sv(Succ);
506 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000507 ThenBlock = Visit(Then);
508
509 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
510 ThenBlock = sv.get();
511 else if (Block)
512 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000513 }
514
515 // Now create a new block containing the if statement.
516 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000517
518 // Set the terminator of the new block to the If statement.
519 Block->setTerminator(I);
520
521 // Now add the successors.
522 Block->addSuccessor(ThenBlock);
523 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000524
525 // Add the condition as the last statement in the new block. This
526 // may create new blocks as the condition may contain control-flow. Any
527 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000528 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000529}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000530
Ted Kremenek73543912007-08-23 21:42:29 +0000531
532CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
533 // If we were in the middle of a block we stop processing that block
534 // and reverse its statements.
535 //
536 // NOTE: If a "return" appears in the middle of a block, this means
537 // that the code afterwards is DEAD (unreachable). We still
538 // keep a basic block for that code; a simple "mark-and-sweep"
539 // from the entry block will be able to report such dead
540 // blocks.
541 if (Block) FinishBlock(Block);
542
543 // Create the new block.
544 Block = createBlock(false);
545
546 // The Exit block is the only successor.
547 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000548
549 // Add the return statement to the block. This may create new blocks
550 // if R contains control-flow (short-circuit operations).
551 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000552}
553
554CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
555 // Get the block of the labeled statement. Add it to our map.
556 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000557
558 if (!LabelBlock) // This can happen when the body is empty, i.e.
559 LabelBlock=createBlock(); // scopes that only contains NullStmts.
560
Ted Kremenek73543912007-08-23 21:42:29 +0000561 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
562 LabelMap[ L ] = LabelBlock;
563
564 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000565 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000566 // label (and we have already processed the substatement) there is no
567 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000568 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000569 FinishBlock(LabelBlock);
570
571 // We set Block to NULL to allow lazy creation of a new block
572 // (if necessary);
573 Block = NULL;
574
575 // This block is now the implicit successor of other blocks.
576 Succ = LabelBlock;
577
578 return LabelBlock;
579}
580
581CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
582 // Goto is a control-flow statement. Thus we stop processing the
583 // current block and create a new one.
584 if (Block) FinishBlock(Block);
585 Block = createBlock(false);
586 Block->setTerminator(G);
587
588 // If we already know the mapping to the label block add the
589 // successor now.
590 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
591
592 if (I == LabelMap.end())
593 // We will need to backpatch this block later.
594 BackpatchBlocks.push_back(Block);
595 else
596 Block->addSuccessor(I->second);
597
598 return Block;
599}
600
601CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
602 // "for" is a control-flow statement. Thus we stop processing the
603 // current block.
604
605 CFGBlock* LoopSuccessor = NULL;
606
607 if (Block) {
608 FinishBlock(Block);
609 LoopSuccessor = Block;
610 }
611 else LoopSuccessor = Succ;
612
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000613 // Because of short-circuit evaluation, the condition of the loop
614 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
615 // blocks that evaluate the condition.
616 CFGBlock* ExitConditionBlock = createBlock(false);
617 CFGBlock* EntryConditionBlock = ExitConditionBlock;
618
619 // Set the terminator for the "exit" condition block.
620 ExitConditionBlock->setTerminator(F);
621
622 // Now add the actual condition to the condition block. Because the
623 // condition itself may contain control-flow, new blocks may be created.
624 if (Stmt* C = F->getCond()) {
625 Block = ExitConditionBlock;
626 EntryConditionBlock = addStmt(C);
627 if (Block) FinishBlock(EntryConditionBlock);
628 }
Ted Kremenek73543912007-08-23 21:42:29 +0000629
630 // The condition block is the implicit successor for the loop body as
631 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000632 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000633
634 // Now create the loop body.
635 {
636 assert (F->getBody());
637
638 // Save the current values for Block, Succ, and continue and break targets
639 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
640 save_continue(ContinueTargetBlock),
641 save_break(BreakTargetBlock);
642
643 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000644 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000645
646 // All breaks should go to the code following the loop.
647 BreakTargetBlock = LoopSuccessor;
648
Ted Kremenek390b9762007-08-30 18:39:40 +0000649 // Create a new block to contain the (bottom) of the loop body.
650 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000651
652 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000653 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000654
655 // Now populate the body block, and in the process create new blocks
656 // as we walk the body of the loop.
657 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000658
659 if (!BodyBlock)
660 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
661 else if (Block)
662 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000663
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000664 // This new body block is a successor to our "exit" condition block.
665 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000666 }
667
668 // Link up the condition block with the code that follows the loop.
669 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000670 ExitConditionBlock->addSuccessor(LoopSuccessor);
671
Ted Kremenek73543912007-08-23 21:42:29 +0000672 // If the loop contains initialization, create a new block for those
673 // statements. This block can also contain statements that precede
674 // the loop.
675 if (Stmt* I = F->getInit()) {
676 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000677 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000678 }
679 else {
680 // There is no loop initialization. We are thus basically a while
681 // loop. NULL out Block to force lazy block construction.
682 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000683 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000684 }
685}
686
687CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
688 // "while" is a control-flow statement. Thus we stop processing the
689 // current block.
690
691 CFGBlock* LoopSuccessor = NULL;
692
693 if (Block) {
694 FinishBlock(Block);
695 LoopSuccessor = Block;
696 }
697 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000698
699 // Because of short-circuit evaluation, the condition of the loop
700 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
701 // blocks that evaluate the condition.
702 CFGBlock* ExitConditionBlock = createBlock(false);
703 CFGBlock* EntryConditionBlock = ExitConditionBlock;
704
705 // Set the terminator for the "exit" condition block.
706 ExitConditionBlock->setTerminator(W);
707
708 // Now add the actual condition to the condition block. Because the
709 // condition itself may contain control-flow, new blocks may be created.
710 // Thus we update "Succ" after adding the condition.
711 if (Stmt* C = W->getCond()) {
712 Block = ExitConditionBlock;
713 EntryConditionBlock = addStmt(C);
714 if (Block) FinishBlock(EntryConditionBlock);
715 }
Ted Kremenek73543912007-08-23 21:42:29 +0000716
717 // The condition block is the implicit successor for the loop body as
718 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000719 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000720
721 // Process the loop body.
722 {
723 assert (W->getBody());
724
725 // Save the current values for Block, Succ, and continue and break targets
726 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
727 save_continue(ContinueTargetBlock),
728 save_break(BreakTargetBlock);
729
730 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000731 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000732
733 // All breaks should go to the code following the loop.
734 BreakTargetBlock = LoopSuccessor;
735
736 // NULL out Block to force lazy instantiation of blocks for the body.
737 Block = NULL;
738
739 // Create the body. The returned block is the entry to the loop body.
740 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000741
742 if (!BodyBlock)
743 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
744 else if (Block)
745 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000746
747 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000748 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000749 }
750
751 // Link up the condition block with the code that follows the loop.
752 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000753 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000754
755 // There can be no more statements in the condition block
756 // since we loop back to this block. NULL out Block to force
757 // lazy creation of another block.
758 Block = NULL;
759
760 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000761 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000762}
763
764CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
765 // "do...while" is a control-flow statement. Thus we stop processing the
766 // current block.
767
768 CFGBlock* LoopSuccessor = NULL;
769
770 if (Block) {
771 FinishBlock(Block);
772 LoopSuccessor = Block;
773 }
774 else LoopSuccessor = Succ;
775
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000776 // Because of short-circuit evaluation, the condition of the loop
777 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
778 // blocks that evaluate the condition.
779 CFGBlock* ExitConditionBlock = createBlock(false);
780 CFGBlock* EntryConditionBlock = ExitConditionBlock;
781
782 // Set the terminator for the "exit" condition block.
783 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000784
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000785 // Now add the actual condition to the condition block. Because the
786 // condition itself may contain control-flow, new blocks may be created.
787 if (Stmt* C = D->getCond()) {
788 Block = ExitConditionBlock;
789 EntryConditionBlock = addStmt(C);
790 if (Block) FinishBlock(EntryConditionBlock);
791 }
Ted Kremenek73543912007-08-23 21:42:29 +0000792
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000793 // The condition block is the implicit successor for the loop body as
794 // well as any code above the loop.
795 Succ = EntryConditionBlock;
796
797
Ted Kremenek73543912007-08-23 21:42:29 +0000798 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000799 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000800 {
801 assert (D->getBody());
802
803 // Save the current values for Block, Succ, and continue and break targets
804 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
805 save_continue(ContinueTargetBlock),
806 save_break(BreakTargetBlock);
807
808 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000809 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000810
811 // All breaks should go to the code following the loop.
812 BreakTargetBlock = LoopSuccessor;
813
814 // NULL out Block to force lazy instantiation of blocks for the body.
815 Block = NULL;
816
817 // Create the body. The returned block is the entry to the loop body.
818 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000819
Ted Kremenek390b9762007-08-30 18:39:40 +0000820 if (!BodyBlock)
821 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
822 else if (Block)
823 FinishBlock(BodyBlock);
824
Ted Kremenek73543912007-08-23 21:42:29 +0000825 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000826 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000827 }
828
829 // Link up the condition block with the code that follows the loop.
830 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000831 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000832
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000833 // There can be no more statements in the body block(s)
834 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000835 // lazy creation of another block.
836 Block = NULL;
837
838 // Return the loop body, which is the dominating block for the loop.
839 return BodyBlock;
840}
841
842CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
843 // "continue" is a control-flow statement. Thus we stop processing the
844 // current block.
845 if (Block) FinishBlock(Block);
846
847 // Now create a new block that ends with the continue statement.
848 Block = createBlock(false);
849 Block->setTerminator(C);
850
851 // If there is no target for the continue, then we are looking at an
852 // incomplete AST. Handle this by not registering a successor.
853 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
854
855 return Block;
856}
857
858CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
859 // "break" is a control-flow statement. Thus we stop processing the
860 // current block.
861 if (Block) FinishBlock(Block);
862
863 // Now create a new block that ends with the continue statement.
864 Block = createBlock(false);
865 Block->setTerminator(B);
866
867 // If there is no target for the break, then we are looking at an
868 // incomplete AST. Handle this by not registering a successor.
869 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
870
871 return Block;
872}
873
874CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
875 // "switch" is a control-flow statement. Thus we stop processing the
876 // current block.
877 CFGBlock* SwitchSuccessor = NULL;
878
879 if (Block) {
880 FinishBlock(Block);
881 SwitchSuccessor = Block;
882 }
883 else SwitchSuccessor = Succ;
884
885 // Save the current "switch" context.
886 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
887 save_break(BreakTargetBlock);
888
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000889 SaveAndRestore<bool> save_has_default_case(SwitchHasDefaultCase);
890 SwitchHasDefaultCase = false;
891
Ted Kremenek73543912007-08-23 21:42:29 +0000892 // Create a new block that will contain the switch statement.
893 SwitchTerminatedBlock = createBlock(false);
894
Ted Kremenek73543912007-08-23 21:42:29 +0000895 // Now process the switch body. The code after the switch is the implicit
896 // successor.
897 Succ = SwitchSuccessor;
898 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000899
900 // When visiting the body, the case statements should automatically get
901 // linked up to the switch. We also don't keep a pointer to the body,
902 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000903 assert (S->getBody() && "switch must contain a non-NULL body");
904 Block = NULL;
905 CFGBlock *BodyBlock = Visit(S->getBody());
906 if (Block) FinishBlock(BodyBlock);
907
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000908 // If we have no "default:" case, the default transition is to the
909 // code following the switch body.
910 if (!SwitchHasDefaultCase)
911 SwitchTerminatedBlock->addSuccessor(SwitchSuccessor);
912
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000913 // Add the terminator and condition in the switch block.
914 SwitchTerminatedBlock->setTerminator(S);
915 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000916 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000917
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000918 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000919}
920
921CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
922 // A SwitchCase is either a "default" or "case" statement. We handle
923 // both in the same way. They are essentially labels, so they are the
924 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000925
926 if (S->getSubStmt()) Visit(S->getSubStmt());
927 CFGBlock* CaseBlock = Block;
928 if (!CaseBlock) CaseBlock = createBlock();
929
Ted Kremenekec055e12007-08-29 23:20:49 +0000930 // Cases/Default statements partition block, so this is the top of
931 // the basic block we were processing (the case/default is the label).
932 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000933 FinishBlock(CaseBlock);
934
935 // Add this block to the list of successors for the block with the
936 // switch statement.
937 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
938
939 // We set Block to NULL to allow lazy creation of a new block (if necessary)
940 Block = NULL;
941
942 // This block is now the implicit successor of other blocks.
943 Succ = CaseBlock;
944
945 return CaseBlock;
946}
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000947
948CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* D) {
949 SwitchHasDefaultCase = true;
950 return VisitSwitchCase(D);
951}
Ted Kremenek73543912007-08-23 21:42:29 +0000952
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000953CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
954 // Lazily create the indirect-goto dispatch block if there isn't one
955 // already.
956 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
957
958 if (!IBlock) {
959 IBlock = createBlock(false);
960 cfg->setIndirectGotoBlock(IBlock);
961 }
962
963 // IndirectGoto is a control-flow statement. Thus we stop processing the
964 // current block and create a new one.
965 if (Block) FinishBlock(Block);
966 Block = createBlock(false);
967 Block->setTerminator(I);
968 Block->addSuccessor(IBlock);
969 return addStmt(I->getTarget());
970}
971
Ted Kremenek73543912007-08-23 21:42:29 +0000972
Ted Kremenekd6e50602007-08-23 21:26:19 +0000973} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000974
975/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
976/// block has no successors or predecessors. If this is the first block
977/// created in the CFG, it is automatically set to be the Entry and Exit
978/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +0000979CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000980 bool first_block = begin() == end();
981
982 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +0000983 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +0000984
985 // If this is the first block, set it as the Entry and Exit.
986 if (first_block) Entry = Exit = &front();
987
988 // Return the block.
989 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000990}
991
Ted Kremenek4db5b452007-08-23 16:51:22 +0000992/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
993/// CFG is returned to the caller.
994CFG* CFG::buildCFG(Stmt* Statement) {
995 CFGBuilder Builder;
996 return Builder.buildCFG(Statement);
997}
998
999/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001000void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1001
Ted Kremenek3a819822007-10-01 19:33:33 +00001002//===----------------------------------------------------------------------===//
1003// CFG: Queries for BlkExprs.
1004//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001005
Ted Kremenek3a819822007-10-01 19:33:33 +00001006namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001007 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001008}
1009
Ted Kremenekc6fda602008-01-26 00:03:27 +00001010static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1011 if (!S)
1012 return;
1013
1014 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1015 if (!*I) continue;
1016
1017 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1018 if (B->isAssignmentOp()) Set.insert(B);
1019
1020 FindSubExprAssignments(*I, Set);
1021 }
1022}
1023
Ted Kremenek3a819822007-10-01 19:33:33 +00001024static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1025 BlkExprMapTy* M = new BlkExprMapTy();
1026
Ted Kremenekc6fda602008-01-26 00:03:27 +00001027 // Look for assignments that are used as subexpressions. These are the
1028 // only assignments that we want to register as a block-level expression.
1029 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1030
Ted Kremenek3a819822007-10-01 19:33:33 +00001031 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1032 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001033 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001034
Ted Kremenekc6fda602008-01-26 00:03:27 +00001035 // Iterate over the statements again on identify the Expr* and Stmt* at
1036 // the block-level that are block-level expressions.
1037 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1038 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1039 if (Expr* E = dyn_cast<Expr>(*BI)) {
1040
1041 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1042 // Assignment expressions that are not nested within another
1043 // expression are really "statements" whose value is never
1044 // used by another expression.
1045 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1046 continue;
1047 }
1048 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1049 // Special handling for statement expressions. The last statement
1050 // in the statement expression is also a block-level expr.
Ted Kremenekab6c5902008-01-17 20:48:37 +00001051 const CompoundStmt* C = S->getSubStmt();
1052 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001053 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001054 (*M)[C->body_back()] = x;
1055 }
1056 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001057
Ted Kremenekc6fda602008-01-26 00:03:27 +00001058 unsigned x = M->size();
1059 (*M)[E] = x;
1060 }
1061
Ted Kremenek3a819822007-10-01 19:33:33 +00001062 return M;
1063}
1064
Ted Kremenekab6c5902008-01-17 20:48:37 +00001065CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1066 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001067 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1068
1069 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001070 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001071
1072 if (I == M->end()) return CFG::BlkExprNumTy();
1073 else return CFG::BlkExprNumTy(I->second);
1074}
1075
1076unsigned CFG::getNumBlkExprs() {
1077 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1078 return M->size();
1079 else {
1080 // We assume callers interested in the number of BlkExprs will want
1081 // the map constructed if it doesn't already exist.
1082 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1083 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1084 }
1085}
1086
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001087typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1088
1089const std::pair<CFGBlock*,CFGBlock*>*
1090CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1091
1092 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1093 if (!p) p = new BlkEdgeSetTy();
1094
1095 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1096 const_cast<CFGBlock*>(B2))).first);
1097}
1098
Ted Kremenek3a819822007-10-01 19:33:33 +00001099CFG::~CFG() {
1100 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001101 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001102}
1103
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001104//===----------------------------------------------------------------------===//
1105// CFG pretty printing
1106//===----------------------------------------------------------------------===//
1107
Ted Kremenekd8313202007-08-22 18:22:34 +00001108namespace {
1109
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001110class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001111
Ted Kremenek08176a52007-08-31 21:30:12 +00001112 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1113 StmtMapTy StmtMap;
1114 signed CurrentBlock;
1115 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001116
Ted Kremenek73543912007-08-23 21:42:29 +00001117public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001118
Ted Kremenek08176a52007-08-31 21:30:12 +00001119 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1120 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1121 unsigned j = 1;
1122 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1123 BI != BEnd; ++BI, ++j )
1124 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1125 }
1126 }
1127
1128 virtual ~StmtPrinterHelper() {}
1129
1130 void setBlockID(signed i) { CurrentBlock = i; }
1131 void setStmtID(unsigned i) { CurrentStmt = i; }
1132
Ted Kremenek86afc042007-08-31 22:26:13 +00001133 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1134
1135 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek08176a52007-08-31 21:30:12 +00001136
1137 if (I == StmtMap.end())
1138 return false;
1139
1140 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1141 && I->second.second == CurrentStmt)
1142 return false;
1143
Ted Kremenek86afc042007-08-31 22:26:13 +00001144 OS << "[B" << I->second.first << "." << I->second.second << "]";
1145 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001146 }
1147};
1148
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001149class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1150 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1151
Ted Kremenek08176a52007-08-31 21:30:12 +00001152 std::ostream& OS;
1153 StmtPrinterHelper* Helper;
1154public:
1155 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1156 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001157
1158 void VisitIfStmt(IfStmt* I) {
1159 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001160 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001161 }
1162
1163 // Default case.
Ted Kremenek621e1592007-08-31 21:49:40 +00001164 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001165
1166 void VisitForStmt(ForStmt* F) {
1167 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001168 if (F->getInit()) OS << "...";
1169 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001170 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001171 OS << "; ";
1172 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001173 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001174 }
1175
1176 void VisitWhileStmt(WhileStmt* W) {
1177 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001178 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001179 }
1180
1181 void VisitDoStmt(DoStmt* D) {
1182 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001183 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001184 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001185
Ted Kremenek65cfa562007-08-27 21:27:44 +00001186 void VisitSwitchStmt(SwitchStmt* S) {
1187 OS << "switch ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001188 S->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001189 }
1190
Ted Kremenek621e1592007-08-31 21:49:40 +00001191 void VisitConditionalOperator(ConditionalOperator* C) {
1192 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001193 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001194 }
1195
Ted Kremenek2025cc92007-08-31 22:29:13 +00001196 void VisitChooseExpr(ChooseExpr* C) {
1197 OS << "__builtin_choose_expr( ";
1198 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001199 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001200 }
1201
Ted Kremenek86afc042007-08-31 22:26:13 +00001202 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1203 OS << "goto *";
1204 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001205 }
1206
Ted Kremenek621e1592007-08-31 21:49:40 +00001207 void VisitBinaryOperator(BinaryOperator* B) {
1208 if (!B->isLogicalOp()) {
1209 VisitExpr(B);
1210 return;
1211 }
1212
1213 B->getLHS()->printPretty(OS,Helper);
1214
1215 switch (B->getOpcode()) {
1216 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001217 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001218 return;
1219 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001220 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001221 return;
1222 default:
1223 assert(false && "Invalid logical operator.");
1224 }
1225 }
1226
Ted Kremenekcfaae762007-08-27 21:54:41 +00001227 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001228 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001229 }
Ted Kremenek73543912007-08-23 21:42:29 +00001230};
Ted Kremenek08176a52007-08-31 21:30:12 +00001231
1232
Ted Kremenek86afc042007-08-31 22:26:13 +00001233void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1234 if (Helper) {
1235 // special printing for statement-expressions.
1236 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1237 CompoundStmt* Sub = SE->getSubStmt();
1238
1239 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001240 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001241 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001242 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001243 return;
1244 }
1245 }
1246
1247 // special printing for comma expressions.
1248 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1249 if (B->getOpcode() == BinaryOperator::Comma) {
1250 OS << "... , ";
1251 Helper->handledStmt(B->getRHS(),OS);
1252 OS << '\n';
1253 return;
1254 }
1255 }
1256 }
1257
1258 S->printPretty(OS, Helper);
1259
1260 // Expressions need a newline.
1261 if (isa<Expr>(S)) OS << '\n';
1262}
1263
Ted Kremenek08176a52007-08-31 21:30:12 +00001264void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1265 StmtPrinterHelper* Helper, bool print_edges) {
1266
1267 if (Helper) Helper->setBlockID(B.getBlockID());
1268
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001269 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001270 OS << "\n [ B" << B.getBlockID();
1271
1272 if (&B == &cfg->getEntry())
1273 OS << " (ENTRY) ]\n";
1274 else if (&B == &cfg->getExit())
1275 OS << " (EXIT) ]\n";
1276 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001277 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001278 else
1279 OS << " ]\n";
1280
Ted Kremenekec055e12007-08-29 23:20:49 +00001281 // Print the label of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001282 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1283
1284 if (print_edges)
1285 OS << " ";
1286
Ted Kremenekec055e12007-08-29 23:20:49 +00001287 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1288 OS << L->getName();
1289 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1290 OS << "case ";
1291 C->getLHS()->printPretty(OS);
1292 if (C->getRHS()) {
1293 OS << " ... ";
1294 C->getRHS()->printPretty(OS);
1295 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001296 }
Chris Lattner1501e122007-09-16 19:11:53 +00001297 else if (isa<DefaultStmt>(S))
Ted Kremenekec055e12007-08-29 23:20:49 +00001298 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001299 else
1300 assert(false && "Invalid label statement in CFGBlock.");
1301
Ted Kremenekec055e12007-08-29 23:20:49 +00001302 OS << ":\n";
1303 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001304
Ted Kremenek97f75312007-08-21 21:42:03 +00001305 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001306 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001307
1308 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1309 I != E ; ++I, ++j ) {
1310
Ted Kremenekec055e12007-08-29 23:20:49 +00001311 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001312 if (print_edges)
1313 OS << " ";
1314
1315 OS << std::setw(3) << j << ": ";
1316
1317 if (Helper)
1318 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001319
1320 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001321 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001322
Ted Kremenekec055e12007-08-29 23:20:49 +00001323 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001324 if (B.getTerminator()) {
1325 if (print_edges)
1326 OS << " ";
1327
Ted Kremenekec055e12007-08-29 23:20:49 +00001328 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001329
1330 if (Helper) Helper->setBlockID(-1);
1331
1332 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1333 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001334 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001335 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001336
Ted Kremenekec055e12007-08-29 23:20:49 +00001337 if (print_edges) {
1338 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001339 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001340 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001341
Ted Kremenek08176a52007-08-31 21:30:12 +00001342 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1343 I != E; ++I, ++i) {
1344
1345 if (i == 8 || (i-8) == 0)
1346 OS << "\n ";
1347
Ted Kremenekec055e12007-08-29 23:20:49 +00001348 OS << " B" << (*I)->getBlockID();
1349 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001350
1351 OS << '\n';
1352
1353 // Print the successors of this block.
1354 OS << " Successors (" << B.succ_size() << "):";
1355 i = 0;
1356
1357 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1358 I != E; ++I, ++i) {
1359
1360 if (i == 8 || (i-8) % 10 == 0)
1361 OS << "\n ";
1362
1363 OS << " B" << (*I)->getBlockID();
1364 }
1365
Ted Kremenekec055e12007-08-29 23:20:49 +00001366 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001367 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001368}
1369
1370} // end anonymous namespace
1371
1372/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001373void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001374
1375/// print - A simple pretty printer of a CFG that outputs to an ostream.
1376void CFG::print(std::ostream& OS) const {
1377
1378 StmtPrinterHelper Helper(this);
1379
1380 // Print the entry block.
1381 print_block(OS, this, getEntry(), &Helper, true);
1382
1383 // Iterate through the CFGBlocks and print them one by one.
1384 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1385 // Skip the entry block, because we already printed it.
1386 if (&(*I) == &getEntry() || &(*I) == &getExit())
1387 continue;
1388
1389 print_block(OS, this, *I, &Helper, true);
1390 }
1391
1392 // Print the exit block.
1393 print_block(OS, this, getExit(), &Helper, true);
1394}
1395
1396/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001397void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001398
1399/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1400/// Generally this will only be called from CFG::print.
1401void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1402 StmtPrinterHelper Helper(cfg);
1403 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001404}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001405
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001406/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1407void CFGBlock::printTerminator(std::ostream& OS) const {
1408 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1409 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1410}
1411
1412
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001413//===----------------------------------------------------------------------===//
1414// CFG Graphviz Visualization
1415//===----------------------------------------------------------------------===//
1416
Ted Kremenek08176a52007-08-31 21:30:12 +00001417
1418#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001419static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001420#endif
1421
1422void CFG::viewCFG() const {
1423#ifndef NDEBUG
1424 StmtPrinterHelper H(this);
1425 GraphHelper = &H;
1426 llvm::ViewGraph(this,"CFG");
1427 GraphHelper = NULL;
1428#else
1429 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser284bff92007-09-17 12:29:55 +00001430 << "systems with Graphviz or gv!\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001431#endif
1432}
1433
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001434namespace llvm {
1435template<>
1436struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1437 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1438
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001439#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001440 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001441 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001442 std::string OutStr = Out.str();
1443
1444 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1445
1446 // Process string output to make it nicer...
1447 for (unsigned i = 0; i != OutStr.length(); ++i)
1448 if (OutStr[i] == '\n') { // Left justify
1449 OutStr[i] = '\\';
1450 OutStr.insert(OutStr.begin()+i+1, 'l');
1451 }
1452
1453 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001454#else
1455 return "";
1456#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001457 }
1458};
1459} // end namespace llvm