blob: 9bafb05daf4ca14470101efa03ddca0015017471 [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek97f75312007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
16#include "clang/AST/Expr.h"
Ted Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek5ee98a72008-01-11 00:40:29 +000024#include <set>
Ted Kremenek97f75312007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000027#include <sstream>
Chris Lattner8b8720f2008-03-10 17:04:53 +000028#include <iostream>
Ted Kremenek5ee98a72008-01-11 00:40:29 +000029
Ted Kremenek97f75312007-08-21 21:42:03 +000030using namespace clang;
31
32namespace {
33
Ted Kremenekd6e50602007-08-23 21:26:19 +000034// SaveAndRestore - A utility class that uses RIIA to save and restore
35// the value of a variable.
36template<typename T>
Ted Kremenek98cee3a2008-01-08 18:15:10 +000037struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000038 SaveAndRestore(T& x) : X(x), old_value(x) {}
39 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000040 T get() { return old_value; }
41
Ted Kremenekd6e50602007-08-23 21:26:19 +000042 T& X;
43 T old_value;
44};
Ted Kremenek97f75312007-08-21 21:42:03 +000045
46/// CFGBuilder - This class is implements CFG construction from an AST.
47/// The builder is stateful: an instance of the builder should be used to only
48/// construct a single CFG.
49///
50/// Example usage:
51///
52/// CFGBuilder builder;
53/// CFG* cfg = builder.BuildAST(stmt1);
54///
Ted Kremenek95e854d2007-08-21 22:06:14 +000055/// CFG construction is done via a recursive walk of an AST.
56/// We actually parse the AST in reverse order so that the successor
57/// of a basic block is constructed prior to its predecessor. This
58/// allows us to nicely capture implicit fall-throughs without extra
59/// basic blocks.
60///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000061class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000062 CFG* cfg;
63 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000064 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000065 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000066 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000067 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +000068 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000069
Ted Kremenek0edd3a92007-08-28 19:26:49 +000070 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000071 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
72 LabelMapTy LabelMap;
73
Ted Kremenek0edd3a92007-08-28 19:26:49 +000074 // A list of blocks that end with a "goto" that must be backpatched to
75 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000076 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000077 BackpatchBlocksTy BackpatchBlocks;
78
Ted Kremenek0edd3a92007-08-28 19:26:49 +000079 // A list of labels whose address has been taken (for indirect gotos).
80 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
81 LabelSetTy AddressTakenLabels;
82
Ted Kremenek97f75312007-08-21 21:42:03 +000083public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000084 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000085 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +000086 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000087 // Create an empty CFG.
88 cfg = new CFG();
89 }
90
91 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000092
Ted Kremenek73543912007-08-23 21:42:29 +000093 // buildCFG - Used by external clients to construct the CFG.
94 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000095
Ted Kremenek73543912007-08-23 21:42:29 +000096 // Visitors to walk an AST and construct the CFG. Called by
97 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000098
Ted Kremenek73543912007-08-23 21:42:29 +000099 CFGBlock* VisitStmt(Stmt* Statement);
100 CFGBlock* VisitNullStmt(NullStmt* Statement);
101 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
102 CFGBlock* VisitIfStmt(IfStmt* I);
103 CFGBlock* VisitReturnStmt(ReturnStmt* R);
104 CFGBlock* VisitLabelStmt(LabelStmt* L);
105 CFGBlock* VisitGotoStmt(GotoStmt* G);
106 CFGBlock* VisitForStmt(ForStmt* F);
107 CFGBlock* VisitWhileStmt(WhileStmt* W);
108 CFGBlock* VisitDoStmt(DoStmt* D);
109 CFGBlock* VisitContinueStmt(ContinueStmt* C);
110 CFGBlock* VisitBreakStmt(BreakStmt* B);
111 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
Ted Kremenek97bc3422008-02-13 22:05:39 +0000112 CFGBlock* VisitCaseStmt(CaseStmt* S);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000113 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000114 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000115
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000116 // FIXME: Add support for ObjC-specific control-flow structures.
117
118 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S) {
119 badCFG = true;
120 return Block;
121 }
122
123 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) {
124 badCFG = true;
125 return Block;
126 }
127
Ted Kremenek73543912007-08-23 21:42:29 +0000128private:
129 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000130 CFGBlock* addStmt(Stmt* S);
131 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
132 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000133 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000134 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenek73543912007-08-23 21:42:29 +0000135 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000136
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000137 bool badCFG;
Ted Kremenek97f75312007-08-21 21:42:03 +0000138};
Ted Kremenek73543912007-08-23 21:42:29 +0000139
140/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
141/// represent an arbitrary statement. Examples include a single expression
142/// or a function body (compound statement). The ownership of the returned
143/// CFG is transferred to the caller. If CFG construction fails, this method
144/// returns NULL.
145CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000146 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000147 if (!Statement) return NULL;
148
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000149 badCFG = false;
150
Ted Kremenek73543912007-08-23 21:42:29 +0000151 // Create an empty block that will serve as the exit block for the CFG.
152 // Since this is the first block added to the CFG, it will be implicitly
153 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000154 Succ = createBlock();
155 assert (Succ == &cfg->getExit());
156 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000157
158 // Visit the statements and create the CFG.
Ted Kremenekfa38c7a2008-02-27 17:33:02 +0000159 CFGBlock* B = Visit(Statement);
160 if (!B) B = Succ;
161
162 if (B) {
Ted Kremenek73543912007-08-23 21:42:29 +0000163 // Finalize the last constructed block. This usually involves
164 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000165 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000166
167 // Backpatch the gotos whose label -> block mappings we didn't know
168 // when we encountered them.
169 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
170 E = BackpatchBlocks.end(); I != E; ++I ) {
171
172 CFGBlock* B = *I;
173 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
174 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
175
176 // If there is no target for the goto, then we are looking at an
177 // incomplete AST. Handle this by not registering a successor.
178 if (LI == LabelMap.end()) continue;
179
180 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000181 }
Ted Kremenek73543912007-08-23 21:42:29 +0000182
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000183 // Add successors to the Indirect Goto Dispatch block (if we have one).
184 if (CFGBlock* B = cfg->getIndirectGotoBlock())
185 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
186 E = AddressTakenLabels.end(); I != E; ++I ) {
187
188 // Lookup the target block.
189 LabelMapTy::iterator LI = LabelMap.find(*I);
190
191 // If there is no target block that contains label, then we are looking
192 // at an incomplete AST. Handle this by not registering a successor.
193 if (LI == LabelMap.end()) continue;
194
195 B->addSuccessor(LI->second);
196 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000197
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000198 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000199 }
200
201 // Create an empty entry block that has no predecessors.
202 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000203
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000204 if (badCFG) {
205 delete cfg;
206 cfg = NULL;
207 return NULL;
208 }
209
Ted Kremenek680fcb82007-09-26 21:23:31 +0000210 // NULL out cfg so that repeated calls to the builder will fail and that
211 // the ownership of the constructed CFG is passed to the caller.
212 CFG* t = cfg;
213 cfg = NULL;
214 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000215}
216
217/// createBlock - Used to lazily create blocks that are connected
218/// to the current (global) succcessor.
219CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000220 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000221 if (add_successor && Succ) B->addSuccessor(Succ);
222 return B;
223}
224
225/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000226/// we must reverse the statements because they have been inserted
227/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000228void CFGBuilder::FinishBlock(CFGBlock* B) {
229 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000230 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000231}
232
Ted Kremenek65cfa562007-08-27 21:27:44 +0000233/// addStmt - Used to add statements/expressions to the current CFGBlock
234/// "Block". This method calls WalkAST on the passed statement to see if it
235/// contains any short-circuit expressions. If so, it recursively creates
236/// the necessary blocks for such expressions. It returns the "topmost" block
237/// of the created blocks, or the original value of "Block" when this method
238/// was called if no additional blocks are created.
239CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000240 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-08-27 21:27:44 +0000241 return WalkAST(S,true);
242}
243
244/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000245/// add extra blocks for ternary operators, &&, and ||. We also
246/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek65cfa562007-08-27 21:27:44 +0000247CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
248 switch (S->getStmtClass()) {
249 case Stmt::ConditionalOperatorClass: {
250 ConditionalOperator* C = cast<ConditionalOperator>(S);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000251
252 // Create the confluence block that will "merge" the results
253 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000254 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
255 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000256 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000257
258 // Create a block for the LHS expression if there is an LHS expression.
259 // A GCC extension allows LHS to be NULL, causing the condition to
260 // be the value that is returned instead.
261 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000262 Succ = ConfluenceBlock;
263 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000264 CFGBlock* LHSBlock = NULL;
265 if (C->getLHS()) {
266 LHSBlock = Visit(C->getLHS());
267 FinishBlock(LHSBlock);
268 Block = NULL;
269 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000270
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000271 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000272 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000273 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000274 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000275
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000276 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000277 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000278
279 if (LHSBlock)
280 Block->addSuccessor(LHSBlock);
281 else {
282 // If we have no LHS expression, add the ConfluenceBlock as a direct
283 // successor for the block containing the condition. Moreover,
284 // we need to reverse the order of the predecessors in the
285 // ConfluenceBlock because the RHSBlock will have been added to
286 // the succcessors already, and we want the first predecessor to the
287 // the block containing the expression for the case when the ternary
288 // expression evaluates to true.
289 Block->addSuccessor(ConfluenceBlock);
290 assert (ConfluenceBlock->pred_size() == 2);
291 std::reverse(ConfluenceBlock->pred_begin(),
292 ConfluenceBlock->pred_end());
293 }
294
Ted Kremenek65cfa562007-08-27 21:27:44 +0000295 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000296
Ted Kremenek65cfa562007-08-27 21:27:44 +0000297 Block->setTerminator(C);
298 return addStmt(C->getCond());
299 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000300
301 case Stmt::ChooseExprClass: {
302 ChooseExpr* C = cast<ChooseExpr>(S);
303
304 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
305 ConfluenceBlock->appendStmt(C);
306 FinishBlock(ConfluenceBlock);
307
308 Succ = ConfluenceBlock;
309 Block = NULL;
310 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000311 FinishBlock(LHSBlock);
312
Ted Kremenek7f788422007-08-31 17:03:41 +0000313 Succ = ConfluenceBlock;
314 Block = NULL;
315 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000316 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000317
318 Block = createBlock(false);
319 Block->addSuccessor(LHSBlock);
320 Block->addSuccessor(RHSBlock);
321 Block->setTerminator(C);
322 return addStmt(C->getCond());
323 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000324
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000325 case Stmt::DeclStmtClass: {
326 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
327 Block->appendStmt(S);
328
329 StmtIterator I(D);
330 return WalkAST_VisitDeclSubExprs(I);
331 }
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000332
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000333 case Stmt::AddrLabelExprClass: {
334 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
335 AddressTakenLabels.insert(A->getLabel());
336
337 if (AlwaysAddStmt) Block->appendStmt(S);
338 return Block;
339 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000340
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000341 case Stmt::StmtExprClass:
342 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000343
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000344 case Stmt::UnaryOperatorClass: {
345 UnaryOperator* U = cast<UnaryOperator>(S);
346
347 // sizeof(expressions). For such expressions,
348 // the subexpression is not really evaluated, so
349 // we don't care about control-flow within the sizeof.
350 if (U->getOpcode() == UnaryOperator::SizeOf) {
351 Block->appendStmt(S);
352 return Block;
353 }
354
355 break;
356 }
357
Ted Kremenekcfaae762007-08-27 21:54:41 +0000358 case Stmt::BinaryOperatorClass: {
359 BinaryOperator* B = cast<BinaryOperator>(S);
360
361 if (B->isLogicalOp()) { // && or ||
362 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
363 ConfluenceBlock->appendStmt(B);
364 FinishBlock(ConfluenceBlock);
365
366 // create the block evaluating the LHS
367 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000368 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000369
370 // create the block evaluating the RHS
371 Succ = ConfluenceBlock;
372 Block = NULL;
373 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000374
375 // Now link the LHSBlock with RHSBlock.
376 if (B->getOpcode() == BinaryOperator::LOr) {
377 LHSBlock->addSuccessor(ConfluenceBlock);
378 LHSBlock->addSuccessor(RHSBlock);
379 }
380 else {
381 assert (B->getOpcode() == BinaryOperator::LAnd);
382 LHSBlock->addSuccessor(RHSBlock);
383 LHSBlock->addSuccessor(ConfluenceBlock);
384 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000385
386 // Generate the blocks for evaluating the LHS.
387 Block = LHSBlock;
388 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000389 }
390 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
391 Block->appendStmt(B);
392 addStmt(B->getRHS());
393 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000394 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000395
396 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000397 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000398
399 case Stmt::ParenExprClass:
400 return WalkAST(cast<ParenExpr>(S)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000401
Ted Kremenek65cfa562007-08-27 21:27:44 +0000402 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000403 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000404 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000405
406 if (AlwaysAddStmt) Block->appendStmt(S);
407 return WalkAST_VisitChildren(S);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000408}
409
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000410/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
411/// DeclStmts. Because the initialization code (and sometimes the
412/// the type declarations) for DeclStmts can contain arbitrary expressions,
413/// we must linearize declarations to handle arbitrary control-flow induced by
414/// those expressions.
415CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000416 if (I == StmtIterator())
417 return Block;
418
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000419 Stmt* S = *I;
420 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000421 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000422
423 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000424
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000425 switch (S->getStmtClass()) {
426 case Stmt::IntegerLiteralClass:
427 case Stmt::CharacterLiteralClass:
428 case Stmt::StringLiteralClass:
429 break;
430
431 // All other cases.
432
433 default:
434 Block = addStmt(S);
435 }
436
Ted Kremeneke822b622007-08-28 18:14:37 +0000437 return Block;
438}
439
Ted Kremenek65cfa562007-08-27 21:27:44 +0000440/// WalkAST_VisitChildren - Utility method to call WalkAST on the
441/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000442CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000443 CFGBlock* B = Block;
444 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
445 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000446 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000447
448 return B;
449}
450
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000451/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
452/// expressions (a GCC extension).
453CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
454 Block->appendStmt(S);
455 return VisitCompoundStmt(S->getSubStmt());
456}
457
Ted Kremenek73543912007-08-23 21:42:29 +0000458/// VisitStmt - Handle statements with no branching control flow.
459CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
460 // We cannot assume that we are in the middle of a basic block, since
461 // the CFG might only be constructed for this single statement. If
462 // we have no current basic block, just create one lazily.
463 if (!Block) Block = createBlock();
464
465 // Simply add the statement to the current block. We actually
466 // insert statements in reverse order; this order is reversed later
467 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000468 addStmt(Statement);
469
Ted Kremenek73543912007-08-23 21:42:29 +0000470 return Block;
471}
472
473CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
474 return Block;
475}
476
477CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek73543912007-08-23 21:42:29 +0000478
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000479 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
480 I != E; ++I ) {
481 Visit(*I);
482 }
483
484 return Block;
Ted Kremenek73543912007-08-23 21:42:29 +0000485}
486
487CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
488 // We may see an if statement in the middle of a basic block, or
489 // it may be the first statement we are processing. In either case,
490 // we create a new basic block. First, we create the blocks for
491 // the then...else statements, and then we create the block containing
492 // the if statement. If we were in the middle of a block, we
493 // stop processing that block and reverse its statements. That block
494 // is then the implicit successor for the "then" and "else" clauses.
495
496 // The block we were proccessing is now finished. Make it the
497 // successor block.
498 if (Block) {
499 Succ = Block;
500 FinishBlock(Block);
501 }
502
503 // Process the false branch. NULL out Block so that the recursive
504 // call to Visit will create a new basic block.
505 // Null out Block so that all successor
506 CFGBlock* ElseBlock = Succ;
507
508 if (Stmt* Else = I->getElse()) {
509 SaveAndRestore<CFGBlock*> sv(Succ);
510
511 // NULL out Block so that the recursive call to Visit will
512 // create a new basic block.
513 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000514 ElseBlock = Visit(Else);
515
516 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
517 ElseBlock = sv.get();
518 else if (Block)
519 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000520 }
521
522 // Process the true branch. NULL out Block so that the recursive
523 // call to Visit will create a new basic block.
524 // Null out Block so that all successor
525 CFGBlock* ThenBlock;
526 {
527 Stmt* Then = I->getThen();
528 assert (Then);
529 SaveAndRestore<CFGBlock*> sv(Succ);
530 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000531 ThenBlock = Visit(Then);
532
533 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
534 ThenBlock = sv.get();
535 else if (Block)
536 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000537 }
538
539 // Now create a new block containing the if statement.
540 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000541
542 // Set the terminator of the new block to the If statement.
543 Block->setTerminator(I);
544
545 // Now add the successors.
546 Block->addSuccessor(ThenBlock);
547 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000548
549 // Add the condition as the last statement in the new block. This
550 // may create new blocks as the condition may contain control-flow. Any
551 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000552 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000553}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000554
Ted Kremenek73543912007-08-23 21:42:29 +0000555
556CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
557 // If we were in the middle of a block we stop processing that block
558 // and reverse its statements.
559 //
560 // NOTE: If a "return" appears in the middle of a block, this means
561 // that the code afterwards is DEAD (unreachable). We still
562 // keep a basic block for that code; a simple "mark-and-sweep"
563 // from the entry block will be able to report such dead
564 // blocks.
565 if (Block) FinishBlock(Block);
566
567 // Create the new block.
568 Block = createBlock(false);
569
570 // The Exit block is the only successor.
571 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000572
573 // Add the return statement to the block. This may create new blocks
574 // if R contains control-flow (short-circuit operations).
575 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000576}
577
578CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
579 // Get the block of the labeled statement. Add it to our map.
580 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000581
582 if (!LabelBlock) // This can happen when the body is empty, i.e.
583 LabelBlock=createBlock(); // scopes that only contains NullStmts.
584
Ted Kremenek73543912007-08-23 21:42:29 +0000585 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
586 LabelMap[ L ] = LabelBlock;
587
588 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000589 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000590 // label (and we have already processed the substatement) there is no
591 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000592 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000593 FinishBlock(LabelBlock);
594
595 // We set Block to NULL to allow lazy creation of a new block
596 // (if necessary);
597 Block = NULL;
598
599 // This block is now the implicit successor of other blocks.
600 Succ = LabelBlock;
601
602 return LabelBlock;
603}
604
605CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
606 // Goto is a control-flow statement. Thus we stop processing the
607 // current block and create a new one.
608 if (Block) FinishBlock(Block);
609 Block = createBlock(false);
610 Block->setTerminator(G);
611
612 // If we already know the mapping to the label block add the
613 // successor now.
614 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
615
616 if (I == LabelMap.end())
617 // We will need to backpatch this block later.
618 BackpatchBlocks.push_back(Block);
619 else
620 Block->addSuccessor(I->second);
621
622 return Block;
623}
624
625CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
626 // "for" is a control-flow statement. Thus we stop processing the
627 // current block.
628
629 CFGBlock* LoopSuccessor = NULL;
630
631 if (Block) {
632 FinishBlock(Block);
633 LoopSuccessor = Block;
634 }
635 else LoopSuccessor = Succ;
636
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000637 // Because of short-circuit evaluation, the condition of the loop
638 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
639 // blocks that evaluate the condition.
640 CFGBlock* ExitConditionBlock = createBlock(false);
641 CFGBlock* EntryConditionBlock = ExitConditionBlock;
642
643 // Set the terminator for the "exit" condition block.
644 ExitConditionBlock->setTerminator(F);
645
646 // Now add the actual condition to the condition block. Because the
647 // condition itself may contain control-flow, new blocks may be created.
648 if (Stmt* C = F->getCond()) {
649 Block = ExitConditionBlock;
650 EntryConditionBlock = addStmt(C);
651 if (Block) FinishBlock(EntryConditionBlock);
652 }
Ted Kremenek73543912007-08-23 21:42:29 +0000653
654 // The condition block is the implicit successor for the loop body as
655 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000656 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000657
658 // Now create the loop body.
659 {
660 assert (F->getBody());
661
662 // Save the current values for Block, Succ, and continue and break targets
663 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
664 save_continue(ContinueTargetBlock),
665 save_break(BreakTargetBlock);
666
667 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000668 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000669
670 // All breaks should go to the code following the loop.
671 BreakTargetBlock = LoopSuccessor;
672
Ted Kremenek390b9762007-08-30 18:39:40 +0000673 // Create a new block to contain the (bottom) of the loop body.
674 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000675
676 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000677 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000678
679 // Now populate the body block, and in the process create new blocks
680 // as we walk the body of the loop.
681 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000682
683 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000684 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000685 else if (Block)
686 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000687
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000688 // This new body block is a successor to our "exit" condition block.
689 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000690 }
691
692 // Link up the condition block with the code that follows the loop.
693 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000694 ExitConditionBlock->addSuccessor(LoopSuccessor);
695
Ted Kremenek73543912007-08-23 21:42:29 +0000696 // If the loop contains initialization, create a new block for those
697 // statements. This block can also contain statements that precede
698 // the loop.
699 if (Stmt* I = F->getInit()) {
700 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000701 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000702 }
703 else {
704 // There is no loop initialization. We are thus basically a while
705 // loop. NULL out Block to force lazy block construction.
706 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000707 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000708 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000709 }
710}
711
712CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
713 // "while" is a control-flow statement. Thus we stop processing the
714 // current block.
715
716 CFGBlock* LoopSuccessor = NULL;
717
718 if (Block) {
719 FinishBlock(Block);
720 LoopSuccessor = Block;
721 }
722 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000723
724 // Because of short-circuit evaluation, the condition of the loop
725 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
726 // blocks that evaluate the condition.
727 CFGBlock* ExitConditionBlock = createBlock(false);
728 CFGBlock* EntryConditionBlock = ExitConditionBlock;
729
730 // Set the terminator for the "exit" condition block.
731 ExitConditionBlock->setTerminator(W);
732
733 // Now add the actual condition to the condition block. Because the
734 // condition itself may contain control-flow, new blocks may be created.
735 // Thus we update "Succ" after adding the condition.
736 if (Stmt* C = W->getCond()) {
737 Block = ExitConditionBlock;
738 EntryConditionBlock = addStmt(C);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000739 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000740 if (Block) FinishBlock(EntryConditionBlock);
741 }
Ted Kremenek73543912007-08-23 21:42:29 +0000742
743 // The condition block is the implicit successor for the loop body as
744 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000745 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000746
747 // Process the loop body.
748 {
749 assert (W->getBody());
750
751 // Save the current values for Block, Succ, and continue and break targets
752 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
753 save_continue(ContinueTargetBlock),
754 save_break(BreakTargetBlock);
755
756 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000757 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000758
759 // All breaks should go to the code following the loop.
760 BreakTargetBlock = LoopSuccessor;
761
762 // NULL out Block to force lazy instantiation of blocks for the body.
763 Block = NULL;
764
765 // Create the body. The returned block is the entry to the loop body.
766 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000767
768 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000769 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000770 else if (Block)
771 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000772
773 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000774 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000775 }
776
777 // Link up the condition block with the code that follows the loop.
778 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000779 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000780
781 // There can be no more statements in the condition block
782 // since we loop back to this block. NULL out Block to force
783 // lazy creation of another block.
784 Block = NULL;
785
786 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000787 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000788 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000789}
790
791CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
792 // "do...while" is a control-flow statement. Thus we stop processing the
793 // current block.
794
795 CFGBlock* LoopSuccessor = NULL;
796
797 if (Block) {
798 FinishBlock(Block);
799 LoopSuccessor = Block;
800 }
801 else LoopSuccessor = Succ;
802
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000803 // Because of short-circuit evaluation, the condition of the loop
804 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
805 // blocks that evaluate the condition.
806 CFGBlock* ExitConditionBlock = createBlock(false);
807 CFGBlock* EntryConditionBlock = ExitConditionBlock;
808
809 // Set the terminator for the "exit" condition block.
810 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000811
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000812 // Now add the actual condition to the condition block. Because the
813 // condition itself may contain control-flow, new blocks may be created.
814 if (Stmt* C = D->getCond()) {
815 Block = ExitConditionBlock;
816 EntryConditionBlock = addStmt(C);
817 if (Block) FinishBlock(EntryConditionBlock);
818 }
Ted Kremenek73543912007-08-23 21:42:29 +0000819
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000820 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000821 Succ = EntryConditionBlock;
822
Ted Kremenek73543912007-08-23 21:42:29 +0000823 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000824 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000825 {
826 assert (D->getBody());
827
828 // Save the current values for Block, Succ, and continue and break targets
829 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
830 save_continue(ContinueTargetBlock),
831 save_break(BreakTargetBlock);
832
833 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000834 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000835
836 // All breaks should go to the code following the loop.
837 BreakTargetBlock = LoopSuccessor;
838
839 // NULL out Block to force lazy instantiation of blocks for the body.
840 Block = NULL;
841
842 // Create the body. The returned block is the entry to the loop body.
843 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000844
Ted Kremenek390b9762007-08-30 18:39:40 +0000845 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000846 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000847 else if (Block)
848 FinishBlock(BodyBlock);
849
Ted Kremenek73543912007-08-23 21:42:29 +0000850 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000851 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000852 }
853
854 // Link up the condition block with the code that follows the loop.
855 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000856 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000857
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000858 // There can be no more statements in the body block(s)
859 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000860 // lazy creation of another block.
861 Block = NULL;
862
863 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000864 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000865 return BodyBlock;
866}
867
868CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
869 // "continue" is a control-flow statement. Thus we stop processing the
870 // current block.
871 if (Block) FinishBlock(Block);
872
873 // Now create a new block that ends with the continue statement.
874 Block = createBlock(false);
875 Block->setTerminator(C);
876
877 // If there is no target for the continue, then we are looking at an
878 // incomplete AST. Handle this by not registering a successor.
879 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
880
881 return Block;
882}
883
884CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
885 // "break" is a control-flow statement. Thus we stop processing the
886 // current block.
887 if (Block) FinishBlock(Block);
888
889 // Now create a new block that ends with the continue statement.
890 Block = createBlock(false);
891 Block->setTerminator(B);
892
893 // If there is no target for the break, then we are looking at an
894 // incomplete AST. Handle this by not registering a successor.
895 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
896
897 return Block;
898}
899
900CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
901 // "switch" is a control-flow statement. Thus we stop processing the
902 // current block.
903 CFGBlock* SwitchSuccessor = NULL;
904
905 if (Block) {
906 FinishBlock(Block);
907 SwitchSuccessor = Block;
908 }
909 else SwitchSuccessor = Succ;
910
911 // Save the current "switch" context.
912 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000913 save_break(BreakTargetBlock),
914 save_default(DefaultCaseBlock);
915
916 // Set the "default" case to be the block after the switch statement.
917 // If the switch statement contains a "default:", this value will
918 // be overwritten with the block for that code.
919 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000920
Ted Kremenek73543912007-08-23 21:42:29 +0000921 // Create a new block that will contain the switch statement.
922 SwitchTerminatedBlock = createBlock(false);
923
Ted Kremenek73543912007-08-23 21:42:29 +0000924 // Now process the switch body. The code after the switch is the implicit
925 // successor.
926 Succ = SwitchSuccessor;
927 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000928
929 // When visiting the body, the case statements should automatically get
930 // linked up to the switch. We also don't keep a pointer to the body,
931 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000932 assert (S->getBody() && "switch must contain a non-NULL body");
933 Block = NULL;
934 CFGBlock *BodyBlock = Visit(S->getBody());
935 if (Block) FinishBlock(BodyBlock);
936
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000937 // If we have no "default:" case, the default transition is to the
938 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000939 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000940
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000941 // Add the terminator and condition in the switch block.
942 SwitchTerminatedBlock->setTerminator(S);
943 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000944 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000945
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000946 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000947}
948
Ted Kremenek97bc3422008-02-13 22:05:39 +0000949CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* S) {
950 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +0000951 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000952
953 if (S->getSubStmt()) Visit(S->getSubStmt());
954 CFGBlock* CaseBlock = Block;
955 if (!CaseBlock) CaseBlock = createBlock();
956
Ted Kremenek97bc3422008-02-13 22:05:39 +0000957 // Cases statements partition blocks, so this is the top of
958 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenekec055e12007-08-29 23:20:49 +0000959 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000960 FinishBlock(CaseBlock);
961
962 // Add this block to the list of successors for the block with the
963 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000964 assert (SwitchTerminatedBlock);
965 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000966
967 // We set Block to NULL to allow lazy creation of a new block (if necessary)
968 Block = NULL;
969
970 // This block is now the implicit successor of other blocks.
971 Succ = CaseBlock;
972
973 return CaseBlock;
974}
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000975
Ted Kremenek97bc3422008-02-13 22:05:39 +0000976CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* S) {
977 if (S->getSubStmt()) Visit(S->getSubStmt());
978 DefaultCaseBlock = Block;
979 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
980
981 // Default statements partition blocks, so this is the top of
982 // the basic block we were processing (the "default:" is the label).
983 DefaultCaseBlock->setLabel(S);
984 FinishBlock(DefaultCaseBlock);
985
986 // Unlike case statements, we don't add the default block to the
987 // successors for the switch statement immediately. This is done
988 // when we finish processing the switch statement. This allows for
989 // the default case (including a fall-through to the code after the
990 // switch statement) to always be the last successor of a switch-terminated
991 // block.
992
993 // We set Block to NULL to allow lazy creation of a new block (if necessary)
994 Block = NULL;
995
996 // This block is now the implicit successor of other blocks.
997 Succ = DefaultCaseBlock;
998
999 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001000}
Ted Kremenek73543912007-08-23 21:42:29 +00001001
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001002CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1003 // Lazily create the indirect-goto dispatch block if there isn't one
1004 // already.
1005 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1006
1007 if (!IBlock) {
1008 IBlock = createBlock(false);
1009 cfg->setIndirectGotoBlock(IBlock);
1010 }
1011
1012 // IndirectGoto is a control-flow statement. Thus we stop processing the
1013 // current block and create a new one.
1014 if (Block) FinishBlock(Block);
1015 Block = createBlock(false);
1016 Block->setTerminator(I);
1017 Block->addSuccessor(IBlock);
1018 return addStmt(I->getTarget());
1019}
1020
Ted Kremenek73543912007-08-23 21:42:29 +00001021
Ted Kremenekd6e50602007-08-23 21:26:19 +00001022} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +00001023
1024/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1025/// block has no successors or predecessors. If this is the first block
1026/// created in the CFG, it is automatically set to be the Entry and Exit
1027/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001028CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001029 bool first_block = begin() == end();
1030
1031 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001032 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001033
1034 // If this is the first block, set it as the Entry and Exit.
1035 if (first_block) Entry = Exit = &front();
1036
1037 // Return the block.
1038 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001039}
1040
Ted Kremenek4db5b452007-08-23 16:51:22 +00001041/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1042/// CFG is returned to the caller.
1043CFG* CFG::buildCFG(Stmt* Statement) {
1044 CFGBuilder Builder;
1045 return Builder.buildCFG(Statement);
1046}
1047
1048/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001049void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1050
Ted Kremenek3a819822007-10-01 19:33:33 +00001051//===----------------------------------------------------------------------===//
1052// CFG: Queries for BlkExprs.
1053//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001054
Ted Kremenek3a819822007-10-01 19:33:33 +00001055namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001056 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001057}
1058
Ted Kremenekc6fda602008-01-26 00:03:27 +00001059static void FindSubExprAssignments(Stmt* S, llvm::SmallPtrSet<Expr*,50>& Set) {
1060 if (!S)
1061 return;
1062
1063 for (Stmt::child_iterator I=S->child_begin(), E=S->child_end(); I!=E; ++I) {
1064 if (!*I) continue;
1065
1066 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1067 if (B->isAssignmentOp()) Set.insert(B);
1068
1069 FindSubExprAssignments(*I, Set);
1070 }
1071}
1072
Ted Kremenek3a819822007-10-01 19:33:33 +00001073static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1074 BlkExprMapTy* M = new BlkExprMapTy();
1075
Ted Kremenekc6fda602008-01-26 00:03:27 +00001076 // Look for assignments that are used as subexpressions. These are the
1077 // only assignments that we want to register as a block-level expression.
1078 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1079
Ted Kremenek3a819822007-10-01 19:33:33 +00001080 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1081 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001082 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001083
Ted Kremenekc6fda602008-01-26 00:03:27 +00001084 // Iterate over the statements again on identify the Expr* and Stmt* at
1085 // the block-level that are block-level expressions.
1086 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1087 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
1088 if (Expr* E = dyn_cast<Expr>(*BI)) {
1089
1090 if (BinaryOperator* B = dyn_cast<BinaryOperator>(E)) {
1091 // Assignment expressions that are not nested within another
1092 // expression are really "statements" whose value is never
1093 // used by another expression.
1094 if (B->isAssignmentOp() && !SubExprAssignments.count(E))
1095 continue;
1096 }
1097 else if (const StmtExpr* S = dyn_cast<StmtExpr>(E)) {
1098 // Special handling for statement expressions. The last statement
1099 // in the statement expression is also a block-level expr.
Ted Kremenekab6c5902008-01-17 20:48:37 +00001100 const CompoundStmt* C = S->getSubStmt();
1101 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001102 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001103 (*M)[C->body_back()] = x;
1104 }
1105 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001106
Ted Kremenekc6fda602008-01-26 00:03:27 +00001107 unsigned x = M->size();
1108 (*M)[E] = x;
1109 }
1110
Ted Kremenek3a819822007-10-01 19:33:33 +00001111 return M;
1112}
1113
Ted Kremenekab6c5902008-01-17 20:48:37 +00001114CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1115 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001116 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1117
1118 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001119 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001120
1121 if (I == M->end()) return CFG::BlkExprNumTy();
1122 else return CFG::BlkExprNumTy(I->second);
1123}
1124
1125unsigned CFG::getNumBlkExprs() {
1126 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1127 return M->size();
1128 else {
1129 // We assume callers interested in the number of BlkExprs will want
1130 // the map constructed if it doesn't already exist.
1131 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1132 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1133 }
1134}
1135
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001136typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1137
1138const std::pair<CFGBlock*,CFGBlock*>*
1139CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1140
1141 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1142 if (!p) p = new BlkEdgeSetTy();
1143
1144 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1145 const_cast<CFGBlock*>(B2))).first);
1146}
1147
Ted Kremenek3a819822007-10-01 19:33:33 +00001148CFG::~CFG() {
1149 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001150 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001151}
1152
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001153//===----------------------------------------------------------------------===//
1154// CFG pretty printing
1155//===----------------------------------------------------------------------===//
1156
Ted Kremenekd8313202007-08-22 18:22:34 +00001157namespace {
1158
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001159class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001160
Ted Kremenek08176a52007-08-31 21:30:12 +00001161 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1162 StmtMapTy StmtMap;
1163 signed CurrentBlock;
1164 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001165
Ted Kremenek73543912007-08-23 21:42:29 +00001166public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001167
Ted Kremenek08176a52007-08-31 21:30:12 +00001168 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1169 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1170 unsigned j = 1;
1171 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1172 BI != BEnd; ++BI, ++j )
1173 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1174 }
1175 }
1176
1177 virtual ~StmtPrinterHelper() {}
1178
1179 void setBlockID(signed i) { CurrentBlock = i; }
1180 void setStmtID(unsigned i) { CurrentStmt = i; }
1181
Ted Kremenek86afc042007-08-31 22:26:13 +00001182 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1183
1184 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek08176a52007-08-31 21:30:12 +00001185
1186 if (I == StmtMap.end())
1187 return false;
1188
1189 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1190 && I->second.second == CurrentStmt)
1191 return false;
1192
Ted Kremenek86afc042007-08-31 22:26:13 +00001193 OS << "[B" << I->second.first << "." << I->second.second << "]";
1194 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001195 }
1196};
1197
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001198class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1199 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1200
Ted Kremenek08176a52007-08-31 21:30:12 +00001201 std::ostream& OS;
1202 StmtPrinterHelper* Helper;
1203public:
1204 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1205 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001206
1207 void VisitIfStmt(IfStmt* I) {
1208 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001209 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001210 }
1211
1212 // Default case.
Ted Kremenek621e1592007-08-31 21:49:40 +00001213 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001214
1215 void VisitForStmt(ForStmt* F) {
1216 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001217 if (F->getInit()) OS << "...";
1218 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001219 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001220 OS << "; ";
1221 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001222 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001223 }
1224
1225 void VisitWhileStmt(WhileStmt* W) {
1226 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001227 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001228 }
1229
1230 void VisitDoStmt(DoStmt* D) {
1231 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001232 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001233 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001234
Ted Kremenek65cfa562007-08-27 21:27:44 +00001235 void VisitSwitchStmt(SwitchStmt* S) {
1236 OS << "switch ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001237 S->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001238 }
1239
Ted Kremenek621e1592007-08-31 21:49:40 +00001240 void VisitConditionalOperator(ConditionalOperator* C) {
1241 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001242 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001243 }
1244
Ted Kremenek2025cc92007-08-31 22:29:13 +00001245 void VisitChooseExpr(ChooseExpr* C) {
1246 OS << "__builtin_choose_expr( ";
1247 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001248 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001249 }
1250
Ted Kremenek86afc042007-08-31 22:26:13 +00001251 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1252 OS << "goto *";
1253 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001254 }
1255
Ted Kremenek621e1592007-08-31 21:49:40 +00001256 void VisitBinaryOperator(BinaryOperator* B) {
1257 if (!B->isLogicalOp()) {
1258 VisitExpr(B);
1259 return;
1260 }
1261
1262 B->getLHS()->printPretty(OS,Helper);
1263
1264 switch (B->getOpcode()) {
1265 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001266 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001267 return;
1268 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001269 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001270 return;
1271 default:
1272 assert(false && "Invalid logical operator.");
1273 }
1274 }
1275
Ted Kremenekcfaae762007-08-27 21:54:41 +00001276 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001277 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001278 }
Ted Kremenek73543912007-08-23 21:42:29 +00001279};
Ted Kremenek08176a52007-08-31 21:30:12 +00001280
1281
Ted Kremenek86afc042007-08-31 22:26:13 +00001282void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1283 if (Helper) {
1284 // special printing for statement-expressions.
1285 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1286 CompoundStmt* Sub = SE->getSubStmt();
1287
1288 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001289 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001290 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001291 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001292 return;
1293 }
1294 }
1295
1296 // special printing for comma expressions.
1297 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1298 if (B->getOpcode() == BinaryOperator::Comma) {
1299 OS << "... , ";
1300 Helper->handledStmt(B->getRHS(),OS);
1301 OS << '\n';
1302 return;
1303 }
1304 }
1305 }
1306
1307 S->printPretty(OS, Helper);
1308
1309 // Expressions need a newline.
1310 if (isa<Expr>(S)) OS << '\n';
1311}
1312
Ted Kremenek08176a52007-08-31 21:30:12 +00001313void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1314 StmtPrinterHelper* Helper, bool print_edges) {
1315
1316 if (Helper) Helper->setBlockID(B.getBlockID());
1317
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001318 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001319 OS << "\n [ B" << B.getBlockID();
1320
1321 if (&B == &cfg->getEntry())
1322 OS << " (ENTRY) ]\n";
1323 else if (&B == &cfg->getExit())
1324 OS << " (EXIT) ]\n";
1325 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001326 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001327 else
1328 OS << " ]\n";
1329
Ted Kremenekec055e12007-08-29 23:20:49 +00001330 // Print the label of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001331 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1332
1333 if (print_edges)
1334 OS << " ";
1335
Ted Kremenekec055e12007-08-29 23:20:49 +00001336 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1337 OS << L->getName();
1338 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1339 OS << "case ";
1340 C->getLHS()->printPretty(OS);
1341 if (C->getRHS()) {
1342 OS << " ... ";
1343 C->getRHS()->printPretty(OS);
1344 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001345 }
Chris Lattner1501e122007-09-16 19:11:53 +00001346 else if (isa<DefaultStmt>(S))
Ted Kremenekec055e12007-08-29 23:20:49 +00001347 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001348 else
1349 assert(false && "Invalid label statement in CFGBlock.");
1350
Ted Kremenekec055e12007-08-29 23:20:49 +00001351 OS << ":\n";
1352 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001353
Ted Kremenek97f75312007-08-21 21:42:03 +00001354 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001355 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001356
1357 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1358 I != E ; ++I, ++j ) {
1359
Ted Kremenekec055e12007-08-29 23:20:49 +00001360 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001361 if (print_edges)
1362 OS << " ";
1363
1364 OS << std::setw(3) << j << ": ";
1365
1366 if (Helper)
1367 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001368
1369 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001370 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001371
Ted Kremenekec055e12007-08-29 23:20:49 +00001372 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001373 if (B.getTerminator()) {
1374 if (print_edges)
1375 OS << " ";
1376
Ted Kremenekec055e12007-08-29 23:20:49 +00001377 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001378
1379 if (Helper) Helper->setBlockID(-1);
1380
1381 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1382 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001383 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001384 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001385
Ted Kremenekec055e12007-08-29 23:20:49 +00001386 if (print_edges) {
1387 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001388 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001389 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001390
Ted Kremenek08176a52007-08-31 21:30:12 +00001391 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1392 I != E; ++I, ++i) {
1393
1394 if (i == 8 || (i-8) == 0)
1395 OS << "\n ";
1396
Ted Kremenekec055e12007-08-29 23:20:49 +00001397 OS << " B" << (*I)->getBlockID();
1398 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001399
1400 OS << '\n';
1401
1402 // Print the successors of this block.
1403 OS << " Successors (" << B.succ_size() << "):";
1404 i = 0;
1405
1406 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1407 I != E; ++I, ++i) {
1408
1409 if (i == 8 || (i-8) % 10 == 0)
1410 OS << "\n ";
1411
1412 OS << " B" << (*I)->getBlockID();
1413 }
1414
Ted Kremenekec055e12007-08-29 23:20:49 +00001415 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001416 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001417}
1418
1419} // end anonymous namespace
1420
1421/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001422void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001423
1424/// print - A simple pretty printer of a CFG that outputs to an ostream.
1425void CFG::print(std::ostream& OS) const {
1426
1427 StmtPrinterHelper Helper(this);
1428
1429 // Print the entry block.
1430 print_block(OS, this, getEntry(), &Helper, true);
1431
1432 // Iterate through the CFGBlocks and print them one by one.
1433 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1434 // Skip the entry block, because we already printed it.
1435 if (&(*I) == &getEntry() || &(*I) == &getExit())
1436 continue;
1437
1438 print_block(OS, this, *I, &Helper, true);
1439 }
1440
1441 // Print the exit block.
1442 print_block(OS, this, getExit(), &Helper, true);
1443}
1444
1445/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001446void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001447
1448/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1449/// Generally this will only be called from CFG::print.
1450void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1451 StmtPrinterHelper Helper(cfg);
1452 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001453}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001454
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001455/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1456void CFGBlock::printTerminator(std::ostream& OS) const {
1457 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1458 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1459}
1460
1461
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001462//===----------------------------------------------------------------------===//
1463// CFG Graphviz Visualization
1464//===----------------------------------------------------------------------===//
1465
Ted Kremenek08176a52007-08-31 21:30:12 +00001466
1467#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001468static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001469#endif
1470
1471void CFG::viewCFG() const {
1472#ifndef NDEBUG
1473 StmtPrinterHelper H(this);
1474 GraphHelper = &H;
1475 llvm::ViewGraph(this,"CFG");
1476 GraphHelper = NULL;
1477#else
1478 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser284bff92007-09-17 12:29:55 +00001479 << "systems with Graphviz or gv!\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001480#endif
1481}
1482
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001483namespace llvm {
1484template<>
1485struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1486 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1487
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001488#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001489 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001490 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001491 std::string OutStr = Out.str();
1492
1493 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1494
1495 // Process string output to make it nicer...
1496 for (unsigned i = 0; i != OutStr.length(); ++i)
1497 if (OutStr[i] == '\n') { // Left justify
1498 OutStr[i] = '\\';
1499 OutStr.insert(OutStr.begin()+i+1, 'l');
1500 }
1501
1502 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001503#else
1504 return "";
1505#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001506 }
1507};
1508} // end namespace llvm