blob: 3ea531361947bb9988f6785b8e0de4f781149607 [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 Kremenek97bc3422008-02-13 22:05:39 +000068 CFGBlock* DefaultCaseBlock;
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 Kremenek97bc3422008-02-13 22:05:39 +000086 SwitchTerminatedBlock(NULL), DefaultCaseBlock(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);
Ted Kremenek97bc3422008-02-13 22:05:39 +0000112 CFGBlock* VisitCaseStmt(CaseStmt* 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 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000378
379 case Stmt::ParenExprClass:
380 return WalkAST(cast<ParenExpr>(S)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000381
Ted Kremenek65cfa562007-08-27 21:27:44 +0000382 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000383 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000384 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000385
386 if (AlwaysAddStmt) Block->appendStmt(S);
387 return WalkAST_VisitChildren(S);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000388}
389
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000390/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
391/// DeclStmts. Because the initialization code (and sometimes the
392/// the type declarations) for DeclStmts can contain arbitrary expressions,
393/// we must linearize declarations to handle arbitrary control-flow induced by
394/// those expressions.
395CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000396 if (I == StmtIterator())
397 return Block;
398
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000399 Stmt* S = *I;
400 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000401 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000402
403 Block = addStmt(S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000404 return Block;
405}
406
Ted Kremenek65cfa562007-08-27 21:27:44 +0000407/// WalkAST_VisitChildren - Utility method to call WalkAST on the
408/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000409CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000410 CFGBlock* B = Block;
411 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
412 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000413 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000414
415 return B;
416}
417
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000418/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
419/// expressions (a GCC extension).
420CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
421 Block->appendStmt(S);
422 return VisitCompoundStmt(S->getSubStmt());
423}
424
Ted Kremenekd11620d2007-09-11 21:29:43 +0000425/// WalkAST_VisitCallExpr - Utility method to handle function calls that
426/// are nested in expressions. The idea is that each function call should
427/// appear as a distinct statement in the CFGBlock.
428CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
429 Block->appendStmt(C);
430 return WalkAST_VisitChildren(C);
431}
432
Ted Kremenek73543912007-08-23 21:42:29 +0000433/// VisitStmt - Handle statements with no branching control flow.
434CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
435 // We cannot assume that we are in the middle of a basic block, since
436 // the CFG might only be constructed for this single statement. If
437 // we have no current basic block, just create one lazily.
438 if (!Block) Block = createBlock();
439
440 // Simply add the statement to the current block. We actually
441 // insert statements in reverse order; this order is reversed later
442 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000443 addStmt(Statement);
444
Ted Kremenek73543912007-08-23 21:42:29 +0000445 return Block;
446}
447
448CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
449 return Block;
450}
451
452CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek73543912007-08-23 21:42:29 +0000453
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000454 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
455 I != E; ++I ) {
456 Visit(*I);
457 }
458
459 return Block;
Ted Kremenek73543912007-08-23 21:42:29 +0000460}
461
462CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
463 // We may see an if statement in the middle of a basic block, or
464 // it may be the first statement we are processing. In either case,
465 // we create a new basic block. First, we create the blocks for
466 // the then...else statements, and then we create the block containing
467 // the if statement. If we were in the middle of a block, we
468 // stop processing that block and reverse its statements. That block
469 // is then the implicit successor for the "then" and "else" clauses.
470
471 // The block we were proccessing is now finished. Make it the
472 // successor block.
473 if (Block) {
474 Succ = Block;
475 FinishBlock(Block);
476 }
477
478 // Process the false branch. NULL out Block so that the recursive
479 // call to Visit will create a new basic block.
480 // Null out Block so that all successor
481 CFGBlock* ElseBlock = Succ;
482
483 if (Stmt* Else = I->getElse()) {
484 SaveAndRestore<CFGBlock*> sv(Succ);
485
486 // NULL out Block so that the recursive call to Visit will
487 // create a new basic block.
488 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000489 ElseBlock = Visit(Else);
490
491 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
492 ElseBlock = sv.get();
493 else if (Block)
494 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000495 }
496
497 // Process the true branch. NULL out Block so that the recursive
498 // call to Visit will create a new basic block.
499 // Null out Block so that all successor
500 CFGBlock* ThenBlock;
501 {
502 Stmt* Then = I->getThen();
503 assert (Then);
504 SaveAndRestore<CFGBlock*> sv(Succ);
505 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000506 ThenBlock = Visit(Then);
507
508 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
509 ThenBlock = sv.get();
510 else if (Block)
511 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000512 }
513
514 // Now create a new block containing the if statement.
515 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000516
517 // Set the terminator of the new block to the If statement.
518 Block->setTerminator(I);
519
520 // Now add the successors.
521 Block->addSuccessor(ThenBlock);
522 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000523
524 // Add the condition as the last statement in the new block. This
525 // may create new blocks as the condition may contain control-flow. Any
526 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000527 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000528}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000529
Ted Kremenek73543912007-08-23 21:42:29 +0000530
531CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
532 // If we were in the middle of a block we stop processing that block
533 // and reverse its statements.
534 //
535 // NOTE: If a "return" appears in the middle of a block, this means
536 // that the code afterwards is DEAD (unreachable). We still
537 // keep a basic block for that code; a simple "mark-and-sweep"
538 // from the entry block will be able to report such dead
539 // blocks.
540 if (Block) FinishBlock(Block);
541
542 // Create the new block.
543 Block = createBlock(false);
544
545 // The Exit block is the only successor.
546 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000547
548 // Add the return statement to the block. This may create new blocks
549 // if R contains control-flow (short-circuit operations).
550 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000551}
552
553CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
554 // Get the block of the labeled statement. Add it to our map.
555 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000556
557 if (!LabelBlock) // This can happen when the body is empty, i.e.
558 LabelBlock=createBlock(); // scopes that only contains NullStmts.
559
Ted Kremenek73543912007-08-23 21:42:29 +0000560 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
561 LabelMap[ L ] = LabelBlock;
562
563 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000564 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000565 // label (and we have already processed the substatement) there is no
566 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000567 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000568 FinishBlock(LabelBlock);
569
570 // We set Block to NULL to allow lazy creation of a new block
571 // (if necessary);
572 Block = NULL;
573
574 // This block is now the implicit successor of other blocks.
575 Succ = LabelBlock;
576
577 return LabelBlock;
578}
579
580CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
581 // Goto is a control-flow statement. Thus we stop processing the
582 // current block and create a new one.
583 if (Block) FinishBlock(Block);
584 Block = createBlock(false);
585 Block->setTerminator(G);
586
587 // If we already know the mapping to the label block add the
588 // successor now.
589 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
590
591 if (I == LabelMap.end())
592 // We will need to backpatch this block later.
593 BackpatchBlocks.push_back(Block);
594 else
595 Block->addSuccessor(I->second);
596
597 return Block;
598}
599
600CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
601 // "for" is a control-flow statement. Thus we stop processing the
602 // current block.
603
604 CFGBlock* LoopSuccessor = NULL;
605
606 if (Block) {
607 FinishBlock(Block);
608 LoopSuccessor = Block;
609 }
610 else LoopSuccessor = Succ;
611
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000612 // Because of short-circuit evaluation, the condition of the loop
613 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
614 // blocks that evaluate the condition.
615 CFGBlock* ExitConditionBlock = createBlock(false);
616 CFGBlock* EntryConditionBlock = ExitConditionBlock;
617
618 // Set the terminator for the "exit" condition block.
619 ExitConditionBlock->setTerminator(F);
620
621 // Now add the actual condition to the condition block. Because the
622 // condition itself may contain control-flow, new blocks may be created.
623 if (Stmt* C = F->getCond()) {
624 Block = ExitConditionBlock;
625 EntryConditionBlock = addStmt(C);
626 if (Block) FinishBlock(EntryConditionBlock);
627 }
Ted Kremenek73543912007-08-23 21:42:29 +0000628
629 // The condition block is the implicit successor for the loop body as
630 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000631 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000632
633 // Now create the loop body.
634 {
635 assert (F->getBody());
636
637 // Save the current values for Block, Succ, and continue and break targets
638 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
639 save_continue(ContinueTargetBlock),
640 save_break(BreakTargetBlock);
641
642 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000643 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000644
645 // All breaks should go to the code following the loop.
646 BreakTargetBlock = LoopSuccessor;
647
Ted Kremenek390b9762007-08-30 18:39:40 +0000648 // Create a new block to contain the (bottom) of the loop body.
649 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000650
651 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000652 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000653
654 // Now populate the body block, and in the process create new blocks
655 // as we walk the body of the loop.
656 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000657
658 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000659 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000660 else if (Block)
661 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000662
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000663 // This new body block is a successor to our "exit" condition block.
664 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000665 }
666
667 // Link up the condition block with the code that follows the loop.
668 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000669 ExitConditionBlock->addSuccessor(LoopSuccessor);
670
Ted Kremenek73543912007-08-23 21:42:29 +0000671 // If the loop contains initialization, create a new block for those
672 // statements. This block can also contain statements that precede
673 // the loop.
674 if (Stmt* I = F->getInit()) {
675 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000676 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000677 }
678 else {
679 // There is no loop initialization. We are thus basically a while
680 // loop. NULL out Block to force lazy block construction.
681 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000682 Succ = EntryConditionBlock;
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);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000714 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000715 if (Block) FinishBlock(EntryConditionBlock);
716 }
Ted Kremenek73543912007-08-23 21:42:29 +0000717
718 // The condition block is the implicit successor for the loop body as
719 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000720 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000721
722 // Process the loop body.
723 {
724 assert (W->getBody());
725
726 // Save the current values for Block, Succ, and continue and break targets
727 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
728 save_continue(ContinueTargetBlock),
729 save_break(BreakTargetBlock);
730
731 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000732 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000733
734 // All breaks should go to the code following the loop.
735 BreakTargetBlock = LoopSuccessor;
736
737 // NULL out Block to force lazy instantiation of blocks for the body.
738 Block = NULL;
739
740 // Create the body. The returned block is the entry to the loop body.
741 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000742
743 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000744 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000745 else if (Block)
746 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000747
748 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000749 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000750 }
751
752 // Link up the condition block with the code that follows the loop.
753 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000754 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000755
756 // There can be no more statements in the condition block
757 // since we loop back to this block. NULL out Block to force
758 // lazy creation of another block.
759 Block = NULL;
760
761 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000762 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000763 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000764}
765
766CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
767 // "do...while" is a control-flow statement. Thus we stop processing the
768 // current block.
769
770 CFGBlock* LoopSuccessor = NULL;
771
772 if (Block) {
773 FinishBlock(Block);
774 LoopSuccessor = Block;
775 }
776 else LoopSuccessor = Succ;
777
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000778 // Because of short-circuit evaluation, the condition of the loop
779 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
780 // blocks that evaluate the condition.
781 CFGBlock* ExitConditionBlock = createBlock(false);
782 CFGBlock* EntryConditionBlock = ExitConditionBlock;
783
784 // Set the terminator for the "exit" condition block.
785 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000786
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000787 // Now add the actual condition to the condition block. Because the
788 // condition itself may contain control-flow, new blocks may be created.
789 if (Stmt* C = D->getCond()) {
790 Block = ExitConditionBlock;
791 EntryConditionBlock = addStmt(C);
792 if (Block) FinishBlock(EntryConditionBlock);
793 }
Ted Kremenek73543912007-08-23 21:42:29 +0000794
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000795 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000796 Succ = EntryConditionBlock;
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)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000821 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000822 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.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000839 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000840 return BodyBlock;
841}
842
843CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
844 // "continue" is a control-flow statement. Thus we stop processing the
845 // current block.
846 if (Block) FinishBlock(Block);
847
848 // Now create a new block that ends with the continue statement.
849 Block = createBlock(false);
850 Block->setTerminator(C);
851
852 // If there is no target for the continue, then we are looking at an
853 // incomplete AST. Handle this by not registering a successor.
854 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
855
856 return Block;
857}
858
859CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
860 // "break" is a control-flow statement. Thus we stop processing the
861 // current block.
862 if (Block) FinishBlock(Block);
863
864 // Now create a new block that ends with the continue statement.
865 Block = createBlock(false);
866 Block->setTerminator(B);
867
868 // If there is no target for the break, then we are looking at an
869 // incomplete AST. Handle this by not registering a successor.
870 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
871
872 return Block;
873}
874
875CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
876 // "switch" is a control-flow statement. Thus we stop processing the
877 // current block.
878 CFGBlock* SwitchSuccessor = NULL;
879
880 if (Block) {
881 FinishBlock(Block);
882 SwitchSuccessor = Block;
883 }
884 else SwitchSuccessor = Succ;
885
886 // Save the current "switch" context.
887 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000888 save_break(BreakTargetBlock),
889 save_default(DefaultCaseBlock);
890
891 // Set the "default" case to be the block after the switch statement.
892 // If the switch statement contains a "default:", this value will
893 // be overwritten with the block for that code.
894 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000895
Ted Kremenek73543912007-08-23 21:42:29 +0000896 // Create a new block that will contain the switch statement.
897 SwitchTerminatedBlock = createBlock(false);
898
Ted Kremenek73543912007-08-23 21:42:29 +0000899 // Now process the switch body. The code after the switch is the implicit
900 // successor.
901 Succ = SwitchSuccessor;
902 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000903
904 // When visiting the body, the case statements should automatically get
905 // linked up to the switch. We also don't keep a pointer to the body,
906 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000907 assert (S->getBody() && "switch must contain a non-NULL body");
908 Block = NULL;
909 CFGBlock *BodyBlock = Visit(S->getBody());
910 if (Block) FinishBlock(BodyBlock);
911
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000912 // If we have no "default:" case, the default transition is to the
913 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000914 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000915
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000916 // Add the terminator and condition in the switch block.
917 SwitchTerminatedBlock->setTerminator(S);
918 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000919 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000920
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000921 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000922}
923
Ted Kremenek97bc3422008-02-13 22:05:39 +0000924CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
925 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +0000926 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000927
928 if (S->getSubStmt()) Visit(S->getSubStmt());
929 CFGBlock* CaseBlock = Block;
930 if (!CaseBlock) CaseBlock = createBlock();
931
Ted Kremenek97bc3422008-02-13 22:05:39 +0000932 // Cases statements partition blocks, so this is the top of
933 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenekec055e12007-08-29 23:20:49 +0000934 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000935 FinishBlock(CaseBlock);
936
937 // Add this block to the list of successors for the block with the
938 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000939 assert (SwitchTerminatedBlock);
940 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000941
942 // We set Block to NULL to allow lazy creation of a new block (if necessary)
943 Block = NULL;
944
945 // This block is now the implicit successor of other blocks.
946 Succ = CaseBlock;
947
948 return CaseBlock;
949}
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000950
Ted Kremenek97bc3422008-02-13 22:05:39 +0000951CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
952 if (S->getSubStmt()) Visit(S->getSubStmt());
953 DefaultCaseBlock = Block;
954 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
955
956 // Default statements partition blocks, so this is the top of
957 // the basic block we were processing (the "default:" is the label).
958 DefaultCaseBlock->setLabel(S);
959 FinishBlock(DefaultCaseBlock);
960
961 // Unlike case statements, we don't add the default block to the
962 // successors for the switch statement immediately. This is done
963 // when we finish processing the switch statement. This allows for
964 // the default case (including a fall-through to the code after the
965 // switch statement) to always be the last successor of a switch-terminated
966 // block.
967
968 // We set Block to NULL to allow lazy creation of a new block (if necessary)
969 Block = NULL;
970
971 // This block is now the implicit successor of other blocks.
972 Succ = DefaultCaseBlock;
973
974 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000975}
Ted Kremenek73543912007-08-23 21:42:29 +0000976
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000977CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
978 // Lazily create the indirect-goto dispatch block if there isn't one
979 // already.
980 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
981
982 if (!IBlock) {
983 IBlock = createBlock(false);
984 cfg->setIndirectGotoBlock(IBlock);
985 }
986
987 // IndirectGoto is a control-flow statement. Thus we stop processing the
988 // current block and create a new one.
989 if (Block) FinishBlock(Block);
990 Block = createBlock(false);
991 Block->setTerminator(I);
992 Block->addSuccessor(IBlock);
993 return addStmt(I->getTarget());
994}
995
Ted Kremenek73543912007-08-23 21:42:29 +0000996
Ted Kremenekd6e50602007-08-23 21:26:19 +0000997} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000998
999/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1000/// block has no successors or predecessors. If this is the first block
1001/// created in the CFG, it is automatically set to be the Entry and Exit
1002/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001003CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001004 bool first_block = begin() == end();
1005
1006 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001007 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001008
1009 // If this is the first block, set it as the Entry and Exit.
1010 if (first_block) Entry = Exit = &front();
1011
1012 // Return the block.
1013 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001014}
1015
Ted Kremenek4db5b452007-08-23 16:51:22 +00001016/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1017/// CFG is returned to the caller.
1018CFG* CFG::buildCFG(Stmt* Statement) {
1019 CFGBuilder Builder;
1020 return Builder.buildCFG(Statement);
1021}
1022
1023/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001024void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1025
Ted Kremenek3a819822007-10-01 19:33:33 +00001026//===----------------------------------------------------------------------===//
1027// CFG: Queries for BlkExprs.
1028//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001029
Ted Kremenek3a819822007-10-01 19:33:33 +00001030namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001031 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001032}
1033
Ted Kremenekc6fda602008-01-26 00:03:27 +00001034static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1035 if (!S)
1036 return;
1037
1038 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1039 if (!*I) continue;
1040
1041 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1042 if (B->isAssignmentOp()) Set.insert(B);
1043
1044 FindSubExprAssignments(*I, Set);
1045 }
1046}
1047
Ted Kremenek3a819822007-10-01 19:33:33 +00001048static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1049 BlkExprMapTy* M = new BlkExprMapTy();
1050
Ted Kremenekc6fda602008-01-26 00:03:27 +00001051 // Look for assignments that are used as subexpressions. These are the
1052 // only assignments that we want to register as a block-level expression.
1053 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1054
Ted Kremenek3a819822007-10-01 19:33:33 +00001055 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1056 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001057 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001058
Ted Kremenekc6fda602008-01-26 00:03:27 +00001059 // Iterate over the statements again on identify the Expr* and Stmt* at
1060 // the block-level that are block-level expressions.
1061 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1062 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1063 if (Expr* E = dyn_cast<Expr>(*BI)) {
1064
1065 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1066 // Assignment expressions that are not nested within another
1067 // expression are really "statements" whose value is never
1068 // used by another expression.
1069 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1070 continue;
1071 }
1072 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1073 // Special handling for statement expressions. The last statement
1074 // in the statement expression is also a block-level expr.
Ted Kremenekab6c5902008-01-17 20:48:37 +00001075 const CompoundStmt* C = S->getSubStmt();
1076 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001077 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001078 (*M)[C->body_back()] = x;
1079 }
1080 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001081
Ted Kremenekc6fda602008-01-26 00:03:27 +00001082 unsigned x = M->size();
1083 (*M)[E] = x;
1084 }
1085
Ted Kremenek3a819822007-10-01 19:33:33 +00001086 return M;
1087}
1088
Ted Kremenekab6c5902008-01-17 20:48:37 +00001089CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1090 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001091 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1092
1093 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001094 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001095
1096 if (I == M->end()) return CFG::BlkExprNumTy();
1097 else return CFG::BlkExprNumTy(I->second);
1098}
1099
1100unsigned CFG::getNumBlkExprs() {
1101 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1102 return M->size();
1103 else {
1104 // We assume callers interested in the number of BlkExprs will want
1105 // the map constructed if it doesn't already exist.
1106 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1107 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1108 }
1109}
1110
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001111typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1112
1113const std::pair<CFGBlock*,CFGBlock*>*
1114CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1115
1116 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1117 if (!p) p = new BlkEdgeSetTy();
1118
1119 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1120 const_cast<CFGBlock*>(B2))).first);
1121}
1122
Ted Kremenek3a819822007-10-01 19:33:33 +00001123CFG::~CFG() {
1124 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001125 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001126}
1127
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001128//===----------------------------------------------------------------------===//
1129// CFG pretty printing
1130//===----------------------------------------------------------------------===//
1131
Ted Kremenekd8313202007-08-22 18:22:34 +00001132namespace {
1133
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001134class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001135
Ted Kremenek08176a52007-08-31 21:30:12 +00001136 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1137 StmtMapTy StmtMap;
1138 signed CurrentBlock;
1139 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001140
Ted Kremenek73543912007-08-23 21:42:29 +00001141public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001142
Ted Kremenek08176a52007-08-31 21:30:12 +00001143 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1144 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1145 unsigned j = 1;
1146 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1147 BI != BEnd; ++BI, ++j )
1148 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1149 }
1150 }
1151
1152 virtual ~StmtPrinterHelper() {}
1153
1154 void setBlockID(signed i) { CurrentBlock = i; }
1155 void setStmtID(unsigned i) { CurrentStmt = i; }
1156
Ted Kremenek86afc042007-08-31 22:26:13 +00001157 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1158
1159 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek08176a52007-08-31 21:30:12 +00001160
1161 if (I == StmtMap.end())
1162 return false;
1163
1164 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1165 && I->second.second == CurrentStmt)
1166 return false;
1167
Ted Kremenek86afc042007-08-31 22:26:13 +00001168 OS << "[B" << I->second.first << "." << I->second.second << "]";
1169 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001170 }
1171};
1172
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001173class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1174 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1175
Ted Kremenek08176a52007-08-31 21:30:12 +00001176 std::ostream& OS;
1177 StmtPrinterHelper* Helper;
1178public:
1179 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1180 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001181
1182 void VisitIfStmt(IfStmt* I) {
1183 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001184 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001185 }
1186
1187 // Default case.
Ted Kremenek621e1592007-08-31 21:49:40 +00001188 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001189
1190 void VisitForStmt(ForStmt* F) {
1191 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001192 if (F->getInit()) OS << "...";
1193 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001194 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001195 OS << "; ";
1196 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001197 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001198 }
1199
1200 void VisitWhileStmt(WhileStmt* W) {
1201 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001202 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001203 }
1204
1205 void VisitDoStmt(DoStmt* D) {
1206 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001207 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001208 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001209
Ted Kremenek65cfa562007-08-27 21:27:44 +00001210 void VisitSwitchStmt(SwitchStmt* S) {
1211 OS << "switch ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001212 S->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001213 }
1214
Ted Kremenek621e1592007-08-31 21:49:40 +00001215 void VisitConditionalOperator(ConditionalOperator* C) {
1216 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001217 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001218 }
1219
Ted Kremenek2025cc92007-08-31 22:29:13 +00001220 void VisitChooseExpr(ChooseExpr* C) {
1221 OS << "__builtin_choose_expr( ";
1222 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001223 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001224 }
1225
Ted Kremenek86afc042007-08-31 22:26:13 +00001226 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1227 OS << "goto *";
1228 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001229 }
1230
Ted Kremenek621e1592007-08-31 21:49:40 +00001231 void VisitBinaryOperator(BinaryOperator* B) {
1232 if (!B->isLogicalOp()) {
1233 VisitExpr(B);
1234 return;
1235 }
1236
1237 B->getLHS()->printPretty(OS,Helper);
1238
1239 switch (B->getOpcode()) {
1240 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001241 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001242 return;
1243 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001244 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001245 return;
1246 default:
1247 assert(false && "Invalid logical operator.");
1248 }
1249 }
1250
Ted Kremenekcfaae762007-08-27 21:54:41 +00001251 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001252 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001253 }
Ted Kremenek73543912007-08-23 21:42:29 +00001254};
Ted Kremenek08176a52007-08-31 21:30:12 +00001255
1256
Ted Kremenek86afc042007-08-31 22:26:13 +00001257void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1258 if (Helper) {
1259 // special printing for statement-expressions.
1260 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1261 CompoundStmt* Sub = SE->getSubStmt();
1262
1263 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001264 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001265 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001266 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001267 return;
1268 }
1269 }
1270
1271 // special printing for comma expressions.
1272 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1273 if (B->getOpcode() == BinaryOperator::Comma) {
1274 OS << "... , ";
1275 Helper->handledStmt(B->getRHS(),OS);
1276 OS << '\n';
1277 return;
1278 }
1279 }
1280 }
1281
1282 S->printPretty(OS, Helper);
1283
1284 // Expressions need a newline.
1285 if (isa<Expr>(S)) OS << '\n';
1286}
1287
Ted Kremenek08176a52007-08-31 21:30:12 +00001288void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1289 StmtPrinterHelper* Helper, bool print_edges) {
1290
1291 if (Helper) Helper->setBlockID(B.getBlockID());
1292
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001293 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001294 OS << "\n [ B" << B.getBlockID();
1295
1296 if (&B == &cfg->getEntry())
1297 OS << " (ENTRY) ]\n";
1298 else if (&B == &cfg->getExit())
1299 OS << " (EXIT) ]\n";
1300 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001301 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001302 else
1303 OS << " ]\n";
1304
Ted Kremenekec055e12007-08-29 23:20:49 +00001305 // Print the label of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001306 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1307
1308 if (print_edges)
1309 OS << " ";
1310
Ted Kremenekec055e12007-08-29 23:20:49 +00001311 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1312 OS << L->getName();
1313 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1314 OS << "case ";
1315 C->getLHS()->printPretty(OS);
1316 if (C->getRHS()) {
1317 OS << " ... ";
1318 C->getRHS()->printPretty(OS);
1319 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001320 }
Chris Lattner1501e122007-09-16 19:11:53 +00001321 else if (isa<DefaultStmt>(S))
Ted Kremenekec055e12007-08-29 23:20:49 +00001322 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001323 else
1324 assert(false && "Invalid label statement in CFGBlock.");
1325
Ted Kremenekec055e12007-08-29 23:20:49 +00001326 OS << ":\n";
1327 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001328
Ted Kremenek97f75312007-08-21 21:42:03 +00001329 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001330 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001331
1332 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1333 I != E ; ++I, ++j ) {
1334
Ted Kremenekec055e12007-08-29 23:20:49 +00001335 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001336 if (print_edges)
1337 OS << " ";
1338
1339 OS << std::setw(3) << j << ": ";
1340
1341 if (Helper)
1342 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001343
1344 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001345 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001346
Ted Kremenekec055e12007-08-29 23:20:49 +00001347 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001348 if (B.getTerminator()) {
1349 if (print_edges)
1350 OS << " ";
1351
Ted Kremenekec055e12007-08-29 23:20:49 +00001352 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001353
1354 if (Helper) Helper->setBlockID(-1);
1355
1356 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1357 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001358 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001359 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001360
Ted Kremenekec055e12007-08-29 23:20:49 +00001361 if (print_edges) {
1362 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001363 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001364 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001365
Ted Kremenek08176a52007-08-31 21:30:12 +00001366 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1367 I != E; ++I, ++i) {
1368
1369 if (i == 8 || (i-8) == 0)
1370 OS << "\n ";
1371
Ted Kremenekec055e12007-08-29 23:20:49 +00001372 OS << " B" << (*I)->getBlockID();
1373 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001374
1375 OS << '\n';
1376
1377 // Print the successors of this block.
1378 OS << " Successors (" << B.succ_size() << "):";
1379 i = 0;
1380
1381 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1382 I != E; ++I, ++i) {
1383
1384 if (i == 8 || (i-8) % 10 == 0)
1385 OS << "\n ";
1386
1387 OS << " B" << (*I)->getBlockID();
1388 }
1389
Ted Kremenekec055e12007-08-29 23:20:49 +00001390 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001391 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001392}
1393
1394} // end anonymous namespace
1395
1396/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001397void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001398
1399/// print - A simple pretty printer of a CFG that outputs to an ostream.
1400void CFG::print(std::ostream& OS) const {
1401
1402 StmtPrinterHelper Helper(this);
1403
1404 // Print the entry block.
1405 print_block(OS, this, getEntry(), &Helper, true);
1406
1407 // Iterate through the CFGBlocks and print them one by one.
1408 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1409 // Skip the entry block, because we already printed it.
1410 if (&(*I) == &getEntry() || &(*I) == &getExit())
1411 continue;
1412
1413 print_block(OS, this, *I, &Helper, true);
1414 }
1415
1416 // Print the exit block.
1417 print_block(OS, this, getExit(), &Helper, true);
1418}
1419
1420/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001421void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001422
1423/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1424/// Generally this will only be called from CFG::print.
1425void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1426 StmtPrinterHelper Helper(cfg);
1427 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001428}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001429
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001430/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1431void CFGBlock::printTerminator(std::ostream& OS) const {
1432 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1433 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1434}
1435
1436
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001437//===----------------------------------------------------------------------===//
1438// CFG Graphviz Visualization
1439//===----------------------------------------------------------------------===//
1440
Ted Kremenek08176a52007-08-31 21:30:12 +00001441
1442#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001443static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001444#endif
1445
1446void CFG::viewCFG() const {
1447#ifndef NDEBUG
1448 StmtPrinterHelper H(this);
1449 GraphHelper = &H;
1450 llvm::ViewGraph(this,"CFG");
1451 GraphHelper = NULL;
1452#else
1453 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser284bff92007-09-17 12:29:55 +00001454 << "systems with Graphviz or gv!\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001455#endif
1456}
1457
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001458namespace llvm {
1459template<>
1460struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1461 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1462
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001463#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001464 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001465 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001466 std::string OutStr = Out.str();
1467
1468 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1469
1470 // Process string output to make it nicer...
1471 for (unsigned i = 0; i != OutStr.length(); ++i)
1472 if (OutStr[i] == '\n') { // Left justify
1473 OutStr[i] = '\\';
1474 OutStr.insert(OutStr.begin()+i+1, 'l');
1475 }
1476
1477 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001478#else
1479 return "";
1480#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001481 }
1482};
1483} // end namespace llvm