blob: b05f8d549540cb7bcec514619fd6892fb4d88f4b [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 Kremenekc5de2222007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek97f75312007-08-21 21:42:03 +000019#include <iostream>
20#include <iomanip>
21#include <algorithm>
22using namespace clang;
23
24namespace {
25
26 // SaveAndRestore - A utility class that uses RIIA to save and restore
27 // the value of a variable.
28 template<typename T>
29 struct SaveAndRestore {
30 SaveAndRestore(T& x) : X(x), old_value(x) {}
31 ~SaveAndRestore() { X = old_value; }
32
33 T& X;
34 T old_value;
35 };
36}
37
38/// CFGBuilder - This class is implements CFG construction from an AST.
39/// The builder is stateful: an instance of the builder should be used to only
40/// construct a single CFG.
41///
42/// Example usage:
43///
44/// CFGBuilder builder;
45/// CFG* cfg = builder.BuildAST(stmt1);
46///
Ted Kremenek95e854d2007-08-21 22:06:14 +000047/// CFG construction is done via a recursive walk of an AST.
48/// We actually parse the AST in reverse order so that the successor
49/// of a basic block is constructed prior to its predecessor. This
50/// allows us to nicely capture implicit fall-throughs without extra
51/// basic blocks.
52///
53class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000054 CFG* cfg;
55 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000056 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000057 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000058 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000059 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000060 unsigned NumBlocks;
61
Ted Kremenekc5de2222007-08-21 23:26:17 +000062 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
63 LabelMapTy LabelMap;
64
Ted Kremenekf5392b72007-08-22 15:40:58 +000065 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000066 BackpatchBlocksTy BackpatchBlocks;
67
Ted Kremenek97f75312007-08-21 21:42:03 +000068public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000069 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000070 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremeneke809ebf2007-08-23 18:43:24 +000071 SwitchTerminatedBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000072 NumBlocks(0) {
73 // Create an empty CFG.
74 cfg = new CFG();
75 }
76
77 ~CFGBuilder() { delete cfg; }
Ted Kremenekd8313202007-08-22 18:22:34 +000078
Ted Kremenekbec06e82007-08-22 21:05:42 +000079 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
Ted Kremenek97f75312007-08-21 21:42:03 +000080 /// represent an arbitrary statement. Examples include a single expression
81 /// or a function body (compound statement). The ownership of the returned
82 /// CFG is transferred to the caller. If CFG construction fails, this method
83 /// returns NULL.
Ted Kremenek4db5b452007-08-23 16:51:22 +000084 CFG* buildCFG(Stmt* Statement) {
Ted Kremenek97f75312007-08-21 21:42:03 +000085 if (!Statement) return NULL;
86
Ted Kremenek4db5b452007-08-23 16:51:22 +000087 // Create an empty block that will serve as the exit block for the CFG.
88 // Since this is the first block added to the CFG, it will be implicitly
89 // registered as the exit block.
Ted Kremenek97f75312007-08-21 21:42:03 +000090 Block = createBlock();
Ted Kremenek4db5b452007-08-23 16:51:22 +000091 assert (Block == &cfg->getExit());
Ted Kremenek97f75312007-08-21 21:42:03 +000092
93 // Visit the statements and create the CFG.
Ted Kremenek95e854d2007-08-21 22:06:14 +000094 if (CFGBlock* B = Visit(Statement)) {
Ted Kremenekd8313202007-08-22 18:22:34 +000095 // Finalize the last constructed block. This usually involves
96 // reversing the order of the statements in the block.
97 FinishBlock(B);
Ted Kremenekbec06e82007-08-22 21:05:42 +000098 cfg->setEntry(B);
Ted Kremenekc5de2222007-08-21 23:26:17 +000099
100 // Backpatch the gotos whose label -> block mappings we didn't know
101 // when we encountered them.
102 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
103 E = BackpatchBlocks.end(); I != E; ++I ) {
104
105 CFGBlock* B = *I;
106 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
107 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
108
Ted Kremenek7372bb22007-08-23 17:29:58 +0000109 // If there is no target for the goto, then we are looking at an
110 // incomplete AST. Handle this by not registering a successor.
111 if (LI == LabelMap.end()) continue;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000112
113 B->addSuccessor(LI->second);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000114 }
Ted Kremenekc5de2222007-08-21 23:26:17 +0000115
Ted Kremenek97f75312007-08-21 21:42:03 +0000116 // NULL out cfg so that repeated calls
117 CFG* t = cfg;
118 cfg = NULL;
119 return t;
120 }
Ted Kremenekc5de2222007-08-21 23:26:17 +0000121 else return NULL;
Ted Kremenek97f75312007-08-21 21:42:03 +0000122 }
Ted Kremenek95e854d2007-08-21 22:06:14 +0000123
Ted Kremenek97f75312007-08-21 21:42:03 +0000124 // createBlock - Used to lazily create blocks that are connected
125 // to the current (global) succcessor.
126 CFGBlock* createBlock( bool add_successor = true ) {
127 CFGBlock* B = cfg->createBlock(NumBlocks++);
128 if (add_successor && Succ) B->addSuccessor(Succ);
129 return B;
130 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000131
132 // FinishBlock - When the last statement has been added to the block,
133 // usually we must reverse the statements because they have been inserted
134 // in reverse order. When processing labels, however, there are cases
135 // in the recursion where we may have already reversed the statements
136 // in a block. This method safely tidies up a block: if the block
137 // has a label at the front, it has already been reversed. Otherwise,
138 // we reverse it.
139 void FinishBlock(CFGBlock* B) {
140 assert (B);
141 CFGBlock::iterator I = B->begin();
142 if (I != B->end()) {
143 Stmt* S = *I;
Ted Kremeneke809ebf2007-08-23 18:43:24 +0000144
145 if (isa<LabelStmt>(S) || isa<SwitchCase>(S))
146 return;
147
148 B->reverseStmts();
Ted Kremenekd8313202007-08-22 18:22:34 +0000149 }
150 }
Ted Kremenek97f75312007-08-21 21:42:03 +0000151
Ted Kremenek95e854d2007-08-21 22:06:14 +0000152 /// Here we handle statements with no branching control flow.
153 CFGBlock* VisitStmt(Stmt* Statement) {
154 // We cannot assume that we are in the middle of a basic block, since
155 // the CFG might only be constructed for this single statement. If
156 // we have no current basic block, just create one lazily.
157 if (!Block) Block = createBlock();
158
159 // Simply add the statement to the current block. We actually
160 // insert statements in reverse order; this order is reversed later
161 // when processing the containing element in the AST.
162 Block->appendStmt(Statement);
Ted Kremenek97f75312007-08-21 21:42:03 +0000163
164 return Block;
165 }
166
Ted Kremenekd8313202007-08-22 18:22:34 +0000167 CFGBlock* VisitNullStmt(NullStmt* Statement) {
168 return Block;
169 }
170
Ted Kremenek95e854d2007-08-21 22:06:14 +0000171 CFGBlock* VisitCompoundStmt(CompoundStmt* C) {
172 // The value returned from this function is the last created CFGBlock
173 // that represents the "entry" point for the translated AST node.
Ted Kremenekd8313202007-08-22 18:22:34 +0000174 CFGBlock* LastBlock;
175
Ted Kremenek95e854d2007-08-21 22:06:14 +0000176 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
Ted Kremenekd8313202007-08-22 18:22:34 +0000177 E = C->body_rend(); I != E; ++I )
Ted Kremenek95e854d2007-08-21 22:06:14 +0000178 // Add the statement to the current block.
Ted Kremenekd8313202007-08-22 18:22:34 +0000179 if (!(LastBlock=Visit(*I)))
180 return NULL;
Ted Kremenek95e854d2007-08-21 22:06:14 +0000181
Ted Kremenekd8313202007-08-22 18:22:34 +0000182 return LastBlock;
Ted Kremenek95e854d2007-08-21 22:06:14 +0000183 }
184
185 CFGBlock* VisitIfStmt(IfStmt* I) {
186
187 // We may see an if statement in the middle of a basic block, or
188 // it may be the first statement we are processing. In either case,
189 // we create a new basic block. First, we create the blocks for
190 // the then...else statements, and then we create the block containing
191 // the if statement. If we were in the middle of a block, we
192 // stop processing that block and reverse its statements. That block
193 // is then the implicit successor for the "then" and "else" clauses.
194
195 // The block we were proccessing is now finished. Make it the
196 // successor block.
197 if (Block) {
198 Succ = Block;
Ted Kremenekd8313202007-08-22 18:22:34 +0000199 FinishBlock(Block);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000200 }
201
202 // Process the false branch. NULL out Block so that the recursive
203 // call to Visit will create a new basic block.
204 // Null out Block so that all successor
205 CFGBlock* ElseBlock = Succ;
206
207 if (Stmt* Else = I->getElse()) {
208 SaveAndRestore<CFGBlock*> sv(Succ);
209
210 // NULL out Block so that the recursive call to Visit will
211 // create a new basic block.
212 Block = NULL;
213 ElseBlock = Visit(Else);
214 if (!ElseBlock) return NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000215 FinishBlock(ElseBlock);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000216 }
217
218 // Process the true branch. NULL out Block so that the recursive
219 // call to Visit will create a new basic block.
220 // Null out Block so that all successor
221 CFGBlock* ThenBlock;
222 {
223 Stmt* Then = I->getThen();
224 assert (Then);
225 SaveAndRestore<CFGBlock*> sv(Succ);
226 Block = NULL;
227 ThenBlock = Visit(Then);
228 if (!ThenBlock) return NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000229 FinishBlock(ThenBlock);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000230 }
231
232 // Now create a new block containing the if statement.
233 Block = createBlock(false);
234
235 // Add the condition as the last statement in the new block.
236 Block->appendStmt(I->getCond());
237
238 // Set the terminator of the new block to the If statement.
239 Block->setTerminator(I);
240
241 // Now add the successors.
242 Block->addSuccessor(ThenBlock);
243 Block->addSuccessor(ElseBlock);
244
245 return Block;
246 }
247
248 CFGBlock* VisitReturnStmt(ReturnStmt* R) {
249 // If we were in the middle of a block we stop processing that block
250 // and reverse its statements.
251 //
252 // NOTE: If a "return" appears in the middle of a block, this means
253 // that the code afterwards is DEAD (unreachable). We still
254 // keep a basic block for that code; a simple "mark-and-sweep"
255 // from the entry block will be able to report such dead
256 // blocks.
Ted Kremenekd8313202007-08-22 18:22:34 +0000257 if (Block) FinishBlock(Block);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000258
259 // Create the new block.
260 Block = createBlock(false);
261
262 // The Exit block is the only successor.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000263 Block->addSuccessor(&cfg->getExit());
Ted Kremenek95e854d2007-08-21 22:06:14 +0000264
Ted Kremenek4db5b452007-08-23 16:51:22 +0000265 // Add the return statement to the block.
Ted Kremenek95e854d2007-08-21 22:06:14 +0000266 Block->appendStmt(R);
267
Ted Kremenek4db5b452007-08-23 16:51:22 +0000268 // Also add the return statement as the terminator.
269 Block->setTerminator(R);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000270
271 return Block;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000272 }
273
274 CFGBlock* VisitLabelStmt(LabelStmt* L) {
275 // Get the block of the labeled statement. Add it to our map.
276 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenekd8313202007-08-22 18:22:34 +0000277 assert (LabelBlock);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000278
279 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
280 LabelMap[ L ] = LabelBlock;
281
282 // Labels partition blocks, so this is the end of the basic block
283 // we were processing (the label is the first statement).
Ted Kremenekd8313202007-08-22 18:22:34 +0000284 LabelBlock->appendStmt(L);
285 FinishBlock(LabelBlock);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000286
287 // We set Block to NULL to allow lazy creation of a new block
288 // (if necessary);
289 Block = NULL;
290
291 // This block is now the implicit successor of other blocks.
292 Succ = LabelBlock;
293
294 return LabelBlock;
295 }
296
297 CFGBlock* VisitGotoStmt(GotoStmt* G) {
298 // Goto is a control-flow statement. Thus we stop processing the
299 // current block and create a new one.
Ted Kremenekd8313202007-08-22 18:22:34 +0000300 if (Block) FinishBlock(Block);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000301 Block = createBlock(false);
302 Block->setTerminator(G);
303
304 // If we already know the mapping to the label block add the
305 // successor now.
306 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
307
308 if (I == LabelMap.end())
309 // We will need to backpatch this block later.
310 BackpatchBlocks.push_back(Block);
311 else
312 Block->addSuccessor(I->second);
313
314 return Block;
315 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000316
317 CFGBlock* VisitForStmt(ForStmt* F) {
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000318 // "for" is a control-flow statement. Thus we stop processing the
Ted Kremenekd8313202007-08-22 18:22:34 +0000319 // current block.
Ted Kremenekd8313202007-08-22 18:22:34 +0000320
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000321 CFGBlock* LoopSuccessor = NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000322
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000323 if (Block) {
324 FinishBlock(Block);
325 LoopSuccessor = Block;
326 }
327 else LoopSuccessor = Succ;
328
329 // Create the condition block.
Ted Kremenekf511d672007-08-22 21:36:54 +0000330 CFGBlock* ConditionBlock = createBlock(false);
Ted Kremenekf511d672007-08-22 21:36:54 +0000331 ConditionBlock->setTerminator(F);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000332 if (Stmt* C = F->getCond()) ConditionBlock->appendStmt(C);
Ted Kremenekf511d672007-08-22 21:36:54 +0000333
334 // The condition block is the implicit successor for the loop body as
335 // well as any code above the loop.
336 Succ = ConditionBlock;
Ted Kremenekd8313202007-08-22 18:22:34 +0000337
338 // Now create the loop body.
339 {
340 assert (F->getBody());
Ted Kremenekf511d672007-08-22 21:36:54 +0000341
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000342 // Save the current values for Block, Succ, and continue and break targets
Ted Kremenekf511d672007-08-22 21:36:54 +0000343 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000344 save_continue(ContinueTargetBlock),
345 save_break(BreakTargetBlock);
346
Ted Kremenekf511d672007-08-22 21:36:54 +0000347 // All continues within this loop should go to the condition block
348 ContinueTargetBlock = ConditionBlock;
Ted Kremenekd8313202007-08-22 18:22:34 +0000349
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000350 // All breaks should go to the code following the loop.
351 BreakTargetBlock = LoopSuccessor;
Ted Kremenekf308d372007-08-22 21:51:58 +0000352
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000353 // Create a new block to contain the (bottom) of the loop body.
Ted Kremenekd8313202007-08-22 18:22:34 +0000354 Block = createBlock();
355
356 // If we have increment code, insert it at the end of the body block.
357 if (Stmt* I = F->getInc()) Block->appendStmt(I);
358
359 // Now populate the body block, and in the process create new blocks
360 // as we walk the body of the loop.
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000361 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekd8313202007-08-22 18:22:34 +0000362 assert (BodyBlock);
363 FinishBlock(BodyBlock);
364
365 // This new body block is a successor to our condition block.
Ted Kremenekf511d672007-08-22 21:36:54 +0000366 ConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd8313202007-08-22 18:22:34 +0000367 }
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000368
Ted Kremenekd8313202007-08-22 18:22:34 +0000369 // Link up the condition block with the code that follows the loop.
370 // (the false branch).
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000371 ConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd8313202007-08-22 18:22:34 +0000372
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000373 // If the loop contains initialization, create a new block for those
374 // statements. This block can also contain statements that precede
375 // the loop.
376 if (Stmt* I = F->getInit()) {
377 Block = createBlock();
378 Block->appendStmt(I);
379 return Block;
380 }
381 else {
382 // There is no loop initialization. We are thus basically a while
383 // loop. NULL out Block to force lazy block construction.
384 Block = NULL;
385 return ConditionBlock;
386 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000387 }
Ted Kremenekbec06e82007-08-22 21:05:42 +0000388
389 CFGBlock* VisitWhileStmt(WhileStmt* W) {
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000390 // "while" is a control-flow statement. Thus we stop processing the
Ted Kremenekbec06e82007-08-22 21:05:42 +0000391 // current block.
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000392
393 CFGBlock* LoopSuccessor = NULL;
394
395 if (Block) {
396 FinishBlock(Block);
397 LoopSuccessor = Block;
398 }
399 else LoopSuccessor = Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +0000400
401 // Create the condition block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000402 CFGBlock* ConditionBlock = createBlock(false);
403 ConditionBlock->setTerminator(W);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000404 if (Stmt* C = W->getCond()) ConditionBlock->appendStmt(C);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000405
Ted Kremenekf511d672007-08-22 21:36:54 +0000406 // The condition block is the implicit successor for the loop body as
407 // well as any code above the loop.
408 Succ = ConditionBlock;
409
Ted Kremenekbec06e82007-08-22 21:05:42 +0000410 // Process the loop body.
411 {
412 assert (W->getBody());
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000413
414 // Save the current values for Block, Succ, and continue and break targets
Ted Kremenekf511d672007-08-22 21:36:54 +0000415 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
Ted Kremenekf308d372007-08-22 21:51:58 +0000416 save_continue(ContinueTargetBlock),
417 save_break(BreakTargetBlock);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000418
Ted Kremenekf511d672007-08-22 21:36:54 +0000419 // All continues within this loop should go to the condition block
420 ContinueTargetBlock = ConditionBlock;
421
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000422 // All breaks should go to the code following the loop.
423 BreakTargetBlock = LoopSuccessor;
Ted Kremenekf308d372007-08-22 21:51:58 +0000424
Ted Kremenekf511d672007-08-22 21:36:54 +0000425 // NULL out Block to force lazy instantiation of blocks for the body.
426 Block = NULL;
427
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000428 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekf511d672007-08-22 21:36:54 +0000429 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekbec06e82007-08-22 21:05:42 +0000430 assert (BodyBlock);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000431 FinishBlock(BodyBlock);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000432
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000433 // Add the loop body entry as a successor to the condition.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000434 ConditionBlock->addSuccessor(BodyBlock);
435 }
436
Ted Kremenekf308d372007-08-22 21:51:58 +0000437 // Link up the condition block with the code that follows the loop.
438 // (the false branch).
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000439 ConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000440
441 // There can be no more statements in the condition block
442 // since we loop back to this block. NULL out Block to force
443 // lazy creation of another block.
444 Block = NULL;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000445
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000446 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000447 return ConditionBlock;
448 }
449
Ted Kremenek95cc35c2007-08-23 17:15:32 +0000450 CFGBlock* VisitDoStmt(DoStmt* D) {
451 // "do...while" is a control-flow statement. Thus we stop processing the
452 // current block.
453
454 CFGBlock* LoopSuccessor = NULL;
455
456 if (Block) {
457 FinishBlock(Block);
458 LoopSuccessor = Block;
459 }
460 else LoopSuccessor = Succ;
461
462 // Create the condition block.
463 CFGBlock* ConditionBlock = createBlock(false);
464 ConditionBlock->setTerminator(D);
465 if (Stmt* C = D->getCond()) ConditionBlock->appendStmt(C);
466
467 // The condition block is the implicit successor for the loop body.
468 Succ = ConditionBlock;
469
470 CFGBlock* BodyBlock = NULL;
471 // Process the loop body.
472 {
473 assert (D->getBody());
474
475 // Save the current values for Block, Succ, and continue and break targets
476 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
477 save_continue(ContinueTargetBlock),
478 save_break(BreakTargetBlock);
479
480 // All continues within this loop should go to the condition block
481 ContinueTargetBlock = ConditionBlock;
482
483 // All breaks should go to the code following the loop.
484 BreakTargetBlock = LoopSuccessor;
485
486 // NULL out Block to force lazy instantiation of blocks for the body.
487 Block = NULL;
488
489 // Create the body. The returned block is the entry to the loop body.
490 BodyBlock = Visit(D->getBody());
491 assert (BodyBlock);
492 FinishBlock(BodyBlock);
493
494 // Add the loop body entry as a successor to the condition.
495 ConditionBlock->addSuccessor(BodyBlock);
496 }
497
498 // Link up the condition block with the code that follows the loop.
499 // (the false branch).
500 ConditionBlock->addSuccessor(LoopSuccessor);
501
502 // There can be no more statements in the condition block
503 // since we loop back to this block. NULL out Block to force
504 // lazy creation of another block.
505 Block = NULL;
506
507 // Return the loop body, which is the dominating block for the loop.
508 return BodyBlock;
509 }
510
Ted Kremenekf511d672007-08-22 21:36:54 +0000511 CFGBlock* VisitContinueStmt(ContinueStmt* C) {
Ted Kremenekf308d372007-08-22 21:51:58 +0000512 // "continue" is a control-flow statement. Thus we stop processing the
Ted Kremenekf511d672007-08-22 21:36:54 +0000513 // current block.
514 if (Block) FinishBlock(Block);
515
516 // Now create a new block that ends with the continue statement.
517 Block = createBlock(false);
518 Block->setTerminator(C);
519
Ted Kremenek7372bb22007-08-23 17:29:58 +0000520 // If there is no target for the continue, then we are looking at an
521 // incomplete AST. Handle this by not registering a successor.
522 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
Ted Kremenekf511d672007-08-22 21:36:54 +0000523
Ted Kremenekf511d672007-08-22 21:36:54 +0000524 return Block;
525 }
526
Ted Kremenekf308d372007-08-22 21:51:58 +0000527 CFGBlock* VisitBreakStmt(BreakStmt* B) {
528 // "break" is a control-flow statement. Thus we stop processing the
529 // current block.
530 if (Block) FinishBlock(Block);
531
532 // Now create a new block that ends with the continue statement.
533 Block = createBlock(false);
534 Block->setTerminator(B);
535
Ted Kremenek7372bb22007-08-23 17:29:58 +0000536 // If there is no target for the break, then we are looking at an
537 // incomplete AST. Handle this by not registering a successor.
538 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
539
Ted Kremenekf308d372007-08-22 21:51:58 +0000540 return Block;
541 }
542
Ted Kremeneke809ebf2007-08-23 18:43:24 +0000543 CFGBlock* VisitSwitchStmt(SwitchStmt* S) {
544 // "switch" is a control-flow statement. Thus we stop processing the
545 // current block.
546 CFGBlock* SwitchSuccessor = NULL;
547
548 if (Block) {
549 FinishBlock(Block);
550 SwitchSuccessor = Block;
551 }
552 else SwitchSuccessor = Succ;
553
554 // Save the current "switch" context.
555 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
556 save_break(BreakTargetBlock);
557
558 // Create a new block that will contain the switch statement.
559 SwitchTerminatedBlock = createBlock(false);
560
561 // Add the terminator and condition in the switch block.
562 assert (S->getCond() && "switch condition must be non-NULL");
563 SwitchTerminatedBlock->appendStmt(S->getCond());
564 SwitchTerminatedBlock->setTerminator(S);
565
566
567 // Now process the switch body. The code after the switch is the implicit
568 // successor.
569 Succ = SwitchSuccessor;
570 BreakTargetBlock = SwitchSuccessor;
571
572 assert (S->getBody() && "switch must contain a non-NULL body");
573 Block = NULL;
574
575 // When visiting the body, the case statements should automatically get
576 // linked up to the switch. We also don't keep a pointer to the body,
577 // since all control-flow from the switch goes to case/default statements.
578 Visit(S->getBody());
579
580 Block = SwitchTerminatedBlock;
581 return SwitchTerminatedBlock;
582 }
583
584 CFGBlock* VisitSwitchCase(SwitchCase* S) {
585 // A SwitchCase is either a "default" or "case" statement. We handle
586 // both in the same way. They are essentially labels, so they are the
587 // first statement in a block.
588 CFGBlock* CaseBlock = Visit(S->getSubStmt());
589 assert (CaseBlock);
590
591 // Cases/Default statements parition block, so this is the top of
592 // the basic block we were processing (the case/default is the first stmt).
593 CaseBlock->appendStmt(S);
594 FinishBlock(CaseBlock);
595
596 // Add this block to the list of successors for the block with the
597 // switch statement.
598 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
599
600 // We set Block to NULL to allow lazy creation of a new block (if necessary)
601 Block = NULL;
602
603 // This block is now the implicit successor of other blocks.
604 Succ = CaseBlock;
605
606 return CaseBlock;
607 }
608
Ted Kremenek97f75312007-08-21 21:42:03 +0000609};
610
Ted Kremenek4db5b452007-08-23 16:51:22 +0000611
612/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
613/// block has no successors or predecessors. If this is the first block
614/// created in the CFG, it is automatically set to be the Entry and Exit
615/// of the CFG.
616CFGBlock* CFG::createBlock(unsigned blockID) {
617 bool first_block = begin() == end();
618
619 // Create the block.
620 Blocks.push_front(CFGBlock(blockID));
621
622 // If this is the first block, set it as the Entry and Exit.
623 if (first_block) Entry = Exit = &front();
624
625 // Return the block.
626 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000627}
628
Ted Kremenek4db5b452007-08-23 16:51:22 +0000629/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
630/// CFG is returned to the caller.
631CFG* CFG::buildCFG(Stmt* Statement) {
632 CFGBuilder Builder;
633 return Builder.buildCFG(Statement);
634}
635
636/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000637void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
638
Ted Kremenek4db5b452007-08-23 16:51:22 +0000639/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000640void CFG::dump() { print(std::cerr); }
641
Ted Kremenek4db5b452007-08-23 16:51:22 +0000642/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek97f75312007-08-21 21:42:03 +0000643void CFG::print(std::ostream& OS) {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000644
645 // Print the Entry block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000646 if (begin() != end()) {
647 CFGBlock& Entry = getEntry();
648 OS << "\n [ B" << Entry.getBlockID() << " (ENTRY) ]\n";
649 Entry.print(OS);
650 }
651
Ted Kremenek4db5b452007-08-23 16:51:22 +0000652 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenek97f75312007-08-21 21:42:03 +0000653 for (iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000654 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000655 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000656
Ted Kremenek4db5b452007-08-23 16:51:22 +0000657 OS << "\n [ B" << I->getBlockID() << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000658 I->print(OS);
659 }
Ted Kremenek4db5b452007-08-23 16:51:22 +0000660
661 // Print the Exit Block.
662 if (begin() != end()) {
663 CFGBlock& Exit = getExit();
664 OS << "\n [ B" << Exit.getBlockID() << " (EXIT) ]\n";
665 Exit.print(OS);
666 }
667
Ted Kremenek97f75312007-08-21 21:42:03 +0000668 OS << "\n";
669}
670
Ted Kremenekd8313202007-08-22 18:22:34 +0000671
672namespace {
673
674 class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
675 void > {
676 std::ostream& OS;
677 public:
678 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
679
680 void VisitIfStmt(IfStmt* I) {
681 OS << "if ";
682 I->getCond()->printPretty(std::cerr);
683 OS << "\n";
684 }
685
686 // Default case.
687 void VisitStmt(Stmt* S) { S->printPretty(OS); }
688
689 void VisitForStmt(ForStmt* F) {
690 OS << "for (" ;
691 if (Stmt* I = F->getInit()) I->printPretty(OS);
692 OS << " ; ";
693 if (Stmt* C = F->getCond()) C->printPretty(OS);
694 OS << " ; ";
695 if (Stmt* I = F->getInc()) I->printPretty(OS);
696 OS << ")\n";
Ted Kremenekbec06e82007-08-22 21:05:42 +0000697 }
698
699 void VisitWhileStmt(WhileStmt* W) {
700 OS << "while " ;
701 if (Stmt* C = W->getCond()) C->printPretty(OS);
702 OS << "\n";
Ted Kremenek95cc35c2007-08-23 17:15:32 +0000703 }
704
705 void VisitDoStmt(DoStmt* D) {
706 OS << "do ... while ";
707 if (Stmt* C = D->getCond()) C->printPretty(OS);
708 OS << "\n";
Ted Kremenekbec06e82007-08-22 21:05:42 +0000709 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000710 };
711}
712
Ted Kremenek4db5b452007-08-23 16:51:22 +0000713/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000714void CFGBlock::dump() { print(std::cerr); }
715
Ted Kremenek4db5b452007-08-23 16:51:22 +0000716/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
717/// Generally this will only be called from CFG::print.
Ted Kremenek97f75312007-08-21 21:42:03 +0000718void CFGBlock::print(std::ostream& OS) {
719
720 // Iterate through the statements in the block and print them.
721 OS << " ------------------------\n";
722 unsigned j = 1;
723 for (iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekc5de2222007-08-21 23:26:17 +0000724 // Print the statement # in the basic block.
725 OS << " " << std::setw(3) << j << ": ";
726
727 // Print the statement/expression.
728 Stmt* S = *I;
729
730 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
731 OS << L->getName() << ": (LABEL)\n";
732 else
733 (*I)->printPretty(OS);
734
735 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +0000736 if (isa<Expr>(*I)) OS << '\n';
737 }
738 OS << " ------------------------\n";
739
740 // Print the predecessors of this block.
741 OS << " Predecessors (" << pred_size() << "):";
742 unsigned i = 0;
743 for (pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i ) {
744 if (i == 8 || (i-8) == 0) {
745 OS << "\n ";
746 }
747 OS << " B" << (*I)->getBlockID();
748 }
749
750 // Print the terminator of this block.
751 OS << "\n Terminator: ";
Ted Kremenekd8313202007-08-22 18:22:34 +0000752 if (ControlFlowStmt)
753 CFGBlockTerminatorPrint(OS).Visit(ControlFlowStmt);
754 else
755 OS << "<NULL>\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000756
757 // Print the successors of this block.
758 OS << " Successors (" << succ_size() << "):";
759 i = 0;
760 for (succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i ) {
761 if (i == 8 || (i-8) % 10 == 0) {
762 OS << "\n ";
763 }
764 OS << " B" << (*I)->getBlockID();
765 }
766 OS << '\n';
Ted Kremenek4db5b452007-08-23 16:51:22 +0000767}