blob: b93d77e3fa06117cc0a91da9d41684bf1a532744 [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);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000223
224 // Create the confluence block that will "merge" the results
225 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000226 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
227 ConfluenceBlock->appendStmt(C);
228 FinishBlock(ConfluenceBlock);
229
Ted Kremenekecc04c92007-11-26 18:20:26 +0000230
231 // Create a block for the LHS expression if there is an LHS expression.
232 // A GCC extension allows LHS to be NULL, causing the condition to
233 // be the value that is returned instead.
234 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000235 Succ = ConfluenceBlock;
236 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000237 CFGBlock* LHSBlock = NULL;
238 if (C->getLHS()) {
239 LHSBlock = Visit(C->getLHS());
240 FinishBlock(LHSBlock);
241 Block = NULL;
242 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000243
Ted Kremenekecc04c92007-11-26 18:20:26 +0000244 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000245 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000246 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000247 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000248
Ted Kremenekecc04c92007-11-26 18:20:26 +0000249 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000250 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000251
252 if (LHSBlock)
253 Block->addSuccessor(LHSBlock);
254 else {
255 // If we have no LHS expression, add the ConfluenceBlock as a direct
256 // successor for the block containing the condition. Moreover,
257 // we need to reverse the order of the predecessors in the
258 // ConfluenceBlock because the RHSBlock will have been added to
259 // the succcessors already, and we want the first predecessor to the
260 // the block containing the expression for the case when the ternary
261 // expression evaluates to true.
262 Block->addSuccessor(ConfluenceBlock);
263 assert (ConfluenceBlock->pred_size() == 2);
264 std::reverse(ConfluenceBlock->pred_begin(),
265 ConfluenceBlock->pred_end());
266 }
267
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000268 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000269
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000270 Block->setTerminator(C);
271 return addStmt(C->getCond());
272 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000273
274 case Stmt::ChooseExprClass: {
275 ChooseExpr* C = cast<ChooseExpr>(S);
276
277 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
278 ConfluenceBlock->appendStmt(C);
279 FinishBlock(ConfluenceBlock);
280
281 Succ = ConfluenceBlock;
282 Block = NULL;
283 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000284 FinishBlock(LHSBlock);
285
Ted Kremenek49a436d2007-08-31 17:03:41 +0000286 Succ = ConfluenceBlock;
287 Block = NULL;
288 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000289 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000290
291 Block = createBlock(false);
292 Block->addSuccessor(LHSBlock);
293 Block->addSuccessor(RHSBlock);
294 Block->setTerminator(C);
295 return addStmt(C->getCond());
296 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000297
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000298 case Stmt::DeclStmtClass: {
299 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
300 Block->appendStmt(S);
301
302 StmtIterator I(D);
303 return WalkAST_VisitDeclSubExprs(I);
304 }
Ted Kremenek15c27a82007-08-28 18:30:10 +0000305
Ted Kremenek19bb3562007-08-28 19:26:49 +0000306 case Stmt::AddrLabelExprClass: {
307 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
308 AddressTakenLabels.insert(A->getLabel());
309
310 if (AlwaysAddStmt) Block->appendStmt(S);
311 return Block;
312 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000313
314 case Stmt::CallExprClass:
315 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek19bb3562007-08-28 19:26:49 +0000316
Ted Kremenek15c27a82007-08-28 18:30:10 +0000317 case Stmt::StmtExprClass:
318 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000319
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000320 case Stmt::BinaryOperatorClass: {
321 BinaryOperator* B = cast<BinaryOperator>(S);
322
323 if (B->isLogicalOp()) { // && or ||
324 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
325 ConfluenceBlock->appendStmt(B);
326 FinishBlock(ConfluenceBlock);
327
328 // create the block evaluating the LHS
329 CFGBlock* LHSBlock = createBlock(false);
330 LHSBlock->addSuccessor(ConfluenceBlock);
331 LHSBlock->setTerminator(B);
332
333 // create the block evaluating the RHS
334 Succ = ConfluenceBlock;
335 Block = NULL;
336 CFGBlock* RHSBlock = Visit(B->getRHS());
337 LHSBlock->addSuccessor(RHSBlock);
338
339 // Generate the blocks for evaluating the LHS.
340 Block = LHSBlock;
341 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000342 }
343 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
344 Block->appendStmt(B);
345 addStmt(B->getRHS());
346 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000347 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000348
349 // Fall through to the default case.
350 }
351
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000352 default:
353 if (AlwaysAddStmt) Block->appendStmt(S);
354 return WalkAST_VisitChildren(S);
355 };
356}
357
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000358/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
359/// DeclStmts. Because the initialization code (and sometimes the
360/// the type declarations) for DeclStmts can contain arbitrary expressions,
361/// we must linearize declarations to handle arbitrary control-flow induced by
362/// those expressions.
363CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekd6603222007-11-18 20:06:01 +0000364 if (I == StmtIterator())
365 return Block;
366
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000367 Stmt* S = *I;
368 ++I;
Ted Kremenekd6603222007-11-18 20:06:01 +0000369 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000370
371 Block = addStmt(S);
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000372 return Block;
373}
374
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000375/// WalkAST_VisitChildren - Utility method to call WalkAST on the
376/// children of a Stmt.
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000377CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000378 CFGBlock* B = Block;
379 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
380 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000381 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000382
383 return B;
384}
385
Ted Kremenek15c27a82007-08-28 18:30:10 +0000386/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
387/// expressions (a GCC extension).
388CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
389 Block->appendStmt(S);
390 return VisitCompoundStmt(S->getSubStmt());
391}
392
Ted Kremenekf50ec102007-09-11 21:29:43 +0000393/// WalkAST_VisitCallExpr - Utility method to handle function calls that
394/// are nested in expressions. The idea is that each function call should
395/// appear as a distinct statement in the CFGBlock.
396CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
397 Block->appendStmt(C);
398 return WalkAST_VisitChildren(C);
399}
400
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000401/// VisitStmt - Handle statements with no branching control flow.
402CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
403 // We cannot assume that we are in the middle of a basic block, since
404 // the CFG might only be constructed for this single statement. If
405 // we have no current basic block, just create one lazily.
406 if (!Block) Block = createBlock();
407
408 // Simply add the statement to the current block. We actually
409 // insert statements in reverse order; this order is reversed later
410 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000411 addStmt(Statement);
412
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000413 return Block;
414}
415
416CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
417 return Block;
418}
419
420CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
421 // The value returned from this function is the last created CFGBlock
422 // that represents the "entry" point for the translated AST node.
Chris Lattner271f1a62007-09-27 15:15:46 +0000423 CFGBlock* LastBlock = 0;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000424
425 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
426 E = C->body_rend(); I != E; ++I )
427 // Add the statement to the current block.
428 if (!(LastBlock=Visit(*I)))
429 return NULL;
430
431 return LastBlock;
432}
433
434CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
435 // We may see an if statement in the middle of a basic block, or
436 // it may be the first statement we are processing. In either case,
437 // we create a new basic block. First, we create the blocks for
438 // the then...else statements, and then we create the block containing
439 // the if statement. If we were in the middle of a block, we
440 // stop processing that block and reverse its statements. That block
441 // is then the implicit successor for the "then" and "else" clauses.
442
443 // The block we were proccessing is now finished. Make it the
444 // successor block.
445 if (Block) {
446 Succ = Block;
447 FinishBlock(Block);
448 }
449
450 // Process the false branch. NULL out Block so that the recursive
451 // call to Visit will create a new basic block.
452 // Null out Block so that all successor
453 CFGBlock* ElseBlock = Succ;
454
455 if (Stmt* Else = I->getElse()) {
456 SaveAndRestore<CFGBlock*> sv(Succ);
457
458 // NULL out Block so that the recursive call to Visit will
459 // create a new basic block.
460 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000461 ElseBlock = Visit(Else);
462
463 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
464 ElseBlock = sv.get();
465 else if (Block)
466 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000467 }
468
469 // Process the true branch. NULL out Block so that the recursive
470 // call to Visit will create a new basic block.
471 // Null out Block so that all successor
472 CFGBlock* ThenBlock;
473 {
474 Stmt* Then = I->getThen();
475 assert (Then);
476 SaveAndRestore<CFGBlock*> sv(Succ);
477 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000478 ThenBlock = Visit(Then);
479
480 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
481 ThenBlock = sv.get();
482 else if (Block)
483 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000484 }
485
486 // Now create a new block containing the if statement.
487 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000488
489 // Set the terminator of the new block to the If statement.
490 Block->setTerminator(I);
491
492 // Now add the successors.
493 Block->addSuccessor(ThenBlock);
494 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000495
496 // Add the condition as the last statement in the new block. This
497 // may create new blocks as the condition may contain control-flow. Any
498 // newly created blocks will be pointed to be "Block".
499 return addStmt(I->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000500}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000501
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000502
503CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
504 // If we were in the middle of a block we stop processing that block
505 // and reverse its statements.
506 //
507 // NOTE: If a "return" appears in the middle of a block, this means
508 // that the code afterwards is DEAD (unreachable). We still
509 // keep a basic block for that code; a simple "mark-and-sweep"
510 // from the entry block will be able to report such dead
511 // blocks.
512 if (Block) FinishBlock(Block);
513
514 // Create the new block.
515 Block = createBlock(false);
516
517 // The Exit block is the only successor.
518 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000519
520 // Add the return statement to the block. This may create new blocks
521 // if R contains control-flow (short-circuit operations).
522 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000523}
524
525CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
526 // Get the block of the labeled statement. Add it to our map.
527 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000528
529 if (!LabelBlock) // This can happen when the body is empty, i.e.
530 LabelBlock=createBlock(); // scopes that only contains NullStmts.
531
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000532 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
533 LabelMap[ L ] = LabelBlock;
534
535 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000536 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000537 // label (and we have already processed the substatement) there is no
538 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000539 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000540 FinishBlock(LabelBlock);
541
542 // We set Block to NULL to allow lazy creation of a new block
543 // (if necessary);
544 Block = NULL;
545
546 // This block is now the implicit successor of other blocks.
547 Succ = LabelBlock;
548
549 return LabelBlock;
550}
551
552CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
553 // Goto is a control-flow statement. Thus we stop processing the
554 // current block and create a new one.
555 if (Block) FinishBlock(Block);
556 Block = createBlock(false);
557 Block->setTerminator(G);
558
559 // If we already know the mapping to the label block add the
560 // successor now.
561 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
562
563 if (I == LabelMap.end())
564 // We will need to backpatch this block later.
565 BackpatchBlocks.push_back(Block);
566 else
567 Block->addSuccessor(I->second);
568
569 return Block;
570}
571
572CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
573 // "for" is a control-flow statement. Thus we stop processing the
574 // current block.
575
576 CFGBlock* LoopSuccessor = NULL;
577
578 if (Block) {
579 FinishBlock(Block);
580 LoopSuccessor = Block;
581 }
582 else LoopSuccessor = Succ;
583
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000584 // Because of short-circuit evaluation, the condition of the loop
585 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
586 // blocks that evaluate the condition.
587 CFGBlock* ExitConditionBlock = createBlock(false);
588 CFGBlock* EntryConditionBlock = ExitConditionBlock;
589
590 // Set the terminator for the "exit" condition block.
591 ExitConditionBlock->setTerminator(F);
592
593 // Now add the actual condition to the condition block. Because the
594 // condition itself may contain control-flow, new blocks may be created.
595 if (Stmt* C = F->getCond()) {
596 Block = ExitConditionBlock;
597 EntryConditionBlock = addStmt(C);
598 if (Block) FinishBlock(EntryConditionBlock);
599 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000600
601 // The condition block is the implicit successor for the loop body as
602 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000603 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000604
605 // Now create the loop body.
606 {
607 assert (F->getBody());
608
609 // Save the current values for Block, Succ, and continue and break targets
610 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
611 save_continue(ContinueTargetBlock),
612 save_break(BreakTargetBlock);
613
614 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000615 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000616
617 // All breaks should go to the code following the loop.
618 BreakTargetBlock = LoopSuccessor;
619
Ted Kremenekaf603f72007-08-30 18:39:40 +0000620 // Create a new block to contain the (bottom) of the loop body.
621 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000622
623 // If we have increment code, insert it at the end of the body block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000624 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000625
626 // Now populate the body block, and in the process create new blocks
627 // as we walk the body of the loop.
628 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000629
630 if (!BodyBlock)
631 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
632 else if (Block)
633 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000634
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000635 // This new body block is a successor to our "exit" condition block.
636 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000637 }
638
639 // Link up the condition block with the code that follows the loop.
640 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000641 ExitConditionBlock->addSuccessor(LoopSuccessor);
642
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000643 // If the loop contains initialization, create a new block for those
644 // statements. This block can also contain statements that precede
645 // the loop.
646 if (Stmt* I = F->getInit()) {
647 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000648 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000649 }
650 else {
651 // There is no loop initialization. We are thus basically a while
652 // loop. NULL out Block to force lazy block construction.
653 Block = NULL;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000654 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000655 }
656}
657
658CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
659 // "while" is a control-flow statement. Thus we stop processing the
660 // current block.
661
662 CFGBlock* LoopSuccessor = NULL;
663
664 if (Block) {
665 FinishBlock(Block);
666 LoopSuccessor = Block;
667 }
668 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000669
670 // Because of short-circuit evaluation, the condition of the loop
671 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
672 // blocks that evaluate the condition.
673 CFGBlock* ExitConditionBlock = createBlock(false);
674 CFGBlock* EntryConditionBlock = ExitConditionBlock;
675
676 // Set the terminator for the "exit" condition block.
677 ExitConditionBlock->setTerminator(W);
678
679 // Now add the actual condition to the condition block. Because the
680 // condition itself may contain control-flow, new blocks may be created.
681 // Thus we update "Succ" after adding the condition.
682 if (Stmt* C = W->getCond()) {
683 Block = ExitConditionBlock;
684 EntryConditionBlock = addStmt(C);
685 if (Block) FinishBlock(EntryConditionBlock);
686 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000687
688 // The condition block is the implicit successor for the loop body as
689 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000690 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000691
692 // Process the loop body.
693 {
694 assert (W->getBody());
695
696 // Save the current values for Block, Succ, and continue and break targets
697 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
698 save_continue(ContinueTargetBlock),
699 save_break(BreakTargetBlock);
700
701 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000702 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000703
704 // All breaks should go to the code following the loop.
705 BreakTargetBlock = LoopSuccessor;
706
707 // NULL out Block to force lazy instantiation of blocks for the body.
708 Block = NULL;
709
710 // Create the body. The returned block is the entry to the loop body.
711 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000712
713 if (!BodyBlock)
714 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
715 else if (Block)
716 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000717
718 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000719 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000720 }
721
722 // Link up the condition block with the code that follows the loop.
723 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000724 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000725
726 // There can be no more statements in the condition block
727 // since we loop back to this block. NULL out Block to force
728 // lazy creation of another block.
729 Block = NULL;
730
731 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000732 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000733}
734
735CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
736 // "do...while" is a control-flow statement. Thus we stop processing the
737 // current block.
738
739 CFGBlock* LoopSuccessor = NULL;
740
741 if (Block) {
742 FinishBlock(Block);
743 LoopSuccessor = Block;
744 }
745 else LoopSuccessor = Succ;
746
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000747 // Because of short-circuit evaluation, the condition of the loop
748 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
749 // blocks that evaluate the condition.
750 CFGBlock* ExitConditionBlock = createBlock(false);
751 CFGBlock* EntryConditionBlock = ExitConditionBlock;
752
753 // Set the terminator for the "exit" condition block.
754 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000755
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000756 // Now add the actual condition to the condition block. Because the
757 // condition itself may contain control-flow, new blocks may be created.
758 if (Stmt* C = D->getCond()) {
759 Block = ExitConditionBlock;
760 EntryConditionBlock = addStmt(C);
761 if (Block) FinishBlock(EntryConditionBlock);
762 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000763
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000764 // The condition block is the implicit successor for the loop body as
765 // well as any code above the loop.
766 Succ = EntryConditionBlock;
767
768
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000769 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000770 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000771 {
772 assert (D->getBody());
773
774 // Save the current values for Block, Succ, and continue and break targets
775 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
776 save_continue(ContinueTargetBlock),
777 save_break(BreakTargetBlock);
778
779 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000780 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000781
782 // All breaks should go to the code following the loop.
783 BreakTargetBlock = LoopSuccessor;
784
785 // NULL out Block to force lazy instantiation of blocks for the body.
786 Block = NULL;
787
788 // Create the body. The returned block is the entry to the loop body.
789 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000790
Ted Kremenekaf603f72007-08-30 18:39:40 +0000791 if (!BodyBlock)
792 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
793 else if (Block)
794 FinishBlock(BodyBlock);
795
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000796 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000797 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000798 }
799
800 // Link up the condition block with the code that follows the loop.
801 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000802 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000803
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000804 // There can be no more statements in the body block(s)
805 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000806 // lazy creation of another block.
807 Block = NULL;
808
809 // Return the loop body, which is the dominating block for the loop.
810 return BodyBlock;
811}
812
813CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
814 // "continue" is a control-flow statement. Thus we stop processing the
815 // current block.
816 if (Block) FinishBlock(Block);
817
818 // Now create a new block that ends with the continue statement.
819 Block = createBlock(false);
820 Block->setTerminator(C);
821
822 // If there is no target for the continue, then we are looking at an
823 // incomplete AST. Handle this by not registering a successor.
824 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
825
826 return Block;
827}
828
829CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
830 // "break" is a control-flow statement. Thus we stop processing the
831 // current block.
832 if (Block) FinishBlock(Block);
833
834 // Now create a new block that ends with the continue statement.
835 Block = createBlock(false);
836 Block->setTerminator(B);
837
838 // If there is no target for the break, then we are looking at an
839 // incomplete AST. Handle this by not registering a successor.
840 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
841
842 return Block;
843}
844
845CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
846 // "switch" is a control-flow statement. Thus we stop processing the
847 // current block.
848 CFGBlock* SwitchSuccessor = NULL;
849
850 if (Block) {
851 FinishBlock(Block);
852 SwitchSuccessor = Block;
853 }
854 else SwitchSuccessor = Succ;
855
856 // Save the current "switch" context.
857 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
858 save_break(BreakTargetBlock);
859
860 // Create a new block that will contain the switch statement.
861 SwitchTerminatedBlock = createBlock(false);
862
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000863 // Now process the switch body. The code after the switch is the implicit
864 // successor.
865 Succ = SwitchSuccessor;
866 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000867
868 // When visiting the body, the case statements should automatically get
869 // linked up to the switch. We also don't keep a pointer to the body,
870 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000871 assert (S->getBody() && "switch must contain a non-NULL body");
872 Block = NULL;
873 CFGBlock *BodyBlock = Visit(S->getBody());
874 if (Block) FinishBlock(BodyBlock);
875
876 // Add the terminator and condition in the switch block.
877 SwitchTerminatedBlock->setTerminator(S);
878 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000879 Block = SwitchTerminatedBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000880 return addStmt(S->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000881}
882
883CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
884 // A SwitchCase is either a "default" or "case" statement. We handle
885 // both in the same way. They are essentially labels, so they are the
886 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +0000887
888 if (S->getSubStmt()) Visit(S->getSubStmt());
889 CFGBlock* CaseBlock = Block;
890 if (!CaseBlock) CaseBlock = createBlock();
891
Ted Kremenek9cffe732007-08-29 23:20:49 +0000892 // Cases/Default statements partition block, so this is the top of
893 // the basic block we were processing (the case/default is the label).
894 CaseBlock->setLabel(S);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000895 FinishBlock(CaseBlock);
896
897 // Add this block to the list of successors for the block with the
898 // switch statement.
899 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
900
901 // We set Block to NULL to allow lazy creation of a new block (if necessary)
902 Block = NULL;
903
904 // This block is now the implicit successor of other blocks.
905 Succ = CaseBlock;
906
907 return CaseBlock;
908}
909
Ted Kremenek19bb3562007-08-28 19:26:49 +0000910CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
911 // Lazily create the indirect-goto dispatch block if there isn't one
912 // already.
913 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
914
915 if (!IBlock) {
916 IBlock = createBlock(false);
917 cfg->setIndirectGotoBlock(IBlock);
918 }
919
920 // IndirectGoto is a control-flow statement. Thus we stop processing the
921 // current block and create a new one.
922 if (Block) FinishBlock(Block);
923 Block = createBlock(false);
924 Block->setTerminator(I);
925 Block->addSuccessor(IBlock);
926 return addStmt(I->getTarget());
927}
928
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000929
Ted Kremenekbefef2f2007-08-23 21:26:19 +0000930} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +0000931
932/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
933/// block has no successors or predecessors. If this is the first block
934/// created in the CFG, it is automatically set to be the Entry and Exit
935/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +0000936CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +0000937 bool first_block = begin() == end();
938
939 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +0000940 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +0000941
942 // If this is the first block, set it as the Entry and Exit.
943 if (first_block) Entry = Exit = &front();
944
945 // Return the block.
946 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +0000947}
948
Ted Kremenek026473c2007-08-23 16:51:22 +0000949/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
950/// CFG is returned to the caller.
951CFG* CFG::buildCFG(Stmt* Statement) {
952 CFGBuilder Builder;
953 return Builder.buildCFG(Statement);
954}
955
956/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +0000957void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
958
Ted Kremenek63f58872007-10-01 19:33:33 +0000959//===----------------------------------------------------------------------===//
960// CFG: Queries for BlkExprs.
961//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +0000962
Ted Kremenek63f58872007-10-01 19:33:33 +0000963namespace {
964 typedef llvm::DenseMap<const Expr*,unsigned> BlkExprMapTy;
965}
966
967static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
968 BlkExprMapTy* M = new BlkExprMapTy();
969
970 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
971 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek9a8385d2007-12-10 23:58:39 +0000972 if (const Expr* E = dyn_cast<Expr>(*BI)) {
973 unsigned x = M->size();
974 (*M)[E] = x;
975 }
Ted Kremenek63f58872007-10-01 19:33:33 +0000976
977 return M;
978}
979
980bool CFG::isBlkExpr(const Stmt* S) {
Ted Kremenek11e72182007-10-01 20:33:52 +0000981 assert (S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +0000982 if (const Expr* E = dyn_cast<Expr>(S)) return getBlkExprNum(E);
983 else return true; // Statements are by default "block-level expressions."
984}
985
986CFG::BlkExprNumTy CFG::getBlkExprNum(const Expr* E) {
Ted Kremenek11e72182007-10-01 20:33:52 +0000987 assert(E != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +0000988 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
989
990 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
991 BlkExprMapTy::iterator I = M->find(E);
992
993 if (I == M->end()) return CFG::BlkExprNumTy();
994 else return CFG::BlkExprNumTy(I->second);
995}
996
997unsigned CFG::getNumBlkExprs() {
998 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
999 return M->size();
1000 else {
1001 // We assume callers interested in the number of BlkExprs will want
1002 // the map constructed if it doesn't already exist.
1003 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1004 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1005 }
1006}
1007
1008CFG::~CFG() {
1009 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1010}
1011
Ted Kremenek7dba8602007-08-29 21:56:09 +00001012//===----------------------------------------------------------------------===//
1013// CFG pretty printing
1014//===----------------------------------------------------------------------===//
1015
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001016namespace {
1017
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001018class StmtPrinterHelper : public PrinterHelper {
1019
Ted Kremenek42a509f2007-08-31 21:30:12 +00001020 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1021 StmtMapTy StmtMap;
1022 signed CurrentBlock;
1023 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001024
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001025public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001026
Ted Kremenek42a509f2007-08-31 21:30:12 +00001027 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1028 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1029 unsigned j = 1;
1030 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1031 BI != BEnd; ++BI, ++j )
1032 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1033 }
1034 }
1035
1036 virtual ~StmtPrinterHelper() {}
1037
1038 void setBlockID(signed i) { CurrentBlock = i; }
1039 void setStmtID(unsigned i) { CurrentStmt = i; }
1040
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001041 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1042
1043 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001044
1045 if (I == StmtMap.end())
1046 return false;
1047
1048 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1049 && I->second.second == CurrentStmt)
1050 return false;
1051
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001052 OS << "[B" << I->second.first << "." << I->second.second << "]";
1053 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001054 }
1055};
1056
1057class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek805e9a82007-08-31 21:49:40 +00001058 void >
1059{
Ted Kremenek42a509f2007-08-31 21:30:12 +00001060 std::ostream& OS;
1061 StmtPrinterHelper* Helper;
1062public:
1063 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1064 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001065
1066 void VisitIfStmt(IfStmt* I) {
1067 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001068 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001069 OS << "\n";
1070 }
1071
1072 // Default case.
Ted Kremenek805e9a82007-08-31 21:49:40 +00001073 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001074
1075 void VisitForStmt(ForStmt* F) {
1076 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001077 if (F->getInit()) OS << "...";
1078 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001079 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001080 OS << "; ";
1081 if (F->getInc()) OS << "...";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001082 OS << ")\n";
1083 }
1084
1085 void VisitWhileStmt(WhileStmt* W) {
1086 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001087 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001088 OS << "\n";
1089 }
1090
1091 void VisitDoStmt(DoStmt* D) {
1092 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001093 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001094 OS << '\n';
1095 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001096
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001097 void VisitSwitchStmt(SwitchStmt* S) {
1098 OS << "switch ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001099 S->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001100 OS << '\n';
1101 }
1102
Ted Kremenek805e9a82007-08-31 21:49:40 +00001103 void VisitConditionalOperator(ConditionalOperator* C) {
1104 C->getCond()->printPretty(OS,Helper);
1105 OS << " ? ... : ...\n";
1106 }
1107
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001108 void VisitChooseExpr(ChooseExpr* C) {
1109 OS << "__builtin_choose_expr( ";
1110 C->getCond()->printPretty(OS,Helper);
1111 OS << " )\n";
1112 }
1113
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001114 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1115 OS << "goto *";
1116 I->getTarget()->printPretty(OS,Helper);
1117 OS << '\n';
1118 }
1119
Ted Kremenek805e9a82007-08-31 21:49:40 +00001120 void VisitBinaryOperator(BinaryOperator* B) {
1121 if (!B->isLogicalOp()) {
1122 VisitExpr(B);
1123 return;
1124 }
1125
1126 B->getLHS()->printPretty(OS,Helper);
1127
1128 switch (B->getOpcode()) {
1129 case BinaryOperator::LOr:
1130 OS << " || ...\n";
1131 return;
1132 case BinaryOperator::LAnd:
1133 OS << " && ...\n";
1134 return;
1135 default:
1136 assert(false && "Invalid logical operator.");
1137 }
1138 }
1139
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001140 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001141 E->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001142 OS << '\n';
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001143 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001144};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001145
1146
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001147void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1148 if (Helper) {
1149 // special printing for statement-expressions.
1150 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1151 CompoundStmt* Sub = SE->getSubStmt();
1152
1153 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001154 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001155 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001156 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001157 return;
1158 }
1159 }
1160
1161 // special printing for comma expressions.
1162 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1163 if (B->getOpcode() == BinaryOperator::Comma) {
1164 OS << "... , ";
1165 Helper->handledStmt(B->getRHS(),OS);
1166 OS << '\n';
1167 return;
1168 }
1169 }
1170 }
1171
1172 S->printPretty(OS, Helper);
1173
1174 // Expressions need a newline.
1175 if (isa<Expr>(S)) OS << '\n';
1176}
1177
Ted Kremenek42a509f2007-08-31 21:30:12 +00001178void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1179 StmtPrinterHelper* Helper, bool print_edges) {
1180
1181 if (Helper) Helper->setBlockID(B.getBlockID());
1182
Ted Kremenek7dba8602007-08-29 21:56:09 +00001183 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001184 OS << "\n [ B" << B.getBlockID();
1185
1186 if (&B == &cfg->getEntry())
1187 OS << " (ENTRY) ]\n";
1188 else if (&B == &cfg->getExit())
1189 OS << " (EXIT) ]\n";
1190 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001191 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001192 else
1193 OS << " ]\n";
1194
Ted Kremenek9cffe732007-08-29 23:20:49 +00001195 // Print the label of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001196 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1197
1198 if (print_edges)
1199 OS << " ";
1200
Ted Kremenek9cffe732007-08-29 23:20:49 +00001201 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1202 OS << L->getName();
1203 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1204 OS << "case ";
1205 C->getLHS()->printPretty(OS);
1206 if (C->getRHS()) {
1207 OS << " ... ";
1208 C->getRHS()->printPretty(OS);
1209 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001210 }
Chris Lattnerf874c132007-09-16 19:11:53 +00001211 else if (isa<DefaultStmt>(S))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001212 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001213 else
1214 assert(false && "Invalid label statement in CFGBlock.");
1215
Ted Kremenek9cffe732007-08-29 23:20:49 +00001216 OS << ":\n";
1217 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001218
Ted Kremenekfddd5182007-08-21 21:42:03 +00001219 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001220 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001221
1222 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1223 I != E ; ++I, ++j ) {
1224
Ted Kremenek9cffe732007-08-29 23:20:49 +00001225 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001226 if (print_edges)
1227 OS << " ";
1228
1229 OS << std::setw(3) << j << ": ";
1230
1231 if (Helper)
1232 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001233
1234 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001235 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001236
Ted Kremenek9cffe732007-08-29 23:20:49 +00001237 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001238 if (B.getTerminator()) {
1239 if (print_edges)
1240 OS << " ";
1241
Ted Kremenek9cffe732007-08-29 23:20:49 +00001242 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001243
1244 if (Helper) Helper->setBlockID(-1);
1245
1246 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1247 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenekfddd5182007-08-21 21:42:03 +00001248 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001249
Ted Kremenek9cffe732007-08-29 23:20:49 +00001250 if (print_edges) {
1251 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001252 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001253 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001254
Ted Kremenek42a509f2007-08-31 21:30:12 +00001255 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1256 I != E; ++I, ++i) {
1257
1258 if (i == 8 || (i-8) == 0)
1259 OS << "\n ";
1260
Ted Kremenek9cffe732007-08-29 23:20:49 +00001261 OS << " B" << (*I)->getBlockID();
1262 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001263
1264 OS << '\n';
1265
1266 // Print the successors of this block.
1267 OS << " Successors (" << B.succ_size() << "):";
1268 i = 0;
1269
1270 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1271 I != E; ++I, ++i) {
1272
1273 if (i == 8 || (i-8) % 10 == 0)
1274 OS << "\n ";
1275
1276 OS << " B" << (*I)->getBlockID();
1277 }
1278
Ted Kremenek9cffe732007-08-29 23:20:49 +00001279 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001280 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001281}
1282
1283} // end anonymous namespace
1284
1285/// dump - A simple pretty printer of a CFG that outputs to stderr.
1286void CFG::dump() const { print(std::cerr); }
1287
1288/// print - A simple pretty printer of a CFG that outputs to an ostream.
1289void CFG::print(std::ostream& OS) const {
1290
1291 StmtPrinterHelper Helper(this);
1292
1293 // Print the entry block.
1294 print_block(OS, this, getEntry(), &Helper, true);
1295
1296 // Iterate through the CFGBlocks and print them one by one.
1297 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1298 // Skip the entry block, because we already printed it.
1299 if (&(*I) == &getEntry() || &(*I) == &getExit())
1300 continue;
1301
1302 print_block(OS, this, *I, &Helper, true);
1303 }
1304
1305 // Print the exit block.
1306 print_block(OS, this, getExit(), &Helper, true);
1307}
1308
1309/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
1310void CFGBlock::dump(const CFG* cfg) const { print(std::cerr, cfg); }
1311
1312/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1313/// Generally this will only be called from CFG::print.
1314void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1315 StmtPrinterHelper Helper(cfg);
1316 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001317}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001318
1319//===----------------------------------------------------------------------===//
1320// CFG Graphviz Visualization
1321//===----------------------------------------------------------------------===//
1322
Ted Kremenek42a509f2007-08-31 21:30:12 +00001323
1324#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001325static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001326#endif
1327
1328void CFG::viewCFG() const {
1329#ifndef NDEBUG
1330 StmtPrinterHelper H(this);
1331 GraphHelper = &H;
1332 llvm::ViewGraph(this,"CFG");
1333 GraphHelper = NULL;
1334#else
1335 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser3860c112007-09-17 12:29:55 +00001336 << "systems with Graphviz or gv!\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001337#endif
1338}
1339
Ted Kremenek7dba8602007-08-29 21:56:09 +00001340namespace llvm {
1341template<>
1342struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1343 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1344
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001345#ifndef NDEBUG
Ted Kremenek7dba8602007-08-29 21:56:09 +00001346 std::ostringstream Out;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001347 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenek7dba8602007-08-29 21:56:09 +00001348 std::string OutStr = Out.str();
1349
1350 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1351
1352 // Process string output to make it nicer...
1353 for (unsigned i = 0; i != OutStr.length(); ++i)
1354 if (OutStr[i] == '\n') { // Left justify
1355 OutStr[i] = '\\';
1356 OutStr.insert(OutStr.begin()+i+1, 'l');
1357 }
1358
1359 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001360#else
1361 return "";
1362#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001363 }
1364};
1365} // end namespace llvm