blob: 93230744e6fd1500fdbefa120bb1ef5029004060 [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
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 Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek97f75312007-08-21 21:42:03 +000023#include <iomanip>
24#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000025#include <sstream>
26
Ted Kremenek97f75312007-08-21 21:42:03 +000027using namespace clang;
28
29namespace {
30
Ted Kremenekd6e50602007-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 Kremenek44db7872007-08-30 18:13:31 +000037 T get() { return old_value; }
38
Ted Kremenekd6e50602007-08-23 21:26:19 +000039 T& X;
40 T old_value;
41};
Ted Kremenek97f75312007-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 Kremenek95e854d2007-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 Kremenek97f75312007-08-21 21:42:03 +000059 CFG* cfg;
60 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000061 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000062 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000063 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000064 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000065
Ted Kremenek0edd3a92007-08-28 19:26:49 +000066 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000067 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
68 LabelMapTy LabelMap;
69
Ted Kremenek0edd3a92007-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 Kremenekf5392b72007-08-22 15:40:58 +000072 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000073 BackpatchBlocksTy BackpatchBlocks;
74
Ted Kremenek0edd3a92007-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 Kremenek97f75312007-08-21 21:42:03 +000079public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000080 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000081 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek14594572007-09-05 20:02:05 +000082 SwitchTerminatedBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000083 // Create an empty CFG.
84 cfg = new CFG();
85 }
86
87 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000088
Ted Kremenek73543912007-08-23 21:42:29 +000089 // buildCFG - Used by external clients to construct the CFG.
90 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000091
Ted Kremenek73543912007-08-23 21:42:29 +000092 // Visitors to walk an AST and construct the CFG. Called by
93 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000094
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000109 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000110
Ted Kremenek73543912007-08-23 21:42:29 +0000111private:
112 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000113 CFGBlock* addStmt(Stmt* S);
114 CFGBlock* WalkAST(Stmt* S, bool AlwaysAddStmt);
115 CFGBlock* WalkAST_VisitChildren(Stmt* S);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000116 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000117 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* S);
Ted Kremenekd11620d2007-09-11 21:29:43 +0000118 CFGBlock* WalkAST_VisitCallExpr(CallExpr* C);
Ted Kremenek73543912007-08-23 21:42:29 +0000119 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000120
Ted Kremenek97f75312007-08-21 21:42:03 +0000121};
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000129 assert (cfg);
Ted Kremenek73543912007-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 Kremenekcfee50c2007-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 Kremenek73543912007-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 Kremenekcfee50c2007-08-27 19:46:09 +0000143 if (Block) FinishBlock(B);
Ted Kremenek73543912007-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 Kremenek0edd3a92007-08-28 19:26:49 +0000159 }
Ted Kremenek73543912007-08-23 21:42:29 +0000160
Ted Kremenek0edd3a92007-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 Kremenek680fcb82007-09-26 21:23:31 +0000175
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000176 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000177 }
178
179 // Create an empty entry block that has no predecessors.
180 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000181
Ted Kremenek680fcb82007-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 Kremenek73543912007-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 Kremenek14594572007-09-05 20:02:05 +0000192 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-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 Kremenekcfee50c2007-08-27 19:46:09 +0000198/// we must reverse the statements because they have been inserted
199/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000200void CFGBuilder::FinishBlock(CFGBlock* B) {
201 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000202 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000203}
204
Ted Kremenek65cfa562007-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 Kremenek390b9762007-08-30 18:39:40 +0000212 if (!Block) Block = createBlock();
Ted Kremenek65cfa562007-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 Kremeneke822b622007-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 Kremenek65cfa562007-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 Kremenekc0980cd2007-11-26 18:20:26 +0000223
224 // Create the confluence block that will "merge" the results
225 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000226 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
227 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000228 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000229
230 // Create a block for the LHS expression if there is an LHS expression.
231 // A GCC extension allows LHS to be NULL, causing the condition to
232 // be the value that is returned instead.
233 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000234 Succ = ConfluenceBlock;
235 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000236 CFGBlock* LHSBlock = NULL;
237 if (C->getLHS()) {
238 LHSBlock = Visit(C->getLHS());
239 FinishBlock(LHSBlock);
240 Block = NULL;
241 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000242
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000243 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000244 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000245 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000246 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000247
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000248 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000249 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000250
251 if (LHSBlock)
252 Block->addSuccessor(LHSBlock);
253 else {
254 // If we have no LHS expression, add the ConfluenceBlock as a direct
255 // successor for the block containing the condition. Moreover,
256 // we need to reverse the order of the predecessors in the
257 // ConfluenceBlock because the RHSBlock will have been added to
258 // the succcessors already, and we want the first predecessor to the
259 // the block containing the expression for the case when the ternary
260 // expression evaluates to true.
261 Block->addSuccessor(ConfluenceBlock);
262 assert (ConfluenceBlock->pred_size() == 2);
263 std::reverse(ConfluenceBlock->pred_begin(),
264 ConfluenceBlock->pred_end());
265 }
266
Ted Kremenek65cfa562007-08-27 21:27:44 +0000267 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000268
Ted Kremenek65cfa562007-08-27 21:27:44 +0000269 Block->setTerminator(C);
270 return addStmt(C->getCond());
271 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000272
273 case Stmt::ChooseExprClass: {
274 ChooseExpr* C = cast<ChooseExpr>(S);
275
276 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
277 ConfluenceBlock->appendStmt(C);
278 FinishBlock(ConfluenceBlock);
279
280 Succ = ConfluenceBlock;
281 Block = NULL;
282 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000283 FinishBlock(LHSBlock);
284
Ted Kremenek7f788422007-08-31 17:03:41 +0000285 Succ = ConfluenceBlock;
286 Block = NULL;
287 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000288 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000289
290 Block = createBlock(false);
291 Block->addSuccessor(LHSBlock);
292 Block->addSuccessor(RHSBlock);
293 Block->setTerminator(C);
294 return addStmt(C->getCond());
295 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000296
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000297 case Stmt::DeclStmtClass: {
298 ScopedDecl* D = cast<DeclStmt>(S)->getDecl();
299 Block->appendStmt(S);
300
301 StmtIterator I(D);
302 return WalkAST_VisitDeclSubExprs(I);
303 }
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000304
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000305 case Stmt::AddrLabelExprClass: {
306 AddrLabelExpr* A = cast<AddrLabelExpr>(S);
307 AddressTakenLabels.insert(A->getLabel());
308
309 if (AlwaysAddStmt) Block->appendStmt(S);
310 return Block;
311 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000312
313 case Stmt::CallExprClass:
314 return WalkAST_VisitCallExpr(cast<CallExpr>(S));
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000315
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000316 case Stmt::StmtExprClass:
317 return WalkAST_VisitStmtExpr(cast<StmtExpr>(S));
Ted Kremeneke822b622007-08-28 18:14:37 +0000318
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000319 case Stmt::UnaryOperatorClass: {
320 UnaryOperator* U = cast<UnaryOperator>(S);
321
322 // sizeof(expressions). For such expressions,
323 // the subexpression is not really evaluated, so
324 // we don't care about control-flow within the sizeof.
325 if (U->getOpcode() == UnaryOperator::SizeOf) {
326 Block->appendStmt(S);
327 return Block;
328 }
329
330 break;
331 }
332
Ted Kremenekcfaae762007-08-27 21:54:41 +0000333 case Stmt::BinaryOperatorClass: {
334 BinaryOperator* B = cast<BinaryOperator>(S);
335
336 if (B->isLogicalOp()) { // && or ||
337 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
338 ConfluenceBlock->appendStmt(B);
339 FinishBlock(ConfluenceBlock);
340
341 // create the block evaluating the LHS
342 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000343 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000344
345 // create the block evaluating the RHS
346 Succ = ConfluenceBlock;
347 Block = NULL;
348 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000349
350 // Now link the LHSBlock with RHSBlock.
351 if (B->getOpcode() == BinaryOperator::LOr) {
352 LHSBlock->addSuccessor(ConfluenceBlock);
353 LHSBlock->addSuccessor(RHSBlock);
354 }
355 else {
356 assert (B->getOpcode() == BinaryOperator::LAnd);
357 LHSBlock->addSuccessor(RHSBlock);
358 LHSBlock->addSuccessor(ConfluenceBlock);
359 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000360
361 // Generate the blocks for evaluating the LHS.
362 Block = LHSBlock;
363 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000364 }
365 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
366 Block->appendStmt(B);
367 addStmt(B->getRHS());
368 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000369 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000370
371 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000372 }
373
Ted Kremenek65cfa562007-08-27 21:27:44 +0000374 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000375 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000376 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000377
378 if (AlwaysAddStmt) Block->appendStmt(S);
379 return WalkAST_VisitChildren(S);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000380}
381
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000382/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
383/// DeclStmts. Because the initialization code (and sometimes the
384/// the type declarations) for DeclStmts can contain arbitrary expressions,
385/// we must linearize declarations to handle arbitrary control-flow induced by
386/// those expressions.
387CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000388 if (I == StmtIterator())
389 return Block;
390
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000391 Stmt* S = *I;
392 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000393 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000394
395 Block = addStmt(S);
Ted Kremeneke822b622007-08-28 18:14:37 +0000396 return Block;
397}
398
Ted Kremenek65cfa562007-08-27 21:27:44 +0000399/// WalkAST_VisitChildren - Utility method to call WalkAST on the
400/// children of a Stmt.
Ted Kremenekcfaae762007-08-27 21:54:41 +0000401CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* S) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000402 CFGBlock* B = Block;
403 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
404 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000405 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000406
407 return B;
408}
409
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000410/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
411/// expressions (a GCC extension).
412CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* S) {
413 Block->appendStmt(S);
414 return VisitCompoundStmt(S->getSubStmt());
415}
416
Ted Kremenekd11620d2007-09-11 21:29:43 +0000417/// WalkAST_VisitCallExpr - Utility method to handle function calls that
418/// are nested in expressions. The idea is that each function call should
419/// appear as a distinct statement in the CFGBlock.
420CFGBlock* CFGBuilder::WalkAST_VisitCallExpr(CallExpr* C) {
421 Block->appendStmt(C);
422 return WalkAST_VisitChildren(C);
423}
424
Ted Kremenek73543912007-08-23 21:42:29 +0000425/// VisitStmt - Handle statements with no branching control flow.
426CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
427 // We cannot assume that we are in the middle of a basic block, since
428 // the CFG might only be constructed for this single statement. If
429 // we have no current basic block, just create one lazily.
430 if (!Block) Block = createBlock();
431
432 // Simply add the statement to the current block. We actually
433 // insert statements in reverse order; this order is reversed later
434 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000435 addStmt(Statement);
436
Ted Kremenek73543912007-08-23 21:42:29 +0000437 return Block;
438}
439
440CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
441 return Block;
442}
443
444CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
445 // The value returned from this function is the last created CFGBlock
446 // that represents the "entry" point for the translated AST node.
Chris Lattner265c8172007-09-27 15:15:46 +0000447 CFGBlock* LastBlock = 0;
Ted Kremenek73543912007-08-23 21:42:29 +0000448
449 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
450 E = C->body_rend(); I != E; ++I )
451 // Add the statement to the current block.
452 if (!(LastBlock=Visit(*I)))
453 return NULL;
454
455 return LastBlock;
456}
457
458CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
459 // We may see an if statement in the middle of a basic block, or
460 // it may be the first statement we are processing. In either case,
461 // we create a new basic block. First, we create the blocks for
462 // the then...else statements, and then we create the block containing
463 // the if statement. If we were in the middle of a block, we
464 // stop processing that block and reverse its statements. That block
465 // is then the implicit successor for the "then" and "else" clauses.
466
467 // The block we were proccessing is now finished. Make it the
468 // successor block.
469 if (Block) {
470 Succ = Block;
471 FinishBlock(Block);
472 }
473
474 // Process the false branch. NULL out Block so that the recursive
475 // call to Visit will create a new basic block.
476 // Null out Block so that all successor
477 CFGBlock* ElseBlock = Succ;
478
479 if (Stmt* Else = I->getElse()) {
480 SaveAndRestore<CFGBlock*> sv(Succ);
481
482 // NULL out Block so that the recursive call to Visit will
483 // create a new basic block.
484 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000485 ElseBlock = Visit(Else);
486
487 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
488 ElseBlock = sv.get();
489 else if (Block)
490 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000491 }
492
493 // Process the true branch. NULL out Block so that the recursive
494 // call to Visit will create a new basic block.
495 // Null out Block so that all successor
496 CFGBlock* ThenBlock;
497 {
498 Stmt* Then = I->getThen();
499 assert (Then);
500 SaveAndRestore<CFGBlock*> sv(Succ);
501 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000502 ThenBlock = Visit(Then);
503
504 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
505 ThenBlock = sv.get();
506 else if (Block)
507 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000508 }
509
510 // Now create a new block containing the if statement.
511 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000512
513 // Set the terminator of the new block to the If statement.
514 Block->setTerminator(I);
515
516 // Now add the successors.
517 Block->addSuccessor(ThenBlock);
518 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000519
520 // Add the condition as the last statement in the new block. This
521 // may create new blocks as the condition may contain control-flow. Any
522 // newly created blocks will be pointed to be "Block".
523 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000524}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000525
Ted Kremenek73543912007-08-23 21:42:29 +0000526
527CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
528 // If we were in the middle of a block we stop processing that block
529 // and reverse its statements.
530 //
531 // NOTE: If a "return" appears in the middle of a block, this means
532 // that the code afterwards is DEAD (unreachable). We still
533 // keep a basic block for that code; a simple "mark-and-sweep"
534 // from the entry block will be able to report such dead
535 // blocks.
536 if (Block) FinishBlock(Block);
537
538 // Create the new block.
539 Block = createBlock(false);
540
541 // The Exit block is the only successor.
542 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000543
544 // Add the return statement to the block. This may create new blocks
545 // if R contains control-flow (short-circuit operations).
546 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000547}
548
549CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
550 // Get the block of the labeled statement. Add it to our map.
551 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000552
553 if (!LabelBlock) // This can happen when the body is empty, i.e.
554 LabelBlock=createBlock(); // scopes that only contains NullStmts.
555
Ted Kremenek73543912007-08-23 21:42:29 +0000556 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
557 LabelMap[ L ] = LabelBlock;
558
559 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000560 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000561 // label (and we have already processed the substatement) there is no
562 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000563 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000564 FinishBlock(LabelBlock);
565
566 // We set Block to NULL to allow lazy creation of a new block
567 // (if necessary);
568 Block = NULL;
569
570 // This block is now the implicit successor of other blocks.
571 Succ = LabelBlock;
572
573 return LabelBlock;
574}
575
576CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
577 // Goto is a control-flow statement. Thus we stop processing the
578 // current block and create a new one.
579 if (Block) FinishBlock(Block);
580 Block = createBlock(false);
581 Block->setTerminator(G);
582
583 // If we already know the mapping to the label block add the
584 // successor now.
585 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
586
587 if (I == LabelMap.end())
588 // We will need to backpatch this block later.
589 BackpatchBlocks.push_back(Block);
590 else
591 Block->addSuccessor(I->second);
592
593 return Block;
594}
595
596CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
597 // "for" is a control-flow statement. Thus we stop processing the
598 // current block.
599
600 CFGBlock* LoopSuccessor = NULL;
601
602 if (Block) {
603 FinishBlock(Block);
604 LoopSuccessor = Block;
605 }
606 else LoopSuccessor = Succ;
607
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000608 // Because of short-circuit evaluation, the condition of the loop
609 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
610 // blocks that evaluate the condition.
611 CFGBlock* ExitConditionBlock = createBlock(false);
612 CFGBlock* EntryConditionBlock = ExitConditionBlock;
613
614 // Set the terminator for the "exit" condition block.
615 ExitConditionBlock->setTerminator(F);
616
617 // Now add the actual condition to the condition block. Because the
618 // condition itself may contain control-flow, new blocks may be created.
619 if (Stmt* C = F->getCond()) {
620 Block = ExitConditionBlock;
621 EntryConditionBlock = addStmt(C);
622 if (Block) FinishBlock(EntryConditionBlock);
623 }
Ted Kremenek73543912007-08-23 21:42:29 +0000624
625 // The condition block is the implicit successor for the loop body as
626 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000627 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000628
629 // Now create the loop body.
630 {
631 assert (F->getBody());
632
633 // Save the current values for Block, Succ, and continue and break targets
634 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
635 save_continue(ContinueTargetBlock),
636 save_break(BreakTargetBlock);
637
638 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000639 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000640
641 // All breaks should go to the code following the loop.
642 BreakTargetBlock = LoopSuccessor;
643
Ted Kremenek390b9762007-08-30 18:39:40 +0000644 // Create a new block to contain the (bottom) of the loop body.
645 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000646
647 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000648 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000649
650 // Now populate the body block, and in the process create new blocks
651 // as we walk the body of the loop.
652 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000653
654 if (!BodyBlock)
655 BodyBlock = ExitConditionBlock; // can happen for "for (...;...; ) ;"
656 else if (Block)
657 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000658
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000659 // This new body block is a successor to our "exit" condition block.
660 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000661 }
662
663 // Link up the condition block with the code that follows the loop.
664 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000665 ExitConditionBlock->addSuccessor(LoopSuccessor);
666
Ted Kremenek73543912007-08-23 21:42:29 +0000667 // If the loop contains initialization, create a new block for those
668 // statements. This block can also contain statements that precede
669 // the loop.
670 if (Stmt* I = F->getInit()) {
671 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000672 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000673 }
674 else {
675 // There is no loop initialization. We are thus basically a while
676 // loop. NULL out Block to force lazy block construction.
677 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000678 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000679 }
680}
681
682CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
683 // "while" is a control-flow statement. Thus we stop processing the
684 // current block.
685
686 CFGBlock* LoopSuccessor = NULL;
687
688 if (Block) {
689 FinishBlock(Block);
690 LoopSuccessor = Block;
691 }
692 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000693
694 // Because of short-circuit evaluation, the condition of the loop
695 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
696 // blocks that evaluate the condition.
697 CFGBlock* ExitConditionBlock = createBlock(false);
698 CFGBlock* EntryConditionBlock = ExitConditionBlock;
699
700 // Set the terminator for the "exit" condition block.
701 ExitConditionBlock->setTerminator(W);
702
703 // Now add the actual condition to the condition block. Because the
704 // condition itself may contain control-flow, new blocks may be created.
705 // Thus we update "Succ" after adding the condition.
706 if (Stmt* C = W->getCond()) {
707 Block = ExitConditionBlock;
708 EntryConditionBlock = addStmt(C);
709 if (Block) FinishBlock(EntryConditionBlock);
710 }
Ted Kremenek73543912007-08-23 21:42:29 +0000711
712 // The condition block is the implicit successor for the loop body as
713 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000714 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000715
716 // Process the loop body.
717 {
718 assert (W->getBody());
719
720 // Save the current values for Block, Succ, and continue and break targets
721 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
722 save_continue(ContinueTargetBlock),
723 save_break(BreakTargetBlock);
724
725 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000726 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000727
728 // All breaks should go to the code following the loop.
729 BreakTargetBlock = LoopSuccessor;
730
731 // NULL out Block to force lazy instantiation of blocks for the body.
732 Block = NULL;
733
734 // Create the body. The returned block is the entry to the loop body.
735 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000736
737 if (!BodyBlock)
738 BodyBlock = ExitConditionBlock; // can happen for "while(...) ;"
739 else if (Block)
740 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000741
742 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000743 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000744 }
745
746 // Link up the condition block with the code that follows the loop.
747 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000748 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000749
750 // There can be no more statements in the condition block
751 // since we loop back to this block. NULL out Block to force
752 // lazy creation of another block.
753 Block = NULL;
754
755 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000756 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000757}
758
759CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
760 // "do...while" is a control-flow statement. Thus we stop processing the
761 // current block.
762
763 CFGBlock* LoopSuccessor = NULL;
764
765 if (Block) {
766 FinishBlock(Block);
767 LoopSuccessor = Block;
768 }
769 else LoopSuccessor = Succ;
770
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000771 // Because of short-circuit evaluation, the condition of the loop
772 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
773 // blocks that evaluate the condition.
774 CFGBlock* ExitConditionBlock = createBlock(false);
775 CFGBlock* EntryConditionBlock = ExitConditionBlock;
776
777 // Set the terminator for the "exit" condition block.
778 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000779
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000780 // Now add the actual condition to the condition block. Because the
781 // condition itself may contain control-flow, new blocks may be created.
782 if (Stmt* C = D->getCond()) {
783 Block = ExitConditionBlock;
784 EntryConditionBlock = addStmt(C);
785 if (Block) FinishBlock(EntryConditionBlock);
786 }
Ted Kremenek73543912007-08-23 21:42:29 +0000787
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000788 // The condition block is the implicit successor for the loop body as
789 // well as any code above the loop.
790 Succ = EntryConditionBlock;
791
792
Ted Kremenek73543912007-08-23 21:42:29 +0000793 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000794 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000795 {
796 assert (D->getBody());
797
798 // Save the current values for Block, Succ, and continue and break targets
799 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
800 save_continue(ContinueTargetBlock),
801 save_break(BreakTargetBlock);
802
803 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000804 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000805
806 // All breaks should go to the code following the loop.
807 BreakTargetBlock = LoopSuccessor;
808
809 // NULL out Block to force lazy instantiation of blocks for the body.
810 Block = NULL;
811
812 // Create the body. The returned block is the entry to the loop body.
813 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000814
Ted Kremenek390b9762007-08-30 18:39:40 +0000815 if (!BodyBlock)
816 BodyBlock = ExitConditionBlock; // can happen for "do ; while(...)"
817 else if (Block)
818 FinishBlock(BodyBlock);
819
Ted Kremenek73543912007-08-23 21:42:29 +0000820 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000821 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000822 }
823
824 // Link up the condition block with the code that follows the loop.
825 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000826 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000827
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000828 // There can be no more statements in the body block(s)
829 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000830 // lazy creation of another block.
831 Block = NULL;
832
833 // Return the loop body, which is the dominating block for the loop.
834 return BodyBlock;
835}
836
837CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
838 // "continue" is a control-flow statement. Thus we stop processing the
839 // current block.
840 if (Block) FinishBlock(Block);
841
842 // Now create a new block that ends with the continue statement.
843 Block = createBlock(false);
844 Block->setTerminator(C);
845
846 // If there is no target for the continue, then we are looking at an
847 // incomplete AST. Handle this by not registering a successor.
848 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
849
850 return Block;
851}
852
853CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
854 // "break" is a control-flow statement. Thus we stop processing the
855 // current block.
856 if (Block) FinishBlock(Block);
857
858 // Now create a new block that ends with the continue statement.
859 Block = createBlock(false);
860 Block->setTerminator(B);
861
862 // If there is no target for the break, then we are looking at an
863 // incomplete AST. Handle this by not registering a successor.
864 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
865
866 return Block;
867}
868
869CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
870 // "switch" is a control-flow statement. Thus we stop processing the
871 // current block.
872 CFGBlock* SwitchSuccessor = NULL;
873
874 if (Block) {
875 FinishBlock(Block);
876 SwitchSuccessor = Block;
877 }
878 else SwitchSuccessor = Succ;
879
880 // Save the current "switch" context.
881 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
882 save_break(BreakTargetBlock);
883
884 // Create a new block that will contain the switch statement.
885 SwitchTerminatedBlock = createBlock(false);
886
Ted Kremenek73543912007-08-23 21:42:29 +0000887 // Now process the switch body. The code after the switch is the implicit
888 // successor.
889 Succ = SwitchSuccessor;
890 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000891
892 // When visiting the body, the case statements should automatically get
893 // linked up to the switch. We also don't keep a pointer to the body,
894 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000895 assert (S->getBody() && "switch must contain a non-NULL body");
896 Block = NULL;
897 CFGBlock *BodyBlock = Visit(S->getBody());
898 if (Block) FinishBlock(BodyBlock);
899
900 // Add the terminator and condition in the switch block.
901 SwitchTerminatedBlock->setTerminator(S);
902 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000903 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000904 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000905}
906
907CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
908 // A SwitchCase is either a "default" or "case" statement. We handle
909 // both in the same way. They are essentially labels, so they are the
910 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000911
912 if (S->getSubStmt()) Visit(S->getSubStmt());
913 CFGBlock* CaseBlock = Block;
914 if (!CaseBlock) CaseBlock = createBlock();
915
Ted Kremenekec055e12007-08-29 23:20:49 +0000916 // Cases/Default statements partition block, so this is the top of
917 // the basic block we were processing (the case/default is the label).
918 CaseBlock->setLabel(S);
Ted Kremenek73543912007-08-23 21:42:29 +0000919 FinishBlock(CaseBlock);
920
921 // Add this block to the list of successors for the block with the
922 // switch statement.
923 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
924
925 // We set Block to NULL to allow lazy creation of a new block (if necessary)
926 Block = NULL;
927
928 // This block is now the implicit successor of other blocks.
929 Succ = CaseBlock;
930
931 return CaseBlock;
932}
933
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000934CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
935 // Lazily create the indirect-goto dispatch block if there isn't one
936 // already.
937 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
938
939 if (!IBlock) {
940 IBlock = createBlock(false);
941 cfg->setIndirectGotoBlock(IBlock);
942 }
943
944 // IndirectGoto is a control-flow statement. Thus we stop processing the
945 // current block and create a new one.
946 if (Block) FinishBlock(Block);
947 Block = createBlock(false);
948 Block->setTerminator(I);
949 Block->addSuccessor(IBlock);
950 return addStmt(I->getTarget());
951}
952
Ted Kremenek73543912007-08-23 21:42:29 +0000953
Ted Kremenekd6e50602007-08-23 21:26:19 +0000954} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000955
956/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
957/// block has no successors or predecessors. If this is the first block
958/// created in the CFG, it is automatically set to be the Entry and Exit
959/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +0000960CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000961 bool first_block = begin() == end();
962
963 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +0000964 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +0000965
966 // If this is the first block, set it as the Entry and Exit.
967 if (first_block) Entry = Exit = &front();
968
969 // Return the block.
970 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000971}
972
Ted Kremenek4db5b452007-08-23 16:51:22 +0000973/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
974/// CFG is returned to the caller.
975CFG* CFG::buildCFG(Stmt* Statement) {
976 CFGBuilder Builder;
977 return Builder.buildCFG(Statement);
978}
979
980/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000981void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
982
Ted Kremenek3a819822007-10-01 19:33:33 +0000983//===----------------------------------------------------------------------===//
984// CFG: Queries for BlkExprs.
985//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +0000986
Ted Kremenek3a819822007-10-01 19:33:33 +0000987namespace {
988 typedef llvm::DenseMap<const Expr*,unsigned> BlkExprMapTy;
989}
990
991static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
992 BlkExprMapTy* M = new BlkExprMapTy();
993
994 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
995 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek962212d2007-12-10 23:58:39 +0000996 if (const Expr* E = dyn_cast<Expr>(*BI)) {
997 unsigned x = M->size();
998 (*M)[E] = x;
999 }
Ted Kremenek3a819822007-10-01 19:33:33 +00001000
1001 return M;
1002}
1003
1004bool CFG::isBlkExpr(const Stmt* S) {
Ted Kremenek8ce772b2007-10-01 20:33:52 +00001005 assert (S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001006 if (const Expr* E = dyn_cast<Expr>(S)) return getBlkExprNum(E);
1007 else return true; // Statements are by default "block-level expressions."
1008}
1009
1010CFG::BlkExprNumTy CFG::getBlkExprNum(const Expr* E) {
Ted Kremenek8ce772b2007-10-01 20:33:52 +00001011 assert(E != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001012 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1013
1014 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
1015 BlkExprMapTy::iterator I = M->find(E);
1016
1017 if (I == M->end()) return CFG::BlkExprNumTy();
1018 else return CFG::BlkExprNumTy(I->second);
1019}
1020
1021unsigned CFG::getNumBlkExprs() {
1022 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1023 return M->size();
1024 else {
1025 // We assume callers interested in the number of BlkExprs will want
1026 // the map constructed if it doesn't already exist.
1027 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1028 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1029 }
1030}
1031
1032CFG::~CFG() {
1033 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1034}
1035
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001036//===----------------------------------------------------------------------===//
1037// CFG pretty printing
1038//===----------------------------------------------------------------------===//
1039
Ted Kremenekd8313202007-08-22 18:22:34 +00001040namespace {
1041
Ted Kremenek86afc042007-08-31 22:26:13 +00001042class StmtPrinterHelper : public PrinterHelper {
1043
Ted Kremenek08176a52007-08-31 21:30:12 +00001044 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1045 StmtMapTy StmtMap;
1046 signed CurrentBlock;
1047 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001048
Ted Kremenek73543912007-08-23 21:42:29 +00001049public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001050
Ted Kremenek08176a52007-08-31 21:30:12 +00001051 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1052 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1053 unsigned j = 1;
1054 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1055 BI != BEnd; ++BI, ++j )
1056 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1057 }
1058 }
1059
1060 virtual ~StmtPrinterHelper() {}
1061
1062 void setBlockID(signed i) { CurrentBlock = i; }
1063 void setStmtID(unsigned i) { CurrentStmt = i; }
1064
Ted Kremenek86afc042007-08-31 22:26:13 +00001065 virtual bool handledStmt(Stmt* S, std::ostream& OS) {
1066
1067 StmtMapTy::iterator I = StmtMap.find(S);
Ted Kremenek08176a52007-08-31 21:30:12 +00001068
1069 if (I == StmtMap.end())
1070 return false;
1071
1072 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1073 && I->second.second == CurrentStmt)
1074 return false;
1075
Ted Kremenek86afc042007-08-31 22:26:13 +00001076 OS << "[B" << I->second.first << "." << I->second.second << "]";
1077 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001078 }
1079};
1080
1081class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
Ted Kremenek621e1592007-08-31 21:49:40 +00001082 void >
1083{
Ted Kremenek08176a52007-08-31 21:30:12 +00001084 std::ostream& OS;
1085 StmtPrinterHelper* Helper;
1086public:
1087 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1088 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001089
1090 void VisitIfStmt(IfStmt* I) {
1091 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001092 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001093 OS << "\n";
1094 }
1095
1096 // Default case.
Ted Kremenek621e1592007-08-31 21:49:40 +00001097 void VisitStmt(Stmt* S) { S->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001098
1099 void VisitForStmt(ForStmt* F) {
1100 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001101 if (F->getInit()) OS << "...";
1102 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001103 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001104 OS << "; ";
1105 if (F->getInc()) OS << "...";
Ted Kremenek73543912007-08-23 21:42:29 +00001106 OS << ")\n";
1107 }
1108
1109 void VisitWhileStmt(WhileStmt* W) {
1110 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001111 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001112 OS << "\n";
1113 }
1114
1115 void VisitDoStmt(DoStmt* D) {
1116 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001117 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001118 OS << '\n';
1119 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001120
Ted Kremenek65cfa562007-08-27 21:27:44 +00001121 void VisitSwitchStmt(SwitchStmt* S) {
1122 OS << "switch ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001123 S->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001124 OS << '\n';
1125 }
1126
Ted Kremenek621e1592007-08-31 21:49:40 +00001127 void VisitConditionalOperator(ConditionalOperator* C) {
1128 C->getCond()->printPretty(OS,Helper);
1129 OS << " ? ... : ...\n";
1130 }
1131
Ted Kremenek2025cc92007-08-31 22:29:13 +00001132 void VisitChooseExpr(ChooseExpr* C) {
1133 OS << "__builtin_choose_expr( ";
1134 C->getCond()->printPretty(OS,Helper);
1135 OS << " )\n";
1136 }
1137
Ted Kremenek86afc042007-08-31 22:26:13 +00001138 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1139 OS << "goto *";
1140 I->getTarget()->printPretty(OS,Helper);
1141 OS << '\n';
1142 }
1143
Ted Kremenek621e1592007-08-31 21:49:40 +00001144 void VisitBinaryOperator(BinaryOperator* B) {
1145 if (!B->isLogicalOp()) {
1146 VisitExpr(B);
1147 return;
1148 }
1149
1150 B->getLHS()->printPretty(OS,Helper);
1151
1152 switch (B->getOpcode()) {
1153 case BinaryOperator::LOr:
1154 OS << " || ...\n";
1155 return;
1156 case BinaryOperator::LAnd:
1157 OS << " && ...\n";
1158 return;
1159 default:
1160 assert(false && "Invalid logical operator.");
1161 }
1162 }
1163
Ted Kremenekcfaae762007-08-27 21:54:41 +00001164 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001165 E->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001166 OS << '\n';
Ted Kremenekcfaae762007-08-27 21:54:41 +00001167 }
Ted Kremenek73543912007-08-23 21:42:29 +00001168};
Ted Kremenek08176a52007-08-31 21:30:12 +00001169
1170
Ted Kremenek86afc042007-08-31 22:26:13 +00001171void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* S) {
1172 if (Helper) {
1173 // special printing for statement-expressions.
1174 if (StmtExpr* SE = dyn_cast<StmtExpr>(S)) {
1175 CompoundStmt* Sub = SE->getSubStmt();
1176
1177 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001178 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001179 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001180 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001181 return;
1182 }
1183 }
1184
1185 // special printing for comma expressions.
1186 if (BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
1187 if (B->getOpcode() == BinaryOperator::Comma) {
1188 OS << "... , ";
1189 Helper->handledStmt(B->getRHS(),OS);
1190 OS << '\n';
1191 return;
1192 }
1193 }
1194 }
1195
1196 S->printPretty(OS, Helper);
1197
1198 // Expressions need a newline.
1199 if (isa<Expr>(S)) OS << '\n';
1200}
1201
Ted Kremenek08176a52007-08-31 21:30:12 +00001202void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1203 StmtPrinterHelper* Helper, bool print_edges) {
1204
1205 if (Helper) Helper->setBlockID(B.getBlockID());
1206
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001207 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001208 OS << "\n [ B" << B.getBlockID();
1209
1210 if (&B == &cfg->getEntry())
1211 OS << " (ENTRY) ]\n";
1212 else if (&B == &cfg->getExit())
1213 OS << " (EXIT) ]\n";
1214 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001215 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001216 else
1217 OS << " ]\n";
1218
Ted Kremenekec055e12007-08-29 23:20:49 +00001219 // Print the label of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001220 if (Stmt* S = const_cast<Stmt*>(B.getLabel())) {
1221
1222 if (print_edges)
1223 OS << " ";
1224
Ted Kremenekec055e12007-08-29 23:20:49 +00001225 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
1226 OS << L->getName();
1227 else if (CaseStmt* C = dyn_cast<CaseStmt>(S)) {
1228 OS << "case ";
1229 C->getLHS()->printPretty(OS);
1230 if (C->getRHS()) {
1231 OS << " ... ";
1232 C->getRHS()->printPretty(OS);
1233 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001234 }
Chris Lattner1501e122007-09-16 19:11:53 +00001235 else if (isa<DefaultStmt>(S))
Ted Kremenekec055e12007-08-29 23:20:49 +00001236 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001237 else
1238 assert(false && "Invalid label statement in CFGBlock.");
1239
Ted Kremenekec055e12007-08-29 23:20:49 +00001240 OS << ":\n";
1241 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001242
Ted Kremenek97f75312007-08-21 21:42:03 +00001243 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001244 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001245
1246 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1247 I != E ; ++I, ++j ) {
1248
Ted Kremenekec055e12007-08-29 23:20:49 +00001249 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001250 if (print_edges)
1251 OS << " ";
1252
1253 OS << std::setw(3) << j << ": ";
1254
1255 if (Helper)
1256 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001257
1258 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001259 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001260
Ted Kremenekec055e12007-08-29 23:20:49 +00001261 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001262 if (B.getTerminator()) {
1263 if (print_edges)
1264 OS << " ";
1265
Ted Kremenekec055e12007-08-29 23:20:49 +00001266 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001267
1268 if (Helper) Helper->setBlockID(-1);
1269
1270 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1271 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek97f75312007-08-21 21:42:03 +00001272 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001273
Ted Kremenekec055e12007-08-29 23:20:49 +00001274 if (print_edges) {
1275 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001276 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001277 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001278
Ted Kremenek08176a52007-08-31 21:30:12 +00001279 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1280 I != E; ++I, ++i) {
1281
1282 if (i == 8 || (i-8) == 0)
1283 OS << "\n ";
1284
Ted Kremenekec055e12007-08-29 23:20:49 +00001285 OS << " B" << (*I)->getBlockID();
1286 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001287
1288 OS << '\n';
1289
1290 // Print the successors of this block.
1291 OS << " Successors (" << B.succ_size() << "):";
1292 i = 0;
1293
1294 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1295 I != E; ++I, ++i) {
1296
1297 if (i == 8 || (i-8) % 10 == 0)
1298 OS << "\n ";
1299
1300 OS << " B" << (*I)->getBlockID();
1301 }
1302
Ted Kremenekec055e12007-08-29 23:20:49 +00001303 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001304 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001305}
1306
1307} // end anonymous namespace
1308
1309/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001310void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001311
1312/// print - A simple pretty printer of a CFG that outputs to an ostream.
1313void CFG::print(std::ostream& OS) const {
1314
1315 StmtPrinterHelper Helper(this);
1316
1317 // Print the entry block.
1318 print_block(OS, this, getEntry(), &Helper, true);
1319
1320 // Iterate through the CFGBlocks and print them one by one.
1321 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1322 // Skip the entry block, because we already printed it.
1323 if (&(*I) == &getEntry() || &(*I) == &getExit())
1324 continue;
1325
1326 print_block(OS, this, *I, &Helper, true);
1327 }
1328
1329 // Print the exit block.
1330 print_block(OS, this, getExit(), &Helper, true);
1331}
1332
1333/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001334void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001335
1336/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1337/// Generally this will only be called from CFG::print.
1338void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1339 StmtPrinterHelper Helper(cfg);
1340 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001341}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001342
1343//===----------------------------------------------------------------------===//
1344// CFG Graphviz Visualization
1345//===----------------------------------------------------------------------===//
1346
Ted Kremenek08176a52007-08-31 21:30:12 +00001347
1348#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001349static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001350#endif
1351
1352void CFG::viewCFG() const {
1353#ifndef NDEBUG
1354 StmtPrinterHelper H(this);
1355 GraphHelper = &H;
1356 llvm::ViewGraph(this,"CFG");
1357 GraphHelper = NULL;
1358#else
1359 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser284bff92007-09-17 12:29:55 +00001360 << "systems with Graphviz or gv!\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001361#endif
1362}
1363
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001364namespace llvm {
1365template<>
1366struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1367 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1368
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001369#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001370 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001371 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001372 std::string OutStr = Out.str();
1373
1374 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1375
1376 // Process string output to make it nicer...
1377 for (unsigned i = 0; i != OutStr.length(); ++i)
1378 if (OutStr[i] == '\n') { // Left justify
1379 OutStr[i] = '\\';
1380 OutStr.insert(OutStr.begin()+i+1, 'l');
1381 }
1382
1383 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001384#else
1385 return "";
1386#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001387 }
1388};
1389} // end namespace llvm