blob: da8159cdfed2c19e1ab309e8ca6d78d3d8d394fa [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>
Chris Lattner87cf5ac2008-03-10 17:04:53 +000028#include <iostream>
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 Kremenekd4fdee32007-08-23 21:42:29 +0000123 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000124
Ted Kremenekfddd5182007-08-21 21:42:03 +0000125};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000126
127/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
128/// represent an arbitrary statement. Examples include a single expression
129/// or a function body (compound statement). The ownership of the returned
130/// CFG is transferred to the caller. If CFG construction fails, this method
131/// returns NULL.
132CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000133 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000134 if (!Statement) return NULL;
135
136 // Create an empty block that will serve as the exit block for the CFG.
137 // Since this is the first block added to the CFG, it will be implicitly
138 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000139 Succ = createBlock();
140 assert (Succ == &cfg->getExit());
141 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000142
143 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000144 CFGBlock* B = Visit(Statement);
145 if (!B) B = Succ;
146
147 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000148 // Finalize the last constructed block. This usually involves
149 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000150 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000151
152 // Backpatch the gotos whose label -> block mappings we didn't know
153 // when we encountered them.
154 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
155 E = BackpatchBlocks.end(); I != E; ++I ) {
156
157 CFGBlock* B = *I;
158 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
159 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
160
161 // If there is no target for the goto, then we are looking at an
162 // incomplete AST. Handle this by not registering a successor.
163 if (LI == LabelMap.end()) continue;
164
165 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000166 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000167
Ted Kremenek19bb3562007-08-28 19:26:49 +0000168 // Add successors to the Indirect Goto Dispatch block (if we have one).
169 if (CFGBlock* B = cfg->getIndirectGotoBlock())
170 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
171 E = AddressTakenLabels.end(); I != E; ++I ) {
172
173 // Lookup the target block.
174 LabelMapTy::iterator LI = LabelMap.find(*I);
175
176 // If there is no target block that contains label, then we are looking
177 // at an incomplete AST. Handle this by not registering a successor.
178 if (LI == LabelMap.end()) continue;
179
180 B->addSuccessor(LI->second);
181 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000182
Ted Kremenek94b33162007-09-17 16:18:02 +0000183 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000184 }
185
186 // Create an empty entry block that has no predecessors.
187 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000188
Ted Kremenek322f58d2007-09-26 21:23:31 +0000189 // NULL out cfg so that repeated calls to the builder will fail and that
190 // the ownership of the constructed CFG is passed to the caller.
191 CFG* t = cfg;
192 cfg = NULL;
193 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000194}
195
196/// createBlock - Used to lazily create blocks that are connected
197/// to the current (global) succcessor.
198CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000199 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000200 if (add_successor && Succ) B->addSuccessor(Succ);
201 return B;
202}
203
204/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000205/// we must reverse the statements because they have been inserted
206/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000207void CFGBuilder::FinishBlock(CFGBlock* B) {
208 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000209 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000210}
211
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000212/// addStmt - Used to add statements/expressions to the current CFGBlock
213/// "Block". This method calls WalkAST on the passed statement to see if it
214/// contains any short-circuit expressions. If so, it recursively creates
215/// the necessary blocks for such expressions. It returns the "topmost" block
216/// of the created blocks, or the original value of "Block" when this method
217/// was called if no additional blocks are created.
218CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000219 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000220 return WalkAST(S,true);
221}
222
223/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000224/// add extra blocks for ternary operators, &&, and ||. We also
225/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000226CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
227 switch (S->getStmtClass()) {
228 case Stmt::ConditionalOperatorClass: {
229 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000230
231 // Create the confluence block that will "merge" the results
232 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000233 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
234 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000235 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000236
237 // Create a block for the LHS expression if there is an LHS expression.
238 // A GCC extension allows LHS to be NULL, causing the condition to
239 // be the value that is returned instead.
240 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000241 Succ = ConfluenceBlock;
242 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000243 CFGBlock* LHSBlock = NULL;
244 if (C->getLHS()) {
245 LHSBlock = Visit(C->getLHS());
246 FinishBlock(LHSBlock);
247 Block = NULL;
248 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000249
Ted Kremenekecc04c92007-11-26 18:20:26 +0000250 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000251 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000252 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000253 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000254
Ted Kremenekecc04c92007-11-26 18:20:26 +0000255 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000256 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000257
258 if (LHSBlock)
259 Block->addSuccessor(LHSBlock);
260 else {
261 // If we have no LHS expression, add the ConfluenceBlock as a direct
262 // successor for the block containing the condition. Moreover,
263 // we need to reverse the order of the predecessors in the
264 // ConfluenceBlock because the RHSBlock will have been added to
265 // the succcessors already, and we want the first predecessor to the
266 // the block containing the expression for the case when the ternary
267 // expression evaluates to true.
268 Block->addSuccessor(ConfluenceBlock);
269 assert (ConfluenceBlock->pred_size() == 2);
270 std::reverse(ConfluenceBlock->pred_begin(),
271 ConfluenceBlock->pred_end());
272 }
273
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000274 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000275
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000276 Block->setTerminator(C);
277 return addStmt(C->getCond());
278 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000279
280 case Stmt::ChooseExprClass: {
281 ChooseExpr* C = cast<ChooseExpr>(S);
282
283 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
284 ConfluenceBlock->appendStmt(C);
285 FinishBlock(ConfluenceBlock);
286
287 Succ = ConfluenceBlock;
288 Block = NULL;
289 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000290 FinishBlock(LHSBlock);
291
Ted Kremenek49a436d2007-08-31 17:03:41 +0000292 Succ = ConfluenceBlock;
293 Block = NULL;
294 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000295 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000296
297 Block = createBlock(false);
298 Block->addSuccessor(LHSBlock);
299 Block->addSuccessor(RHSBlock);
300 Block->setTerminator(C);
301 return addStmt(C->getCond());
302 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000303
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000304 case Stmt::DeclStmtClass: {
305 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
306 Block->appendStmt(S);
307
308 StmtIterator I(D);
309 return WalkAST_VisitDeclSubExprs(I);
310 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000311
Ted Kremenek19bb3562007-08-28 19:26:49 +0000312 case Stmt::AddrLabelExprClass: {
313 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
314 AddressTakenLabels.insert(A->getLabel());
315
316 if (AlwaysAddStmt) Block->appendStmt(S);
317 return Block;
318 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000319
Ted Kremenek15c27a82007-08-28 18:30:10 +0000320 case Stmt::StmtExprClass:
321 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000322
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000323 case Stmt::UnaryOperatorClass: {
324 UnaryOperator* U = cast<UnaryOperator>(S);
325
326 // sizeof(expressions). For such expressions,
327 // the subexpression is not really evaluated, so
328 // we don't care about control-flow within the sizeof.
329 if (U->getOpcode() == UnaryOperator::SizeOf) {
330 Block->appendStmt(S);
331 return Block;
332 }
333
334 break;
335 }
336
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000337 case Stmt::BinaryOperatorClass: {
338 BinaryOperator* B = cast<BinaryOperator>(S);
339
340 if (B->isLogicalOp()) { // && or ||
341 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
342 ConfluenceBlock->appendStmt(B);
343 FinishBlock(ConfluenceBlock);
344
345 // create the block evaluating the LHS
346 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000347 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000348
349 // create the block evaluating the RHS
350 Succ = ConfluenceBlock;
351 Block = NULL;
352 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000353
354 // Now link the LHSBlock with RHSBlock.
355 if (B->getOpcode() == BinaryOperator::LOr) {
356 LHSBlock->addSuccessor(ConfluenceBlock);
357 LHSBlock->addSuccessor(RHSBlock);
358 }
359 else {
360 assert (B->getOpcode() == BinaryOperator::LAnd);
361 LHSBlock->addSuccessor(RHSBlock);
362 LHSBlock->addSuccessor(ConfluenceBlock);
363 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000364
365 // Generate the blocks for evaluating the LHS.
366 Block = LHSBlock;
367 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000368 }
369 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
370 Block->appendStmt(B);
371 addStmt(B->getRHS());
372 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000373 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000374
375 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000376 }
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000377
378 case Stmt::ParenExprClass:
379 return WalkAST(cast<ParenExpr>(S)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000380
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000381 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000382 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000383 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000384
385 if (AlwaysAddStmt) Block->appendStmt(S);
386 return WalkAST_VisitChildren(S);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000387}
388
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000389/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
390/// DeclStmts. Because the initialization code (and sometimes the
391/// the type declarations) for DeclStmts can contain arbitrary expressions,
392/// we must linearize declarations to handle arbitrary control-flow induced by
393/// those expressions.
394CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000395 if (I == StmtIterator())
396 return Block;
397
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000398 Stmt* S = *I;
399 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000400 WalkAST_VisitDeclSubExprs(I);
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000401
402 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000403
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000404 switch (S->getStmtClass()) {
405 case Stmt::IntegerLiteralClass:
406 case Stmt::CharacterLiteralClass:
407 case Stmt::StringLiteralClass:
408 break;
409
410 // All other cases.
411
412 default:
413 Block = addStmt(S);
414 }
415
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000416 return Block;
417}
418
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000419/// WalkAST_VisitChildren - Utility method to call WalkAST on the
420/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000421CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000422 CFGBlock* B = Block;
423 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
424 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000425 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000426
427 return B;
428}
429
Ted Kremenek15c27a82007-08-28 18:30:10 +0000430/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
431/// expressions (a GCC extension).
432CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
433 Block->appendStmt(S);
434 return VisitCompoundStmt(S->getSubStmt());
435}
436
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000437/// VisitStmt - Handle statements with no branching control flow.
438CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
439 // We cannot assume that we are in the middle of a basic block, since
440 // the CFG might only be constructed for this single statement. If
441 // we have no current basic block, just create one lazily.
442 if (!Block) Block = createBlock();
443
444 // Simply add the statement to the current block. We actually
445 // insert statements in reverse order; this order is reversed later
446 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000447 addStmt(Statement);
448
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000449 return Block;
450}
451
452CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
453 return Block;
454}
455
456CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000457
Ted Kremenekd34066c2008-02-26 00:22:58 +0000458 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
459 I != E; ++I ) {
460 Visit(*I);
461 }
462
463 return Block;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000464}
465
466CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
467 // We may see an if statement in the middle of a basic block, or
468 // it may be the first statement we are processing. In either case,
469 // we create a new basic block. First, we create the blocks for
470 // the then...else statements, and then we create the block containing
471 // the if statement. If we were in the middle of a block, we
472 // stop processing that block and reverse its statements. That block
473 // is then the implicit successor for the "then" and "else" clauses.
474
475 // The block we were proccessing is now finished. Make it the
476 // successor block.
477 if (Block) {
478 Succ = Block;
479 FinishBlock(Block);
480 }
481
482 // Process the false branch. NULL out Block so that the recursive
483 // call to Visit will create a new basic block.
484 // Null out Block so that all successor
485 CFGBlock* ElseBlock = Succ;
486
487 if (Stmt* Else = I->getElse()) {
488 SaveAndRestore<CFGBlock*> sv(Succ);
489
490 // NULL out Block so that the recursive call to Visit will
491 // create a new basic block.
492 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000493 ElseBlock = Visit(Else);
494
495 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
496 ElseBlock = sv.get();
497 else if (Block)
498 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000499 }
500
501 // Process the true branch. NULL out Block so that the recursive
502 // call to Visit will create a new basic block.
503 // Null out Block so that all successor
504 CFGBlock* ThenBlock;
505 {
506 Stmt* Then = I->getThen();
507 assert (Then);
508 SaveAndRestore<CFGBlock*> sv(Succ);
509 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000510 ThenBlock = Visit(Then);
511
512 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
513 ThenBlock = sv.get();
514 else if (Block)
515 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000516 }
517
518 // Now create a new block containing the if statement.
519 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000520
521 // Set the terminator of the new block to the If statement.
522 Block->setTerminator(I);
523
524 // Now add the successors.
525 Block->addSuccessor(ThenBlock);
526 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000527
528 // Add the condition as the last statement in the new block. This
529 // may create new blocks as the condition may contain control-flow. Any
530 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000531 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000532}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000533
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000534
535CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
536 // If we were in the middle of a block we stop processing that block
537 // and reverse its statements.
538 //
539 // NOTE: If a "return" appears in the middle of a block, this means
540 // that the code afterwards is DEAD (unreachable). We still
541 // keep a basic block for that code; a simple "mark-and-sweep"
542 // from the entry block will be able to report such dead
543 // blocks.
544 if (Block) FinishBlock(Block);
545
546 // Create the new block.
547 Block = createBlock(false);
548
549 // The Exit block is the only successor.
550 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000551
552 // Add the return statement to the block. This may create new blocks
553 // if R contains control-flow (short-circuit operations).
554 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000555}
556
557CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
558 // Get the block of the labeled statement. Add it to our map.
559 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000560
561 if (!LabelBlock) // This can happen when the body is empty, i.e.
562 LabelBlock=createBlock(); // scopes that only contains NullStmts.
563
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000564 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
565 LabelMap[ L ] = LabelBlock;
566
567 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000568 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000569 // label (and we have already processed the substatement) there is no
570 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000571 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000572 FinishBlock(LabelBlock);
573
574 // We set Block to NULL to allow lazy creation of a new block
575 // (if necessary);
576 Block = NULL;
577
578 // This block is now the implicit successor of other blocks.
579 Succ = LabelBlock;
580
581 return LabelBlock;
582}
583
584CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
585 // Goto is a control-flow statement. Thus we stop processing the
586 // current block and create a new one.
587 if (Block) FinishBlock(Block);
588 Block = createBlock(false);
589 Block->setTerminator(G);
590
591 // If we already know the mapping to the label block add the
592 // successor now.
593 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
594
595 if (I == LabelMap.end())
596 // We will need to backpatch this block later.
597 BackpatchBlocks.push_back(Block);
598 else
599 Block->addSuccessor(I->second);
600
601 return Block;
602}
603
604CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
605 // "for" is a control-flow statement. Thus we stop processing the
606 // current block.
607
608 CFGBlock* LoopSuccessor = NULL;
609
610 if (Block) {
611 FinishBlock(Block);
612 LoopSuccessor = Block;
613 }
614 else LoopSuccessor = Succ;
615
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000616 // Because of short-circuit evaluation, the condition of the loop
617 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
618 // blocks that evaluate the condition.
619 CFGBlock* ExitConditionBlock = createBlock(false);
620 CFGBlock* EntryConditionBlock = ExitConditionBlock;
621
622 // Set the terminator for the "exit" condition block.
623 ExitConditionBlock->setTerminator(F);
624
625 // Now add the actual condition to the condition block. Because the
626 // condition itself may contain control-flow, new blocks may be created.
627 if (Stmt* C = F->getCond()) {
628 Block = ExitConditionBlock;
629 EntryConditionBlock = addStmt(C);
630 if (Block) FinishBlock(EntryConditionBlock);
631 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000632
633 // The condition block is the implicit successor for the loop body as
634 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000635 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000636
637 // Now create the loop body.
638 {
639 assert (F->getBody());
640
641 // Save the current values for Block, Succ, and continue and break targets
642 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
643 save_continue(ContinueTargetBlock),
644 save_break(BreakTargetBlock);
645
646 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000647 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000648
649 // All breaks should go to the code following the loop.
650 BreakTargetBlock = LoopSuccessor;
651
Ted Kremenekaf603f72007-08-30 18:39:40 +0000652 // Create a new block to contain the (bottom) of the loop body.
653 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000654
655 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000656 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000657
658 // Now populate the body block, and in the process create new blocks
659 // as we walk the body of the loop.
660 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000661
662 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000663 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000664 else if (Block)
665 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000666
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000667 // This new body block is a successor to our "exit" condition block.
668 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000669 }
670
671 // Link up the condition block with the code that follows the loop.
672 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000673 ExitConditionBlock->addSuccessor(LoopSuccessor);
674
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000675 // If the loop contains initialization, create a new block for those
676 // statements. This block can also contain statements that precede
677 // the loop.
678 if (Stmt* I = F->getInit()) {
679 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000680 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000681 }
682 else {
683 // There is no loop initialization. We are thus basically a while
684 // loop. NULL out Block to force lazy block construction.
685 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000686 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000687 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000688 }
689}
690
691CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
692 // "while" is a control-flow statement. Thus we stop processing the
693 // current block.
694
695 CFGBlock* LoopSuccessor = NULL;
696
697 if (Block) {
698 FinishBlock(Block);
699 LoopSuccessor = Block;
700 }
701 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000702
703 // Because of short-circuit evaluation, the condition of the loop
704 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
705 // blocks that evaluate the condition.
706 CFGBlock* ExitConditionBlock = createBlock(false);
707 CFGBlock* EntryConditionBlock = ExitConditionBlock;
708
709 // Set the terminator for the "exit" condition block.
710 ExitConditionBlock->setTerminator(W);
711
712 // Now add the actual condition to the condition block. Because the
713 // condition itself may contain control-flow, new blocks may be created.
714 // Thus we update "Succ" after adding the condition.
715 if (Stmt* C = W->getCond()) {
716 Block = ExitConditionBlock;
717 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000718 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000719 if (Block) FinishBlock(EntryConditionBlock);
720 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000721
722 // The condition block is the implicit successor for the loop body as
723 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000724 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000725
726 // Process the loop body.
727 {
728 assert (W->getBody());
729
730 // Save the current values for Block, Succ, and continue and break targets
731 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
732 save_continue(ContinueTargetBlock),
733 save_break(BreakTargetBlock);
734
735 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000736 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000737
738 // All breaks should go to the code following the loop.
739 BreakTargetBlock = LoopSuccessor;
740
741 // NULL out Block to force lazy instantiation of blocks for the body.
742 Block = NULL;
743
744 // Create the body. The returned block is the entry to the loop body.
745 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000746
747 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000748 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000749 else if (Block)
750 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000751
752 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000753 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000754 }
755
756 // Link up the condition block with the code that follows the loop.
757 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000758 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000759
760 // There can be no more statements in the condition block
761 // since we loop back to this block. NULL out Block to force
762 // lazy creation of another block.
763 Block = NULL;
764
765 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000766 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000767 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000768}
769
770CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
771 // "do...while" is a control-flow statement. Thus we stop processing the
772 // current block.
773
774 CFGBlock* LoopSuccessor = NULL;
775
776 if (Block) {
777 FinishBlock(Block);
778 LoopSuccessor = Block;
779 }
780 else LoopSuccessor = Succ;
781
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000782 // Because of short-circuit evaluation, the condition of the loop
783 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
784 // blocks that evaluate the condition.
785 CFGBlock* ExitConditionBlock = createBlock(false);
786 CFGBlock* EntryConditionBlock = ExitConditionBlock;
787
788 // Set the terminator for the "exit" condition block.
789 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000790
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000791 // Now add the actual condition to the condition block. Because the
792 // condition itself may contain control-flow, new blocks may be created.
793 if (Stmt* C = D->getCond()) {
794 Block = ExitConditionBlock;
795 EntryConditionBlock = addStmt(C);
796 if (Block) FinishBlock(EntryConditionBlock);
797 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000798
Ted Kremenek54827132008-02-27 07:20:00 +0000799 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000800 Succ = EntryConditionBlock;
801
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000802 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000803 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000804 {
805 assert (D->getBody());
806
807 // Save the current values for Block, Succ, and continue and break targets
808 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
809 save_continue(ContinueTargetBlock),
810 save_break(BreakTargetBlock);
811
812 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000813 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000814
815 // All breaks should go to the code following the loop.
816 BreakTargetBlock = LoopSuccessor;
817
818 // NULL out Block to force lazy instantiation of blocks for the body.
819 Block = NULL;
820
821 // Create the body. The returned block is the entry to the loop body.
822 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000823
Ted Kremenekaf603f72007-08-30 18:39:40 +0000824 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000825 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000826 else if (Block)
827 FinishBlock(BodyBlock);
828
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000829 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000830 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000831 }
832
833 // Link up the condition block with the code that follows the loop.
834 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000835 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000836
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000837 // There can be no more statements in the body block(s)
838 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000839 // lazy creation of another block.
840 Block = NULL;
841
842 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000843 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000844 return BodyBlock;
845}
846
847CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
848 // "continue" is a control-flow statement. Thus we stop processing the
849 // current block.
850 if (Block) FinishBlock(Block);
851
852 // Now create a new block that ends with the continue statement.
853 Block = createBlock(false);
854 Block->setTerminator(C);
855
856 // If there is no target for the continue, then we are looking at an
857 // incomplete AST. Handle this by not registering a successor.
858 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
859
860 return Block;
861}
862
863CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
864 // "break" is a control-flow statement. Thus we stop processing the
865 // current block.
866 if (Block) FinishBlock(Block);
867
868 // Now create a new block that ends with the continue statement.
869 Block = createBlock(false);
870 Block->setTerminator(B);
871
872 // If there is no target for the break, then we are looking at an
873 // incomplete AST. Handle this by not registering a successor.
874 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
875
876 return Block;
877}
878
879CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
880 // "switch" is a control-flow statement. Thus we stop processing the
881 // current block.
882 CFGBlock* SwitchSuccessor = NULL;
883
884 if (Block) {
885 FinishBlock(Block);
886 SwitchSuccessor = Block;
887 }
888 else SwitchSuccessor = Succ;
889
890 // Save the current "switch" context.
891 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000892 save_break(BreakTargetBlock),
893 save_default(DefaultCaseBlock);
894
895 // Set the "default" case to be the block after the switch statement.
896 // If the switch statement contains a "default:", this value will
897 // be overwritten with the block for that code.
898 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000899
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000900 // Create a new block that will contain the switch statement.
901 SwitchTerminatedBlock = createBlock(false);
902
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000903 // Now process the switch body. The code after the switch is the implicit
904 // successor.
905 Succ = SwitchSuccessor;
906 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000907
908 // When visiting the body, the case statements should automatically get
909 // linked up to the switch. We also don't keep a pointer to the body,
910 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000911 assert (S->getBody() && "switch must contain a non-NULL body");
912 Block = NULL;
913 CFGBlock *BodyBlock = Visit(S->getBody());
914 if (Block) FinishBlock(BodyBlock);
915
Ted Kremenek295222c2008-02-13 21:46:34 +0000916 // If we have no "default:" case, the default transition is to the
917 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000918 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +0000919
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000920 // Add the terminator and condition in the switch block.
921 SwitchTerminatedBlock->setTerminator(S);
922 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000923 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000924
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000925 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000926}
927
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000928CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
929 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000930 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000931
932 if (S->getSubStmt()) Visit(S->getSubStmt());
933 CFGBlock* CaseBlock = Block;
934 if (!CaseBlock) CaseBlock = createBlock();
935
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000936 // Cases statements partition blocks, so this is the top of
937 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek9cffe732007-08-29 23:20:49 +0000938 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000939 FinishBlock(CaseBlock);
940
941 // Add this block to the list of successors for the block with the
942 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000943 assert (SwitchTerminatedBlock);
944 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000945
946 // We set Block to NULL to allow lazy creation of a new block (if necessary)
947 Block = NULL;
948
949 // This block is now the implicit successor of other blocks.
950 Succ = CaseBlock;
951
952 return CaseBlock;
953}
Ted Kremenek295222c2008-02-13 21:46:34 +0000954
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000955CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
956 if (S->getSubStmt()) Visit(S->getSubStmt());
957 DefaultCaseBlock = Block;
958 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
959
960 // Default statements partition blocks, so this is the top of
961 // the basic block we were processing (the "default:" is the label).
962 DefaultCaseBlock->setLabel(S);
963 FinishBlock(DefaultCaseBlock);
964
965 // Unlike case statements, we don't add the default block to the
966 // successors for the switch statement immediately. This is done
967 // when we finish processing the switch statement. This allows for
968 // the default case (including a fall-through to the code after the
969 // switch statement) to always be the last successor of a switch-terminated
970 // block.
971
972 // We set Block to NULL to allow lazy creation of a new block (if necessary)
973 Block = NULL;
974
975 // This block is now the implicit successor of other blocks.
976 Succ = DefaultCaseBlock;
977
978 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +0000979}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000980
Ted Kremenek19bb3562007-08-28 19:26:49 +0000981CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
982 // Lazily create the indirect-goto dispatch block if there isn't one
983 // already.
984 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
985
986 if (!IBlock) {
987 IBlock = createBlock(false);
988 cfg->setIndirectGotoBlock(IBlock);
989 }
990
991 // IndirectGoto is a control-flow statement. Thus we stop processing the
992 // current block and create a new one.
993 if (Block) FinishBlock(Block);
994 Block = createBlock(false);
995 Block->setTerminator(I);
996 Block->addSuccessor(IBlock);
997 return addStmt(I->getTarget());
998}
999
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001000
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001001} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001002
1003/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1004/// block has no successors or predecessors. If this is the first block
1005/// created in the CFG, it is automatically set to be the Entry and Exit
1006/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001007CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001008 bool first_block = begin() == end();
1009
1010 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001011 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001012
1013 // If this is the first block, set it as the Entry and Exit.
1014 if (first_block) Entry = Exit = &front();
1015
1016 // Return the block.
1017 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001018}
1019
Ted Kremenek026473c2007-08-23 16:51:22 +00001020/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1021/// CFG is returned to the caller.
1022CFG* CFG::buildCFG(Stmt* Statement) {
1023 CFGBuilder Builder;
1024 return Builder.buildCFG(Statement);
1025}
1026
1027/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001028void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1029
Ted Kremenek63f58872007-10-01 19:33:33 +00001030//===----------------------------------------------------------------------===//
1031// CFG: Queries for BlkExprs.
1032//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001033
Ted Kremenek63f58872007-10-01 19:33:33 +00001034namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001035 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001036}
1037
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001038static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1039 if (!S)
1040 return;
1041
1042 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1043 if (!*I) continue;
1044
1045 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1046 if (B->isAssignmentOp()) Set.insert(B);
1047
1048 FindSubExprAssignments(*I, Set);
1049 }
1050}
1051
Ted Kremenek63f58872007-10-01 19:33:33 +00001052static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1053 BlkExprMapTy* M = new BlkExprMapTy();
1054
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001055 // Look for assignments that are used as subexpressions. These are the
1056 // only assignments that we want to register as a block-level expression.
1057 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1058
Ted Kremenek63f58872007-10-01 19:33:33 +00001059 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1060 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001061 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001062
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001063 // Iterate over the statements again on identify the Expr* and Stmt* at
1064 // the block-level that are block-level expressions.
1065 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1066 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1067 if (Expr* E = dyn_cast<Expr>(*BI)) {
1068
1069 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1070 // Assignment expressions that are not nested within another
1071 // expression are really "statements" whose value is never
1072 // used by another expression.
1073 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1074 continue;
1075 }
1076 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1077 // Special handling for statement expressions. The last statement
1078 // in the statement expression is also a block-level expr.
Ted Kremenek86946742008-01-17 20:48:37 +00001079 const CompoundStmt* C = S->getSubStmt();
1080 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001081 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001082 (*M)[C->body_back()] = x;
1083 }
1084 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001085
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001086 unsigned x = M->size();
1087 (*M)[E] = x;
1088 }
1089
Ted Kremenek63f58872007-10-01 19:33:33 +00001090 return M;
1091}
1092
Ted Kremenek86946742008-01-17 20:48:37 +00001093CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1094 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001095 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1096
1097 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001098 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001099
1100 if (I == M->end()) return CFG::BlkExprNumTy();
1101 else return CFG::BlkExprNumTy(I->second);
1102}
1103
1104unsigned CFG::getNumBlkExprs() {
1105 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1106 return M->size();
1107 else {
1108 // We assume callers interested in the number of BlkExprs will want
1109 // the map constructed if it doesn't already exist.
1110 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1111 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1112 }
1113}
1114
Ted Kremenek83c01da2008-01-11 00:40:29 +00001115typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1116
1117const std::pair<CFGBlock*,CFGBlock*>*
1118CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1119
1120 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1121 if (!p) p = new BlkEdgeSetTy();
1122
1123 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1124 const_cast<CFGBlock*>(B2))).first);
1125}
1126
Ted Kremenek63f58872007-10-01 19:33:33 +00001127CFG::~CFG() {
1128 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek83c01da2008-01-11 00:40:29 +00001129 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek63f58872007-10-01 19:33:33 +00001130}
1131
Ted Kremenek7dba8602007-08-29 21:56:09 +00001132//===----------------------------------------------------------------------===//
1133// CFG pretty printing
1134//===----------------------------------------------------------------------===//
1135
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001136namespace {
1137
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001138class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001139
Ted Kremenek42a509f2007-08-31 21:30:12 +00001140 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1141 StmtMapTy StmtMap;
1142 signed CurrentBlock;
1143 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001144
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001145public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001146
Ted Kremenek42a509f2007-08-31 21:30:12 +00001147 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1148 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1149 unsigned j = 1;
1150 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1151 BI != BEnd; ++BI, ++j )
1152 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1153 }
1154 }
1155
1156 virtual ~StmtPrinterHelper() {}
1157
1158 void setBlockID(signed i) { CurrentBlock = i; }
1159 void setStmtID(unsigned i) { CurrentStmt = i; }
1160
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001161 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1162
1163 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001164
1165 if (I == StmtMap.end())
1166 return false;
1167
1168 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1169 && I->second.second == CurrentStmt)
1170 return false;
1171
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001172 OS << "[B" << I->second.first << "." << I->second.second << "]";
1173 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001174 }
1175};
1176
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001177class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1178 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1179
Ted Kremenek42a509f2007-08-31 21:30:12 +00001180 std::ostream& OS;
1181 StmtPrinterHelper* Helper;
1182public:
1183 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1184 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001185
1186 void VisitIfStmt(IfStmt* I) {
1187 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001188 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001189 }
1190
1191 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001192 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001193
1194 void VisitForStmt(ForStmt* F) {
1195 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001196 if (F->getInit()) OS << "...";
1197 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001198 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001199 OS << "; ";
1200 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001201 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001202 }
1203
1204 void VisitWhileStmt(WhileStmt* W) {
1205 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001206 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001207 }
1208
1209 void VisitDoStmt(DoStmt* D) {
1210 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001211 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001212 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001213
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001214 void VisitSwitchStmt(SwitchStmt* S) {
1215 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001216 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001217 }
1218
Ted Kremenek805e9a82007-08-31 21:49:40 +00001219 void VisitConditionalOperator(ConditionalOperator* C) {
1220 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001221 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001222 }
1223
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001224 void VisitChooseExpr(ChooseExpr* C) {
1225 OS << "__builtin_choose_expr( ";
1226 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001227 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001228 }
1229
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001230 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1231 OS << "goto *";
1232 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001233 }
1234
Ted Kremenek805e9a82007-08-31 21:49:40 +00001235 void VisitBinaryOperator(BinaryOperator* B) {
1236 if (!B->isLogicalOp()) {
1237 VisitExpr(B);
1238 return;
1239 }
1240
1241 B->getLHS()->printPretty(OS,Helper);
1242
1243 switch (B->getOpcode()) {
1244 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001245 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001246 return;
1247 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001248 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001249 return;
1250 default:
1251 assert(false && "Invalid logical operator.");
1252 }
1253 }
1254
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001255 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001256 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001257 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001258};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001259
1260
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001261void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1262 if (Helper) {
1263 // special printing for statement-expressions.
1264 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1265 CompoundStmt* Sub = SE->getSubStmt();
1266
1267 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001268 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001269 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001270 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001271 return;
1272 }
1273 }
1274
1275 // special printing for comma expressions.
1276 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1277 if (B->getOpcode() == BinaryOperator::Comma) {
1278 OS << "... , ";
1279 Helper->handledStmt(B->getRHS(),OS);
1280 OS << '\n';
1281 return;
1282 }
1283 }
1284 }
1285
1286 S->printPretty(OS, Helper);
1287
1288 // Expressions need a newline.
1289 if (isa<Expr>(S)) OS << '\n';
1290}
1291
Ted Kremenek42a509f2007-08-31 21:30:12 +00001292void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1293 StmtPrinterHelper* Helper, bool print_edges) {
1294
1295 if (Helper) Helper->setBlockID(B.getBlockID());
1296
Ted Kremenek7dba8602007-08-29 21:56:09 +00001297 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001298 OS << "\n [ B" << B.getBlockID();
1299
1300 if (&B == &cfg->getEntry())
1301 OS << " (ENTRY) ]\n";
1302 else if (&B == &cfg->getExit())
1303 OS << " (EXIT) ]\n";
1304 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001305 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001306 else
1307 OS << " ]\n";
1308
Ted Kremenek9cffe732007-08-29 23:20:49 +00001309 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001310 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1311
1312 if (print_edges)
1313 OS << " ";
1314
Ted Kremenek9cffe732007-08-29 23:20:49 +00001315 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1316 OS << L->getName();
1317 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1318 OS << "case ";
1319 C->getLHS()->printPretty(OS);
1320 if (C->getRHS()) {
1321 OS << " ... ";
1322 C->getRHS()->printPretty(OS);
1323 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001324 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001325 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001326 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001327 else
1328 assert(false && "Invalid label statement in CFGBlock.");
1329
Ted Kremenek9cffe732007-08-29 23:20:49 +00001330 OS << ":\n";
1331 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001332
Ted Kremenekfddd5182007-08-21 21:42:03 +00001333 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001334 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001335
1336 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1337 I != E ; ++I, ++j ) {
1338
Ted Kremenek9cffe732007-08-29 23:20:49 +00001339 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001340 if (print_edges)
1341 OS << " ";
1342
1343 OS << std::setw(3) << j << ": ";
1344
1345 if (Helper)
1346 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001347
1348 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001349 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001350
Ted Kremenek9cffe732007-08-29 23:20:49 +00001351 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001352 if (B.getTerminator()) {
1353 if (print_edges)
1354 OS << " ";
1355
Ted Kremenek9cffe732007-08-29 23:20:49 +00001356 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001357
1358 if (Helper) Helper->setBlockID(-1);
1359
1360 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1361 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001362 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001363 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001364
Ted Kremenek9cffe732007-08-29 23:20:49 +00001365 if (print_edges) {
1366 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001367 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001368 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001369
Ted Kremenek42a509f2007-08-31 21:30:12 +00001370 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1371 I != E; ++I, ++i) {
1372
1373 if (i == 8 || (i-8) == 0)
1374 OS << "\n ";
1375
Ted Kremenek9cffe732007-08-29 23:20:49 +00001376 OS << " B" << (*I)->getBlockID();
1377 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001378
1379 OS << '\n';
1380
1381 // Print the successors of this block.
1382 OS << " Successors (" << B.succ_size() << "):";
1383 i = 0;
1384
1385 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1386 I != E; ++I, ++i) {
1387
1388 if (i == 8 || (i-8) % 10 == 0)
1389 OS << "\n ";
1390
1391 OS << " B" << (*I)->getBlockID();
1392 }
1393
Ted Kremenek9cffe732007-08-29 23:20:49 +00001394 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001395 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001396}
1397
1398} // end anonymous namespace
1399
1400/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001401void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001402
1403/// print - A simple pretty printer of a CFG that outputs to an ostream.
1404void CFG::print(std::ostream& OS) const {
1405
1406 StmtPrinterHelper Helper(this);
1407
1408 // Print the entry block.
1409 print_block(OS, this, getEntry(), &Helper, true);
1410
1411 // Iterate through the CFGBlocks and print them one by one.
1412 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1413 // Skip the entry block, because we already printed it.
1414 if (&(*I) == &getEntry() || &(*I) == &getExit())
1415 continue;
1416
1417 print_block(OS, this, *I, &Helper, true);
1418 }
1419
1420 // Print the exit block.
1421 print_block(OS, this, getExit(), &Helper, true);
1422}
1423
1424/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek7e3a89d2007-12-17 19:35:20 +00001425void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001426
1427/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1428/// Generally this will only be called from CFG::print.
1429void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1430 StmtPrinterHelper Helper(cfg);
1431 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001432}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001433
Ted Kremeneka2925852008-01-30 23:02:42 +00001434/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1435void CFGBlock::printTerminator(std::ostream& OS) const {
1436 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1437 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1438}
1439
1440
Ted Kremenek7dba8602007-08-29 21:56:09 +00001441//===----------------------------------------------------------------------===//
1442// CFG Graphviz Visualization
1443//===----------------------------------------------------------------------===//
1444
Ted Kremenek42a509f2007-08-31 21:30:12 +00001445
1446#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001447static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001448#endif
1449
1450void CFG::viewCFG() const {
1451#ifndef NDEBUG
1452 StmtPrinterHelper H(this);
1453 GraphHelper = &H;
1454 llvm::ViewGraph(this,"CFG");
1455 GraphHelper = NULL;
1456#else
1457 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001458 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001459#endif
1460}
1461
Ted Kremenek7dba8602007-08-29 21:56:09 +00001462namespace llvm {
1463template<>
1464struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1465 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1466
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001467#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001468 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001469 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001470 std::string OutStr = Out.str();
1471
1472 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1473
1474 // Process string output to make it nicer...
1475 for (unsigned i = 0; i != OutStr.length(); ++i)
1476 if (OutStr[i] == '\n') { // Left justify
1477 OutStr[i] = '\\';
1478 OutStr.insert(OutStr.begin()+i+1, 'l');
1479 }
1480
1481 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001482#else
1483 return "";
1484#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001485 }
1486};
1487} // end namespace llvm