blob: 6277aae85a9f085def01193e0402241be76e2123 [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//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek97f75312007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
16#include "clang/AST/Expr.h"
Ted Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenek5ee98a72008-01-11 00:40:29 +000024#include <set>
Ted Kremenek97f75312007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000027#include <sstream>
Chris Lattner8b8720f2008-03-10 17:04:53 +000028#include <iostream>
Ted Kremenek5ee98a72008-01-11 00:40:29 +000029
Ted Kremenek97f75312007-08-21 21:42:03 +000030using namespace clang;
31
32namespace {
33
Ted Kremenekd6e50602007-08-23 21:26:19 +000034// SaveAndRestore - A utility class that uses RIIA to save and restore
35// the value of a variable.
36template<typename T>
Ted Kremenek98cee3a2008-01-08 18:15:10 +000037struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000038 SaveAndRestore(T& x) : X(x), old_value(x) {}
39 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000040 T get() { return old_value; }
41
Ted Kremenekd6e50602007-08-23 21:26:19 +000042 T& X;
43 T old_value;
44};
Ted Kremenek97f75312007-08-21 21:42:03 +000045
46/// CFGBuilder - This class is implements CFG construction from an AST.
47/// The builder is stateful: an instance of the builder should be used to only
48/// construct a single CFG.
49///
50/// Example usage:
51///
52/// CFGBuilder builder;
53/// CFG* cfg = builder.BuildAST(stmt1);
54///
Ted Kremenek95e854d2007-08-21 22:06:14 +000055/// CFG construction is done via a recursive walk of an AST.
56/// We actually parse the AST in reverse order so that the successor
57/// of a basic block is constructed prior to its predecessor. This
58/// allows us to nicely capture implicit fall-throughs without extra
59/// basic blocks.
60///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000061class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000062 CFG* cfg;
63 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000064 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000065 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000066 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000067 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +000068 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000069
Ted Kremenek0edd3a92007-08-28 19:26:49 +000070 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000071 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
72 LabelMapTy LabelMap;
73
Ted Kremenek0edd3a92007-08-28 19:26:49 +000074 // A list of blocks that end with a "goto" that must be backpatched to
75 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000076 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000077 BackpatchBlocksTy BackpatchBlocks;
78
Ted Kremenek0edd3a92007-08-28 19:26:49 +000079 // A list of labels whose address has been taken (for indirect gotos).
80 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
81 LabelSetTy AddressTakenLabels;
82
Ted Kremenek97f75312007-08-21 21:42:03 +000083public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000084 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000085 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +000086 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000087 // Create an empty CFG.
88 cfg = new CFG();
89 }
90
91 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000092
Ted Kremenek73543912007-08-23 21:42:29 +000093 // buildCFG - Used by external clients to construct the CFG.
94 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000095
Ted Kremenek73543912007-08-23 21:42:29 +000096 // Visitors to walk an AST and construct the CFG. Called by
97 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000098
Ted Kremenek73543912007-08-23 21:42:29 +000099 CFGBlock* VisitStmt(Stmt* Statement);
100 CFGBlock* VisitNullStmt(NullStmt* Statement);
101 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
102 CFGBlock* VisitIfStmt(IfStmt* I);
103 CFGBlock* VisitReturnStmt(ReturnStmt* R);
104 CFGBlock* VisitLabelStmt(LabelStmt* L);
105 CFGBlock* VisitGotoStmt(GotoStmt* G);
106 CFGBlock* VisitForStmt(ForStmt* F);
107 CFGBlock* VisitWhileStmt(WhileStmt* W);
108 CFGBlock* VisitDoStmt(DoStmt* D);
109 CFGBlock* VisitContinueStmt(ContinueStmt* C);
110 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000111 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
112 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000113 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000114 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000115
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000116 // FIXME: Add support for ObjC-specific control-flow structures.
117
Ted Kremenek79f0a632008-04-16 21:10:48 +0000118 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* Terminator) {
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000119 badCFG = true;
120 return Block;
121 }
122
Ted Kremenek79f0a632008-04-16 21:10:48 +0000123 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* Terminator) {
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000124 badCFG = true;
125 return Block;
126 }
127
Ted Kremenek73543912007-08-23 21:42:29 +0000128private:
129 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000130 CFGBlock* addStmt(Stmt* Terminator);
131 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
132 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000133 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000134 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +0000135 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000136
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000137 bool badCFG;
Ted Kremenek97f75312007-08-21 21:42:03 +0000138};
Ted Kremenek73543912007-08-23 21:42:29 +0000139
140/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
141/// represent an arbitrary statement. Examples include a single expression
142/// or a function body (compound statement). The ownership of the returned
143/// CFG is transferred to the caller. If CFG construction fails, this method
144/// returns NULL.
145CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000146 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000147 if (!Statement) return NULL;
148
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000149 badCFG = false;
150
Ted Kremenek73543912007-08-23 21:42:29 +0000151 // Create an empty block that will serve as the exit block for the CFG.
152 // Since this is the first block added to the CFG, it will be implicitly
153 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000154 Succ = createBlock();
155 assert (Succ == &cfg->getExit());
156 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000157
158 // Visit the statements and create the CFG.
Ted Kremenekfa38c7a2008-02-27 17:33:02 +0000159 CFGBlock* B = Visit(Statement);
160 if (!B) B = Succ;
161
162 if (B) {
Ted Kremenek73543912007-08-23 21:42:29 +0000163 // Finalize the last constructed block. This usually involves
164 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000165 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000166
167 // Backpatch the gotos whose label -> block mappings we didn't know
168 // when we encountered them.
169 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
170 E = BackpatchBlocks.end(); I != E; ++I ) {
171
172 CFGBlock* B = *I;
173 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
174 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
175
176 // If there is no target for the goto, then we are looking at an
177 // incomplete AST. Handle this by not registering a successor.
178 if (LI == LabelMap.end()) continue;
179
180 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000181 }
Ted Kremenek73543912007-08-23 21:42:29 +0000182
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000183 // Add successors to the Indirect Goto Dispatch block (if we have one).
184 if (CFGBlock* B = cfg->getIndirectGotoBlock())
185 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
186 E = AddressTakenLabels.end(); I != E; ++I ) {
187
188 // Lookup the target block.
189 LabelMapTy::iterator LI = LabelMap.find(*I);
190
191 // If there is no target block that contains label, then we are looking
192 // at an incomplete AST. Handle this by not registering a successor.
193 if (LI == LabelMap.end()) continue;
194
195 B->addSuccessor(LI->second);
196 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000197
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000198 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000199 }
200
201 // Create an empty entry block that has no predecessors.
202 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000203
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000204 if (badCFG) {
205 delete cfg;
206 cfg = NULL;
207 return NULL;
208 }
209
Ted Kremenek680fcb82007-09-26 21:23:31 +0000210 // NULL out cfg so that repeated calls to the builder will fail and that
211 // the ownership of the constructed CFG is passed to the caller.
212 CFG* t = cfg;
213 cfg = NULL;
214 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000215}
216
217/// createBlock - Used to lazily create blocks that are connected
218/// to the current (global) succcessor.
219CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000220 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000221 if (add_successor && Succ) B->addSuccessor(Succ);
222 return B;
223}
224
225/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000226/// we must reverse the statements because they have been inserted
227/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000228void CFGBuilder::FinishBlock(CFGBlock* B) {
229 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000230 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000231}
232
Ted Kremenek65cfa562007-08-27 21:27:44 +0000233/// addStmt - Used to add statements/expressions to the current CFGBlock
234/// "Block". This method calls WalkAST on the passed statement to see if it
235/// contains any short-circuit expressions. If so, it recursively creates
236/// the necessary blocks for such expressions. It returns the "topmost" block
237/// of the created blocks, or the original value of "Block" when this method
238/// was called if no additional blocks are created.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000239CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000240 if (!Block) Block = createBlock();
Ted Kremenek79f0a632008-04-16 21:10:48 +0000241 return WalkAST(Terminator,true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000242}
243
244/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000245/// add extra blocks for ternary operators, &&, and ||. We also
246/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000247CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
248 switch (Terminator->getStmtClass()) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000249 case Stmt::ConditionalOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000250 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000251
252 // Create the confluence block that will "merge" the results
253 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000254 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
255 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000256 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000257
258 // Create a block for the LHS expression if there is an LHS expression.
259 // A GCC extension allows LHS to be NULL, causing the condition to
260 // be the value that is returned instead.
261 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000262 Succ = ConfluenceBlock;
263 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000264 CFGBlock* LHSBlock = NULL;
265 if (C->getLHS()) {
266 LHSBlock = Visit(C->getLHS());
267 FinishBlock(LHSBlock);
268 Block = NULL;
269 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000270
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000271 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000272 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000273 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000274 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000275
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000276 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000277 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000278
279 if (LHSBlock)
280 Block->addSuccessor(LHSBlock);
281 else {
282 // If we have no LHS expression, add the ConfluenceBlock as a direct
283 // successor for the block containing the condition. Moreover,
284 // we need to reverse the order of the predecessors in the
285 // ConfluenceBlock because the RHSBlock will have been added to
286 // the succcessors already, and we want the first predecessor to the
287 // the block containing the expression for the case when the ternary
288 // expression evaluates to true.
289 Block->addSuccessor(ConfluenceBlock);
290 assert (ConfluenceBlock->pred_size() == 2);
291 std::reverse(ConfluenceBlock->pred_begin(),
292 ConfluenceBlock->pred_end());
293 }
294
Ted Kremenek65cfa562007-08-27 21:27:44 +0000295 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000296
Ted Kremenek65cfa562007-08-27 21:27:44 +0000297 Block->setTerminator(C);
298 return addStmt(C->getCond());
299 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000300
301 case Stmt::ChooseExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000302 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek7f788422007-08-31 17:03:41 +0000303
304 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
305 ConfluenceBlock->appendStmt(C);
306 FinishBlock(ConfluenceBlock);
307
308 Succ = ConfluenceBlock;
309 Block = NULL;
310 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000311 FinishBlock(LHSBlock);
312
Ted Kremenek7f788422007-08-31 17:03:41 +0000313 Succ = ConfluenceBlock;
314 Block = NULL;
315 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000316 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000317
318 Block = createBlock(false);
319 Block->addSuccessor(LHSBlock);
320 Block->addSuccessor(RHSBlock);
321 Block->setTerminator(C);
322 return addStmt(C->getCond());
323 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000324
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000325 case Stmt::DeclStmtClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000326 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
327 Block->appendStmt(Terminator);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000328
329 StmtIterator I(D);
330 return WalkAST_VisitDeclSubExprs(I);
331 }
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000332
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000333 case Stmt::AddrLabelExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000334 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000335 AddressTakenLabels.insert(A->getLabel());
336
Ted Kremenek79f0a632008-04-16 21:10:48 +0000337 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000338 return Block;
339 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000340
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000341 case Stmt::StmtExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000342 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremeneke822b622007-08-28 18:14:37 +0000343
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000344 case Stmt::UnaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000345 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000346
347 // sizeof(expressions). For such expressions,
348 // the subexpression is not really evaluated, so
349 // we don't care about control-flow within the sizeof.
350 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000351 Block->appendStmt(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000352 return Block;
353 }
354
355 break;
356 }
357
Ted Kremenekcfaae762007-08-27 21:54:41 +0000358 case Stmt::BinaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000359 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000360
361 if (B->isLogicalOp()) { // && or ||
362 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
363 ConfluenceBlock->appendStmt(B);
364 FinishBlock(ConfluenceBlock);
365
366 // create the block evaluating the LHS
367 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000368 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000369
370 // create the block evaluating the RHS
371 Succ = ConfluenceBlock;
372 Block = NULL;
373 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000374
375 // Now link the LHSBlock with RHSBlock.
376 if (B->getOpcode() == BinaryOperator::LOr) {
377 LHSBlock->addSuccessor(ConfluenceBlock);
378 LHSBlock->addSuccessor(RHSBlock);
379 }
380 else {
381 assert (B->getOpcode() == BinaryOperator::LAnd);
382 LHSBlock->addSuccessor(RHSBlock);
383 LHSBlock->addSuccessor(ConfluenceBlock);
384 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000385
386 // Generate the blocks for evaluating the LHS.
387 Block = LHSBlock;
388 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000389 }
390 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
391 Block->appendStmt(B);
392 addStmt(B->getRHS());
393 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000394 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000395
396 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000397 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000398
399 case Stmt::ParenExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000400 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000401
Ted Kremenek65cfa562007-08-27 21:27:44 +0000402 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000403 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000404 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000405
Ted Kremenek79f0a632008-04-16 21:10:48 +0000406 if (AlwaysAddStmt) Block->appendStmt(Terminator);
407 return WalkAST_VisitChildren(Terminator);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000408}
409
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000410/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
411/// DeclStmts. Because the initialization code (and sometimes the
412/// the type declarations) for DeclStmts can contain arbitrary expressions,
413/// we must linearize declarations to handle arbitrary control-flow induced by
414/// those expressions.
415CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000416 if (I == StmtIterator())
417 return Block;
418
Ted Kremenek79f0a632008-04-16 21:10:48 +0000419 Stmt* Terminator = *I;
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000420 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000421 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000422
423 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000424
Ted Kremenek79f0a632008-04-16 21:10:48 +0000425 switch (Terminator->getStmtClass()) {
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000426 case Stmt::IntegerLiteralClass:
427 case Stmt::CharacterLiteralClass:
428 case Stmt::StringLiteralClass:
429 break;
430
431 // All other cases.
432
433 default:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000434 Block = addStmt(Terminator);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000435 }
436
Ted Kremeneke822b622007-08-28 18:14:37 +0000437 return Block;
438}
439
Ted Kremenek65cfa562007-08-27 21:27:44 +0000440/// WalkAST_VisitChildren - Utility method to call WalkAST on the
441/// children of a Stmt.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000442CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000443 CFGBlock* B = Block;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000444 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000445 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000446 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000447
448 return B;
449}
450
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000451/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
452/// expressions (a GCC extension).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000453CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
454 Block->appendStmt(Terminator);
455 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000456}
457
Ted Kremenek73543912007-08-23 21:42:29 +0000458/// VisitStmt - Handle statements with no branching control flow.
459CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
460 // We cannot assume that we are in the middle of a basic block, since
461 // the CFG might only be constructed for this single statement. If
462 // we have no current basic block, just create one lazily.
463 if (!Block) Block = createBlock();
464
465 // Simply add the statement to the current block. We actually
466 // insert statements in reverse order; this order is reversed later
467 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000468 addStmt(Statement);
469
Ted Kremenek73543912007-08-23 21:42:29 +0000470 return Block;
471}
472
473CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
474 return Block;
475}
476
477CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000478
479 CFGBlock* LastBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000480
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000481 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
482 I != E; ++I ) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000483 LastBlock = Visit(*I);
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000484 }
485
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000486 return LastBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000487}
488
489CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
490 // We may see an if statement in the middle of a basic block, or
491 // it may be the first statement we are processing. In either case,
492 // we create a new basic block. First, we create the blocks for
493 // the then...else statements, and then we create the block containing
494 // the if statement. If we were in the middle of a block, we
495 // stop processing that block and reverse its statements. That block
496 // is then the implicit successor for the "then" and "else" clauses.
497
498 // The block we were proccessing is now finished. Make it the
499 // successor block.
500 if (Block) {
501 Succ = Block;
502 FinishBlock(Block);
503 }
504
505 // Process the false branch. NULL out Block so that the recursive
506 // call to Visit will create a new basic block.
507 // Null out Block so that all successor
508 CFGBlock* ElseBlock = Succ;
509
510 if (Stmt* Else = I->getElse()) {
511 SaveAndRestore<CFGBlock*> sv(Succ);
512
513 // NULL out Block so that the recursive call to Visit will
514 // create a new basic block.
515 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000516 ElseBlock = Visit(Else);
517
518 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
519 ElseBlock = sv.get();
520 else if (Block)
521 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000522 }
523
524 // Process the true branch. NULL out Block so that the recursive
525 // call to Visit will create a new basic block.
526 // Null out Block so that all successor
527 CFGBlock* ThenBlock;
528 {
529 Stmt* Then = I->getThen();
530 assert (Then);
531 SaveAndRestore<CFGBlock*> sv(Succ);
532 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000533 ThenBlock = Visit(Then);
534
535 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
536 ThenBlock = sv.get();
537 else if (Block)
538 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000539 }
540
541 // Now create a new block containing the if statement.
542 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000543
544 // Set the terminator of the new block to the If statement.
545 Block->setTerminator(I);
546
547 // Now add the successors.
548 Block->addSuccessor(ThenBlock);
549 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000550
551 // Add the condition as the last statement in the new block. This
552 // may create new blocks as the condition may contain control-flow. Any
553 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000554 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000555}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000556
Ted Kremenek73543912007-08-23 21:42:29 +0000557
558CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
559 // If we were in the middle of a block we stop processing that block
560 // and reverse its statements.
561 //
562 // NOTE: If a "return" appears in the middle of a block, this means
563 // that the code afterwards is DEAD (unreachable). We still
564 // keep a basic block for that code; a simple "mark-and-sweep"
565 // from the entry block will be able to report such dead
566 // blocks.
567 if (Block) FinishBlock(Block);
568
569 // Create the new block.
570 Block = createBlock(false);
571
572 // The Exit block is the only successor.
573 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000574
575 // Add the return statement to the block. This may create new blocks
576 // if R contains control-flow (short-circuit operations).
577 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000578}
579
580CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
581 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek82e8a192008-03-15 07:45:02 +0000582 Visit(L->getSubStmt());
583 CFGBlock* LabelBlock = Block;
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000584
585 if (!LabelBlock) // This can happen when the body is empty, i.e.
586 LabelBlock=createBlock(); // scopes that only contains NullStmts.
587
Ted Kremenek73543912007-08-23 21:42:29 +0000588 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
589 LabelMap[ L ] = LabelBlock;
590
591 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000592 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000593 // label (and we have already processed the substatement) there is no
594 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000595 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000596 FinishBlock(LabelBlock);
597
598 // We set Block to NULL to allow lazy creation of a new block
599 // (if necessary);
600 Block = NULL;
601
602 // This block is now the implicit successor of other blocks.
603 Succ = LabelBlock;
604
605 return LabelBlock;
606}
607
608CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
609 // Goto is a control-flow statement. Thus we stop processing the
610 // current block and create a new one.
611 if (Block) FinishBlock(Block);
612 Block = createBlock(false);
613 Block->setTerminator(G);
614
615 // If we already know the mapping to the label block add the
616 // successor now.
617 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
618
619 if (I == LabelMap.end())
620 // We will need to backpatch this block later.
621 BackpatchBlocks.push_back(Block);
622 else
623 Block->addSuccessor(I->second);
624
625 return Block;
626}
627
628CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
629 // "for" is a control-flow statement. Thus we stop processing the
630 // current block.
631
632 CFGBlock* LoopSuccessor = NULL;
633
634 if (Block) {
635 FinishBlock(Block);
636 LoopSuccessor = Block;
637 }
638 else LoopSuccessor = Succ;
639
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000640 // Because of short-circuit evaluation, the condition of the loop
641 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
642 // blocks that evaluate the condition.
643 CFGBlock* ExitConditionBlock = createBlock(false);
644 CFGBlock* EntryConditionBlock = ExitConditionBlock;
645
646 // Set the terminator for the "exit" condition block.
647 ExitConditionBlock->setTerminator(F);
648
649 // Now add the actual condition to the condition block. Because the
650 // condition itself may contain control-flow, new blocks may be created.
651 if (Stmt* C = F->getCond()) {
652 Block = ExitConditionBlock;
653 EntryConditionBlock = addStmt(C);
654 if (Block) FinishBlock(EntryConditionBlock);
655 }
Ted Kremenek73543912007-08-23 21:42:29 +0000656
657 // The condition block is the implicit successor for the loop body as
658 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000659 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000660
661 // Now create the loop body.
662 {
663 assert (F->getBody());
664
665 // Save the current values for Block, Succ, and continue and break targets
666 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
667 save_continue(ContinueTargetBlock),
668 save_break(BreakTargetBlock);
669
670 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000671 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000672
673 // All breaks should go to the code following the loop.
674 BreakTargetBlock = LoopSuccessor;
675
Ted Kremenek390b9762007-08-30 18:39:40 +0000676 // Create a new block to contain the (bottom) of the loop body.
677 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000678
679 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000680 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000681
682 // Now populate the body block, and in the process create new blocks
683 // as we walk the body of the loop.
684 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000685
686 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000687 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000688 else if (Block)
689 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000690
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000691 // This new body block is a successor to our "exit" condition block.
692 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000693 }
694
695 // Link up the condition block with the code that follows the loop.
696 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000697 ExitConditionBlock->addSuccessor(LoopSuccessor);
698
Ted Kremenek73543912007-08-23 21:42:29 +0000699 // If the loop contains initialization, create a new block for those
700 // statements. This block can also contain statements that precede
701 // the loop.
702 if (Stmt* I = F->getInit()) {
703 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000704 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000705 }
706 else {
707 // There is no loop initialization. We are thus basically a while
708 // loop. NULL out Block to force lazy block construction.
709 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000710 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000711 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000712 }
713}
714
715CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
716 // "while" is a control-flow statement. Thus we stop processing the
717 // current block.
718
719 CFGBlock* LoopSuccessor = NULL;
720
721 if (Block) {
722 FinishBlock(Block);
723 LoopSuccessor = Block;
724 }
725 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000726
727 // Because of short-circuit evaluation, the condition of the loop
728 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
729 // blocks that evaluate the condition.
730 CFGBlock* ExitConditionBlock = createBlock(false);
731 CFGBlock* EntryConditionBlock = ExitConditionBlock;
732
733 // Set the terminator for the "exit" condition block.
734 ExitConditionBlock->setTerminator(W);
735
736 // Now add the actual condition to the condition block. Because the
737 // condition itself may contain control-flow, new blocks may be created.
738 // Thus we update "Succ" after adding the condition.
739 if (Stmt* C = W->getCond()) {
740 Block = ExitConditionBlock;
741 EntryConditionBlock = addStmt(C);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000742 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000743 if (Block) FinishBlock(EntryConditionBlock);
744 }
Ted Kremenek73543912007-08-23 21:42:29 +0000745
746 // The condition block is the implicit successor for the loop body as
747 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000748 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000749
750 // Process the loop body.
751 {
752 assert (W->getBody());
753
754 // Save the current values for Block, Succ, and continue and break targets
755 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
756 save_continue(ContinueTargetBlock),
757 save_break(BreakTargetBlock);
758
759 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000760 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000761
762 // All breaks should go to the code following the loop.
763 BreakTargetBlock = LoopSuccessor;
764
765 // NULL out Block to force lazy instantiation of blocks for the body.
766 Block = NULL;
767
768 // Create the body. The returned block is the entry to the loop body.
769 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000770
771 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000772 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000773 else if (Block)
774 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000775
776 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000777 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000778 }
779
780 // Link up the condition block with the code that follows the loop.
781 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000782 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000783
784 // There can be no more statements in the condition block
785 // since we loop back to this block. NULL out Block to force
786 // lazy creation of another block.
787 Block = NULL;
788
789 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000790 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000791 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000792}
793
794CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
795 // "do...while" is a control-flow statement. Thus we stop processing the
796 // current block.
797
798 CFGBlock* LoopSuccessor = NULL;
799
800 if (Block) {
801 FinishBlock(Block);
802 LoopSuccessor = Block;
803 }
804 else LoopSuccessor = Succ;
805
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000806 // Because of short-circuit evaluation, the condition of the loop
807 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
808 // blocks that evaluate the condition.
809 CFGBlock* ExitConditionBlock = createBlock(false);
810 CFGBlock* EntryConditionBlock = ExitConditionBlock;
811
812 // Set the terminator for the "exit" condition block.
813 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000814
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000815 // Now add the actual condition to the condition block. Because the
816 // condition itself may contain control-flow, new blocks may be created.
817 if (Stmt* C = D->getCond()) {
818 Block = ExitConditionBlock;
819 EntryConditionBlock = addStmt(C);
820 if (Block) FinishBlock(EntryConditionBlock);
821 }
Ted Kremenek73543912007-08-23 21:42:29 +0000822
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000823 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000824 Succ = EntryConditionBlock;
825
Ted Kremenek73543912007-08-23 21:42:29 +0000826 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000827 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000828 {
829 assert (D->getBody());
830
831 // Save the current values for Block, Succ, and continue and break targets
832 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
833 save_continue(ContinueTargetBlock),
834 save_break(BreakTargetBlock);
835
836 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000837 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000838
839 // All breaks should go to the code following the loop.
840 BreakTargetBlock = LoopSuccessor;
841
842 // NULL out Block to force lazy instantiation of blocks for the body.
843 Block = NULL;
844
845 // Create the body. The returned block is the entry to the loop body.
846 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000847
Ted Kremenek390b9762007-08-30 18:39:40 +0000848 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000849 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000850 else if (Block)
851 FinishBlock(BodyBlock);
852
Ted Kremenek73543912007-08-23 21:42:29 +0000853 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000854 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000855 }
856
857 // Link up the condition block with the code that follows the loop.
858 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000859 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000860
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000861 // There can be no more statements in the body block(s)
862 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000863 // lazy creation of another block.
864 Block = NULL;
865
866 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000867 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000868 return BodyBlock;
869}
870
871CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
872 // "continue" is a control-flow statement. Thus we stop processing the
873 // current block.
874 if (Block) FinishBlock(Block);
875
876 // Now create a new block that ends with the continue statement.
877 Block = createBlock(false);
878 Block->setTerminator(C);
879
880 // If there is no target for the continue, then we are looking at an
881 // incomplete AST. Handle this by not registering a successor.
882 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
883
884 return Block;
885}
886
887CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
888 // "break" is a control-flow statement. Thus we stop processing the
889 // current block.
890 if (Block) FinishBlock(Block);
891
892 // Now create a new block that ends with the continue statement.
893 Block = createBlock(false);
894 Block->setTerminator(B);
895
896 // If there is no target for the break, then we are looking at an
897 // incomplete AST. Handle this by not registering a successor.
898 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
899
900 return Block;
901}
902
Ted Kremenek79f0a632008-04-16 21:10:48 +0000903CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek73543912007-08-23 21:42:29 +0000904 // "switch" is a control-flow statement. Thus we stop processing the
905 // current block.
906 CFGBlock* SwitchSuccessor = NULL;
907
908 if (Block) {
909 FinishBlock(Block);
910 SwitchSuccessor = Block;
911 }
912 else SwitchSuccessor = Succ;
913
914 // Save the current "switch" context.
915 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000916 save_break(BreakTargetBlock),
917 save_default(DefaultCaseBlock);
918
919 // Set the "default" case to be the block after the switch statement.
920 // If the switch statement contains a "default:", this value will
921 // be overwritten with the block for that code.
922 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000923
Ted Kremenek73543912007-08-23 21:42:29 +0000924 // Create a new block that will contain the switch statement.
925 SwitchTerminatedBlock = createBlock(false);
926
Ted Kremenek73543912007-08-23 21:42:29 +0000927 // Now process the switch body. The code after the switch is the implicit
928 // successor.
929 Succ = SwitchSuccessor;
930 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000931
932 // When visiting the body, the case statements should automatically get
933 // linked up to the switch. We also don't keep a pointer to the body,
934 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000935 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000936 Block = NULL;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000937 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000938 if (Block) FinishBlock(BodyBlock);
939
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000940 // If we have no "default:" case, the default transition is to the
941 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000942 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000943
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000944 // Add the terminator and condition in the switch block.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000945 SwitchTerminatedBlock->setTerminator(Terminator);
946 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000947 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000948
Ted Kremenek79f0a632008-04-16 21:10:48 +0000949 return addStmt(Terminator->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000950}
951
Ted Kremenek79f0a632008-04-16 21:10:48 +0000952CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenek97bc3422008-02-13 22:05:39 +0000953 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +0000954 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000955
Ted Kremenek79f0a632008-04-16 21:10:48 +0000956 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek44659d82007-08-30 18:48:11 +0000957 CFGBlock* CaseBlock = Block;
958 if (!CaseBlock) CaseBlock = createBlock();
959
Ted Kremenek97bc3422008-02-13 22:05:39 +0000960 // Cases statements partition blocks, so this is the top of
961 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000962 CaseBlock->setLabel(Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +0000963 FinishBlock(CaseBlock);
964
965 // Add this block to the list of successors for the block with the
966 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000967 assert (SwitchTerminatedBlock);
968 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000969
970 // We set Block to NULL to allow lazy creation of a new block (if necessary)
971 Block = NULL;
972
973 // This block is now the implicit successor of other blocks.
974 Succ = CaseBlock;
975
Ted Kremenek82e8a192008-03-15 07:45:02 +0000976 return CaseBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000977}
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000978
Ted Kremenek79f0a632008-04-16 21:10:48 +0000979CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
980 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek97bc3422008-02-13 22:05:39 +0000981 DefaultCaseBlock = Block;
982 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
983
984 // Default statements partition blocks, so this is the top of
985 // the basic block we were processing (the "default:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000986 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek97bc3422008-02-13 22:05:39 +0000987 FinishBlock(DefaultCaseBlock);
988
989 // Unlike case statements, we don't add the default block to the
990 // successors for the switch statement immediately. This is done
991 // when we finish processing the switch statement. This allows for
992 // the default case (including a fall-through to the code after the
993 // switch statement) to always be the last successor of a switch-terminated
994 // block.
995
996 // We set Block to NULL to allow lazy creation of a new block (if necessary)
997 Block = NULL;
998
999 // This block is now the implicit successor of other blocks.
1000 Succ = DefaultCaseBlock;
1001
1002 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001003}
Ted Kremenek73543912007-08-23 21:42:29 +00001004
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001005CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1006 // Lazily create the indirect-goto dispatch block if there isn't one
1007 // already.
1008 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1009
1010 if (!IBlock) {
1011 IBlock = createBlock(false);
1012 cfg->setIndirectGotoBlock(IBlock);
1013 }
1014
1015 // IndirectGoto is a control-flow statement. Thus we stop processing the
1016 // current block and create a new one.
1017 if (Block) FinishBlock(Block);
1018 Block = createBlock(false);
1019 Block->setTerminator(I);
1020 Block->addSuccessor(IBlock);
1021 return addStmt(I->getTarget());
1022}
1023
Ted Kremenek73543912007-08-23 21:42:29 +00001024
Ted Kremenekd6e50602007-08-23 21:26:19 +00001025} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +00001026
1027/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1028/// block has no successors or predecessors. If this is the first block
1029/// created in the CFG, it is automatically set to be the Entry and Exit
1030/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001031CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001032 bool first_block = begin() == end();
1033
1034 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001035 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001036
1037 // If this is the first block, set it as the Entry and Exit.
1038 if (first_block) Entry = Exit = &front();
1039
1040 // Return the block.
1041 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001042}
1043
Ted Kremenek4db5b452007-08-23 16:51:22 +00001044/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1045/// CFG is returned to the caller.
1046CFG* CFG::buildCFG(Stmt* Statement) {
1047 CFGBuilder Builder;
1048 return Builder.buildCFG(Statement);
1049}
1050
1051/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001052void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1053
Ted Kremenek3a819822007-10-01 19:33:33 +00001054//===----------------------------------------------------------------------===//
1055// CFG: Queries for BlkExprs.
1056//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001057
Ted Kremenek3a819822007-10-01 19:33:33 +00001058namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001059 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001060}
1061
Ted Kremenek79f0a632008-04-16 21:10:48 +00001062static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1063 if (!Terminator)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001064 return;
1065
Ted Kremenek79f0a632008-04-16 21:10:48 +00001066 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001067 if (!*I) continue;
1068
1069 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1070 if (B->isAssignmentOp()) Set.insert(B);
1071
1072 FindSubExprAssignments(*I, Set);
1073 }
1074}
1075
Ted Kremenek3a819822007-10-01 19:33:33 +00001076static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1077 BlkExprMapTy* M = new BlkExprMapTy();
1078
Ted Kremenekc6fda602008-01-26 00:03:27 +00001079 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek79f0a632008-04-16 21:10:48 +00001080 // only assignments that we want to *possibly* register as a block-level
1081 // expression. Basically, if an assignment occurs both in a subexpression
1082 // and at the block-level, it is a block-level expression.
Ted Kremenekc6fda602008-01-26 00:03:27 +00001083 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1084
Ted Kremenek3a819822007-10-01 19:33:33 +00001085 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1086 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001087 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001088
Ted Kremenek79f0a632008-04-16 21:10:48 +00001089 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1090
1091 // Iterate over the statements again on identify the Expr* and Stmt* at
1092 // the block-level that are block-level expressions.
1093
Ted Kremenekc6fda602008-01-26 00:03:27 +00001094 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek79f0a632008-04-16 21:10:48 +00001095 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001096
Ted Kremenek79f0a632008-04-16 21:10:48 +00001097 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001098 // Assignment expressions that are not nested within another
1099 // expression are really "statements" whose value is never
1100 // used by another expression.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001101 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenekc6fda602008-01-26 00:03:27 +00001102 continue;
1103 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001104 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001105 // Special handling for statement expressions. The last statement
1106 // in the statement expression is also a block-level expr.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001107 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001108 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001109 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001110 (*M)[C->body_back()] = x;
1111 }
1112 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001113
Ted Kremenekc6fda602008-01-26 00:03:27 +00001114 unsigned x = M->size();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001115 (*M)[Exp] = x;
Ted Kremenekc6fda602008-01-26 00:03:27 +00001116 }
1117
Ted Kremenek79f0a632008-04-16 21:10:48 +00001118 // Look at terminators. The condition is a block-level expression.
1119
1120 Expr* Exp = I->getTerminatorCondition();
1121
1122 if (Exp && M->find(Exp) == M->end()) {
1123 unsigned x = M->size();
1124 (*M)[Exp] = x;
1125 }
1126 }
1127
Ted Kremenek3a819822007-10-01 19:33:33 +00001128 return M;
1129}
1130
Ted Kremenekab6c5902008-01-17 20:48:37 +00001131CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1132 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001133 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1134
1135 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001136 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001137
1138 if (I == M->end()) return CFG::BlkExprNumTy();
1139 else return CFG::BlkExprNumTy(I->second);
1140}
1141
1142unsigned CFG::getNumBlkExprs() {
1143 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1144 return M->size();
1145 else {
1146 // We assume callers interested in the number of BlkExprs will want
1147 // the map constructed if it doesn't already exist.
1148 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1149 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1150 }
1151}
1152
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001153typedef std::set<std::pair<CFGBlock*,CFGBlock*> > BlkEdgeSetTy;
1154
1155const std::pair<CFGBlock*,CFGBlock*>*
1156CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1157
1158 BlkEdgeSetTy*& p = reinterpret_cast<BlkEdgeSetTy*&>(BlkEdgeSet);
1159 if (!p) p = new BlkEdgeSetTy();
1160
1161 return &*(p->insert(std::make_pair(const_cast<CFGBlock*>(B1),
1162 const_cast<CFGBlock*>(B2))).first);
1163}
1164
Ted Kremenek3a819822007-10-01 19:33:33 +00001165CFG::~CFG() {
1166 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001167 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001168}
1169
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001170//===----------------------------------------------------------------------===//
1171// CFG pretty printing
1172//===----------------------------------------------------------------------===//
1173
Ted Kremenekd8313202007-08-22 18:22:34 +00001174namespace {
1175
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001176class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001177
Ted Kremenek08176a52007-08-31 21:30:12 +00001178 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1179 StmtMapTy StmtMap;
1180 signed CurrentBlock;
1181 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001182
Ted Kremenek73543912007-08-23 21:42:29 +00001183public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001184
Ted Kremenek08176a52007-08-31 21:30:12 +00001185 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1186 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1187 unsigned j = 1;
1188 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1189 BI != BEnd; ++BI, ++j )
1190 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1191 }
1192 }
1193
1194 virtual ~StmtPrinterHelper() {}
1195
1196 void setBlockID(signed i) { CurrentBlock = i; }
1197 void setStmtID(unsigned i) { CurrentStmt = i; }
1198
Ted Kremenek79f0a632008-04-16 21:10:48 +00001199 virtual bool handledStmt(Stmt* Terminator, std::ostream& OS) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001200
Ted Kremenek79f0a632008-04-16 21:10:48 +00001201 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek08176a52007-08-31 21:30:12 +00001202
1203 if (I == StmtMap.end())
1204 return false;
1205
1206 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1207 && I->second.second == CurrentStmt)
1208 return false;
1209
Ted Kremenek86afc042007-08-31 22:26:13 +00001210 OS << "[B" << I->second.first << "." << I->second.second << "]";
1211 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001212 }
1213};
1214
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001215class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1216 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1217
Ted Kremenek08176a52007-08-31 21:30:12 +00001218 std::ostream& OS;
1219 StmtPrinterHelper* Helper;
1220public:
1221 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1222 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001223
1224 void VisitIfStmt(IfStmt* I) {
1225 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001226 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001227 }
1228
1229 // Default case.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001230 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001231
1232 void VisitForStmt(ForStmt* F) {
1233 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001234 if (F->getInit()) OS << "...";
1235 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001236 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001237 OS << "; ";
1238 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001239 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001240 }
1241
1242 void VisitWhileStmt(WhileStmt* W) {
1243 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001244 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001245 }
1246
1247 void VisitDoStmt(DoStmt* D) {
1248 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001249 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001250 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001251
Ted Kremenek79f0a632008-04-16 21:10:48 +00001252 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +00001253 OS << "switch ";
Ted Kremenek79f0a632008-04-16 21:10:48 +00001254 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001255 }
1256
Ted Kremenek621e1592007-08-31 21:49:40 +00001257 void VisitConditionalOperator(ConditionalOperator* C) {
1258 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001259 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001260 }
1261
Ted Kremenek2025cc92007-08-31 22:29:13 +00001262 void VisitChooseExpr(ChooseExpr* C) {
1263 OS << "__builtin_choose_expr( ";
1264 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001265 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001266 }
1267
Ted Kremenek86afc042007-08-31 22:26:13 +00001268 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1269 OS << "goto *";
1270 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001271 }
1272
Ted Kremenek621e1592007-08-31 21:49:40 +00001273 void VisitBinaryOperator(BinaryOperator* B) {
1274 if (!B->isLogicalOp()) {
1275 VisitExpr(B);
1276 return;
1277 }
1278
1279 B->getLHS()->printPretty(OS,Helper);
1280
1281 switch (B->getOpcode()) {
1282 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001283 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001284 return;
1285 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001286 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001287 return;
1288 default:
1289 assert(false && "Invalid logical operator.");
1290 }
1291 }
1292
Ted Kremenekcfaae762007-08-27 21:54:41 +00001293 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001294 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001295 }
Ted Kremenek73543912007-08-23 21:42:29 +00001296};
Ted Kremenek08176a52007-08-31 21:30:12 +00001297
1298
Ted Kremenek79f0a632008-04-16 21:10:48 +00001299void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001300 if (Helper) {
1301 // special printing for statement-expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001302 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001303 CompoundStmt* Sub = SE->getSubStmt();
1304
1305 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001306 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001307 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001308 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001309 return;
1310 }
1311 }
1312
1313 // special printing for comma expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001314 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001315 if (B->getOpcode() == BinaryOperator::Comma) {
1316 OS << "... , ";
1317 Helper->handledStmt(B->getRHS(),OS);
1318 OS << '\n';
1319 return;
1320 }
1321 }
1322 }
1323
Ted Kremenek79f0a632008-04-16 21:10:48 +00001324 Terminator->printPretty(OS, Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001325
1326 // Expressions need a newline.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001327 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek86afc042007-08-31 22:26:13 +00001328}
1329
Ted Kremenek08176a52007-08-31 21:30:12 +00001330void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1331 StmtPrinterHelper* Helper, bool print_edges) {
1332
1333 if (Helper) Helper->setBlockID(B.getBlockID());
1334
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001335 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001336 OS << "\n [ B" << B.getBlockID();
1337
1338 if (&B == &cfg->getEntry())
1339 OS << " (ENTRY) ]\n";
1340 else if (&B == &cfg->getExit())
1341 OS << " (EXIT) ]\n";
1342 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001343 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001344 else
1345 OS << " ]\n";
1346
Ted Kremenekec055e12007-08-29 23:20:49 +00001347 // Print the label of this block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001348 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001349
1350 if (print_edges)
1351 OS << " ";
1352
Ted Kremenek79f0a632008-04-16 21:10:48 +00001353 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001354 OS << L->getName();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001355 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001356 OS << "case ";
1357 C->getLHS()->printPretty(OS);
1358 if (C->getRHS()) {
1359 OS << " ... ";
1360 C->getRHS()->printPretty(OS);
1361 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001362 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001363 else if (isa<DefaultStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001364 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001365 else
1366 assert(false && "Invalid label statement in CFGBlock.");
1367
Ted Kremenekec055e12007-08-29 23:20:49 +00001368 OS << ":\n";
1369 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001370
Ted Kremenek97f75312007-08-21 21:42:03 +00001371 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001372 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001373
1374 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1375 I != E ; ++I, ++j ) {
1376
Ted Kremenekec055e12007-08-29 23:20:49 +00001377 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001378 if (print_edges)
1379 OS << " ";
1380
1381 OS << std::setw(3) << j << ": ";
1382
1383 if (Helper)
1384 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001385
1386 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001387 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001388
Ted Kremenekec055e12007-08-29 23:20:49 +00001389 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001390 if (B.getTerminator()) {
1391 if (print_edges)
1392 OS << " ";
1393
Ted Kremenekec055e12007-08-29 23:20:49 +00001394 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001395
1396 if (Helper) Helper->setBlockID(-1);
1397
1398 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1399 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001400 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001401 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001402
Ted Kremenekec055e12007-08-29 23:20:49 +00001403 if (print_edges) {
1404 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001405 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001406 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001407
Ted Kremenek08176a52007-08-31 21:30:12 +00001408 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1409 I != E; ++I, ++i) {
1410
1411 if (i == 8 || (i-8) == 0)
1412 OS << "\n ";
1413
Ted Kremenekec055e12007-08-29 23:20:49 +00001414 OS << " B" << (*I)->getBlockID();
1415 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001416
1417 OS << '\n';
1418
1419 // Print the successors of this block.
1420 OS << " Successors (" << B.succ_size() << "):";
1421 i = 0;
1422
1423 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1424 I != E; ++I, ++i) {
1425
1426 if (i == 8 || (i-8) % 10 == 0)
1427 OS << "\n ";
1428
1429 OS << " B" << (*I)->getBlockID();
1430 }
1431
Ted Kremenekec055e12007-08-29 23:20:49 +00001432 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001433 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001434}
1435
1436} // end anonymous namespace
1437
1438/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001439void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001440
1441/// print - A simple pretty printer of a CFG that outputs to an ostream.
1442void CFG::print(std::ostream& OS) const {
1443
1444 StmtPrinterHelper Helper(this);
1445
1446 // Print the entry block.
1447 print_block(OS, this, getEntry(), &Helper, true);
1448
1449 // Iterate through the CFGBlocks and print them one by one.
1450 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1451 // Skip the entry block, because we already printed it.
1452 if (&(*I) == &getEntry() || &(*I) == &getExit())
1453 continue;
1454
1455 print_block(OS, this, *I, &Helper, true);
1456 }
1457
1458 // Print the exit block.
1459 print_block(OS, this, getExit(), &Helper, true);
1460}
1461
1462/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001463void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001464
1465/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1466/// Generally this will only be called from CFG::print.
1467void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1468 StmtPrinterHelper Helper(cfg);
1469 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001470}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001471
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001472/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1473void CFGBlock::printTerminator(std::ostream& OS) const {
1474 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1475 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1476}
1477
Ted Kremenek79f0a632008-04-16 21:10:48 +00001478Expr* CFGBlock::getTerminatorCondition() {
1479
1480 if (!Terminator)
1481 return NULL;
1482
1483 Expr* E = NULL;
1484
1485 switch (Terminator->getStmtClass()) {
1486 default:
1487 break;
1488
1489 case Stmt::ForStmtClass:
1490 E = cast<ForStmt>(Terminator)->getCond();
1491 break;
1492
1493 case Stmt::WhileStmtClass:
1494 E = cast<WhileStmt>(Terminator)->getCond();
1495 break;
1496
1497 case Stmt::DoStmtClass:
1498 E = cast<DoStmt>(Terminator)->getCond();
1499 break;
1500
1501 case Stmt::IfStmtClass:
1502 E = cast<IfStmt>(Terminator)->getCond();
1503 break;
1504
1505 case Stmt::ChooseExprClass:
1506 E = cast<ChooseExpr>(Terminator)->getCond();
1507 break;
1508
1509 case Stmt::IndirectGotoStmtClass:
1510 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1511 break;
1512
1513 case Stmt::SwitchStmtClass:
1514 E = cast<SwitchStmt>(Terminator)->getCond();
1515 break;
1516
1517 case Stmt::ConditionalOperatorClass:
1518 E = cast<ConditionalOperator>(Terminator)->getCond();
1519 break;
1520
1521 case Stmt::BinaryOperatorClass: // '&&' and '||'
1522 E = cast<BinaryOperator>(Terminator)->getLHS();
1523 break;
1524 }
1525
1526 return E ? E->IgnoreParens() : NULL;
1527}
1528
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001529
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001530//===----------------------------------------------------------------------===//
1531// CFG Graphviz Visualization
1532//===----------------------------------------------------------------------===//
1533
Ted Kremenek08176a52007-08-31 21:30:12 +00001534
1535#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001536static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001537#endif
1538
1539void CFG::viewCFG() const {
1540#ifndef NDEBUG
1541 StmtPrinterHelper H(this);
1542 GraphHelper = &H;
1543 llvm::ViewGraph(this,"CFG");
1544 GraphHelper = NULL;
1545#else
1546 std::cerr << "CFG::viewCFG is only available in debug builds on "
Hartmut Kaiser284bff92007-09-17 12:29:55 +00001547 << "systems with Graphviz or gv!\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001548#endif
1549}
1550
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001551namespace llvm {
1552template<>
1553struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1554 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1555
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001556#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001557 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001558 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001559 std::string OutStr = Out.str();
1560
1561 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1562
1563 // Process string output to make it nicer...
1564 for (unsigned i = 0; i != OutStr.length(); ++i)
1565 if (OutStr[i] == '\n') { // Left justify
1566 OutStr[i] = '\\';
1567 OutStr.insert(OutStr.begin()+i+1, 'l');
1568 }
1569
1570 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001571#else
1572 return "";
1573#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001574 }
1575};
1576} // end namespace llvm