blob: 7b0e4a6b99170c8a17f2e739310f18b06d8e2ebc [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
Ted Kremenekd6e50602007-08-23 21:26:19 +000026// SaveAndRestore - A utility class that uses RIIA to save and restore
27// the value of a variable.
28template<typename T>
29struct SaveAndRestore {
30 SaveAndRestore(T& x) : X(x), old_value(x) {}
31 ~SaveAndRestore() { X = old_value; }
32
33 T& X;
34 T old_value;
35};
Ted Kremenek97f75312007-08-21 21:42:03 +000036
37/// CFGBuilder - This class is implements CFG construction from an AST.
38/// The builder is stateful: an instance of the builder should be used to only
39/// construct a single CFG.
40///
41/// Example usage:
42///
43/// CFGBuilder builder;
44/// CFG* cfg = builder.BuildAST(stmt1);
45///
Ted Kremenek95e854d2007-08-21 22:06:14 +000046/// CFG construction is done via a recursive walk of an AST.
47/// We actually parse the AST in reverse order so that the successor
48/// of a basic block is constructed prior to its predecessor. This
49/// allows us to nicely capture implicit fall-throughs without extra
50/// basic blocks.
51///
52class CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000053 CFG* cfg;
54 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000055 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000056 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000057 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000058 CFGBlock* SwitchTerminatedBlock;
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 Kremeneke809ebf2007-08-23 18:43:24 +000070 SwitchTerminatedBlock(NULL),
Ted Kremenek97f75312007-08-21 21:42:03 +000071 NumBlocks(0) {
72 // Create an empty CFG.
73 cfg = new CFG();
74 }
75
76 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000077
Ted Kremenek73543912007-08-23 21:42:29 +000078 // buildCFG - Used by external clients to construct the CFG.
79 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000080
Ted Kremenek73543912007-08-23 21:42:29 +000081 // Visitors to walk an AST and construct the CFG. Called by
82 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000083
Ted Kremenek73543912007-08-23 21:42:29 +000084 CFGBlock* VisitStmt(Stmt* Statement);
85 CFGBlock* VisitNullStmt(NullStmt* Statement);
86 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
87 CFGBlock* VisitIfStmt(IfStmt* I);
88 CFGBlock* VisitReturnStmt(ReturnStmt* R);
89 CFGBlock* VisitLabelStmt(LabelStmt* L);
90 CFGBlock* VisitGotoStmt(GotoStmt* G);
91 CFGBlock* VisitForStmt(ForStmt* F);
92 CFGBlock* VisitWhileStmt(WhileStmt* W);
93 CFGBlock* VisitDoStmt(DoStmt* D);
94 CFGBlock* VisitContinueStmt(ContinueStmt* C);
95 CFGBlock* VisitBreakStmt(BreakStmt* B);
96 CFGBlock* VisitSwitchStmt(SwitchStmt* S);
97 CFGBlock* VisitSwitchCase(SwitchCase* S);
Ted Kremenek97f75312007-08-21 21:42:03 +000098
Ted Kremenek73543912007-08-23 21:42:29 +000099private:
100 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000101 CFGBlock* addStmt(Stmt* S) { Block->appendStmt(S); return Block; }
Ted Kremenek73543912007-08-23 21:42:29 +0000102 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000103
Ted Kremenek97f75312007-08-21 21:42:03 +0000104};
Ted Kremenek73543912007-08-23 21:42:29 +0000105
106/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
107/// represent an arbitrary statement. Examples include a single expression
108/// or a function body (compound statement). The ownership of the returned
109/// CFG is transferred to the caller. If CFG construction fails, this method
110/// returns NULL.
111CFG* CFGBuilder::buildCFG(Stmt* Statement) {
112 if (!Statement) return NULL;
113
114 // Create an empty block that will serve as the exit block for the CFG.
115 // Since this is the first block added to the CFG, it will be implicitly
116 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000117 Succ = createBlock();
118 assert (Succ == &cfg->getExit());
119 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000120
121 // Visit the statements and create the CFG.
122 if (CFGBlock* B = Visit(Statement)) {
123 // Finalize the last constructed block. This usually involves
124 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000125 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000126
127 // Backpatch the gotos whose label -> block mappings we didn't know
128 // when we encountered them.
129 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
130 E = BackpatchBlocks.end(); I != E; ++I ) {
131
132 CFGBlock* B = *I;
133 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
134 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
135
136 // If there is no target for the goto, then we are looking at an
137 // incomplete AST. Handle this by not registering a successor.
138 if (LI == LabelMap.end()) continue;
139
140 B->addSuccessor(LI->second);
141 }
142
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000143 if (B->pred_size() > 0) {
144 // create an empty entry block that has no predecessors.
145 Succ = B;
146 cfg->setEntry(createBlock());
147 }
148 else cfg->setEntry(B);
149
Ted Kremenek73543912007-08-23 21:42:29 +0000150 // NULL out cfg so that repeated calls
151 CFG* t = cfg;
152 cfg = NULL;
153 return t;
154 }
155 else return NULL;
156}
157
158/// createBlock - Used to lazily create blocks that are connected
159/// to the current (global) succcessor.
160CFGBlock* CFGBuilder::createBlock(bool add_successor) {
161 CFGBlock* B = cfg->createBlock(NumBlocks++);
162 if (add_successor && Succ) B->addSuccessor(Succ);
163 return B;
164}
165
166/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000167/// we must reverse the statements because they have been inserted
168/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000169void CFGBuilder::FinishBlock(CFGBlock* B) {
170 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000171 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000172}
173
174/// VisitStmt - Handle statements with no branching control flow.
175CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
176 // We cannot assume that we are in the middle of a basic block, since
177 // the CFG might only be constructed for this single statement. If
178 // we have no current basic block, just create one lazily.
179 if (!Block) Block = createBlock();
180
181 // Simply add the statement to the current block. We actually
182 // insert statements in reverse order; this order is reversed later
183 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000184 addStmt(Statement);
185
Ted Kremenek73543912007-08-23 21:42:29 +0000186 return Block;
187}
188
189CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
190 return Block;
191}
192
193CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
194 // The value returned from this function is the last created CFGBlock
195 // that represents the "entry" point for the translated AST node.
196 CFGBlock* LastBlock;
197
198 for (CompoundStmt::reverse_body_iterator I = C->body_rbegin(),
199 E = C->body_rend(); I != E; ++I )
200 // Add the statement to the current block.
201 if (!(LastBlock=Visit(*I)))
202 return NULL;
203
204 return LastBlock;
205}
206
207CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
208 // We may see an if statement in the middle of a basic block, or
209 // it may be the first statement we are processing. In either case,
210 // we create a new basic block. First, we create the blocks for
211 // the then...else statements, and then we create the block containing
212 // the if statement. If we were in the middle of a block, we
213 // stop processing that block and reverse its statements. That block
214 // is then the implicit successor for the "then" and "else" clauses.
215
216 // The block we were proccessing is now finished. Make it the
217 // successor block.
218 if (Block) {
219 Succ = Block;
220 FinishBlock(Block);
221 }
222
223 // Process the false branch. NULL out Block so that the recursive
224 // call to Visit will create a new basic block.
225 // Null out Block so that all successor
226 CFGBlock* ElseBlock = Succ;
227
228 if (Stmt* Else = I->getElse()) {
229 SaveAndRestore<CFGBlock*> sv(Succ);
230
231 // NULL out Block so that the recursive call to Visit will
232 // create a new basic block.
233 Block = NULL;
234 ElseBlock = Visit(Else);
235 if (!ElseBlock) return NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000236 if (Block) FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000237 }
238
239 // Process the true branch. NULL out Block so that the recursive
240 // call to Visit will create a new basic block.
241 // Null out Block so that all successor
242 CFGBlock* ThenBlock;
243 {
244 Stmt* Then = I->getThen();
245 assert (Then);
246 SaveAndRestore<CFGBlock*> sv(Succ);
247 Block = NULL;
248 ThenBlock = Visit(Then);
249 if (!ThenBlock) return NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000250 if (Block) FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000251 }
252
253 // Now create a new block containing the if statement.
254 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000255
256 // Set the terminator of the new block to the If statement.
257 Block->setTerminator(I);
258
259 // Now add the successors.
260 Block->addSuccessor(ThenBlock);
261 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000262
263 // Add the condition as the last statement in the new block. This
264 // may create new blocks as the condition may contain control-flow. Any
265 // newly created blocks will be pointed to be "Block".
266 return addStmt(I->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000267}
268
269CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
270 // If we were in the middle of a block we stop processing that block
271 // and reverse its statements.
272 //
273 // NOTE: If a "return" appears in the middle of a block, this means
274 // that the code afterwards is DEAD (unreachable). We still
275 // keep a basic block for that code; a simple "mark-and-sweep"
276 // from the entry block will be able to report such dead
277 // blocks.
278 if (Block) FinishBlock(Block);
279
280 // Create the new block.
281 Block = createBlock(false);
282
283 // The Exit block is the only successor.
284 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000285
Ted Kremenek73543912007-08-23 21:42:29 +0000286 // Also add the return statement as the terminator.
287 Block->setTerminator(R);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000288
289 // Add the return statement to the block. This may create new blocks
290 // if R contains control-flow (short-circuit operations).
291 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000292}
293
294CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
295 // Get the block of the labeled statement. Add it to our map.
296 CFGBlock* LabelBlock = Visit(L->getSubStmt());
297 assert (LabelBlock);
298
299 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
300 LabelMap[ L ] = LabelBlock;
301
302 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000303 // we were processing (the label is the first statement). Add the label
304 // the to end (really the beginning) of the block. Because this is
305 // label (and we have already processed the substatement) there is no
306 // extra control-flow to worry about.
Ted Kremenek73543912007-08-23 21:42:29 +0000307 LabelBlock->appendStmt(L);
308 FinishBlock(LabelBlock);
309
310 // We set Block to NULL to allow lazy creation of a new block
311 // (if necessary);
312 Block = NULL;
313
314 // This block is now the implicit successor of other blocks.
315 Succ = LabelBlock;
316
317 return LabelBlock;
318}
319
320CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
321 // Goto is a control-flow statement. Thus we stop processing the
322 // current block and create a new one.
323 if (Block) FinishBlock(Block);
324 Block = createBlock(false);
325 Block->setTerminator(G);
326
327 // If we already know the mapping to the label block add the
328 // successor now.
329 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
330
331 if (I == LabelMap.end())
332 // We will need to backpatch this block later.
333 BackpatchBlocks.push_back(Block);
334 else
335 Block->addSuccessor(I->second);
336
337 return Block;
338}
339
340CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
341 // "for" is a control-flow statement. Thus we stop processing the
342 // current block.
343
344 CFGBlock* LoopSuccessor = NULL;
345
346 if (Block) {
347 FinishBlock(Block);
348 LoopSuccessor = Block;
349 }
350 else LoopSuccessor = Succ;
351
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000352 // Because of short-circuit evaluation, the condition of the loop
353 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
354 // blocks that evaluate the condition.
355 CFGBlock* ExitConditionBlock = createBlock(false);
356 CFGBlock* EntryConditionBlock = ExitConditionBlock;
357
358 // Set the terminator for the "exit" condition block.
359 ExitConditionBlock->setTerminator(F);
360
361 // Now add the actual condition to the condition block. Because the
362 // condition itself may contain control-flow, new blocks may be created.
363 if (Stmt* C = F->getCond()) {
364 Block = ExitConditionBlock;
365 EntryConditionBlock = addStmt(C);
366 if (Block) FinishBlock(EntryConditionBlock);
367 }
Ted Kremenek73543912007-08-23 21:42:29 +0000368
369 // The condition block is the implicit successor for the loop body as
370 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000371 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000372
373 // Now create the loop body.
374 {
375 assert (F->getBody());
376
377 // Save the current values for Block, Succ, and continue and break targets
378 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
379 save_continue(ContinueTargetBlock),
380 save_break(BreakTargetBlock);
381
382 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000383 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000384
385 // All breaks should go to the code following the loop.
386 BreakTargetBlock = LoopSuccessor;
387
388 // Create a new block to contain the (bottom) of the loop body.
389 Block = createBlock();
390
391 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000392 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000393
394 // Now populate the body block, and in the process create new blocks
395 // as we walk the body of the loop.
396 CFGBlock* BodyBlock = Visit(F->getBody());
397 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000398 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000399
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000400 // This new body block is a successor to our "exit" condition block.
401 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000402 }
403
404 // Link up the condition block with the code that follows the loop.
405 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000406 ExitConditionBlock->addSuccessor(LoopSuccessor);
407
Ted Kremenek73543912007-08-23 21:42:29 +0000408 // If the loop contains initialization, create a new block for those
409 // statements. This block can also contain statements that precede
410 // the loop.
411 if (Stmt* I = F->getInit()) {
412 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000413 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000414 }
415 else {
416 // There is no loop initialization. We are thus basically a while
417 // loop. NULL out Block to force lazy block construction.
418 Block = NULL;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000419 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000420 }
421}
422
423CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
424 // "while" is a control-flow statement. Thus we stop processing the
425 // current block.
426
427 CFGBlock* LoopSuccessor = NULL;
428
429 if (Block) {
430 FinishBlock(Block);
431 LoopSuccessor = Block;
432 }
433 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000434
435 // Because of short-circuit evaluation, the condition of the loop
436 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
437 // blocks that evaluate the condition.
438 CFGBlock* ExitConditionBlock = createBlock(false);
439 CFGBlock* EntryConditionBlock = ExitConditionBlock;
440
441 // Set the terminator for the "exit" condition block.
442 ExitConditionBlock->setTerminator(W);
443
444 // Now add the actual condition to the condition block. Because the
445 // condition itself may contain control-flow, new blocks may be created.
446 // Thus we update "Succ" after adding the condition.
447 if (Stmt* C = W->getCond()) {
448 Block = ExitConditionBlock;
449 EntryConditionBlock = addStmt(C);
450 if (Block) FinishBlock(EntryConditionBlock);
451 }
Ted Kremenek73543912007-08-23 21:42:29 +0000452
453 // The condition block is the implicit successor for the loop body as
454 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000455 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000456
457 // Process the loop body.
458 {
459 assert (W->getBody());
460
461 // Save the current values for Block, Succ, and continue and break targets
462 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
463 save_continue(ContinueTargetBlock),
464 save_break(BreakTargetBlock);
465
466 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000467 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000468
469 // All breaks should go to the code following the loop.
470 BreakTargetBlock = LoopSuccessor;
471
472 // NULL out Block to force lazy instantiation of blocks for the body.
473 Block = NULL;
474
475 // Create the body. The returned block is the entry to the loop body.
476 CFGBlock* BodyBlock = Visit(W->getBody());
477 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000478 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000479
480 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000481 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000482 }
483
484 // Link up the condition block with the code that follows the loop.
485 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000486 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000487
488 // There can be no more statements in the condition block
489 // since we loop back to this block. NULL out Block to force
490 // lazy creation of another block.
491 Block = NULL;
492
493 // Return the condition block, which is the dominating block for the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000494 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000495}
496
497CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
498 // "do...while" is a control-flow statement. Thus we stop processing the
499 // current block.
500
501 CFGBlock* LoopSuccessor = NULL;
502
503 if (Block) {
504 FinishBlock(Block);
505 LoopSuccessor = Block;
506 }
507 else LoopSuccessor = Succ;
508
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000509 // Because of short-circuit evaluation, the condition of the loop
510 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
511 // blocks that evaluate the condition.
512 CFGBlock* ExitConditionBlock = createBlock(false);
513 CFGBlock* EntryConditionBlock = ExitConditionBlock;
514
515 // Set the terminator for the "exit" condition block.
516 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000517
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000518 // Now add the actual condition to the condition block. Because the
519 // condition itself may contain control-flow, new blocks may be created.
520 if (Stmt* C = D->getCond()) {
521 Block = ExitConditionBlock;
522 EntryConditionBlock = addStmt(C);
523 if (Block) FinishBlock(EntryConditionBlock);
524 }
Ted Kremenek73543912007-08-23 21:42:29 +0000525
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000526 // The condition block is the implicit successor for the loop body as
527 // well as any code above the loop.
528 Succ = EntryConditionBlock;
529
530
Ted Kremenek73543912007-08-23 21:42:29 +0000531 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000532 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000533 {
534 assert (D->getBody());
535
536 // Save the current values for Block, Succ, and continue and break targets
537 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
538 save_continue(ContinueTargetBlock),
539 save_break(BreakTargetBlock);
540
541 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000542 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000543
544 // All breaks should go to the code following the loop.
545 BreakTargetBlock = LoopSuccessor;
546
547 // NULL out Block to force lazy instantiation of blocks for the body.
548 Block = NULL;
549
550 // Create the body. The returned block is the entry to the loop body.
551 BodyBlock = Visit(D->getBody());
552 assert (BodyBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000553 if (Block) FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000554
555 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000556 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000557 }
558
559 // Link up the condition block with the code that follows the loop.
560 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000561 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000562
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000563 // There can be no more statements in the body block(s)
564 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000565 // lazy creation of another block.
566 Block = NULL;
567
568 // Return the loop body, which is the dominating block for the loop.
569 return BodyBlock;
570}
571
572CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
573 // "continue" is a control-flow statement. Thus we stop processing the
574 // current block.
575 if (Block) FinishBlock(Block);
576
577 // Now create a new block that ends with the continue statement.
578 Block = createBlock(false);
579 Block->setTerminator(C);
580
581 // If there is no target for the continue, then we are looking at an
582 // incomplete AST. Handle this by not registering a successor.
583 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
584
585 return Block;
586}
587
588CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
589 // "break" is a control-flow statement. Thus we stop processing the
590 // current block.
591 if (Block) FinishBlock(Block);
592
593 // Now create a new block that ends with the continue statement.
594 Block = createBlock(false);
595 Block->setTerminator(B);
596
597 // If there is no target for the break, then we are looking at an
598 // incomplete AST. Handle this by not registering a successor.
599 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
600
601 return Block;
602}
603
604CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* S) {
605 // "switch" is a control-flow statement. Thus we stop processing the
606 // current block.
607 CFGBlock* SwitchSuccessor = NULL;
608
609 if (Block) {
610 FinishBlock(Block);
611 SwitchSuccessor = Block;
612 }
613 else SwitchSuccessor = Succ;
614
615 // Save the current "switch" context.
616 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
617 save_break(BreakTargetBlock);
618
619 // Create a new block that will contain the switch statement.
620 SwitchTerminatedBlock = createBlock(false);
621
Ted Kremenek73543912007-08-23 21:42:29 +0000622 // Now process the switch body. The code after the switch is the implicit
623 // successor.
624 Succ = SwitchSuccessor;
625 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000626
627 // When visiting the body, the case statements should automatically get
628 // linked up to the switch. We also don't keep a pointer to the body,
629 // since all control-flow from the switch goes to case/default statements.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000630 assert (S->getBody() && "switch must contain a non-NULL body");
631 Block = NULL;
632 CFGBlock *BodyBlock = Visit(S->getBody());
633 if (Block) FinishBlock(BodyBlock);
634
635 // Add the terminator and condition in the switch block.
636 SwitchTerminatedBlock->setTerminator(S);
637 assert (S->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000638 Block = SwitchTerminatedBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000639 return addStmt(S->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000640}
641
642CFGBlock* CFGBuilder::VisitSwitchCase(SwitchCase* S) {
643 // A SwitchCase is either a "default" or "case" statement. We handle
644 // both in the same way. They are essentially labels, so they are the
645 // first statement in a block.
646 CFGBlock* CaseBlock = Visit(S->getSubStmt());
647 assert (CaseBlock);
648
649 // Cases/Default statements parition block, so this is the top of
650 // the basic block we were processing (the case/default is the first stmt).
651 CaseBlock->appendStmt(S);
652 FinishBlock(CaseBlock);
653
654 // Add this block to the list of successors for the block with the
655 // switch statement.
656 if (SwitchTerminatedBlock) SwitchTerminatedBlock->addSuccessor(CaseBlock);
657
658 // We set Block to NULL to allow lazy creation of a new block (if necessary)
659 Block = NULL;
660
661 // This block is now the implicit successor of other blocks.
662 Succ = CaseBlock;
663
664 return CaseBlock;
665}
666
667
Ted Kremenekd6e50602007-08-23 21:26:19 +0000668} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +0000669
670/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
671/// block has no successors or predecessors. If this is the first block
672/// created in the CFG, it is automatically set to be the Entry and Exit
673/// of the CFG.
674CFGBlock* CFG::createBlock(unsigned blockID) {
675 bool first_block = begin() == end();
676
677 // Create the block.
678 Blocks.push_front(CFGBlock(blockID));
679
680 // If this is the first block, set it as the Entry and Exit.
681 if (first_block) Entry = Exit = &front();
682
683 // Return the block.
684 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +0000685}
686
Ted Kremenek4db5b452007-08-23 16:51:22 +0000687/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
688/// CFG is returned to the caller.
689CFG* CFG::buildCFG(Stmt* Statement) {
690 CFGBuilder Builder;
691 return Builder.buildCFG(Statement);
692}
693
694/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +0000695void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
696
Ted Kremenek4db5b452007-08-23 16:51:22 +0000697/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000698void CFG::dump() { print(std::cerr); }
699
Ted Kremenek4db5b452007-08-23 16:51:22 +0000700/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremenek97f75312007-08-21 21:42:03 +0000701void CFG::print(std::ostream& OS) {
Ted Kremenek4db5b452007-08-23 16:51:22 +0000702 // Print the Entry block.
Ted Kremenekbec06e82007-08-22 21:05:42 +0000703 if (begin() != end()) {
704 CFGBlock& Entry = getEntry();
705 OS << "\n [ B" << Entry.getBlockID() << " (ENTRY) ]\n";
706 Entry.print(OS);
707 }
708
Ted Kremenek4db5b452007-08-23 16:51:22 +0000709 // Iterate through the CFGBlocks and print them one by one.
Ted Kremenek97f75312007-08-21 21:42:03 +0000710 for (iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
Ted Kremenekbec06e82007-08-22 21:05:42 +0000711 // Skip the entry block, because we already printed it.
Ted Kremenek4db5b452007-08-23 16:51:22 +0000712 if (&(*I) == &getEntry() || &(*I) == &getExit()) continue;
Ted Kremenekbec06e82007-08-22 21:05:42 +0000713
Ted Kremenek4db5b452007-08-23 16:51:22 +0000714 OS << "\n [ B" << I->getBlockID() << " ]\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000715 I->print(OS);
716 }
Ted Kremenek73543912007-08-23 21:42:29 +0000717
Ted Kremenek4db5b452007-08-23 16:51:22 +0000718 // Print the Exit Block.
719 if (begin() != end()) {
720 CFGBlock& Exit = getExit();
721 OS << "\n [ B" << Exit.getBlockID() << " (EXIT) ]\n";
722 Exit.print(OS);
723 }
Ted Kremenek73543912007-08-23 21:42:29 +0000724
Ted Kremenek97f75312007-08-21 21:42:03 +0000725 OS << "\n";
726}
727
Ted Kremenekd8313202007-08-22 18:22:34 +0000728
729namespace {
730
Ted Kremenek73543912007-08-23 21:42:29 +0000731class CFGBlockTerminatorPrint : public StmtVisitor<CFGBlockTerminatorPrint,
732 void > {
733 std::ostream& OS;
734public:
735 CFGBlockTerminatorPrint(std::ostream& os) : OS(os) {}
736
737 void VisitIfStmt(IfStmt* I) {
738 OS << "if ";
739 I->getCond()->printPretty(std::cerr);
740 OS << "\n";
741 }
742
743 // Default case.
744 void VisitStmt(Stmt* S) { S->printPretty(OS); }
745
746 void VisitForStmt(ForStmt* F) {
747 OS << "for (" ;
748 if (Stmt* I = F->getInit()) I->printPretty(OS);
749 OS << " ; ";
750 if (Stmt* C = F->getCond()) C->printPretty(OS);
751 OS << " ; ";
752 if (Stmt* I = F->getInc()) I->printPretty(OS);
753 OS << ")\n";
754 }
755
756 void VisitWhileStmt(WhileStmt* W) {
757 OS << "while " ;
758 if (Stmt* C = W->getCond()) C->printPretty(OS);
759 OS << "\n";
760 }
761
762 void VisitDoStmt(DoStmt* D) {
763 OS << "do ... while ";
764 if (Stmt* C = D->getCond()) C->printPretty(OS);
765 OS << "\n";
766 }
767};
768} // end anonymous namespace
Ted Kremenekd8313202007-08-22 18:22:34 +0000769
Ted Kremenek4db5b452007-08-23 16:51:22 +0000770/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek97f75312007-08-21 21:42:03 +0000771void CFGBlock::dump() { print(std::cerr); }
772
Ted Kremenek4db5b452007-08-23 16:51:22 +0000773/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
774/// Generally this will only be called from CFG::print.
Ted Kremenek97f75312007-08-21 21:42:03 +0000775void CFGBlock::print(std::ostream& OS) {
776
777 // Iterate through the statements in the block and print them.
778 OS << " ------------------------\n";
779 unsigned j = 1;
780 for (iterator I = Stmts.begin(), E = Stmts.end() ; I != E ; ++I, ++j ) {
Ted Kremenekc5de2222007-08-21 23:26:17 +0000781 // Print the statement # in the basic block.
782 OS << " " << std::setw(3) << j << ": ";
783
784 // Print the statement/expression.
785 Stmt* S = *I;
786
787 if (LabelStmt* L = dyn_cast<LabelStmt>(S))
788 OS << L->getName() << ": (LABEL)\n";
789 else
790 (*I)->printPretty(OS);
791
792 // Expressions need a newline.
Ted Kremenek97f75312007-08-21 21:42:03 +0000793 if (isa<Expr>(*I)) OS << '\n';
794 }
795 OS << " ------------------------\n";
796
797 // Print the predecessors of this block.
798 OS << " Predecessors (" << pred_size() << "):";
799 unsigned i = 0;
800 for (pred_iterator I = pred_begin(), E = pred_end(); I != E; ++I, ++i ) {
801 if (i == 8 || (i-8) == 0) {
802 OS << "\n ";
803 }
804 OS << " B" << (*I)->getBlockID();
805 }
806
807 // Print the terminator of this block.
808 OS << "\n Terminator: ";
Ted Kremenekd8313202007-08-22 18:22:34 +0000809 if (ControlFlowStmt)
810 CFGBlockTerminatorPrint(OS).Visit(ControlFlowStmt);
811 else
812 OS << "<NULL>\n";
Ted Kremenek97f75312007-08-21 21:42:03 +0000813
814 // Print the successors of this block.
815 OS << " Successors (" << succ_size() << "):";
816 i = 0;
817 for (succ_iterator I = succ_begin(), E = succ_end(); I != E; ++I, ++i ) {
818 if (i == 8 || (i-8) % 10 == 0) {
819 OS << "\n ";
820 }
821 OS << " B" << (*I)->getBlockID();
822 }
823 OS << '\n';
Ted Kremenek4db5b452007-08-23 16:51:22 +0000824}