blob: 495cfb8d1ec41d1cff6a8a22613d755fd197c233 [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 Kremenek97f75312007-08-21 21:42:03 +000059 unsigned NumBlocks;
60
Ted Kremenekc5de2222007-08-21 23:26:17 +000061 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
62 LabelMapTy LabelMap;
63
Ted Kremenekf5392b72007-08-22 15:40:58 +000064 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000065 BackpatchBlocksTy BackpatchBlocks;
66
Ted Kremenek97f75312007-08-21 21:42:03 +000067public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000068 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000069 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000070 NumBlocks(0) {
71 // Create an empty CFG.
72 cfg = new CFG();
73 }
74
75 ~CFGBuilder() { delete cfg; }
Ted Kremenekd8313202007-08-22 18:22:34 +000076
Ted Kremenekbec06e82007-08-22 21:05:42 +000077 /// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
Ted Kremenek97f75312007-08-21 21:42:03 +000078 /// represent an arbitrary statement. Examples include a single expression
79 /// or a function body (compound statement). The ownership of the returned
80 /// CFG is transferred to the caller. If CFG construction fails, this method
81 /// returns NULL.
Ted Kremenek4db5b452007-08-23 16:51:22 +000082 CFG* buildCFG(Stmt* Statement) {
Ted Kremenek97f75312007-08-21 21:42:03 +000083 if (!Statement) return NULL;
84
Ted Kremenek4db5b452007-08-23 16:51:22 +000085 // Create an empty block that will serve as the exit block for the CFG.
86 // Since this is the first block added to the CFG, it will be implicitly
87 // registered as the exit block.
Ted Kremenek97f75312007-08-21 21:42:03 +000088 Block = createBlock();
Ted Kremenek4db5b452007-08-23 16:51:22 +000089 assert (Block == &cfg->getExit());
Ted Kremenek97f75312007-08-21 21:42:03 +000090
91 // Visit the statements and create the CFG.
Ted Kremenek95e854d2007-08-21 22:06:14 +000092 if (CFGBlock* B = Visit(Statement)) {
Ted Kremenekd8313202007-08-22 18:22:34 +000093 // Finalize the last constructed block. This usually involves
94 // reversing the order of the statements in the block.
95 FinishBlock(B);
Ted Kremenekbec06e82007-08-22 21:05:42 +000096 cfg->setEntry(B);
Ted Kremenekc5de2222007-08-21 23:26:17 +000097
98 // Backpatch the gotos whose label -> block mappings we didn't know
99 // when we encountered them.
100 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
101 E = BackpatchBlocks.end(); I != E; ++I ) {
102
103 CFGBlock* B = *I;
104 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
105 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
106
Ted Kremenek7372bb22007-08-23 17:29:58 +0000107 // If there is no target for the goto, then we are looking at an
108 // incomplete AST. Handle this by not registering a successor.
109 if (LI == LabelMap.end()) continue;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000110
111 B->addSuccessor(LI->second);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000112 }
Ted Kremenekc5de2222007-08-21 23:26:17 +0000113
Ted Kremenek97f75312007-08-21 21:42:03 +0000114 // NULL out cfg so that repeated calls
115 CFG* t = cfg;
116 cfg = NULL;
117 return t;
118 }
Ted Kremenekc5de2222007-08-21 23:26:17 +0000119 else return NULL;
Ted Kremenek97f75312007-08-21 21:42:03 +0000120 }
Ted Kremenek95e854d2007-08-21 22:06:14 +0000121
Ted Kremenek97f75312007-08-21 21:42:03 +0000122 // createBlock - Used to lazily create blocks that are connected
123 // to the current (global) succcessor.
124 CFGBlock* createBlock( bool add_successor = true ) {
125 CFGBlock* B = cfg->createBlock(NumBlocks++);
126 if (add_successor && Succ) B->addSuccessor(Succ);
127 return B;
128 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000129
130 // FinishBlock - When the last statement has been added to the block,
131 // usually we must reverse the statements because they have been inserted
132 // in reverse order. When processing labels, however, there are cases
133 // in the recursion where we may have already reversed the statements
134 // in a block. This method safely tidies up a block: if the block
135 // has a label at the front, it has already been reversed. Otherwise,
136 // we reverse it.
137 void FinishBlock(CFGBlock* B) {
138 assert (B);
139 CFGBlock::iterator I = B->begin();
140 if (I != B->end()) {
141 Stmt* S = *I;
142 if (S->getStmtClass() != Stmt::LabelStmtClass)
143 B->reverseStmts();
144 }
145 }
Ted Kremenek97f75312007-08-21 21:42:03 +0000146
Ted Kremenek95e854d2007-08-21 22:06:14 +0000147 /// Here we handle statements with no branching control flow.
148 CFGBlock* VisitStmt(Stmt* Statement) {
149 // We cannot assume that we are in the middle of a basic block, since
150 // the CFG might only be constructed for this single statement. If
151 // we have no current basic block, just create one lazily.
152 if (!Block) Block = createBlock();
153
154 // Simply add the statement to the current block. We actually
155 // insert statements in reverse order; this order is reversed later
156 // when processing the containing element in the AST.
157 Block->appendStmt(Statement);
Ted Kremenek97f75312007-08-21 21:42:03 +0000158
159 return Block;
160 }
161
Ted Kremenekd8313202007-08-22 18:22:34 +0000162 CFGBlock* VisitNullStmt(NullStmt* Statement) {
163 return Block;
164 }
165
Ted Kremenek95e854d2007-08-21 22:06:14 +0000166 CFGBlock* VisitCompoundStmt(CompoundStmt* C) {
167 // The value returned from this function is the last created CFGBlock
168 // that represents the "entry" point for the translated AST node.
Ted Kremenekd8313202007-08-22 18:22:34 +0000169 CFGBlock* LastBlock;
170
Ted Kremenek95e854d2007-08-21 22:06:14 +0000171 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
Ted Kremenekd8313202007-08-22 18:22:34 +0000172 E = C->body_rend(); I != E; ++I )
Ted Kremenek95e854d2007-08-21 22:06:14 +0000173 // Add the statement to the current block.
Ted Kremenekd8313202007-08-22 18:22:34 +0000174 if (!(LastBlock=Visit(*I)))
175 return NULL;
Ted Kremenek95e854d2007-08-21 22:06:14 +0000176
Ted Kremenekd8313202007-08-22 18:22:34 +0000177 return LastBlock;
Ted Kremenek95e854d2007-08-21 22:06:14 +0000178 }
179
180 CFGBlock* VisitIfStmt(IfStmt* I) {
181
182 // We may see an if statement in the middle of a basic block, or
183 // it may be the first statement we are processing. In either case,
184 // we create a new basic block. First, we create the blocks for
185 // the then...else statements, and then we create the block containing
186 // the if statement. If we were in the middle of a block, we
187 // stop processing that block and reverse its statements. That block
188 // is then the implicit successor for the "then" and "else" clauses.
189
190 // The block we were proccessing is now finished. Make it the
191 // successor block.
192 if (Block) {
193 Succ = Block;
Ted Kremenekd8313202007-08-22 18:22:34 +0000194 FinishBlock(Block);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000195 }
196
197 // Process the false branch. NULL out Block so that the recursive
198 // call to Visit will create a new basic block.
199 // Null out Block so that all successor
200 CFGBlock* ElseBlock = Succ;
201
202 if (Stmt* Else = I->getElse()) {
203 SaveAndRestore<CFGBlock*> sv(Succ);
204
205 // NULL out Block so that the recursive call to Visit will
206 // create a new basic block.
207 Block = NULL;
208 ElseBlock = Visit(Else);
209 if (!ElseBlock) return NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000210 FinishBlock(ElseBlock);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000211 }
212
213 // Process the true branch. NULL out Block so that the recursive
214 // call to Visit will create a new basic block.
215 // Null out Block so that all successor
216 CFGBlock* ThenBlock;
217 {
218 Stmt* Then = I->getThen();
219 assert (Then);
220 SaveAndRestore<CFGBlock*> sv(Succ);
221 Block = NULL;
222 ThenBlock = Visit(Then);
223 if (!ThenBlock) return NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000224 FinishBlock(ThenBlock);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000225 }
226
227 // Now create a new block containing the if statement.
228 Block = createBlock(false);
229
230 // Add the condition as the last statement in the new block.
231 Block->appendStmt(I->getCond());
232
233 // Set the terminator of the new block to the If statement.
234 Block->setTerminator(I);
235
236 // Now add the successors.
237 Block->addSuccessor(ThenBlock);
238 Block->addSuccessor(ElseBlock);
239
240 return Block;
241 }
242
243 CFGBlock* VisitReturnStmt(ReturnStmt* R) {
244 // If we were in the middle of a block we stop processing that block
245 // and reverse its statements.
246 //
247 // NOTE: If a "return" appears in the middle of a block, this means
248 // that the code afterwards is DEAD (unreachable). We still
249 // keep a basic block for that code; a simple "mark-and-sweep"
250 // from the entry block will be able to report such dead
251 // blocks.
Ted Kremenekd8313202007-08-22 18:22:34 +0000252 if (Block) FinishBlock(Block);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000253
254 // Create the new block.
255 Block = createBlock(false);
256
257 // The Exit block is the only successor.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000258 Block->addSuccessor(&cfg->getExit());
Ted Kremenek95e854d2007-08-21 22:06:14 +0000259
Ted Kremenek4db5b452007-08-23 16:51:22 +0000260 // Add the return statement to the block.
Ted Kremenek95e854d2007-08-21 22:06:14 +0000261 Block->appendStmt(R);
262
Ted Kremenek4db5b452007-08-23 16:51:22 +0000263 // Also add the return statement as the terminator.
264 Block->setTerminator(R);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000265
266 return Block;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000267 }
268
269 CFGBlock* VisitLabelStmt(LabelStmt* L) {
270 // Get the block of the labeled statement. Add it to our map.
271 CFGBlock* LabelBlock = Visit(L->getSubStmt());
Ted Kremenekd8313202007-08-22 18:22:34 +0000272 assert (LabelBlock);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000273
274 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
275 LabelMap[ L ] = LabelBlock;
276
277 // Labels partition blocks, so this is the end of the basic block
278 // we were processing (the label is the first statement).
Ted Kremenekd8313202007-08-22 18:22:34 +0000279 LabelBlock->appendStmt(L);
280 FinishBlock(LabelBlock);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000281
282 // We set Block to NULL to allow lazy creation of a new block
283 // (if necessary);
284 Block = NULL;
285
286 // This block is now the implicit successor of other blocks.
287 Succ = LabelBlock;
288
289 return LabelBlock;
290 }
291
292 CFGBlock* VisitGotoStmt(GotoStmt* G) {
293 // Goto is a control-flow statement. Thus we stop processing the
294 // current block and create a new one.
Ted Kremenekd8313202007-08-22 18:22:34 +0000295 if (Block) FinishBlock(Block);
Ted Kremenekc5de2222007-08-21 23:26:17 +0000296 Block = createBlock(false);
297 Block->setTerminator(G);
298
299 // If we already know the mapping to the label block add the
300 // successor now.
301 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
302
303 if (I == LabelMap.end())
304 // We will need to backpatch this block later.
305 BackpatchBlocks.push_back(Block);
306 else
307 Block->addSuccessor(I->second);
308
309 return Block;
310 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000311
312 CFGBlock* VisitForStmt(ForStmt* F) {
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000313 // "for" is a control-flow statement. Thus we stop processing the
Ted Kremenekd8313202007-08-22 18:22:34 +0000314 // current block.
Ted Kremenekd8313202007-08-22 18:22:34 +0000315
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000316 CFGBlock* LoopSuccessor = NULL;
Ted Kremenekd8313202007-08-22 18:22:34 +0000317
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000318 if (Block) {
319 FinishBlock(Block);
320 LoopSuccessor = Block;
321 }
322 else LoopSuccessor = Succ;
323
324 // Create the condition block.
Ted Kremenekf511d672007-08-22 21:36:54 +0000325 CFGBlock* ConditionBlock = createBlock(false);
Ted Kremenekf511d672007-08-22 21:36:54 +0000326 ConditionBlock->setTerminator(F);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000327 if (Stmt* C = F->getCond()) ConditionBlock->appendStmt(C);
Ted Kremenekf511d672007-08-22 21:36:54 +0000328
329 // The condition block is the implicit successor for the loop body as
330 // well as any code above the loop.
331 Succ = ConditionBlock;
Ted Kremenekd8313202007-08-22 18:22:34 +0000332
333 // Now create the loop body.
334 {
335 assert (F->getBody());
Ted Kremenekf511d672007-08-22 21:36:54 +0000336
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000337 // Save the current values for Block, Succ, and continue and break targets
Ted Kremenekf511d672007-08-22 21:36:54 +0000338 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000339 save_continue(ContinueTargetBlock),
340 save_break(BreakTargetBlock);
341
Ted Kremenekf511d672007-08-22 21:36:54 +0000342 // All continues within this loop should go to the condition block
343 ContinueTargetBlock = ConditionBlock;
Ted Kremenekd8313202007-08-22 18:22:34 +0000344
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000345 // All breaks should go to the code following the loop.
346 BreakTargetBlock = LoopSuccessor;
Ted Kremenekf308d372007-08-22 21:51:58 +0000347
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000348 // Create a new block to contain the (bottom) of the loop body.
Ted Kremenekd8313202007-08-22 18:22:34 +0000349 Block = createBlock();
350
351 // If we have increment code, insert it at the end of the body block.
352 if (Stmt* I = F->getInc()) Block->appendStmt(I);
353
354 // Now populate the body block, and in the process create new blocks
355 // as we walk the body of the loop.
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000356 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekd8313202007-08-22 18:22:34 +0000357 assert (BodyBlock);
358 FinishBlock(BodyBlock);
359
360 // This new body block is a successor to our condition block.
Ted Kremenekf511d672007-08-22 21:36:54 +0000361 ConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd8313202007-08-22 18:22:34 +0000362 }
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000363
Ted Kremenekd8313202007-08-22 18:22:34 +0000364 // Link up the condition block with the code that follows the loop.
365 // (the false branch).
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000366 ConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd8313202007-08-22 18:22:34 +0000367
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000368 // If the loop contains initialization, create a new block for those
369 // statements. This block can also contain statements that precede
370 // the loop.
371 if (Stmt* I = F->getInit()) {
372 Block = createBlock();
373 Block->appendStmt(I);
374 return Block;
375 }
376 else {
377 // There is no loop initialization. We are thus basically a while
378 // loop. NULL out Block to force lazy block construction.
379 Block = NULL;
380 return ConditionBlock;
381 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000382 }
Ted Kremenekbec06e82007-08-22 21:05:42 +0000383
384 CFGBlock* VisitWhileStmt(WhileStmt* W) {
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000385 // "while" is a control-flow statement. Thus we stop processing the
Ted Kremenekbec06e82007-08-22 21:05:42 +0000386 // current block.
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000387
388 CFGBlock* LoopSuccessor = NULL;
389
390 if (Block) {
391 FinishBlock(Block);
392 LoopSuccessor = Block;
393 }
394 else LoopSuccessor = Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +0000395
396 // Create the condition block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000397 CFGBlock* ConditionBlock = createBlock(false);
398 ConditionBlock->setTerminator(W);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000399 if (Stmt* C = W->getCond()) ConditionBlock->appendStmt(C);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000400
Ted Kremenekf511d672007-08-22 21:36:54 +0000401 // The condition block is the implicit successor for the loop body as
402 // well as any code above the loop.
403 Succ = ConditionBlock;
404
Ted Kremenekbec06e82007-08-22 21:05:42 +0000405 // Process the loop body.
406 {
407 assert (W->getBody());
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000408
409 // Save the current values for Block, Succ, and continue and break targets
Ted Kremenekf511d672007-08-22 21:36:54 +0000410 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
Ted Kremenekf308d372007-08-22 21:51:58 +0000411 save_continue(ContinueTargetBlock),
412 save_break(BreakTargetBlock);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000413
Ted Kremenekf511d672007-08-22 21:36:54 +0000414 // All continues within this loop should go to the condition block
415 ContinueTargetBlock = ConditionBlock;
416
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000417 // All breaks should go to the code following the loop.
418 BreakTargetBlock = LoopSuccessor;
Ted Kremenekf308d372007-08-22 21:51:58 +0000419
Ted Kremenekf511d672007-08-22 21:36:54 +0000420 // NULL out Block to force lazy instantiation of blocks for the body.
421 Block = NULL;
422
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000423 // Create the body. The returned block is the entry to the loop body.
Ted Kremenekf511d672007-08-22 21:36:54 +0000424 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekbec06e82007-08-22 21:05:42 +0000425 assert (BodyBlock);
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000426 FinishBlock(BodyBlock);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000427
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000428 // Add the loop body entry as a successor to the condition.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000429 ConditionBlock->addSuccessor(BodyBlock);
430 }
431
Ted Kremenekf308d372007-08-22 21:51:58 +0000432 // Link up the condition block with the code that follows the loop.
433 // (the false branch).
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000434 ConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekbec06e82007-08-22 21:05:42 +0000435
436 // There can be no more statements in the condition block
437 // since we loop back to this block. NULL out Block to force
438 // lazy creation of another block.
439 Block = NULL;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000440
Ted Kremenek0baf7c02007-08-22 22:35:28 +0000441 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000442 return ConditionBlock;
443 }
444
Ted Kremenek95cc35c2007-08-23 17:15:32 +0000445 CFGBlock* VisitDoStmt(DoStmt* D) {
446 // "do...while" is a control-flow statement. Thus we stop processing the
447 // current block.
448
449 CFGBlock* LoopSuccessor = NULL;
450
451 if (Block) {
452 FinishBlock(Block);
453 LoopSuccessor = Block;
454 }
455 else LoopSuccessor = Succ;
456
457 // Create the condition block.
458 CFGBlock* ConditionBlock = createBlock(false);
459 ConditionBlock->setTerminator(D);
460 if (Stmt* C = D->getCond()) ConditionBlock->appendStmt(C);
461
462 // The condition block is the implicit successor for the loop body.
463 Succ = ConditionBlock;
464
465 CFGBlock* BodyBlock = NULL;
466 // Process the loop body.
467 {
468 assert (D->getBody());
469
470 // Save the current values for Block, Succ, and continue and break targets
471 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
472 save_continue(ContinueTargetBlock),
473 save_break(BreakTargetBlock);
474
475 // All continues within this loop should go to the condition block
476 ContinueTargetBlock = ConditionBlock;
477
478 // All breaks should go to the code following the loop.
479 BreakTargetBlock = LoopSuccessor;
480
481 // NULL out Block to force lazy instantiation of blocks for the body.
482 Block = NULL;
483
484 // Create the body. The returned block is the entry to the loop body.
485 BodyBlock = Visit(D->getBody());
486 assert (BodyBlock);
487 FinishBlock(BodyBlock);
488
489 // Add the loop body entry as a successor to the condition.
490 ConditionBlock->addSuccessor(BodyBlock);
491 }
492
493 // Link up the condition block with the code that follows the loop.
494 // (the false branch).
495 ConditionBlock->addSuccessor(LoopSuccessor);
496
497 // There can be no more statements in the condition block
498 // since we loop back to this block. NULL out Block to force
499 // lazy creation of another block.
500 Block = NULL;
501
502 // Return the loop body, which is the dominating block for the loop.
503 return BodyBlock;
504 }
505
Ted Kremenekf511d672007-08-22 21:36:54 +0000506 CFGBlock* VisitContinueStmt(ContinueStmt* C) {
Ted Kremenekf308d372007-08-22 21:51:58 +0000507 // "continue" is a control-flow statement. Thus we stop processing the
Ted Kremenekf511d672007-08-22 21:36:54 +0000508 // current block.
509 if (Block) FinishBlock(Block);
510
511 // Now create a new block that ends with the continue statement.
512 Block = createBlock(false);
513 Block->setTerminator(C);
514
Ted Kremenek7372bb22007-08-23 17:29:58 +0000515 // If there is no target for the continue, then we are looking at an
516 // incomplete AST. Handle this by not registering a successor.
517 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
Ted Kremenekf511d672007-08-22 21:36:54 +0000518
Ted Kremenekf511d672007-08-22 21:36:54 +0000519 return Block;
520 }
521
Ted Kremenekf308d372007-08-22 21:51:58 +0000522 CFGBlock* VisitBreakStmt(BreakStmt* B) {
523 // "break" is a control-flow statement. Thus we stop processing the
524 // current block.
525 if (Block) FinishBlock(Block);
526
527 // Now create a new block that ends with the continue statement.
528 Block = createBlock(false);
529 Block->setTerminator(B);
530
Ted Kremenek7372bb22007-08-23 17:29:58 +0000531 // If there is no target for the break, then we are looking at an
532 // incomplete AST. Handle this by not registering a successor.
533 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
534
Ted Kremenekf308d372007-08-22 21:51:58 +0000535 return Block;
536 }
537
Ted Kremenek97f75312007-08-21 21:42:03 +0000538};
539
Ted Kremenek4db5b452007-08-23 16:51:22 +0000540
541/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
542/// block has no successors or predecessors. If this is the first block
543/// created in the CFG, it is automatically set to be the Entry and Exit
544/// of the CFG.
545CFGBlock* CFG::createBlock(unsigned blockID) {
546 bool first_block = begin() == end();
547
548 // Create the block.
549 Blocks.push_front(CFGBlock(blockID));
550
551 // If this is the first block, set it as the Entry and Exit.
552 if (first_block) Entry = Exit = &front();
553
554 // Return the block.
555 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000556}
557
Ted Kremenek4db5b452007-08-23 16:51:22 +0000558/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
559/// CFG is returned to the caller.
560CFG* CFG::buildCFG(Stmt* Statement) {
561 CFGBuilder Builder;
562 return Builder.buildCFG(Statement);
563}
564
565/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000566void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
567
Ted Kremenek4db5b452007-08-23 16:51:22 +0000568/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000569void CFG::dump() { print(std::cerr); }
570
Ted Kremenek4db5b452007-08-23 16:51:22 +0000571/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek97f75312007-08-21 21:42:03 +0000572void CFG::print(std::ostream& OS) {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000573
574 // Print the Entry block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000575 if (begin() != end()) {
576 CFGBlock& Entry = getEntry();
577 OS << "\n [ B" << Entry.getBlockID() << " (ENTRY) ]\n";
578 Entry.print(OS);
579 }
580
Ted Kremenek4db5b452007-08-23 16:51:22 +0000581 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenek97f75312007-08-21 21:42:03 +0000582 for (iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000583 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000584 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000585
Ted Kremenek4db5b452007-08-23 16:51:22 +0000586 OS << "\n [ B" << I->getBlockID() << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000587 I->print(OS);
588 }
Ted Kremenek4db5b452007-08-23 16:51:22 +0000589
590 // Print the Exit Block.
591 if (begin() != end()) {
592 CFGBlock& Exit = getExit();
593 OS << "\n [ B" << Exit.getBlockID() << " (EXIT) ]\n";
594 Exit.print(OS);
595 }
596
Ted Kremenek97f75312007-08-21 21:42:03 +0000597 OS << "\n";
598}
599
Ted Kremenekd8313202007-08-22 18:22:34 +0000600
601namespace {
602
603 class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
604 void > {
605 std::ostream& OS;
606 public:
607 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
608
609 void VisitIfStmt(IfStmt* I) {
610 OS << "if ";
611 I->getCond()->printPretty(std::cerr);
612 OS << "\n";
613 }
614
615 // Default case.
616 void VisitStmt(Stmt* S) { S->printPretty(OS); }
617
618 void VisitForStmt(ForStmt* F) {
619 OS << "for (" ;
620 if (Stmt* I = F->getInit()) I->printPretty(OS);
621 OS << " ; ";
622 if (Stmt* C = F->getCond()) C->printPretty(OS);
623 OS << " ; ";
624 if (Stmt* I = F->getInc()) I->printPretty(OS);
625 OS << ")\n";
Ted Kremenekbec06e82007-08-22 21:05:42 +0000626 }
627
628 void VisitWhileStmt(WhileStmt* W) {
629 OS << "while " ;
630 if (Stmt* C = W->getCond()) C->printPretty(OS);
631 OS << "\n";
Ted Kremenek95cc35c2007-08-23 17:15:32 +0000632 }
633
634 void VisitDoStmt(DoStmt* D) {
635 OS << "do ... while ";
636 if (Stmt* C = D->getCond()) C->printPretty(OS);
637 OS << "\n";
Ted Kremenekbec06e82007-08-22 21:05:42 +0000638 }
Ted Kremenekd8313202007-08-22 18:22:34 +0000639 };
640}
641
Ted Kremenek4db5b452007-08-23 16:51:22 +0000642/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000643void CFGBlock::dump() { print(std::cerr); }
644
Ted Kremenek4db5b452007-08-23 16:51:22 +0000645/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
646/// Generally this will only be called from CFG::print.
Ted Kremenek97f75312007-08-21 21:42:03 +0000647void CFGBlock::print(std::ostream& OS) {
648
649 // Iterate through the statements in the block and print them.
650 OS << " ------------------------\n";
651 unsigned j = 1;
652 for (iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekc5de2222007-08-21 23:26:17 +0000653 // Print the statement # in the basic block.
654 OS << " " << std::setw(3) << j << ": ";
655
656 // Print the statement/expression.
657 Stmt* S = *I;
658
659 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
660 OS << L->getName() << ": (LABEL)\n";
661 else
662 (*I)->printPretty(OS);
663
664 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +0000665 if (isa<Expr>(*I)) OS << '\n';
666 }
667 OS << " ------------------------\n";
668
669 // Print the predecessors of this block.
670 OS << " Predecessors (" << pred_size() << "):";
671 unsigned i = 0;
672 for (pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i ) {
673 if (i == 8 || (i-8) == 0) {
674 OS << "\n ";
675 }
676 OS << " B" << (*I)->getBlockID();
677 }
678
679 // Print the terminator of this block.
680 OS << "\n Terminator: ";
Ted Kremenekd8313202007-08-22 18:22:34 +0000681 if (ControlFlowStmt)
682 CFGBlockTerminatorPrint(OS).Visit(ControlFlowStmt);
683 else
684 OS << "<NULL>\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000685
686 // Print the successors of this block.
687 OS << " Successors (" << succ_size() << "):";
688 i = 0;
689 for (succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i ) {
690 if (i == 8 || (i-8) % 10 == 0) {
691 OS << "\n ";
692 }
693 OS << " B" << (*I)->getBlockID();
694 }
695 OS << '\n';
Ted Kremenek4db5b452007-08-23 16:51:22 +0000696}