blob: f99de1cc79d8d4c4301c45c5adc4d86ef4a734bb [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//
5// This file was developed by Ted Kremenek and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
7//
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 Kremenekfddd5182007-08-21 21:42:03 +000022#include <iostream>
23#include <iomanip>
24#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000025#include <sstream>
26
Ted Kremenekfddd5182007-08-21 21:42:03 +000027using namespace clang;
28
29namespace {
30
Ted Kremenekbefef2f2007-08-23 21:26:19 +000031// SaveAndRestore - A utility class that uses RIIA to save and restore
32// the value of a variable.
33template<typename T>
34struct SaveAndRestore {
35 SaveAndRestore(T& x) : X(x), old_value(x) {}
36 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000037 T get() { return old_value; }
38
Ted Kremenekbefef2f2007-08-23 21:26:19 +000039 T& X;
40 T old_value;
41};
Ted Kremenekfddd5182007-08-21 21:42:03 +000042
43/// CFGBuilder - This class is implements CFG construction from an AST.
44/// The builder is stateful: an instance of the builder should be used to only
45/// construct a single CFG.
46///
47/// Example usage:
48///
49/// CFGBuilder builder;
50/// CFG* cfg = builder.BuildAST(stmt1);
51///
Ted Kremenekc310e932007-08-21 22:06:14 +000052/// CFG construction is done via a recursive walk of an AST.
53/// We actually parse the AST in reverse order so that the successor
54/// of a basic block is constructed prior to its predecessor. This
55/// allows us to nicely capture implicit fall-throughs without extra
56/// basic blocks.
57///
58class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000059 CFG* cfg;
60 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000061 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000062 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000063 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000064 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000065
Ted Kremenek19bb3562007-08-28 19:26:49 +000066 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000067 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
68 LabelMapTy LabelMap;
69
Ted Kremenek19bb3562007-08-28 19:26:49 +000070 // A list of blocks that end with a "goto" that must be backpatched to
71 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000072 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000073 BackpatchBlocksTy BackpatchBlocks;
74
Ted Kremenek19bb3562007-08-28 19:26:49 +000075 // A list of labels whose address has been taken (for indirect gotos).
76 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
77 LabelSetTy AddressTakenLabels;
78
Ted Kremenekfddd5182007-08-21 21:42:03 +000079public:
Ted Kremenek026473c2007-08-23 16:51:22 +000080 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000081 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek94382522007-09-05 20:02:05 +000082 SwitchTerminatedBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000083 // Create an empty CFG.
84 cfg = new CFG();
85 }
86
87 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000088
Ted Kremenekd4fdee32007-08-23 21:42:29 +000089 // buildCFG - Used by external clients to construct the CFG.
90 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +000091
Ted Kremenekd4fdee32007-08-23 21:42:29 +000092 // Visitors to walk an AST and construct the CFG. Called by
93 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +000094
Ted Kremenekd4fdee32007-08-23 21:42:29 +000095 CFGBlock* VisitStmt(Stmt* Statement);
96 CFGBlock* VisitNullStmt(NullStmt* Statement);
97 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
98 CFGBlock* VisitIfStmt(IfStmt* I);
99 CFGBlock* VisitReturnStmt(ReturnStmt* R);
100 CFGBlock* VisitLabelStmt(LabelStmt* L);
101 CFGBlock* VisitGotoStmt(GotoStmt* G);
102 CFGBlock* VisitForStmt(ForStmt* F);
103 CFGBlock* VisitWhileStmt(WhileStmt* W);
104 CFGBlock* VisitDoStmt(DoStmt* D);
105 CFGBlock* VisitContinueStmt(ContinueStmt* C);
106 CFGBlock* VisitBreakStmt(BreakStmt* B);
107 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
108 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000109 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000110
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000111private:
112 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000113 CFGBlock* addStmt(Stmt* S);
114 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
115 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000116 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek15c27a82007-08-28 18:30:10 +0000117 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekf50ec102007-09-11 21:29:43 +0000118 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000119 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000120
Ted Kremenekfddd5182007-08-21 21:42:03 +0000121};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000122
123/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
124/// represent an arbitrary statement. Examples include a single expression
125/// or a function body (compound statement). The ownership of the returned
126/// CFG is transferred to the caller. If CFG construction fails, this method
127/// returns NULL.
128CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000129 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000130 if (!Statement) return NULL;
131
132 // Create an empty block that will serve as the exit block for the CFG.
133 // Since this is the first block added to the CFG, it will be implicitly
134 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000135 Succ = createBlock();
136 assert (Succ == &cfg->getExit());
137 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000138
139 // Visit the statements and create the CFG.
140 if (CFGBlock* B = Visit(Statement)) {
141 // Finalize the last constructed block. This usually involves
142 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000143 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000144
145 // Backpatch the gotos whose label -> block mappings we didn't know
146 // when we encountered them.
147 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
148 E = BackpatchBlocks.end(); I != E; ++I ) {
149
150 CFGBlock* B = *I;
151 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
152 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
153
154 // If there is no target for the goto, then we are looking at an
155 // incomplete AST. Handle this by not registering a successor.
156 if (LI == LabelMap.end()) continue;
157
158 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000159 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000160
Ted Kremenek19bb3562007-08-28 19:26:49 +0000161 // Add successors to the Indirect Goto Dispatch block (if we have one).
162 if (CFGBlock* B = cfg->getIndirectGotoBlock())
163 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
164 E = AddressTakenLabels.end(); I != E; ++I ) {
165
166 // Lookup the target block.
167 LabelMapTy::iterator LI = LabelMap.find(*I);
168
169 // If there is no target block that contains label, then we are looking
170 // at an incomplete AST. Handle this by not registering a successor.
171 if (LI == LabelMap.end()) continue;
172
173 B->addSuccessor(LI->second);
174 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000175
Ted Kremenek94b33162007-09-17 16:18:02 +0000176 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000177 }
178
179 // Create an empty entry block that has no predecessors.
180 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000181
Ted Kremenek322f58d2007-09-26 21:23:31 +0000182 // NULL out cfg so that repeated calls to the builder will fail and that
183 // the ownership of the constructed CFG is passed to the caller.
184 CFG* t = cfg;
185 cfg = NULL;
186 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000187}
188
189/// createBlock - Used to lazily create blocks that are connected
190/// to the current (global) succcessor.
191CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000192 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000193 if (add_successor && Succ) B->addSuccessor(Succ);
194 return B;
195}
196
197/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000198/// we must reverse the statements because they have been inserted
199/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000200void CFGBuilder::FinishBlock(CFGBlock* B) {
201 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000202 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203}
204
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000205/// addStmt - Used to add statements/expressions to the current CFGBlock
206/// "Block". This method calls WalkAST on the passed statement to see if it
207/// contains any short-circuit expressions. If so, it recursively creates
208/// the necessary blocks for such expressions. It returns the "topmost" block
209/// of the created blocks, or the original value of "Block" when this method
210/// was called if no additional blocks are created.
211CFGBlock* CFGBuilder::addStmt(Stmt* S) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000212 if (!Block) Block = createBlock();
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000213 return WalkAST(S,true);
214}
215
216/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000217/// add extra blocks for ternary operators, &&, and ||. We also
218/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000219CFGBlock* CFGBuilder::WalkAST(Stmt* S, bool AlwaysAddStmt = false) {
220 switch (S->getStmtClass()) {
221 case Stmt::ConditionalOperatorClass: {
222 ConditionalOperator* C = cast<ConditionalOperator>(S);
223
224 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
225 ConfluenceBlock->appendStmt(C);
226 FinishBlock(ConfluenceBlock);
227
228 Succ = ConfluenceBlock;
229 Block = NULL;
230 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000231 FinishBlock(LHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000232
233 Succ = ConfluenceBlock;
234 Block = NULL;
235 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000236 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000237
238 Block = createBlock(false);
239 Block->addSuccessor(LHSBlock);
240 Block->addSuccessor(RHSBlock);
241 Block->setTerminator(C);
242 return addStmt(C->getCond());
243 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000244
245 case Stmt::ChooseExprClass: {
246 ChooseExpr* C = cast<ChooseExpr>(S);
247
248 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
249 ConfluenceBlock->appendStmt(C);
250 FinishBlock(ConfluenceBlock);
251
252 Succ = ConfluenceBlock;
253 Block = NULL;
254 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000255 FinishBlock(LHSBlock);
256
Ted Kremenek49a436d2007-08-31 17:03:41 +0000257 Succ = ConfluenceBlock;
258 Block = NULL;
259 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000260 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000261
262 Block = createBlock(false);
263 Block->addSuccessor(LHSBlock);
264 Block->addSuccessor(RHSBlock);
265 Block->setTerminator(C);
266 return addStmt(C->getCond());
267 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000268
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000269 case Stmt::DeclStmtClass: {
270 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
271 Block->appendStmt(S);
272
273 StmtIterator I(D);
274 return WalkAST_VisitDeclSubExprs(I);
275 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000276
Ted Kremenek19bb3562007-08-28 19:26:49 +0000277 case Stmt::AddrLabelExprClass: {
278 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
279 AddressTakenLabels.insert(A->getLabel());
280
281 if (AlwaysAddStmt) Block->appendStmt(S);
282 return Block;
283 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000284
285 case Stmt::CallExprClass:
286 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000287
Ted Kremenek15c27a82007-08-28 18:30:10 +0000288 case Stmt::StmtExprClass:
289 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000290
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000291 case Stmt::BinaryOperatorClass: {
292 BinaryOperator* B = cast<BinaryOperator>(S);
293
294 if (B->isLogicalOp()) { // && or ||
295 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
296 ConfluenceBlock->appendStmt(B);
297 FinishBlock(ConfluenceBlock);
298
299 // create the block evaluating the LHS
300 CFGBlock* LHSBlock = createBlock(false);
301 LHSBlock->addSuccessor(ConfluenceBlock);
302 LHSBlock->setTerminator(B);
303
304 // create the block evaluating the RHS
305 Succ = ConfluenceBlock;
306 Block = NULL;
307 CFGBlock* RHSBlock = Visit(B->getRHS());
308 LHSBlock->addSuccessor(RHSBlock);
309
310 // Generate the blocks for evaluating the LHS.
311 Block = LHSBlock;
312 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000313 }
314 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
315 Block->appendStmt(B);
316 addStmt(B->getRHS());
317 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000318 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000319
320 // Fall through to the default case.
321 }
322
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000323 default:
324 if (AlwaysAddStmt) Block->appendStmt(S);
325 return WalkAST_VisitChildren(S);
326 };
327}
328
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000329/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
330/// DeclStmts. Because the initialization code (and sometimes the
331/// the type declarations) for DeclStmts can contain arbitrary expressions,
332/// we must linearize declarations to handle arbitrary control-flow induced by
333/// those expressions.
334CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000335 if (I == StmtIterator())
336 return Block;
337
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000338 Stmt* S = *I;
339 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000340 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000341
342 Block = addStmt(S);
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000343 return Block;
344}
345
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000346/// WalkAST_VisitChildren - Utility method to call WalkAST on the
347/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000348CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000349 CFGBlock* B = Block;
350 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
351 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000352 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000353
354 return B;
355}
356
Ted Kremenek15c27a82007-08-28 18:30:10 +0000357/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
358/// expressions (a GCC extension).
359CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
360 Block->appendStmt(S);
361 return VisitCompoundStmt(S->getSubStmt());
362}
363
Ted Kremenekf50ec102007-09-11 21:29:43 +0000364/// WalkAST_VisitCallExpr - Utility method to handle function calls that
365/// are nested in expressions. The idea is that each function call should
366/// appear as a distinct statement in the CFGBlock.
367CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
368 Block->appendStmt(C);
369 return WalkAST_VisitChildren(C);
370}
371
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000372/// VisitStmt - Handle statements with no branching control flow.
373CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
374 // We cannot assume that we are in the middle of a basic block, since
375 // the CFG might only be constructed for this single statement. If
376 // we have no current basic block, just create one lazily.
377 if (!Block) Block = createBlock();
378
379 // Simply add the statement to the current block. We actually
380 // insert statements in reverse order; this order is reversed later
381 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000382 addStmt(Statement);
383
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000384 return Block;
385}
386
387CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
388 return Block;
389}
390
391CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
392 // The value returned from this function is the last created CFGBlock
393 // that represents the "entry" point for the translated AST node.
Chris Lattner271f1a62007-09-27 15:15:46 +0000394 CFGBlock* LastBlock = 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000395
396 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
397 E = C->body_rend(); I != E; ++I )
398 // Add the statement to the current block.
399 if (!(LastBlock=Visit(*I)))
400 return NULL;
401
402 return LastBlock;
403}
404
405CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
406 // We may see an if statement in the middle of a basic block, or
407 // it may be the first statement we are processing. In either case,
408 // we create a new basic block. First, we create the blocks for
409 // the then...else statements, and then we create the block containing
410 // the if statement. If we were in the middle of a block, we
411 // stop processing that block and reverse its statements. That block
412 // is then the implicit successor for the "then" and "else" clauses.
413
414 // The block we were proccessing is now finished. Make it the
415 // successor block.
416 if (Block) {
417 Succ = Block;
418 FinishBlock(Block);
419 }
420
421 // Process the false branch. NULL out Block so that the recursive
422 // call to Visit will create a new basic block.
423 // Null out Block so that all successor
424 CFGBlock* ElseBlock = Succ;
425
426 if (Stmt* Else = I->getElse()) {
427 SaveAndRestore<CFGBlock*> sv(Succ);
428
429 // NULL out Block so that the recursive call to Visit will
430 // create a new basic block.
431 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000432 ElseBlock = Visit(Else);
433
434 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
435 ElseBlock = sv.get();
436 else if (Block)
437 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000438 }
439
440 // Process the true branch. NULL out Block so that the recursive
441 // call to Visit will create a new basic block.
442 // Null out Block so that all successor
443 CFGBlock* ThenBlock;
444 {
445 Stmt* Then = I->getThen();
446 assert (Then);
447 SaveAndRestore<CFGBlock*> sv(Succ);
448 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000449 ThenBlock = Visit(Then);
450
451 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
452 ThenBlock = sv.get();
453 else if (Block)
454 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000455 }
456
457 // Now create a new block containing the if statement.
458 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000459
460 // Set the terminator of the new block to the If statement.
461 Block->setTerminator(I);
462
463 // Now add the successors.
464 Block->addSuccessor(ThenBlock);
465 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000466
467 // Add the condition as the last statement in the new block. This
468 // may create new blocks as the condition may contain control-flow. Any
469 // newly created blocks will be pointed to be "Block".
470 return addStmt(I->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000471}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000472
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000473
474CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
475 // If we were in the middle of a block we stop processing that block
476 // and reverse its statements.
477 //
478 // NOTE: If a "return" appears in the middle of a block, this means
479 // that the code afterwards is DEAD (unreachable). We still
480 // keep a basic block for that code; a simple "mark-and-sweep"
481 // from the entry block will be able to report such dead
482 // blocks.
483 if (Block) FinishBlock(Block);
484
485 // Create the new block.
486 Block = createBlock(false);
487
488 // The Exit block is the only successor.
489 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000490
491 // Add the return statement to the block. This may create new blocks
492 // if R contains control-flow (short-circuit operations).
493 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000494}
495
496CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
497 // Get the block of the labeled statement. Add it to our map.
498 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000499
500 if (!LabelBlock) // This can happen when the body is empty, i.e.
501 LabelBlock=createBlock(); // scopes that only contains NullStmts.
502
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000503 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
504 LabelMap[ L ] = LabelBlock;
505
506 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000507 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000508 // label (and we have already processed the substatement) there is no
509 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000510 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000511 FinishBlock(LabelBlock);
512
513 // We set Block to NULL to allow lazy creation of a new block
514 // (if necessary);
515 Block = NULL;
516
517 // This block is now the implicit successor of other blocks.
518 Succ = LabelBlock;
519
520 return LabelBlock;
521}
522
523CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
524 // Goto is a control-flow statement. Thus we stop processing the
525 // current block and create a new one.
526 if (Block) FinishBlock(Block);
527 Block = createBlock(false);
528 Block->setTerminator(G);
529
530 // If we already know the mapping to the label block add the
531 // successor now.
532 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
533
534 if (I == LabelMap.end())
535 // We will need to backpatch this block later.
536 BackpatchBlocks.push_back(Block);
537 else
538 Block->addSuccessor(I->second);
539
540 return Block;
541}
542
543CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
544 // "for" is a control-flow statement. Thus we stop processing the
545 // current block.
546
547 CFGBlock* LoopSuccessor = NULL;
548
549 if (Block) {
550 FinishBlock(Block);
551 LoopSuccessor = Block;
552 }
553 else LoopSuccessor = Succ;
554
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000555 // Because of short-circuit evaluation, the condition of the loop
556 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
557 // blocks that evaluate the condition.
558 CFGBlock* ExitConditionBlock = createBlock(false);
559 CFGBlock* EntryConditionBlock = ExitConditionBlock;
560
561 // Set the terminator for the "exit" condition block.
562 ExitConditionBlock->setTerminator(F);
563
564 // Now add the actual condition to the condition block. Because the
565 // condition itself may contain control-flow, new blocks may be created.
566 if (Stmt* C = F->getCond()) {
567 Block = ExitConditionBlock;
568 EntryConditionBlock = addStmt(C);
569 if (Block) FinishBlock(EntryConditionBlock);
570 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000571
572 // The condition block is the implicit successor for the loop body as
573 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000574 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000575
576 // Now create the loop body.
577 {
578 assert (F->getBody());
579
580 // Save the current values for Block, Succ, and continue and break targets
581 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
582 save_continue(ContinueTargetBlock),
583 save_break(BreakTargetBlock);
584
585 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000586 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000587
588 // All breaks should go to the code following the loop.
589 BreakTargetBlock = LoopSuccessor;
590
Ted Kremenekaf603f72007-08-30 18:39:40 +0000591 // Create a new block to contain the (bottom) of the loop body.
592 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000593
594 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000595 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000596
597 // Now populate the body block, and in the process create new blocks
598 // as we walk the body of the loop.
599 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000600
601 if (!BodyBlock)
602 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
603 else if (Block)
604 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000605
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000606 // This new body block is a successor to our "exit" condition block.
607 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000608 }
609
610 // Link up the condition block with the code that follows the loop.
611 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000612 ExitConditionBlock->addSuccessor(LoopSuccessor);
613
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000614 // If the loop contains initialization, create a new block for those
615 // statements. This block can also contain statements that precede
616 // the loop.
617 if (Stmt* I = F->getInit()) {
618 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000619 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000620 }
621 else {
622 // There is no loop initialization. We are thus basically a while
623 // loop. NULL out Block to force lazy block construction.
624 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000625 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000626 }
627}
628
629CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
630 // "while" is a control-flow statement. Thus we stop processing the
631 // current block.
632
633 CFGBlock* LoopSuccessor = NULL;
634
635 if (Block) {
636 FinishBlock(Block);
637 LoopSuccessor = Block;
638 }
639 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000640
641 // Because of short-circuit evaluation, the condition of the loop
642 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
643 // blocks that evaluate the condition.
644 CFGBlock* ExitConditionBlock = createBlock(false);
645 CFGBlock* EntryConditionBlock = ExitConditionBlock;
646
647 // Set the terminator for the "exit" condition block.
648 ExitConditionBlock->setTerminator(W);
649
650 // Now add the actual condition to the condition block. Because the
651 // condition itself may contain control-flow, new blocks may be created.
652 // Thus we update "Succ" after adding the condition.
653 if (Stmt* C = W->getCond()) {
654 Block = ExitConditionBlock;
655 EntryConditionBlock = addStmt(C);
656 if (Block) FinishBlock(EntryConditionBlock);
657 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000658
659 // The condition block is the implicit successor for the loop body as
660 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000661 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000662
663 // Process the loop body.
664 {
665 assert (W->getBody());
666
667 // Save the current values for Block, Succ, and continue and break targets
668 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
669 save_continue(ContinueTargetBlock),
670 save_break(BreakTargetBlock);
671
672 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000673 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000674
675 // All breaks should go to the code following the loop.
676 BreakTargetBlock = LoopSuccessor;
677
678 // NULL out Block to force lazy instantiation of blocks for the body.
679 Block = NULL;
680
681 // Create the body. The returned block is the entry to the loop body.
682 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000683
684 if (!BodyBlock)
685 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
686 else if (Block)
687 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000688
689 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000690 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000691 }
692
693 // Link up the condition block with the code that follows the loop.
694 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000695 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000696
697 // There can be no more statements in the condition block
698 // since we loop back to this block. NULL out Block to force
699 // lazy creation of another block.
700 Block = NULL;
701
702 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000703 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000704}
705
706CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
707 // "do...while" is a control-flow statement. Thus we stop processing the
708 // current block.
709
710 CFGBlock* LoopSuccessor = NULL;
711
712 if (Block) {
713 FinishBlock(Block);
714 LoopSuccessor = Block;
715 }
716 else LoopSuccessor = Succ;
717
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000718 // Because of short-circuit evaluation, the condition of the loop
719 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
720 // blocks that evaluate the condition.
721 CFGBlock* ExitConditionBlock = createBlock(false);
722 CFGBlock* EntryConditionBlock = ExitConditionBlock;
723
724 // Set the terminator for the "exit" condition block.
725 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000726
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000727 // Now add the actual condition to the condition block. Because the
728 // condition itself may contain control-flow, new blocks may be created.
729 if (Stmt* C = D->getCond()) {
730 Block = ExitConditionBlock;
731 EntryConditionBlock = addStmt(C);
732 if (Block) FinishBlock(EntryConditionBlock);
733 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000734
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000735 // The condition block is the implicit successor for the loop body as
736 // well as any code above the loop.
737 Succ = EntryConditionBlock;
738
739
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000740 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000741 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000742 {
743 assert (D->getBody());
744
745 // Save the current values for Block, Succ, and continue and break targets
746 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
747 save_continue(ContinueTargetBlock),
748 save_break(BreakTargetBlock);
749
750 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000751 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000752
753 // All breaks should go to the code following the loop.
754 BreakTargetBlock = LoopSuccessor;
755
756 // NULL out Block to force lazy instantiation of blocks for the body.
757 Block = NULL;
758
759 // Create the body. The returned block is the entry to the loop body.
760 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000761
Ted Kremenekaf603f72007-08-30 18:39:40 +0000762 if (!BodyBlock)
763 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
764 else if (Block)
765 FinishBlock(BodyBlock);
766
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000767 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000768 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000769 }
770
771 // Link up the condition block with the code that follows the loop.
772 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000773 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000774
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000775 // There can be no more statements in the body block(s)
776 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000777 // lazy creation of another block.
778 Block = NULL;
779
780 // Return the loop body, which is the dominating block for the loop.
781 return BodyBlock;
782}
783
784CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
785 // "continue" is a control-flow statement. Thus we stop processing the
786 // current block.
787 if (Block) FinishBlock(Block);
788
789 // Now create a new block that ends with the continue statement.
790 Block = createBlock(false);
791 Block->setTerminator(C);
792
793 // If there is no target for the continue, then we are looking at an
794 // incomplete AST. Handle this by not registering a successor.
795 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
796
797 return Block;
798}
799
800CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
801 // "break" is a control-flow statement. Thus we stop processing the
802 // current block.
803 if (Block) FinishBlock(Block);
804
805 // Now create a new block that ends with the continue statement.
806 Block = createBlock(false);
807 Block->setTerminator(B);
808
809 // If there is no target for the break, then we are looking at an
810 // incomplete AST. Handle this by not registering a successor.
811 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
812
813 return Block;
814}
815
816CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
817 // "switch" is a control-flow statement. Thus we stop processing the
818 // current block.
819 CFGBlock* SwitchSuccessor = NULL;
820
821 if (Block) {
822 FinishBlock(Block);
823 SwitchSuccessor = Block;
824 }
825 else SwitchSuccessor = Succ;
826
827 // Save the current "switch" context.
828 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
829 save_break(BreakTargetBlock);
830
831 // Create a new block that will contain the switch statement.
832 SwitchTerminatedBlock = createBlock(false);
833
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000834 // Now process the switch body. The code after the switch is the implicit
835 // successor.
836 Succ = SwitchSuccessor;
837 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000838
839 // When visiting the body, the case statements should automatically get
840 // linked up to the switch. We also don't keep a pointer to the body,
841 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000842 assert (S->getBody() && "switch must contain a non-NULL body");
843 Block = NULL;
844 CFGBlock *BodyBlock = Visit(S->getBody());
845 if (Block) FinishBlock(BodyBlock);
846
847 // Add the terminator and condition in the switch block.
848 SwitchTerminatedBlock->setTerminator(S);
849 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000850 Block = SwitchTerminatedBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000851 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000852}
853
854CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
855 // A SwitchCase is either a "default" or "case" statement. We handle
856 // both in the same way. They are essentially labels, so they are the
857 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000858
859 if (S->getSubStmt()) Visit(S->getSubStmt());
860 CFGBlock* CaseBlock = Block;
861 if (!CaseBlock) CaseBlock = createBlock();
862
Ted Kremenek9cffe732007-08-29 23:20:49 +0000863 // Cases/Default statements partition block, so this is the top of
864 // the basic block we were processing (the case/default is the label).
865 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000866 FinishBlock(CaseBlock);
867
868 // Add this block to the list of successors for the block with the
869 // switch statement.
870 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
871
872 // We set Block to NULL to allow lazy creation of a new block (if necessary)
873 Block = NULL;
874
875 // This block is now the implicit successor of other blocks.
876 Succ = CaseBlock;
877
878 return CaseBlock;
879}
880
Ted Kremenek19bb3562007-08-28 19:26:49 +0000881CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
882 // Lazily create the indirect-goto dispatch block if there isn't one
883 // already.
884 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
885
886 if (!IBlock) {
887 IBlock = createBlock(false);
888 cfg->setIndirectGotoBlock(IBlock);
889 }
890
891 // IndirectGoto is a control-flow statement. Thus we stop processing the
892 // current block and create a new one.
893 if (Block) FinishBlock(Block);
894 Block = createBlock(false);
895 Block->setTerminator(I);
896 Block->addSuccessor(IBlock);
897 return addStmt(I->getTarget());
898}
899
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000900
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000901} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000902
903/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
904/// block has no successors or predecessors. If this is the first block
905/// created in the CFG, it is automatically set to be the Entry and Exit
906/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000907CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000908 bool first_block = begin() == end();
909
910 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +0000911 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +0000912
913 // If this is the first block, set it as the Entry and Exit.
914 if (first_block) Entry = Exit = &front();
915
916 // Return the block.
917 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +0000918}
919
Ted Kremenek026473c2007-08-23 16:51:22 +0000920/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
921/// CFG is returned to the caller.
922CFG* CFG::buildCFG(Stmt* Statement) {
923 CFGBuilder Builder;
924 return Builder.buildCFG(Statement);
925}
926
927/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +0000928void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
929
Ted Kremenek63f58872007-10-01 19:33:33 +0000930//===----------------------------------------------------------------------===//
931// CFG: Queries for BlkExprs.
932//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +0000933
Ted Kremenek63f58872007-10-01 19:33:33 +0000934namespace {
935 typedef llvm::DenseMap<const Expr*,unsigned> BlkExprMapTy;
936}
937
938static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
939 BlkExprMapTy* M = new BlkExprMapTy();
940
941 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
942 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
943 if (const Expr* E = dyn_cast<Expr>(*BI))
944 (*M)[E] = M->size();
945
946 return M;
947}
948
949bool CFG::isBlkExpr(const Stmt* S) {
Ted Kremenek11e72182007-10-01 20:33:52 +0000950 assert (S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +0000951 if (const Expr* E = dyn_cast<Expr>(S)) return getBlkExprNum(E);
952 else return true; // Statements are by default "block-level expressions."
953}
954
955CFG::BlkExprNumTy CFG::getBlkExprNum(const Expr* E) {
Ted Kremenek11e72182007-10-01 20:33:52 +0000956 assert(E != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +0000957 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
958
959 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
960 BlkExprMapTy::iterator I = M->find(E);
961
962 if (I == M->end()) return CFG::BlkExprNumTy();
963 else return CFG::BlkExprNumTy(I->second);
964}
965
966unsigned CFG::getNumBlkExprs() {
967 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
968 return M->size();
969 else {
970 // We assume callers interested in the number of BlkExprs will want
971 // the map constructed if it doesn't already exist.
972 BlkExprMap = (void*) PopulateBlkExprMap(*this);
973 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
974 }
975}
976
977CFG::~CFG() {
978 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
979}
980
Ted Kremenek7dba8602007-08-29 21:56:09 +0000981//===----------------------------------------------------------------------===//
982// CFG pretty printing
983//===----------------------------------------------------------------------===//
984
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000985namespace {
986
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000987class StmtPrinterHelper : public PrinterHelper {
988
Ted Kremenek42a509f2007-08-31 21:30:12 +0000989 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
990 StmtMapTy StmtMap;
991 signed CurrentBlock;
992 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000993
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000994public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +0000995
Ted Kremenek42a509f2007-08-31 21:30:12 +0000996 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
997 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
998 unsigned j = 1;
999 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1000 BI != BEnd; ++BI, ++j )
1001 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1002 }
1003 }
1004
1005 virtual ~StmtPrinterHelper() {}
1006
1007 void setBlockID(signed i) { CurrentBlock = i; }
1008 void setStmtID(unsigned i) { CurrentStmt = i; }
1009
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001010 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1011
1012 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001013
1014 if (I == StmtMap.end())
1015 return false;
1016
1017 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1018 && I->second.second == CurrentStmt)
1019 return false;
1020
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001021 OS << "[B" << I->second.first << "." << I->second.second << "]";
1022 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001023 }
1024};
1025
1026class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek805e9a82007-08-31 21:49:40 +00001027 void >
1028{
Ted Kremenek42a509f2007-08-31 21:30:12 +00001029 std::ostream& OS;
1030 StmtPrinterHelper* Helper;
1031public:
1032 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1033 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001034
1035 void VisitIfStmt(IfStmt* I) {
1036 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001037 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001038 OS << "\n";
1039 }
1040
1041 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001042 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001043
1044 void VisitForStmt(ForStmt* F) {
1045 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001046 if (F->getInit()) OS << "...";
1047 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001048 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001049 OS << "; ";
1050 if (F->getInc()) OS << "...";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001051 OS << ")\n";
1052 }
1053
1054 void VisitWhileStmt(WhileStmt* W) {
1055 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001056 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001057 OS << "\n";
1058 }
1059
1060 void VisitDoStmt(DoStmt* D) {
1061 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001062 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001063 OS << '\n';
1064 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001065
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001066 void VisitSwitchStmt(SwitchStmt* S) {
1067 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001068 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001069 OS << '\n';
1070 }
1071
Ted Kremenek805e9a82007-08-31 21:49:40 +00001072 void VisitConditionalOperator(ConditionalOperator* C) {
1073 C->getCond()->printPretty(OS,Helper);
1074 OS << " ? ... : ...\n";
1075 }
1076
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001077 void VisitChooseExpr(ChooseExpr* C) {
1078 OS << "__builtin_choose_expr( ";
1079 C->getCond()->printPretty(OS,Helper);
1080 OS << " )\n";
1081 }
1082
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001083 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1084 OS << "goto *";
1085 I->getTarget()->printPretty(OS,Helper);
1086 OS << '\n';
1087 }
1088
Ted Kremenek805e9a82007-08-31 21:49:40 +00001089 void VisitBinaryOperator(BinaryOperator* B) {
1090 if (!B->isLogicalOp()) {
1091 VisitExpr(B);
1092 return;
1093 }
1094
1095 B->getLHS()->printPretty(OS,Helper);
1096
1097 switch (B->getOpcode()) {
1098 case BinaryOperator::LOr:
1099 OS << " || ...\n";
1100 return;
1101 case BinaryOperator::LAnd:
1102 OS << " && ...\n";
1103 return;
1104 default:
1105 assert(false && "Invalid logical operator.");
1106 }
1107 }
1108
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001109 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001110 E->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001111 OS << '\n';
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001112 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001113};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001114
1115
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001116void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1117 if (Helper) {
1118 // special printing for statement-expressions.
1119 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1120 CompoundStmt* Sub = SE->getSubStmt();
1121
1122 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001123 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001124 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001125 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001126 return;
1127 }
1128 }
1129
1130 // special printing for comma expressions.
1131 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1132 if (B->getOpcode() == BinaryOperator::Comma) {
1133 OS << "... , ";
1134 Helper->handledStmt(B->getRHS(),OS);
1135 OS << '\n';
1136 return;
1137 }
1138 }
1139 }
1140
1141 S->printPretty(OS, Helper);
1142
1143 // Expressions need a newline.
1144 if (isa<Expr>(S)) OS << '\n';
1145}
1146
Ted Kremenek42a509f2007-08-31 21:30:12 +00001147void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1148 StmtPrinterHelper* Helper, bool print_edges) {
1149
1150 if (Helper) Helper->setBlockID(B.getBlockID());
1151
Ted Kremenek7dba8602007-08-29 21:56:09 +00001152 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001153 OS << "\n [ B" << B.getBlockID();
1154
1155 if (&B == &cfg->getEntry())
1156 OS << " (ENTRY) ]\n";
1157 else if (&B == &cfg->getExit())
1158 OS << " (EXIT) ]\n";
1159 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001160 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001161 else
1162 OS << " ]\n";
1163
Ted Kremenek9cffe732007-08-29 23:20:49 +00001164 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001165 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1166
1167 if (print_edges)
1168 OS << " ";
1169
Ted Kremenek9cffe732007-08-29 23:20:49 +00001170 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1171 OS << L->getName();
1172 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1173 OS << "case ";
1174 C->getLHS()->printPretty(OS);
1175 if (C->getRHS()) {
1176 OS << " ... ";
1177 C->getRHS()->printPretty(OS);
1178 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001179 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001180 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001181 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001182 else
1183 assert(false && "Invalid label statement in CFGBlock.");
1184
Ted Kremenek9cffe732007-08-29 23:20:49 +00001185 OS << ":\n";
1186 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001187
Ted Kremenekfddd5182007-08-21 21:42:03 +00001188 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001189 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001190
1191 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1192 I != E ; ++I, ++j ) {
1193
Ted Kremenek9cffe732007-08-29 23:20:49 +00001194 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001195 if (print_edges)
1196 OS << " ";
1197
1198 OS << std::setw(3) << j << ": ";
1199
1200 if (Helper)
1201 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001202
1203 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001204 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001205
Ted Kremenek9cffe732007-08-29 23:20:49 +00001206 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001207 if (B.getTerminator()) {
1208 if (print_edges)
1209 OS << " ";
1210
Ted Kremenek9cffe732007-08-29 23:20:49 +00001211 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001212
1213 if (Helper) Helper->setBlockID(-1);
1214
1215 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1216 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenekfddd5182007-08-21 21:42:03 +00001217 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001218
Ted Kremenek9cffe732007-08-29 23:20:49 +00001219 if (print_edges) {
1220 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001221 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001222 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001223
Ted Kremenek42a509f2007-08-31 21:30:12 +00001224 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1225 I != E; ++I, ++i) {
1226
1227 if (i == 8 || (i-8) == 0)
1228 OS << "\n ";
1229
Ted Kremenek9cffe732007-08-29 23:20:49 +00001230 OS << " B" << (*I)->getBlockID();
1231 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001232
1233 OS << '\n';
1234
1235 // Print the successors of this block.
1236 OS << " Successors (" << B.succ_size() << "):";
1237 i = 0;
1238
1239 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1240 I != E; ++I, ++i) {
1241
1242 if (i == 8 || (i-8) % 10 == 0)
1243 OS << "\n ";
1244
1245 OS << " B" << (*I)->getBlockID();
1246 }
1247
Ted Kremenek9cffe732007-08-29 23:20:49 +00001248 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001249 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001250}
1251
1252} // end anonymous namespace
1253
1254/// dump - A simple pretty printer of a CFG that outputs to stderr.
1255void CFG::dump() const { print(std::cerr); }
1256
1257/// print - A simple pretty printer of a CFG that outputs to an ostream.
1258void CFG::print(std::ostream& OS) const {
1259
1260 StmtPrinterHelper Helper(this);
1261
1262 // Print the entry block.
1263 print_block(OS, this, getEntry(), &Helper, true);
1264
1265 // Iterate through the CFGBlocks and print them one by one.
1266 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1267 // Skip the entry block, because we already printed it.
1268 if (&(*I) == &getEntry() || &(*I) == &getExit())
1269 continue;
1270
1271 print_block(OS, this, *I, &Helper, true);
1272 }
1273
1274 // Print the exit block.
1275 print_block(OS, this, getExit(), &Helper, true);
1276}
1277
1278/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1279void CFGBlock::dump(const CFG* cfg) const { print(std::cerr, cfg); }
1280
1281/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1282/// Generally this will only be called from CFG::print.
1283void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1284 StmtPrinterHelper Helper(cfg);
1285 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001286}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001287
1288//===----------------------------------------------------------------------===//
1289// CFG Graphviz Visualization
1290//===----------------------------------------------------------------------===//
1291
Ted Kremenek42a509f2007-08-31 21:30:12 +00001292
1293#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001294static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001295#endif
1296
1297void CFG::viewCFG() const {
1298#ifndef NDEBUG
1299 StmtPrinterHelper H(this);
1300 GraphHelper = &H;
1301 llvm::ViewGraph(this,"CFG");
1302 GraphHelper = NULL;
1303#else
1304 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001305 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001306#endif
1307}
1308
Ted Kremenek7dba8602007-08-29 21:56:09 +00001309namespace llvm {
1310template<>
1311struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1312 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1313
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001314#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001315 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001316 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001317 std::string OutStr = Out.str();
1318
1319 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1320
1321 // Process string output to make it nicer...
1322 for (unsigned i = 0; i != OutStr.length(); ++i)
1323 if (OutStr[i] == '\n') { // Left justify
1324 OutStr[i] = '\\';
1325 OutStr.insert(OutStr.begin()+i+1, 'l');
1326 }
1327
1328 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001329#else
1330 return "";
1331#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001332 }
1333};
1334} // end namespace llvm