blob: 0cab1f1b5c7431b68ac4b4d87c9f1919da263416 [file] [log] [blame]
Ted Kremenekfddd5182007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Kremenekfddd5182007-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 Kremenekc310e932007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek83c01da2008-01-11 00:40:29 +000024#include <set>
Ted Kremenekfddd5182007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000027#include <sstream>
28
Ted Kremenek83c01da2008-01-11 00:40:29 +000029
Ted Kremenekfddd5182007-08-21 21:42:03 +000030using namespace clang;
31
32namespace {
33
Ted Kremenekbefef2f2007-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 Kremenek6fa9b882008-01-08 18:15:10 +000037struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekbefef2f2007-08-23 21:26:19 +000038 SaveAndRestore(T& x) : X(x), old_value(x) {}
39 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000040 T get() { return old_value; }
41
Ted Kremenekbefef2f2007-08-23 21:26:19 +000042 T& X;
43 T old_value;
44};
Ted Kremenekfddd5182007-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 Kremenekc310e932007-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 Kremenek6fa9b882008-01-08 18:15:10 +000061class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000062 CFG* cfg;
63 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000064 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000065 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000066 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000067 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000068 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000069
Ted Kremenek19bb3562007-08-28 19:26:49 +000070 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000071 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
72 LabelMapTy LabelMap;
73
Ted Kremenek19bb3562007-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 Kremenek4a2b8a12007-08-22 15:40:58 +000076 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000077 BackpatchBlocksTy BackpatchBlocks;
78
Ted Kremenek19bb3562007-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 Kremenekfddd5182007-08-21 21:42:03 +000083public:
Ted Kremenek026473c2007-08-23 16:51:22 +000084 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000085 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000086 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000087 // Create an empty CFG.
88 cfg = new CFG();
89 }
90
91 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000092
Ted Kremenekd4fdee32007-08-23 21:42:29 +000093 // buildCFG - Used by external clients to construct the CFG.
94 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000095
Ted Kremenekd4fdee32007-08-23 21:42:29 +000096 // Visitors to walk an AST and construct the CFG. Called by
97 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000098
Ted Kremenekd4fdee32007-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 Kremenekeef5a9a2008-02-13 22:05:39 +0000112 CFGBlock* VisitCaseStmt(CaseStmt* S);
Ted Kremenek295222c2008-02-13 21:46:34 +0000113 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000114 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000115
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000116private:
117 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000118 CFGBlock* addStmt(Stmt* S);
119 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
120 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000121 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000122 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekf50ec102007-09-11 21:29:43 +0000123 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000124 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000125
Ted Kremenekfddd5182007-08-21 21:42:03 +0000126};
Ted Kremenekd4fdee32007-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 Kremenek19bb3562007-08-28 19:26:49 +0000134 assert (cfg);
Ted Kremenekd4fdee32007-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 Kremenek49af7cb2007-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 Kremenekd4fdee32007-08-23 21:42:29 +0000143
144 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000145 CFGBlock* B = Visit(Statement);
146 if (!B) B = Succ;
147
148 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000149 // Finalize the last constructed block. This usually involves
150 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000151 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000152
153 // Backpatch the gotos whose label -> block mappings we didn't know
154 // when we encountered them.
155 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
156 E = BackpatchBlocks.end(); I != E; ++I ) {
157
158 CFGBlock* B = *I;
159 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
160 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
161
162 // If there is no target for the goto, then we are looking at an
163 // incomplete AST. Handle this by not registering a successor.
164 if (LI == LabelMap.end()) continue;
165
166 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000167 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000168
Ted Kremenek19bb3562007-08-28 19:26:49 +0000169 // Add successors to the Indirect Goto Dispatch block (if we have one).
170 if (CFGBlock* B = cfg->getIndirectGotoBlock())
171 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
172 E = AddressTakenLabels.end(); I != E; ++I ) {
173
174 // Lookup the target block.
175 LabelMapTy::iterator LI = LabelMap.find(*I);
176
177 // If there is no target block that contains label, then we are looking
178 // at an incomplete AST. Handle this by not registering a successor.
179 if (LI == LabelMap.end()) continue;
180
181 B->addSuccessor(LI->second);
182 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000183
Ted Kremenek94b33162007-09-17 16:18:02 +0000184 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000185 }
186
187 // Create an empty entry block that has no predecessors.
188 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000189
Ted Kremenek322f58d2007-09-26 21:23:31 +0000190 // NULL out cfg so that repeated calls to the builder will fail and that
191 // the ownership of the constructed CFG is passed to the caller.
192 CFG* t = cfg;
193 cfg = NULL;
194 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000195}
196
197/// createBlock - Used to lazily create blocks that are connected
198/// to the current (global) succcessor.
199CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000200 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000201 if (add_successor && Succ) B->addSuccessor(Succ);
202 return B;
203}
204
205/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000206/// we must reverse the statements because they have been inserted
207/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000208void CFGBuilder::FinishBlock(CFGBlock* B) {
209 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000210 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000211}
212
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000213/// addStmt - Used to add statements/expressions to the current CFGBlock
214/// "Block". This method calls WalkAST on the passed statement to see if it
215/// contains any short-circuit expressions. If so, it recursively creates
216/// the necessary blocks for such expressions. It returns the "topmost" block
217/// of the created blocks, or the original value of "Block" when this method
218/// was called if no additional blocks are created.
219CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000220 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000221 return WalkAST(S,true);
222}
223
224/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000225/// add extra blocks for ternary operators, &&, and ||. We also
226/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000227CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
228 switch (S->getStmtClass()) {
229 case Stmt::ConditionalOperatorClass: {
230 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000231
232 // Create the confluence block that will "merge" the results
233 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000234 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
235 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000236 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000237
238 // Create a block for the LHS expression if there is an LHS expression.
239 // A GCC extension allows LHS to be NULL, causing the condition to
240 // be the value that is returned instead.
241 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000242 Succ = ConfluenceBlock;
243 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000244 CFGBlock* LHSBlock = NULL;
245 if (C->getLHS()) {
246 LHSBlock = Visit(C->getLHS());
247 FinishBlock(LHSBlock);
248 Block = NULL;
249 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000250
Ted Kremenekecc04c92007-11-26 18:20:26 +0000251 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000252 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000253 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000254 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000255
Ted Kremenekecc04c92007-11-26 18:20:26 +0000256 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000257 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000258
259 if (LHSBlock)
260 Block->addSuccessor(LHSBlock);
261 else {
262 // If we have no LHS expression, add the ConfluenceBlock as a direct
263 // successor for the block containing the condition. Moreover,
264 // we need to reverse the order of the predecessors in the
265 // ConfluenceBlock because the RHSBlock will have been added to
266 // the succcessors already, and we want the first predecessor to the
267 // the block containing the expression for the case when the ternary
268 // expression evaluates to true.
269 Block->addSuccessor(ConfluenceBlock);
270 assert (ConfluenceBlock->pred_size() == 2);
271 std::reverse(ConfluenceBlock->pred_begin(),
272 ConfluenceBlock->pred_end());
273 }
274
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000275 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000276
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000277 Block->setTerminator(C);
278 return addStmt(C->getCond());
279 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000280
281 case Stmt::ChooseExprClass: {
282 ChooseExpr* C = cast<ChooseExpr>(S);
283
284 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
285 ConfluenceBlock->appendStmt(C);
286 FinishBlock(ConfluenceBlock);
287
288 Succ = ConfluenceBlock;
289 Block = NULL;
290 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000291 FinishBlock(LHSBlock);
292
Ted Kremenek49a436d2007-08-31 17:03:41 +0000293 Succ = ConfluenceBlock;
294 Block = NULL;
295 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000296 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000297
298 Block = createBlock(false);
299 Block->addSuccessor(LHSBlock);
300 Block->addSuccessor(RHSBlock);
301 Block->setTerminator(C);
302 return addStmt(C->getCond());
303 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000304
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000305 case Stmt::DeclStmtClass: {
306 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
307 Block->appendStmt(S);
308
309 StmtIterator I(D);
310 return WalkAST_VisitDeclSubExprs(I);
311 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000312
Ted Kremenek19bb3562007-08-28 19:26:49 +0000313 case Stmt::AddrLabelExprClass: {
314 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
315 AddressTakenLabels.insert(A->getLabel());
316
317 if (AlwaysAddStmt) Block->appendStmt(S);
318 return Block;
319 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000320
321 case Stmt::CallExprClass:
322 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000323
Ted Kremenek15c27a82007-08-28 18:30:10 +0000324 case Stmt::StmtExprClass:
325 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000326
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000327 case Stmt::UnaryOperatorClass: {
328 UnaryOperator* U = cast<UnaryOperator>(S);
329
330 // sizeof(expressions). For such expressions,
331 // the subexpression is not really evaluated, so
332 // we don't care about control-flow within the sizeof.
333 if (U->getOpcode() == UnaryOperator::SizeOf) {
334 Block->appendStmt(S);
335 return Block;
336 }
337
338 break;
339 }
340
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000341 case Stmt::BinaryOperatorClass: {
342 BinaryOperator* B = cast<BinaryOperator>(S);
343
344 if (B->isLogicalOp()) { // && or ||
345 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
346 ConfluenceBlock->appendStmt(B);
347 FinishBlock(ConfluenceBlock);
348
349 // create the block evaluating the LHS
350 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000351 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000352
353 // create the block evaluating the RHS
354 Succ = ConfluenceBlock;
355 Block = NULL;
356 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000357
358 // Now link the LHSBlock with RHSBlock.
359 if (B->getOpcode() == BinaryOperator::LOr) {
360 LHSBlock->addSuccessor(ConfluenceBlock);
361 LHSBlock->addSuccessor(RHSBlock);
362 }
363 else {
364 assert (B->getOpcode() == BinaryOperator::LAnd);
365 LHSBlock->addSuccessor(RHSBlock);
366 LHSBlock->addSuccessor(ConfluenceBlock);
367 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000368
369 // Generate the blocks for evaluating the LHS.
370 Block = LHSBlock;
371 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000372 }
373 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
374 Block->appendStmt(B);
375 addStmt(B->getRHS());
376 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000377 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000378
379 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000380 }
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000381
382 case Stmt::ParenExprClass:
383 return WalkAST(cast<ParenExpr>(S)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000384
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000385 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000386 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000387 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000388
389 if (AlwaysAddStmt) Block->appendStmt(S);
390 return WalkAST_VisitChildren(S);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000391}
392
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000393/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
394/// DeclStmts. Because the initialization code (and sometimes the
395/// the type declarations) for DeclStmts can contain arbitrary expressions,
396/// we must linearize declarations to handle arbitrary control-flow induced by
397/// those expressions.
398CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000399 if (I == StmtIterator())
400 return Block;
401
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000402 Stmt* S = *I;
403 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000404 WalkAST_VisitDeclSubExprs(I);
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000405
406 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000407
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000408 switch (S->getStmtClass()) {
409 case Stmt::IntegerLiteralClass:
410 case Stmt::CharacterLiteralClass:
411 case Stmt::StringLiteralClass:
412 break;
413
414 // All other cases.
415
416 default:
417 Block = addStmt(S);
418 }
419
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000420 return Block;
421}
422
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000423/// WalkAST_VisitChildren - Utility method to call WalkAST on the
424/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000425CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000426 CFGBlock* B = Block;
427 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
428 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000429 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000430
431 return B;
432}
433
Ted Kremenek15c27a82007-08-28 18:30:10 +0000434/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
435/// expressions (a GCC extension).
436CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
437 Block->appendStmt(S);
438 return VisitCompoundStmt(S->getSubStmt());
439}
440
Ted Kremenekf50ec102007-09-11 21:29:43 +0000441/// WalkAST_VisitCallExpr - Utility method to handle function calls that
442/// are nested in expressions. The idea is that each function call should
443/// appear as a distinct statement in the CFGBlock.
444CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
445 Block->appendStmt(C);
446 return WalkAST_VisitChildren(C);
447}
448
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000449/// VisitStmt - Handle statements with no branching control flow.
450CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
451 // We cannot assume that we are in the middle of a basic block, since
452 // the CFG might only be constructed for this single statement. If
453 // we have no current basic block, just create one lazily.
454 if (!Block) Block = createBlock();
455
456 // Simply add the statement to the current block. We actually
457 // insert statements in reverse order; this order is reversed later
458 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000459 addStmt(Statement);
460
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000461 return Block;
462}
463
464CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
465 return Block;
466}
467
468CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000469
Ted Kremenekd34066c2008-02-26 00:22:58 +0000470 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
471 I != E; ++I ) {
472 Visit(*I);
473 }
474
475 return Block;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000476}
477
478CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
479 // We may see an if statement in the middle of a basic block, or
480 // it may be the first statement we are processing. In either case,
481 // we create a new basic block. First, we create the blocks for
482 // the then...else statements, and then we create the block containing
483 // the if statement. If we were in the middle of a block, we
484 // stop processing that block and reverse its statements. That block
485 // is then the implicit successor for the "then" and "else" clauses.
486
487 // The block we were proccessing is now finished. Make it the
488 // successor block.
489 if (Block) {
490 Succ = Block;
491 FinishBlock(Block);
492 }
493
494 // Process the false branch. NULL out Block so that the recursive
495 // call to Visit will create a new basic block.
496 // Null out Block so that all successor
497 CFGBlock* ElseBlock = Succ;
498
499 if (Stmt* Else = I->getElse()) {
500 SaveAndRestore<CFGBlock*> sv(Succ);
501
502 // NULL out Block so that the recursive call to Visit will
503 // create a new basic block.
504 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000505 ElseBlock = Visit(Else);
506
507 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
508 ElseBlock = sv.get();
509 else if (Block)
510 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000511 }
512
513 // Process the true branch. NULL out Block so that the recursive
514 // call to Visit will create a new basic block.
515 // Null out Block so that all successor
516 CFGBlock* ThenBlock;
517 {
518 Stmt* Then = I->getThen();
519 assert (Then);
520 SaveAndRestore<CFGBlock*> sv(Succ);
521 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000522 ThenBlock = Visit(Then);
523
524 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
525 ThenBlock = sv.get();
526 else if (Block)
527 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000528 }
529
530 // Now create a new block containing the if statement.
531 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000532
533 // Set the terminator of the new block to the If statement.
534 Block->setTerminator(I);
535
536 // Now add the successors.
537 Block->addSuccessor(ThenBlock);
538 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000539
540 // Add the condition as the last statement in the new block. This
541 // may create new blocks as the condition may contain control-flow. Any
542 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000543 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000544}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000545
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000546
547CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
548 // If we were in the middle of a block we stop processing that block
549 // and reverse its statements.
550 //
551 // NOTE: If a "return" appears in the middle of a block, this means
552 // that the code afterwards is DEAD (unreachable). We still
553 // keep a basic block for that code; a simple "mark-and-sweep"
554 // from the entry block will be able to report such dead
555 // blocks.
556 if (Block) FinishBlock(Block);
557
558 // Create the new block.
559 Block = createBlock(false);
560
561 // The Exit block is the only successor.
562 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000563
564 // Add the return statement to the block. This may create new blocks
565 // if R contains control-flow (short-circuit operations).
566 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000567}
568
569CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
570 // Get the block of the labeled statement. Add it to our map.
571 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000572
573 if (!LabelBlock) // This can happen when the body is empty, i.e.
574 LabelBlock=createBlock(); // scopes that only contains NullStmts.
575
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000576 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
577 LabelMap[ L ] = LabelBlock;
578
579 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000580 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000581 // label (and we have already processed the substatement) there is no
582 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000583 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000584 FinishBlock(LabelBlock);
585
586 // We set Block to NULL to allow lazy creation of a new block
587 // (if necessary);
588 Block = NULL;
589
590 // This block is now the implicit successor of other blocks.
591 Succ = LabelBlock;
592
593 return LabelBlock;
594}
595
596CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
597 // Goto is a control-flow statement. Thus we stop processing the
598 // current block and create a new one.
599 if (Block) FinishBlock(Block);
600 Block = createBlock(false);
601 Block->setTerminator(G);
602
603 // If we already know the mapping to the label block add the
604 // successor now.
605 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
606
607 if (I == LabelMap.end())
608 // We will need to backpatch this block later.
609 BackpatchBlocks.push_back(Block);
610 else
611 Block->addSuccessor(I->second);
612
613 return Block;
614}
615
616CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
617 // "for" is a control-flow statement. Thus we stop processing the
618 // current block.
619
620 CFGBlock* LoopSuccessor = NULL;
621
622 if (Block) {
623 FinishBlock(Block);
624 LoopSuccessor = Block;
625 }
626 else LoopSuccessor = Succ;
627
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000628 // Because of short-circuit evaluation, the condition of the loop
629 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
630 // blocks that evaluate the condition.
631 CFGBlock* ExitConditionBlock = createBlock(false);
632 CFGBlock* EntryConditionBlock = ExitConditionBlock;
633
634 // Set the terminator for the "exit" condition block.
635 ExitConditionBlock->setTerminator(F);
636
637 // Now add the actual condition to the condition block. Because the
638 // condition itself may contain control-flow, new blocks may be created.
639 if (Stmt* C = F->getCond()) {
640 Block = ExitConditionBlock;
641 EntryConditionBlock = addStmt(C);
642 if (Block) FinishBlock(EntryConditionBlock);
643 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000644
645 // The condition block is the implicit successor for the loop body as
646 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000647 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000648
649 // Now create the loop body.
650 {
651 assert (F->getBody());
652
653 // Save the current values for Block, Succ, and continue and break targets
654 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
655 save_continue(ContinueTargetBlock),
656 save_break(BreakTargetBlock);
657
658 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000659 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000660
661 // All breaks should go to the code following the loop.
662 BreakTargetBlock = LoopSuccessor;
663
Ted Kremenekaf603f72007-08-30 18:39:40 +0000664 // Create a new block to contain the (bottom) of the loop body.
665 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000666
667 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000668 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000669
670 // Now populate the body block, and in the process create new blocks
671 // as we walk the body of the loop.
672 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000673
674 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000675 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000676 else if (Block)
677 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000678
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000679 // This new body block is a successor to our "exit" condition block.
680 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000681 }
682
683 // Link up the condition block with the code that follows the loop.
684 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000685 ExitConditionBlock->addSuccessor(LoopSuccessor);
686
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000687 // If the loop contains initialization, create a new block for those
688 // statements. This block can also contain statements that precede
689 // the loop.
690 if (Stmt* I = F->getInit()) {
691 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000692 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000693 }
694 else {
695 // There is no loop initialization. We are thus basically a while
696 // loop. NULL out Block to force lazy block construction.
697 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000698 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000699 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000700 }
701}
702
703CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
704 // "while" is a control-flow statement. Thus we stop processing the
705 // current block.
706
707 CFGBlock* LoopSuccessor = NULL;
708
709 if (Block) {
710 FinishBlock(Block);
711 LoopSuccessor = Block;
712 }
713 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000714
715 // Because of short-circuit evaluation, the condition of the loop
716 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
717 // blocks that evaluate the condition.
718 CFGBlock* ExitConditionBlock = createBlock(false);
719 CFGBlock* EntryConditionBlock = ExitConditionBlock;
720
721 // Set the terminator for the "exit" condition block.
722 ExitConditionBlock->setTerminator(W);
723
724 // Now add the actual condition to the condition block. Because the
725 // condition itself may contain control-flow, new blocks may be created.
726 // Thus we update "Succ" after adding the condition.
727 if (Stmt* C = W->getCond()) {
728 Block = ExitConditionBlock;
729 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000730 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000731 if (Block) FinishBlock(EntryConditionBlock);
732 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000733
734 // The condition block is the implicit successor for the loop body as
735 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000736 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000737
738 // Process the loop body.
739 {
740 assert (W->getBody());
741
742 // Save the current values for Block, Succ, and continue and break targets
743 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
744 save_continue(ContinueTargetBlock),
745 save_break(BreakTargetBlock);
746
747 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000748 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000749
750 // All breaks should go to the code following the loop.
751 BreakTargetBlock = LoopSuccessor;
752
753 // NULL out Block to force lazy instantiation of blocks for the body.
754 Block = NULL;
755
756 // Create the body. The returned block is the entry to the loop body.
757 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000758
759 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000760 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000761 else if (Block)
762 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000763
764 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000765 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000766 }
767
768 // Link up the condition block with the code that follows the loop.
769 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000770 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000771
772 // There can be no more statements in the condition block
773 // since we loop back to this block. NULL out Block to force
774 // lazy creation of another block.
775 Block = NULL;
776
777 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000778 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000779 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000780}
781
782CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
783 // "do...while" is a control-flow statement. Thus we stop processing the
784 // current block.
785
786 CFGBlock* LoopSuccessor = NULL;
787
788 if (Block) {
789 FinishBlock(Block);
790 LoopSuccessor = Block;
791 }
792 else LoopSuccessor = Succ;
793
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000794 // Because of short-circuit evaluation, the condition of the loop
795 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
796 // blocks that evaluate the condition.
797 CFGBlock* ExitConditionBlock = createBlock(false);
798 CFGBlock* EntryConditionBlock = ExitConditionBlock;
799
800 // Set the terminator for the "exit" condition block.
801 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000802
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000803 // Now add the actual condition to the condition block. Because the
804 // condition itself may contain control-flow, new blocks may be created.
805 if (Stmt* C = D->getCond()) {
806 Block = ExitConditionBlock;
807 EntryConditionBlock = addStmt(C);
808 if (Block) FinishBlock(EntryConditionBlock);
809 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000810
Ted Kremenek54827132008-02-27 07:20:00 +0000811 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000812 Succ = EntryConditionBlock;
813
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000814 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000815 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000816 {
817 assert (D->getBody());
818
819 // Save the current values for Block, Succ, and continue and break targets
820 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
821 save_continue(ContinueTargetBlock),
822 save_break(BreakTargetBlock);
823
824 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000825 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000826
827 // All breaks should go to the code following the loop.
828 BreakTargetBlock = LoopSuccessor;
829
830 // NULL out Block to force lazy instantiation of blocks for the body.
831 Block = NULL;
832
833 // Create the body. The returned block is the entry to the loop body.
834 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000835
Ted Kremenekaf603f72007-08-30 18:39:40 +0000836 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000837 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000838 else if (Block)
839 FinishBlock(BodyBlock);
840
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000841 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000842 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000843 }
844
845 // Link up the condition block with the code that follows the loop.
846 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000847 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000848
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000849 // There can be no more statements in the body block(s)
850 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000851 // lazy creation of another block.
852 Block = NULL;
853
854 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000855 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000856 return BodyBlock;
857}
858
859CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
860 // "continue" 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(C);
867
868 // If there is no target for the continue, then we are looking at an
869 // incomplete AST. Handle this by not registering a successor.
870 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
871
872 return Block;
873}
874
875CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
876 // "break" is a control-flow statement. Thus we stop processing the
877 // current block.
878 if (Block) FinishBlock(Block);
879
880 // Now create a new block that ends with the continue statement.
881 Block = createBlock(false);
882 Block->setTerminator(B);
883
884 // If there is no target for the break, then we are looking at an
885 // incomplete AST. Handle this by not registering a successor.
886 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
887
888 return Block;
889}
890
891CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
892 // "switch" is a control-flow statement. Thus we stop processing the
893 // current block.
894 CFGBlock* SwitchSuccessor = NULL;
895
896 if (Block) {
897 FinishBlock(Block);
898 SwitchSuccessor = Block;
899 }
900 else SwitchSuccessor = Succ;
901
902 // Save the current "switch" context.
903 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000904 save_break(BreakTargetBlock),
905 save_default(DefaultCaseBlock);
906
907 // Set the "default" case to be the block after the switch statement.
908 // If the switch statement contains a "default:", this value will
909 // be overwritten with the block for that code.
910 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000911
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000912 // Create a new block that will contain the switch statement.
913 SwitchTerminatedBlock = createBlock(false);
914
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000915 // Now process the switch body. The code after the switch is the implicit
916 // successor.
917 Succ = SwitchSuccessor;
918 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000919
920 // When visiting the body, the case statements should automatically get
921 // linked up to the switch. We also don't keep a pointer to the body,
922 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000923 assert (S->getBody() && "switch must contain a non-NULL body");
924 Block = NULL;
925 CFGBlock *BodyBlock = Visit(S->getBody());
926 if (Block) FinishBlock(BodyBlock);
927
Ted Kremenek295222c2008-02-13 21:46:34 +0000928 // If we have no "default:" case, the default transition is to the
929 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000930 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +0000931
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000932 // Add the terminator and condition in the switch block.
933 SwitchTerminatedBlock->setTerminator(S);
934 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000935 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000936
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000937 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000938}
939
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000940CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
941 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000942 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000943
944 if (S->getSubStmt()) Visit(S->getSubStmt());
945 CFGBlock* CaseBlock = Block;
946 if (!CaseBlock) CaseBlock = createBlock();
947
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000948 // Cases statements partition blocks, so this is the top of
949 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek9cffe732007-08-29 23:20:49 +0000950 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000951 FinishBlock(CaseBlock);
952
953 // Add this block to the list of successors for the block with the
954 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000955 assert (SwitchTerminatedBlock);
956 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000957
958 // We set Block to NULL to allow lazy creation of a new block (if necessary)
959 Block = NULL;
960
961 // This block is now the implicit successor of other blocks.
962 Succ = CaseBlock;
963
964 return CaseBlock;
965}
Ted Kremenek295222c2008-02-13 21:46:34 +0000966
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000967CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
968 if (S->getSubStmt()) Visit(S->getSubStmt());
969 DefaultCaseBlock = Block;
970 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
971
972 // Default statements partition blocks, so this is the top of
973 // the basic block we were processing (the "default:" is the label).
974 DefaultCaseBlock->setLabel(S);
975 FinishBlock(DefaultCaseBlock);
976
977 // Unlike case statements, we don't add the default block to the
978 // successors for the switch statement immediately. This is done
979 // when we finish processing the switch statement. This allows for
980 // the default case (including a fall-through to the code after the
981 // switch statement) to always be the last successor of a switch-terminated
982 // block.
983
984 // We set Block to NULL to allow lazy creation of a new block (if necessary)
985 Block = NULL;
986
987 // This block is now the implicit successor of other blocks.
988 Succ = DefaultCaseBlock;
989
990 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000991}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000992
Ted Kremenek19bb3562007-08-28 19:26:49 +0000993CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
994 // Lazily create the indirect-goto dispatch block if there isn't one
995 // already.
996 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
997
998 if (!IBlock) {
999 IBlock = createBlock(false);
1000 cfg->setIndirectGotoBlock(IBlock);
1001 }
1002
1003 // IndirectGoto is a control-flow statement. Thus we stop processing the
1004 // current block and create a new one.
1005 if (Block) FinishBlock(Block);
1006 Block = createBlock(false);
1007 Block->setTerminator(I);
1008 Block->addSuccessor(IBlock);
1009 return addStmt(I->getTarget());
1010}
1011
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001012
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001013} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001014
1015/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1016/// block has no successors or predecessors. If this is the first block
1017/// created in the CFG, it is automatically set to be the Entry and Exit
1018/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001019CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001020 bool first_block = begin() == end();
1021
1022 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001023 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001024
1025 // If this is the first block, set it as the Entry and Exit.
1026 if (first_block) Entry = Exit = &front();
1027
1028 // Return the block.
1029 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001030}
1031
Ted Kremenek026473c2007-08-23 16:51:22 +00001032/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1033/// CFG is returned to the caller.
1034CFG* CFG::buildCFG(Stmt* Statement) {
1035 CFGBuilder Builder;
1036 return Builder.buildCFG(Statement);
1037}
1038
1039/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001040void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1041
Ted Kremenek63f58872007-10-01 19:33:33 +00001042//===----------------------------------------------------------------------===//
1043// CFG: Queries for BlkExprs.
1044//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001045
Ted Kremenek63f58872007-10-01 19:33:33 +00001046namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001047 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001048}
1049
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001050static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1051 if (!S)
1052 return;
1053
1054 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1055 if (!*I) continue;
1056
1057 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1058 if (B->isAssignmentOp()) Set.insert(B);
1059
1060 FindSubExprAssignments(*I, Set);
1061 }
1062}
1063
Ted Kremenek63f58872007-10-01 19:33:33 +00001064static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1065 BlkExprMapTy* M = new BlkExprMapTy();
1066
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001067 // Look for assignments that are used as subexpressions. These are the
1068 // only assignments that we want to register as a block-level expression.
1069 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1070
Ted Kremenek63f58872007-10-01 19:33:33 +00001071 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1072 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001073 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001074
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001075 // Iterate over the statements again on identify the Expr* and Stmt* at
1076 // the block-level that are block-level expressions.
1077 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1078 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1079 if (Expr* E = dyn_cast<Expr>(*BI)) {
1080
1081 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1082 // Assignment expressions that are not nested within another
1083 // expression are really "statements" whose value is never
1084 // used by another expression.
1085 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1086 continue;
1087 }
1088 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1089 // Special handling for statement expressions. The last statement
1090 // in the statement expression is also a block-level expr.
Ted Kremenek86946742008-01-17 20:48:37 +00001091 const CompoundStmt* C = S->getSubStmt();
1092 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001093 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001094 (*M)[C->body_back()] = x;
1095 }
1096 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001097
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001098 unsigned x = M->size();
1099 (*M)[E] = x;
1100 }
1101
Ted Kremenek63f58872007-10-01 19:33:33 +00001102 return M;
1103}
1104
Ted Kremenek86946742008-01-17 20:48:37 +00001105CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1106 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001107 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1108
1109 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001110 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001111
1112 if (I == M->end()) return CFG::BlkExprNumTy();
1113 else return CFG::BlkExprNumTy(I->second);
1114}
1115
1116unsigned CFG::getNumBlkExprs() {
1117 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1118 return M->size();
1119 else {
1120 // We assume callers interested in the number of BlkExprs will want
1121 // the map constructed if it doesn't already exist.
1122 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1123 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1124 }
1125}
1126
Ted Kremenek83c01da2008-01-11 00:40:29 +00001127typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1128
1129const std::pair<CFGBlock*,CFGBlock*>*
1130CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1131
1132 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1133 if (!p) p = new BlkEdgeSetTy();
1134
1135 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1136 const_cast<CFGBlock*>(B2))).first);
1137}
1138
Ted Kremenek63f58872007-10-01 19:33:33 +00001139CFG::~CFG() {
1140 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001141 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek63f58872007-10-01 19:33:33 +00001142}
1143
Ted Kremenek7dba8602007-08-29 21:56:09 +00001144//===----------------------------------------------------------------------===//
1145// CFG pretty printing
1146//===----------------------------------------------------------------------===//
1147
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001148namespace {
1149
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001150class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001151
Ted Kremenek42a509f2007-08-31 21:30:12 +00001152 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1153 StmtMapTy StmtMap;
1154 signed CurrentBlock;
1155 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001156
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001157public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001158
Ted Kremenek42a509f2007-08-31 21:30:12 +00001159 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1160 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1161 unsigned j = 1;
1162 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1163 BI != BEnd; ++BI, ++j )
1164 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1165 }
1166 }
1167
1168 virtual ~StmtPrinterHelper() {}
1169
1170 void setBlockID(signed i) { CurrentBlock = i; }
1171 void setStmtID(unsigned i) { CurrentStmt = i; }
1172
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001173 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1174
1175 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001176
1177 if (I == StmtMap.end())
1178 return false;
1179
1180 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1181 && I->second.second == CurrentStmt)
1182 return false;
1183
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001184 OS << "[B" << I->second.first << "." << I->second.second << "]";
1185 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001186 }
1187};
1188
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001189class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1190 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1191
Ted Kremenek42a509f2007-08-31 21:30:12 +00001192 std::ostream& OS;
1193 StmtPrinterHelper* Helper;
1194public:
1195 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1196 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001197
1198 void VisitIfStmt(IfStmt* I) {
1199 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001200 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001201 }
1202
1203 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001204 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001205
1206 void VisitForStmt(ForStmt* F) {
1207 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001208 if (F->getInit()) OS << "...";
1209 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001210 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001211 OS << "; ";
1212 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001213 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001214 }
1215
1216 void VisitWhileStmt(WhileStmt* W) {
1217 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001218 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001219 }
1220
1221 void VisitDoStmt(DoStmt* D) {
1222 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001223 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001224 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001225
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001226 void VisitSwitchStmt(SwitchStmt* S) {
1227 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001228 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001229 }
1230
Ted Kremenek805e9a82007-08-31 21:49:40 +00001231 void VisitConditionalOperator(ConditionalOperator* C) {
1232 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001233 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001234 }
1235
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001236 void VisitChooseExpr(ChooseExpr* C) {
1237 OS << "__builtin_choose_expr( ";
1238 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001239 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001240 }
1241
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001242 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1243 OS << "goto *";
1244 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001245 }
1246
Ted Kremenek805e9a82007-08-31 21:49:40 +00001247 void VisitBinaryOperator(BinaryOperator* B) {
1248 if (!B->isLogicalOp()) {
1249 VisitExpr(B);
1250 return;
1251 }
1252
1253 B->getLHS()->printPretty(OS,Helper);
1254
1255 switch (B->getOpcode()) {
1256 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001257 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001258 return;
1259 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001260 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001261 return;
1262 default:
1263 assert(false && "Invalid logical operator.");
1264 }
1265 }
1266
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001267 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001268 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001269 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001270};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001271
1272
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001273void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1274 if (Helper) {
1275 // special printing for statement-expressions.
1276 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1277 CompoundStmt* Sub = SE->getSubStmt();
1278
1279 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001280 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001281 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001282 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001283 return;
1284 }
1285 }
1286
1287 // special printing for comma expressions.
1288 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1289 if (B->getOpcode() == BinaryOperator::Comma) {
1290 OS << "... , ";
1291 Helper->handledStmt(B->getRHS(),OS);
1292 OS << '\n';
1293 return;
1294 }
1295 }
1296 }
1297
1298 S->printPretty(OS, Helper);
1299
1300 // Expressions need a newline.
1301 if (isa<Expr>(S)) OS << '\n';
1302}
1303
Ted Kremenek42a509f2007-08-31 21:30:12 +00001304void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1305 StmtPrinterHelper* Helper, bool print_edges) {
1306
1307 if (Helper) Helper->setBlockID(B.getBlockID());
1308
Ted Kremenek7dba8602007-08-29 21:56:09 +00001309 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001310 OS << "\n [ B" << B.getBlockID();
1311
1312 if (&B == &cfg->getEntry())
1313 OS << " (ENTRY) ]\n";
1314 else if (&B == &cfg->getExit())
1315 OS << " (EXIT) ]\n";
1316 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001317 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001318 else
1319 OS << " ]\n";
1320
Ted Kremenek9cffe732007-08-29 23:20:49 +00001321 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001322 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1323
1324 if (print_edges)
1325 OS << " ";
1326
Ted Kremenek9cffe732007-08-29 23:20:49 +00001327 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1328 OS << L->getName();
1329 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1330 OS << "case ";
1331 C->getLHS()->printPretty(OS);
1332 if (C->getRHS()) {
1333 OS << " ... ";
1334 C->getRHS()->printPretty(OS);
1335 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001336 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001337 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001338 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001339 else
1340 assert(false && "Invalid label statement in CFGBlock.");
1341
Ted Kremenek9cffe732007-08-29 23:20:49 +00001342 OS << ":\n";
1343 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001344
Ted Kremenekfddd5182007-08-21 21:42:03 +00001345 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001346 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001347
1348 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1349 I != E ; ++I, ++j ) {
1350
Ted Kremenek9cffe732007-08-29 23:20:49 +00001351 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001352 if (print_edges)
1353 OS << " ";
1354
1355 OS << std::setw(3) << j << ": ";
1356
1357 if (Helper)
1358 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001359
1360 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001361 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001362
Ted Kremenek9cffe732007-08-29 23:20:49 +00001363 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001364 if (B.getTerminator()) {
1365 if (print_edges)
1366 OS << " ";
1367
Ted Kremenek9cffe732007-08-29 23:20:49 +00001368 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001369
1370 if (Helper) Helper->setBlockID(-1);
1371
1372 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1373 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001374 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001375 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001376
Ted Kremenek9cffe732007-08-29 23:20:49 +00001377 if (print_edges) {
1378 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001379 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001380 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001381
Ted Kremenek42a509f2007-08-31 21:30:12 +00001382 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1383 I != E; ++I, ++i) {
1384
1385 if (i == 8 || (i-8) == 0)
1386 OS << "\n ";
1387
Ted Kremenek9cffe732007-08-29 23:20:49 +00001388 OS << " B" << (*I)->getBlockID();
1389 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001390
1391 OS << '\n';
1392
1393 // Print the successors of this block.
1394 OS << " Successors (" << B.succ_size() << "):";
1395 i = 0;
1396
1397 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1398 I != E; ++I, ++i) {
1399
1400 if (i == 8 || (i-8) % 10 == 0)
1401 OS << "\n ";
1402
1403 OS << " B" << (*I)->getBlockID();
1404 }
1405
Ted Kremenek9cffe732007-08-29 23:20:49 +00001406 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001407 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001408}
1409
1410} // end anonymous namespace
1411
1412/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001413void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001414
1415/// print - A simple pretty printer of a CFG that outputs to an ostream.
1416void CFG::print(std::ostream& OS) const {
1417
1418 StmtPrinterHelper Helper(this);
1419
1420 // Print the entry block.
1421 print_block(OS, this, getEntry(), &Helper, true);
1422
1423 // Iterate through the CFGBlocks and print them one by one.
1424 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1425 // Skip the entry block, because we already printed it.
1426 if (&(*I) == &getEntry() || &(*I) == &getExit())
1427 continue;
1428
1429 print_block(OS, this, *I, &Helper, true);
1430 }
1431
1432 // Print the exit block.
1433 print_block(OS, this, getExit(), &Helper, true);
1434}
1435
1436/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001437void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001438
1439/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1440/// Generally this will only be called from CFG::print.
1441void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1442 StmtPrinterHelper Helper(cfg);
1443 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001444}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001445
Ted Kremeneka2925852008-01-30 23:02:42 +00001446/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1447void CFGBlock::printTerminator(std::ostream& OS) const {
1448 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1449 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1450}
1451
1452
Ted Kremenek7dba8602007-08-29 21:56:09 +00001453//===----------------------------------------------------------------------===//
1454// CFG Graphviz Visualization
1455//===----------------------------------------------------------------------===//
1456
Ted Kremenek42a509f2007-08-31 21:30:12 +00001457
1458#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001459static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001460#endif
1461
1462void CFG::viewCFG() const {
1463#ifndef NDEBUG
1464 StmtPrinterHelper H(this);
1465 GraphHelper = &H;
1466 llvm::ViewGraph(this,"CFG");
1467 GraphHelper = NULL;
1468#else
1469 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001470 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001471#endif
1472}
1473
Ted Kremenek7dba8602007-08-29 21:56:09 +00001474namespace llvm {
1475template<>
1476struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1477 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1478
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001479#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001480 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001481 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001482 std::string OutStr = Out.str();
1483
1484 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1485
1486 // Process string output to make it nicer...
1487 for (unsigned i = 0; i != OutStr.length(); ++i)
1488 if (OutStr[i] == '\n') { // Left justify
1489 OutStr[i] = '\\';
1490 OutStr.insert(OutStr.begin()+i+1, 'l');
1491 }
1492
1493 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001494#else
1495 return "";
1496#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001497 }
1498};
1499} // end namespace llvm