blob: 0313ada82c50bfd44636fbd5220fa6303ab39c01 [file] [log] [blame]
Ted Kremenekfddd5182007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Kremenekfddd5182007-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"
Ted Kremenekc310e932007-08-21 22:06:14 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000017#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000021#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000022#include "llvm/Support/Compiler.h"
Ted Kremenek274f4332008-04-28 18:00:46 +000023#include <llvm/Support/Allocator.h>
Ted Kremeneka95d3752008-09-13 05:16:45 +000024#include <llvm/Support/Format.h>
Ted Kremenekfddd5182007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000027#include <sstream>
Ted Kremenek83c01da2008-01-11 00:40:29 +000028
Ted Kremenekfddd5182007-08-21 21:42:03 +000029using namespace clang;
30
31namespace {
32
Ted Kremenekbefef2f2007-08-23 21:26:19 +000033// SaveAndRestore - A utility class that uses RIIA to save and restore
34// the value of a variable.
35template<typename T>
Ted Kremenek6fa9b882008-01-08 18:15:10 +000036struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekbefef2f2007-08-23 21:26:19 +000037 SaveAndRestore(T& x) : X(x), old_value(x) {}
38 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000039 T get() { return old_value; }
40
Ted Kremenekbefef2f2007-08-23 21:26:19 +000041 T& X;
42 T old_value;
43};
Ted Kremenekfddd5182007-08-21 21:42:03 +000044
Ted Kremenekc7eb9032008-08-06 23:20:50 +000045static SourceLocation GetEndLoc(ScopedDecl* D) {
46 if (VarDecl* VD = dyn_cast<VarDecl>(D))
47 if (Expr* Ex = VD->getInit())
48 return Ex->getSourceRange().getEnd();
49
50 return D->getLocation();
51}
52
53class VISIBILITY_HIDDEN UnaryDeclStmt : public DeclStmt {
54 Stmt* Ex;
55public:
56 UnaryDeclStmt(ScopedDecl* D)
57 : DeclStmt(D, D->getLocation(), GetEndLoc(D)), Ex(0) {
58 if (VarDecl* VD = dyn_cast<VarDecl>(D))
59 Ex = VD->getInit();
60 }
61
62 virtual ~UnaryDeclStmt() {}
63 virtual void Destroy(ASTContext& Ctx) { assert(false && "Do not call"); }
64
65 virtual child_iterator child_begin() {
66 return Ex ? &Ex : 0;
67 }
68 virtual child_iterator child_end() {
69 return Ex ? &Ex + 1 : 0;
70 }
71 virtual decl_iterator decl_begin() {
72 return getDecl();
73 }
74 virtual decl_iterator decl_end() {
75 ScopedDecl* D = getDecl();
76 return D ? D->getNextDeclarator() : 0;
77 }
78};
79
Ted Kremeneka34ea072008-08-04 22:51:42 +000080/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenekfddd5182007-08-21 21:42:03 +000081/// The builder is stateful: an instance of the builder should be used to only
82/// construct a single CFG.
83///
84/// Example usage:
85///
86/// CFGBuilder builder;
87/// CFG* cfg = builder.BuildAST(stmt1);
88///
Ted Kremenekc310e932007-08-21 22:06:14 +000089/// CFG construction is done via a recursive walk of an AST.
90/// We actually parse the AST in reverse order so that the successor
91/// of a basic block is constructed prior to its predecessor. This
92/// allows us to nicely capture implicit fall-throughs without extra
93/// basic blocks.
94///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000095class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000096 CFG* cfg;
97 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000098 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000099 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +0000100 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +0000101 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000102 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000103
Ted Kremenek19bb3562007-08-28 19:26:49 +0000104 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +0000105 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
106 LabelMapTy LabelMap;
107
Ted Kremenek19bb3562007-08-28 19:26:49 +0000108 // A list of blocks that end with a "goto" that must be backpatched to
109 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +0000110 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +0000111 BackpatchBlocksTy BackpatchBlocks;
112
Ted Kremenek19bb3562007-08-28 19:26:49 +0000113 // A list of labels whose address has been taken (for indirect gotos).
114 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
115 LabelSetTy AddressTakenLabels;
116
Ted Kremenekfddd5182007-08-21 21:42:03 +0000117public:
Ted Kremenek026473c2007-08-23 16:51:22 +0000118 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +0000119 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000120 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +0000121 // Create an empty CFG.
122 cfg = new CFG();
123 }
124
125 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +0000126
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000127 // buildCFG - Used by external clients to construct the CFG.
128 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +0000129
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000130 // Visitors to walk an AST and construct the CFG. Called by
131 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000132
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000133 CFGBlock* VisitStmt(Stmt* Statement);
134 CFGBlock* VisitNullStmt(NullStmt* Statement);
135 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
136 CFGBlock* VisitIfStmt(IfStmt* I);
137 CFGBlock* VisitReturnStmt(ReturnStmt* R);
138 CFGBlock* VisitLabelStmt(LabelStmt* L);
139 CFGBlock* VisitGotoStmt(GotoStmt* G);
140 CFGBlock* VisitForStmt(ForStmt* F);
141 CFGBlock* VisitWhileStmt(WhileStmt* W);
142 CFGBlock* VisitDoStmt(DoStmt* D);
143 CFGBlock* VisitContinueStmt(ContinueStmt* C);
144 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000145 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
146 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek295222c2008-02-13 21:46:34 +0000147 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000148 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000149
Ted Kremenek4102af92008-03-13 03:04:22 +0000150 // FIXME: Add support for ObjC-specific control-flow structures.
151
Ted Kremenek274f4332008-04-28 18:00:46 +0000152 // NYS == Not Yet Supported
153 CFGBlock* NYS() {
Ted Kremenek4102af92008-03-13 03:04:22 +0000154 badCFG = true;
155 return Block;
156 }
157
Ted Kremenek274f4332008-04-28 18:00:46 +0000158 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
159 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
160 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
161 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
162 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
163
164 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
165 return NYS();
Ted Kremenek4102af92008-03-13 03:04:22 +0000166 }
167
Ted Kremenek00c0a302008-09-26 18:17:07 +0000168 // Blocks.
169 CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); }
170 CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); }
171
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000172private:
173 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000174 CFGBlock* addStmt(Stmt* Terminator);
175 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
176 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000177 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000178 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000179 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000180
Ted Kremenek4102af92008-03-13 03:04:22 +0000181 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000182};
Ted Kremenek610a09e2008-09-26 22:58:57 +0000183
184static VariableArrayType* FindVA(Type* t) {
185 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
186 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
187 if (vat->getSizeExpr())
188 return vat;
189
190 t = vt->getElementType().getTypePtr();
191 }
192
193 return 0;
194}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000195
196/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
197/// represent an arbitrary statement. Examples include a single expression
198/// or a function body (compound statement). The ownership of the returned
199/// CFG is transferred to the caller. If CFG construction fails, this method
200/// returns NULL.
201CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000202 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203 if (!Statement) return NULL;
204
Ted Kremenek4102af92008-03-13 03:04:22 +0000205 badCFG = false;
206
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000207 // Create an empty block that will serve as the exit block for the CFG.
208 // Since this is the first block added to the CFG, it will be implicitly
209 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000210 Succ = createBlock();
211 assert (Succ == &cfg->getExit());
212 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000213
214 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000215 CFGBlock* B = Visit(Statement);
216 if (!B) B = Succ;
217
218 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000219 // Finalize the last constructed block. This usually involves
220 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000221 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000222
223 // Backpatch the gotos whose label -> block mappings we didn't know
224 // when we encountered them.
225 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
226 E = BackpatchBlocks.end(); I != E; ++I ) {
227
228 CFGBlock* B = *I;
229 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
230 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
231
232 // If there is no target for the goto, then we are looking at an
233 // incomplete AST. Handle this by not registering a successor.
234 if (LI == LabelMap.end()) continue;
235
236 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000237 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000238
Ted Kremenek19bb3562007-08-28 19:26:49 +0000239 // Add successors to the Indirect Goto Dispatch block (if we have one).
240 if (CFGBlock* B = cfg->getIndirectGotoBlock())
241 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
242 E = AddressTakenLabels.end(); I != E; ++I ) {
243
244 // Lookup the target block.
245 LabelMapTy::iterator LI = LabelMap.find(*I);
246
247 // If there is no target block that contains label, then we are looking
248 // at an incomplete AST. Handle this by not registering a successor.
249 if (LI == LabelMap.end()) continue;
250
251 B->addSuccessor(LI->second);
252 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000253
Ted Kremenek94b33162007-09-17 16:18:02 +0000254 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000255 }
256
257 // Create an empty entry block that has no predecessors.
258 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000259
Ted Kremenek4102af92008-03-13 03:04:22 +0000260 if (badCFG) {
261 delete cfg;
262 cfg = NULL;
263 return NULL;
264 }
265
Ted Kremenek322f58d2007-09-26 21:23:31 +0000266 // NULL out cfg so that repeated calls to the builder will fail and that
267 // the ownership of the constructed CFG is passed to the caller.
268 CFG* t = cfg;
269 cfg = NULL;
270 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000271}
272
273/// createBlock - Used to lazily create blocks that are connected
274/// to the current (global) succcessor.
275CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000276 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000277 if (add_successor && Succ) B->addSuccessor(Succ);
278 return B;
279}
280
281/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000282/// we must reverse the statements because they have been inserted
283/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000284void CFGBuilder::FinishBlock(CFGBlock* B) {
285 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000286 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000287}
288
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000289/// addStmt - Used to add statements/expressions to the current CFGBlock
290/// "Block". This method calls WalkAST on the passed statement to see if it
291/// contains any short-circuit expressions. If so, it recursively creates
292/// the necessary blocks for such expressions. It returns the "topmost" block
293/// of the created blocks, or the original value of "Block" when this method
294/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000295CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000296 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000297 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000298}
299
300/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000301/// add extra blocks for ternary operators, &&, and ||. We also
302/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000303CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
304 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000305 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000306 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000307
308 // Create the confluence block that will "merge" the results
309 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000310 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
311 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000312 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000313
314 // Create a block for the LHS expression if there is an LHS expression.
315 // A GCC extension allows LHS to be NULL, causing the condition to
316 // be the value that is returned instead.
317 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000318 Succ = ConfluenceBlock;
319 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000320 CFGBlock* LHSBlock = NULL;
321 if (C->getLHS()) {
322 LHSBlock = Visit(C->getLHS());
323 FinishBlock(LHSBlock);
324 Block = NULL;
325 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000326
Ted Kremenekecc04c92007-11-26 18:20:26 +0000327 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000328 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000329 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000330 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000331
Ted Kremenekecc04c92007-11-26 18:20:26 +0000332 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000333 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000334
335 if (LHSBlock)
336 Block->addSuccessor(LHSBlock);
337 else {
338 // If we have no LHS expression, add the ConfluenceBlock as a direct
339 // successor for the block containing the condition. Moreover,
340 // we need to reverse the order of the predecessors in the
341 // ConfluenceBlock because the RHSBlock will have been added to
342 // the succcessors already, and we want the first predecessor to the
343 // the block containing the expression for the case when the ternary
344 // expression evaluates to true.
345 Block->addSuccessor(ConfluenceBlock);
346 assert (ConfluenceBlock->pred_size() == 2);
347 std::reverse(ConfluenceBlock->pred_begin(),
348 ConfluenceBlock->pred_end());
349 }
350
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000351 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000352
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000353 Block->setTerminator(C);
354 return addStmt(C->getCond());
355 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000356
357 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000358 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000359
360 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
361 ConfluenceBlock->appendStmt(C);
362 FinishBlock(ConfluenceBlock);
363
364 Succ = ConfluenceBlock;
365 Block = NULL;
366 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000367 FinishBlock(LHSBlock);
368
Ted Kremenek49a436d2007-08-31 17:03:41 +0000369 Succ = ConfluenceBlock;
370 Block = NULL;
371 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000372 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000373
374 Block = createBlock(false);
375 Block->addSuccessor(LHSBlock);
376 Block->addSuccessor(RHSBlock);
377 Block->setTerminator(C);
378 return addStmt(C->getCond());
379 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000380
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000381 case Stmt::DeclStmtClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000382 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000383
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000384 if (!D->getNextDeclarator()) {
385 Block->appendStmt(Terminator);
386 return WalkAST_VisitDeclSubExpr(D);
387 }
388 else {
389 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
390 BufTy Buf;
391 CFGBlock* B = 0;
392 do { Buf.push_back(D); D = D->getNextDeclarator(); } while (D);
393 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
394 // Get the alignment of UnaryDeclStmt, padding out to >=8 bytes.
395 unsigned A = llvm::AlignOf<UnaryDeclStmt>::Alignment < 8
396 ? 8 : llvm::AlignOf<UnaryDeclStmt>::Alignment;
397
398 // Allocate the UnaryDeclStmt using the BumpPtrAllocator. It will
399 // get automatically freed with the CFG.
400 void* Mem = cfg->getAllocator().Allocate(sizeof(UnaryDeclStmt), A);
401 // Append the fake DeclStmt to block.
402 Block->appendStmt(new (Mem) UnaryDeclStmt(*I));
403 B = WalkAST_VisitDeclSubExpr(*I);
404 }
405 return B;
406 }
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000407 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000408
Ted Kremenek19bb3562007-08-28 19:26:49 +0000409 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000410 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000411 AddressTakenLabels.insert(A->getLabel());
412
Ted Kremenek411cdee2008-04-16 21:10:48 +0000413 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000414 return Block;
415 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000416
Ted Kremenek15c27a82007-08-28 18:30:10 +0000417 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000418 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000419
Ted Kremenek610a09e2008-09-26 22:58:57 +0000420 case Stmt::SizeOfAlignOfTypeExprClass: {
421 SizeOfAlignOfTypeExpr* E = cast<SizeOfAlignOfTypeExpr>(Terminator);
422
423 // VLA types have expressions that must be evaluated.
424 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
425 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
426 addStmt(VA->getSizeExpr());
427
428 return Block;
429 }
430
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000431 case Stmt::UnaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000432 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000433
434 // sizeof(expressions). For such expressions,
435 // the subexpression is not really evaluated, so
436 // we don't care about control-flow within the sizeof.
437 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000438 Block->appendStmt(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000439 return Block;
440 }
441
442 break;
443 }
444
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000445 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000446 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000447
448 if (B->isLogicalOp()) { // && or ||
449 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
450 ConfluenceBlock->appendStmt(B);
451 FinishBlock(ConfluenceBlock);
452
453 // create the block evaluating the LHS
454 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000455 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000456
457 // create the block evaluating the RHS
458 Succ = ConfluenceBlock;
459 Block = NULL;
460 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000461
462 // Now link the LHSBlock with RHSBlock.
463 if (B->getOpcode() == BinaryOperator::LOr) {
464 LHSBlock->addSuccessor(ConfluenceBlock);
465 LHSBlock->addSuccessor(RHSBlock);
466 }
467 else {
468 assert (B->getOpcode() == BinaryOperator::LAnd);
469 LHSBlock->addSuccessor(RHSBlock);
470 LHSBlock->addSuccessor(ConfluenceBlock);
471 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000472
473 // Generate the blocks for evaluating the LHS.
474 Block = LHSBlock;
475 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000476 }
477 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
478 Block->appendStmt(B);
479 addStmt(B->getRHS());
480 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000481 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000482
483 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000484 }
Ted Kremenek00c0a302008-09-26 18:17:07 +0000485
486 // Blocks: No support for blocks ... yet
487 case Stmt::BlockExprClass:
488 case Stmt::BlockDeclRefExprClass:
489 return NYS();
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000490
491 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000492 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000493
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000494 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000495 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000496 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000497
Ted Kremenek411cdee2008-04-16 21:10:48 +0000498 if (AlwaysAddStmt) Block->appendStmt(Terminator);
499 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000500}
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000501
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000502/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
503/// for initializers in Decls.
504CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
505 VarDecl* VD = dyn_cast<VarDecl>(D);
506
507 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000508 return Block;
509
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000510 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000511
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000512 if (Init) {
513 // Optimization: Don't create separate block-level statements for literals.
514 switch (Init->getStmtClass()) {
515 case Stmt::IntegerLiteralClass:
516 case Stmt::CharacterLiteralClass:
517 case Stmt::StringLiteralClass:
518 break;
519 default:
520 Block = addStmt(Init);
521 }
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000522 }
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000523
524 // If the type of VD is a VLA, then we must process its size expressions.
525 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
526 VA = FindVA(VA->getElementType().getTypePtr()))
527 Block = addStmt(VA->getSizeExpr());
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000528
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000529 return Block;
530}
531
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000532/// WalkAST_VisitChildren - Utility method to call WalkAST on the
533/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000534CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000535 CFGBlock* B = Block;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000536 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000537 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000538 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000539
540 return B;
541}
542
Ted Kremenek15c27a82007-08-28 18:30:10 +0000543/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
544/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000545CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
546 Block->appendStmt(Terminator);
547 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000548}
549
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000550/// VisitStmt - Handle statements with no branching control flow.
551CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
552 // We cannot assume that we are in the middle of a basic block, since
553 // the CFG might only be constructed for this single statement. If
554 // we have no current basic block, just create one lazily.
555 if (!Block) Block = createBlock();
556
557 // Simply add the statement to the current block. We actually
558 // insert statements in reverse order; this order is reversed later
559 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000560 addStmt(Statement);
561
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000562 return Block;
563}
564
565CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
566 return Block;
567}
568
569CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000570
571 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000572
Ted Kremenekd34066c2008-02-26 00:22:58 +0000573 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
574 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000575 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000576 }
577
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000578 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000579}
580
581CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
582 // We may see an if statement in the middle of a basic block, or
583 // it may be the first statement we are processing. In either case,
584 // we create a new basic block. First, we create the blocks for
585 // the then...else statements, and then we create the block containing
586 // the if statement. If we were in the middle of a block, we
587 // stop processing that block and reverse its statements. That block
588 // is then the implicit successor for the "then" and "else" clauses.
589
590 // The block we were proccessing is now finished. Make it the
591 // successor block.
592 if (Block) {
593 Succ = Block;
594 FinishBlock(Block);
595 }
596
597 // Process the false branch. NULL out Block so that the recursive
598 // call to Visit will create a new basic block.
599 // Null out Block so that all successor
600 CFGBlock* ElseBlock = Succ;
601
602 if (Stmt* Else = I->getElse()) {
603 SaveAndRestore<CFGBlock*> sv(Succ);
604
605 // NULL out Block so that the recursive call to Visit will
606 // create a new basic block.
607 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000608 ElseBlock = Visit(Else);
609
610 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
611 ElseBlock = sv.get();
612 else if (Block)
613 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000614 }
615
616 // Process the true branch. NULL out Block so that the recursive
617 // call to Visit will create a new basic block.
618 // Null out Block so that all successor
619 CFGBlock* ThenBlock;
620 {
621 Stmt* Then = I->getThen();
622 assert (Then);
623 SaveAndRestore<CFGBlock*> sv(Succ);
624 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000625 ThenBlock = Visit(Then);
626
627 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
628 ThenBlock = sv.get();
629 else if (Block)
630 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000631 }
632
633 // Now create a new block containing the if statement.
634 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000635
636 // Set the terminator of the new block to the If statement.
637 Block->setTerminator(I);
638
639 // Now add the successors.
640 Block->addSuccessor(ThenBlock);
641 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000642
643 // Add the condition as the last statement in the new block. This
644 // may create new blocks as the condition may contain control-flow. Any
645 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000646 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000647}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000648
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000649
650CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
651 // If we were in the middle of a block we stop processing that block
652 // and reverse its statements.
653 //
654 // NOTE: If a "return" appears in the middle of a block, this means
655 // that the code afterwards is DEAD (unreachable). We still
656 // keep a basic block for that code; a simple "mark-and-sweep"
657 // from the entry block will be able to report such dead
658 // blocks.
659 if (Block) FinishBlock(Block);
660
661 // Create the new block.
662 Block = createBlock(false);
663
664 // The Exit block is the only successor.
665 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000666
667 // Add the return statement to the block. This may create new blocks
668 // if R contains control-flow (short-circuit operations).
669 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000670}
671
672CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
673 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000674 Visit(L->getSubStmt());
675 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000676
677 if (!LabelBlock) // This can happen when the body is empty, i.e.
678 LabelBlock=createBlock(); // scopes that only contains NullStmts.
679
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000680 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
681 LabelMap[ L ] = LabelBlock;
682
683 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000684 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000685 // label (and we have already processed the substatement) there is no
686 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000687 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000688 FinishBlock(LabelBlock);
689
690 // We set Block to NULL to allow lazy creation of a new block
691 // (if necessary);
692 Block = NULL;
693
694 // This block is now the implicit successor of other blocks.
695 Succ = LabelBlock;
696
697 return LabelBlock;
698}
699
700CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
701 // Goto is a control-flow statement. Thus we stop processing the
702 // current block and create a new one.
703 if (Block) FinishBlock(Block);
704 Block = createBlock(false);
705 Block->setTerminator(G);
706
707 // If we already know the mapping to the label block add the
708 // successor now.
709 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
710
711 if (I == LabelMap.end())
712 // We will need to backpatch this block later.
713 BackpatchBlocks.push_back(Block);
714 else
715 Block->addSuccessor(I->second);
716
717 return Block;
718}
719
720CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
721 // "for" is a control-flow statement. Thus we stop processing the
722 // current block.
723
724 CFGBlock* LoopSuccessor = NULL;
725
726 if (Block) {
727 FinishBlock(Block);
728 LoopSuccessor = Block;
729 }
730 else LoopSuccessor = Succ;
731
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000732 // Because of short-circuit evaluation, the condition of the loop
733 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
734 // blocks that evaluate the condition.
735 CFGBlock* ExitConditionBlock = createBlock(false);
736 CFGBlock* EntryConditionBlock = ExitConditionBlock;
737
738 // Set the terminator for the "exit" condition block.
739 ExitConditionBlock->setTerminator(F);
740
741 // Now add the actual condition to the condition block. Because the
742 // condition itself may contain control-flow, new blocks may be created.
743 if (Stmt* C = F->getCond()) {
744 Block = ExitConditionBlock;
745 EntryConditionBlock = addStmt(C);
746 if (Block) FinishBlock(EntryConditionBlock);
747 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000748
749 // The condition block is the implicit successor for the loop body as
750 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000751 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000752
753 // Now create the loop body.
754 {
755 assert (F->getBody());
756
757 // Save the current values for Block, Succ, and continue and break targets
758 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
759 save_continue(ContinueTargetBlock),
760 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000761
Ted Kremenekaf603f72007-08-30 18:39:40 +0000762 // Create a new block to contain the (bottom) of the loop body.
763 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000764
Ted Kremeneke9334502008-09-04 21:48:47 +0000765 if (Stmt* I = F->getInc()) {
766 // Generate increment code in its own basic block. This is the target
767 // of continue statements.
768 Succ = addStmt(I);
769 Block = 0;
770 ContinueTargetBlock = Succ;
771 }
772 else {
773 // No increment code. Continues should go the the entry condition block.
774 ContinueTargetBlock = EntryConditionBlock;
775 }
776
777 // All breaks should go to the code following the loop.
778 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000779
780 // Now populate the body block, and in the process create new blocks
781 // as we walk the body of the loop.
782 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000783
784 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000785 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000786 else if (Block)
787 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000788
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000789 // This new body block is a successor to our "exit" condition block.
790 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000791 }
792
793 // Link up the condition block with the code that follows the loop.
794 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000795 ExitConditionBlock->addSuccessor(LoopSuccessor);
796
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000797 // If the loop contains initialization, create a new block for those
798 // statements. This block can also contain statements that precede
799 // the loop.
800 if (Stmt* I = F->getInit()) {
801 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000802 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000803 }
804 else {
805 // There is no loop initialization. We are thus basically a while
806 // loop. NULL out Block to force lazy block construction.
807 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000808 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000809 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000810 }
811}
812
813CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
814 // "while" is a control-flow statement. Thus we stop processing the
815 // current block.
816
817 CFGBlock* LoopSuccessor = NULL;
818
819 if (Block) {
820 FinishBlock(Block);
821 LoopSuccessor = Block;
822 }
823 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000824
825 // Because of short-circuit evaluation, the condition of the loop
826 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
827 // blocks that evaluate the condition.
828 CFGBlock* ExitConditionBlock = createBlock(false);
829 CFGBlock* EntryConditionBlock = ExitConditionBlock;
830
831 // Set the terminator for the "exit" condition block.
832 ExitConditionBlock->setTerminator(W);
833
834 // Now add the actual condition to the condition block. Because the
835 // condition itself may contain control-flow, new blocks may be created.
836 // Thus we update "Succ" after adding the condition.
837 if (Stmt* C = W->getCond()) {
838 Block = ExitConditionBlock;
839 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000840 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000841 if (Block) FinishBlock(EntryConditionBlock);
842 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000843
844 // The condition block is the implicit successor for the loop body as
845 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000846 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000847
848 // Process the loop body.
849 {
850 assert (W->getBody());
851
852 // Save the current values for Block, Succ, and continue and break targets
853 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
854 save_continue(ContinueTargetBlock),
855 save_break(BreakTargetBlock);
856
857 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000858 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000859
860 // All breaks should go to the code following the loop.
861 BreakTargetBlock = LoopSuccessor;
862
863 // NULL out Block to force lazy instantiation of blocks for the body.
864 Block = NULL;
865
866 // Create the body. The returned block is the entry to the loop body.
867 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000868
869 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000870 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000871 else if (Block)
872 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000873
874 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000875 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000876 }
877
878 // Link up the condition block with the code that follows the loop.
879 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000880 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000881
882 // There can be no more statements in the condition block
883 // since we loop back to this block. NULL out Block to force
884 // lazy creation of another block.
885 Block = NULL;
886
887 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000888 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000889 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000890}
891
892CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
893 // "do...while" is a control-flow statement. Thus we stop processing the
894 // current block.
895
896 CFGBlock* LoopSuccessor = NULL;
897
898 if (Block) {
899 FinishBlock(Block);
900 LoopSuccessor = Block;
901 }
902 else LoopSuccessor = Succ;
903
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000904 // Because of short-circuit evaluation, the condition of the loop
905 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
906 // blocks that evaluate the condition.
907 CFGBlock* ExitConditionBlock = createBlock(false);
908 CFGBlock* EntryConditionBlock = ExitConditionBlock;
909
910 // Set the terminator for the "exit" condition block.
911 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000912
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000913 // Now add the actual condition to the condition block. Because the
914 // condition itself may contain control-flow, new blocks may be created.
915 if (Stmt* C = D->getCond()) {
916 Block = ExitConditionBlock;
917 EntryConditionBlock = addStmt(C);
918 if (Block) FinishBlock(EntryConditionBlock);
919 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000920
Ted Kremenek54827132008-02-27 07:20:00 +0000921 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000922 Succ = EntryConditionBlock;
923
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000924 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000925 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000926 {
927 assert (D->getBody());
928
929 // Save the current values for Block, Succ, and continue and break targets
930 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
931 save_continue(ContinueTargetBlock),
932 save_break(BreakTargetBlock);
933
934 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000935 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000936
937 // All breaks should go to the code following the loop.
938 BreakTargetBlock = LoopSuccessor;
939
940 // NULL out Block to force lazy instantiation of blocks for the body.
941 Block = NULL;
942
943 // Create the body. The returned block is the entry to the loop body.
944 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000945
Ted Kremenekaf603f72007-08-30 18:39:40 +0000946 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000947 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000948 else if (Block)
949 FinishBlock(BodyBlock);
950
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000951 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000952 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000953 }
954
955 // Link up the condition block with the code that follows the loop.
956 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000957 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000958
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000959 // There can be no more statements in the body block(s)
960 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000961 // lazy creation of another block.
962 Block = NULL;
963
964 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000965 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000966 return BodyBlock;
967}
968
969CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
970 // "continue" is a control-flow statement. Thus we stop processing the
971 // current block.
972 if (Block) FinishBlock(Block);
973
974 // Now create a new block that ends with the continue statement.
975 Block = createBlock(false);
976 Block->setTerminator(C);
977
978 // If there is no target for the continue, then we are looking at an
979 // incomplete AST. Handle this by not registering a successor.
980 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
981
982 return Block;
983}
984
985CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
986 // "break" is a control-flow statement. Thus we stop processing the
987 // current block.
988 if (Block) FinishBlock(Block);
989
990 // Now create a new block that ends with the continue statement.
991 Block = createBlock(false);
992 Block->setTerminator(B);
993
994 // If there is no target for the break, then we are looking at an
995 // incomplete AST. Handle this by not registering a successor.
996 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
997
998 return Block;
999}
1000
Ted Kremenek411cdee2008-04-16 21:10:48 +00001001CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001002 // "switch" is a control-flow statement. Thus we stop processing the
1003 // current block.
1004 CFGBlock* SwitchSuccessor = NULL;
1005
1006 if (Block) {
1007 FinishBlock(Block);
1008 SwitchSuccessor = Block;
1009 }
1010 else SwitchSuccessor = Succ;
1011
1012 // Save the current "switch" context.
1013 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001014 save_break(BreakTargetBlock),
1015 save_default(DefaultCaseBlock);
1016
1017 // Set the "default" case to be the block after the switch statement.
1018 // If the switch statement contains a "default:", this value will
1019 // be overwritten with the block for that code.
1020 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +00001021
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001022 // Create a new block that will contain the switch statement.
1023 SwitchTerminatedBlock = createBlock(false);
1024
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001025 // Now process the switch body. The code after the switch is the implicit
1026 // successor.
1027 Succ = SwitchSuccessor;
1028 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001029
1030 // When visiting the body, the case statements should automatically get
1031 // linked up to the switch. We also don't keep a pointer to the body,
1032 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001033 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001034 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001035 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001036 if (Block) FinishBlock(BodyBlock);
1037
Ted Kremenek295222c2008-02-13 21:46:34 +00001038 // If we have no "default:" case, the default transition is to the
1039 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001040 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001041
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001042 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001043 SwitchTerminatedBlock->setTerminator(Terminator);
1044 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001045 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001046
Ted Kremenek411cdee2008-04-16 21:10:48 +00001047 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001048}
1049
Ted Kremenek411cdee2008-04-16 21:10:48 +00001050CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001051 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001052 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001053
Ted Kremenek411cdee2008-04-16 21:10:48 +00001054 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001055 CFGBlock* CaseBlock = Block;
1056 if (!CaseBlock) CaseBlock = createBlock();
1057
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001058 // Cases statements partition blocks, so this is the top of
1059 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001060 CaseBlock->setLabel(Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001061 FinishBlock(CaseBlock);
1062
1063 // Add this block to the list of successors for the block with the
1064 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001065 assert (SwitchTerminatedBlock);
1066 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001067
1068 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1069 Block = NULL;
1070
1071 // This block is now the implicit successor of other blocks.
1072 Succ = CaseBlock;
1073
Ted Kremenek2677ea82008-03-15 07:45:02 +00001074 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001075}
Ted Kremenek295222c2008-02-13 21:46:34 +00001076
Ted Kremenek411cdee2008-04-16 21:10:48 +00001077CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1078 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001079 DefaultCaseBlock = Block;
1080 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1081
1082 // Default statements partition blocks, so this is the top of
1083 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001084 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001085 FinishBlock(DefaultCaseBlock);
1086
1087 // Unlike case statements, we don't add the default block to the
1088 // successors for the switch statement immediately. This is done
1089 // when we finish processing the switch statement. This allows for
1090 // the default case (including a fall-through to the code after the
1091 // switch statement) to always be the last successor of a switch-terminated
1092 // block.
1093
1094 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1095 Block = NULL;
1096
1097 // This block is now the implicit successor of other blocks.
1098 Succ = DefaultCaseBlock;
1099
1100 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001101}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001102
Ted Kremenek19bb3562007-08-28 19:26:49 +00001103CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1104 // Lazily create the indirect-goto dispatch block if there isn't one
1105 // already.
1106 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1107
1108 if (!IBlock) {
1109 IBlock = createBlock(false);
1110 cfg->setIndirectGotoBlock(IBlock);
1111 }
1112
1113 // IndirectGoto is a control-flow statement. Thus we stop processing the
1114 // current block and create a new one.
1115 if (Block) FinishBlock(Block);
1116 Block = createBlock(false);
1117 Block->setTerminator(I);
1118 Block->addSuccessor(IBlock);
1119 return addStmt(I->getTarget());
1120}
1121
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001122
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001123} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001124
1125/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1126/// block has no successors or predecessors. If this is the first block
1127/// created in the CFG, it is automatically set to be the Entry and Exit
1128/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001129CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001130 bool first_block = begin() == end();
1131
1132 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001133 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001134
1135 // If this is the first block, set it as the Entry and Exit.
1136 if (first_block) Entry = Exit = &front();
1137
1138 // Return the block.
1139 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001140}
1141
Ted Kremenek026473c2007-08-23 16:51:22 +00001142/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1143/// CFG is returned to the caller.
1144CFG* CFG::buildCFG(Stmt* Statement) {
1145 CFGBuilder Builder;
1146 return Builder.buildCFG(Statement);
1147}
1148
1149/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001150void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1151
Ted Kremenek63f58872007-10-01 19:33:33 +00001152//===----------------------------------------------------------------------===//
1153// CFG: Queries for BlkExprs.
1154//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001155
Ted Kremenek63f58872007-10-01 19:33:33 +00001156namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001157 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001158}
1159
Ted Kremenek411cdee2008-04-16 21:10:48 +00001160static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1161 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001162 return;
1163
Ted Kremenek411cdee2008-04-16 21:10:48 +00001164 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001165 if (!*I) continue;
1166
1167 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1168 if (B->isAssignmentOp()) Set.insert(B);
1169
1170 FindSubExprAssignments(*I, Set);
1171 }
1172}
1173
Ted Kremenek63f58872007-10-01 19:33:33 +00001174static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1175 BlkExprMapTy* M = new BlkExprMapTy();
1176
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001177 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001178 // only assignments that we want to *possibly* register as a block-level
1179 // expression. Basically, if an assignment occurs both in a subexpression
1180 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001181 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1182
Ted Kremenek63f58872007-10-01 19:33:33 +00001183 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1184 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001185 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001186
Ted Kremenek411cdee2008-04-16 21:10:48 +00001187 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1188
1189 // Iterate over the statements again on identify the Expr* and Stmt* at
1190 // the block-level that are block-level expressions.
1191
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001192 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001193 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001194
Ted Kremenek411cdee2008-04-16 21:10:48 +00001195 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001196 // Assignment expressions that are not nested within another
1197 // expression are really "statements" whose value is never
1198 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001199 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001200 continue;
1201 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001202 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001203 // Special handling for statement expressions. The last statement
1204 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001205 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001206 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001207 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001208 (*M)[C->body_back()] = x;
1209 }
1210 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001211
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001212 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001213 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001214 }
1215
Ted Kremenek411cdee2008-04-16 21:10:48 +00001216 // Look at terminators. The condition is a block-level expression.
1217
1218 Expr* Exp = I->getTerminatorCondition();
1219
1220 if (Exp && M->find(Exp) == M->end()) {
1221 unsigned x = M->size();
1222 (*M)[Exp] = x;
1223 }
1224 }
1225
Ted Kremenek63f58872007-10-01 19:33:33 +00001226 return M;
1227}
1228
Ted Kremenek86946742008-01-17 20:48:37 +00001229CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1230 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001231 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1232
1233 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001234 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001235
1236 if (I == M->end()) return CFG::BlkExprNumTy();
1237 else return CFG::BlkExprNumTy(I->second);
1238}
1239
1240unsigned CFG::getNumBlkExprs() {
1241 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1242 return M->size();
1243 else {
1244 // We assume callers interested in the number of BlkExprs will want
1245 // the map constructed if it doesn't already exist.
1246 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1247 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1248 }
1249}
1250
Ted Kremenek274f4332008-04-28 18:00:46 +00001251//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001252// Cleanup: CFG dstor.
1253//===----------------------------------------------------------------------===//
1254
Ted Kremenek63f58872007-10-01 19:33:33 +00001255CFG::~CFG() {
1256 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1257}
1258
Ted Kremenek7dba8602007-08-29 21:56:09 +00001259//===----------------------------------------------------------------------===//
1260// CFG pretty printing
1261//===----------------------------------------------------------------------===//
1262
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001263namespace {
1264
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001265class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001266
Ted Kremenek42a509f2007-08-31 21:30:12 +00001267 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1268 StmtMapTy StmtMap;
1269 signed CurrentBlock;
1270 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001271
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001272public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001273
Ted Kremenek42a509f2007-08-31 21:30:12 +00001274 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1275 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1276 unsigned j = 1;
1277 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1278 BI != BEnd; ++BI, ++j )
1279 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1280 }
1281 }
1282
1283 virtual ~StmtPrinterHelper() {}
1284
1285 void setBlockID(signed i) { CurrentBlock = i; }
1286 void setStmtID(unsigned i) { CurrentStmt = i; }
1287
Ted Kremeneka95d3752008-09-13 05:16:45 +00001288 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001289
Ted Kremenek411cdee2008-04-16 21:10:48 +00001290 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001291
1292 if (I == StmtMap.end())
1293 return false;
1294
1295 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1296 && I->second.second == CurrentStmt)
1297 return false;
1298
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001299 OS << "[B" << I->second.first << "." << I->second.second << "]";
1300 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001301 }
1302};
1303
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001304class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1305 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1306
Ted Kremeneka95d3752008-09-13 05:16:45 +00001307 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001308 StmtPrinterHelper* Helper;
1309public:
Ted Kremeneka95d3752008-09-13 05:16:45 +00001310 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper)
Ted Kremenek42a509f2007-08-31 21:30:12 +00001311 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001312
1313 void VisitIfStmt(IfStmt* I) {
1314 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001315 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001316 }
1317
1318 // Default case.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001319 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001320
1321 void VisitForStmt(ForStmt* F) {
1322 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001323 if (F->getInit()) OS << "...";
1324 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001325 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001326 OS << "; ";
1327 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001328 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001329 }
1330
1331 void VisitWhileStmt(WhileStmt* W) {
1332 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001333 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001334 }
1335
1336 void VisitDoStmt(DoStmt* D) {
1337 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001338 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001339 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001340
Ted Kremenek411cdee2008-04-16 21:10:48 +00001341 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001342 OS << "switch ";
Ted Kremenek411cdee2008-04-16 21:10:48 +00001343 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001344 }
1345
Ted Kremenek805e9a82007-08-31 21:49:40 +00001346 void VisitConditionalOperator(ConditionalOperator* C) {
1347 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001348 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001349 }
1350
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001351 void VisitChooseExpr(ChooseExpr* C) {
1352 OS << "__builtin_choose_expr( ";
1353 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001354 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001355 }
1356
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001357 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1358 OS << "goto *";
1359 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001360 }
1361
Ted Kremenek805e9a82007-08-31 21:49:40 +00001362 void VisitBinaryOperator(BinaryOperator* B) {
1363 if (!B->isLogicalOp()) {
1364 VisitExpr(B);
1365 return;
1366 }
1367
1368 B->getLHS()->printPretty(OS,Helper);
1369
1370 switch (B->getOpcode()) {
1371 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001372 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001373 return;
1374 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001375 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001376 return;
1377 default:
1378 assert(false && "Invalid logical operator.");
1379 }
1380 }
1381
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001382 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001383 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001384 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001385};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001386
1387
Ted Kremeneka95d3752008-09-13 05:16:45 +00001388void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001389 if (Helper) {
1390 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001391 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001392 CompoundStmt* Sub = SE->getSubStmt();
1393
1394 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001395 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001396 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001397 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001398 return;
1399 }
1400 }
1401
1402 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001403 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001404 if (B->getOpcode() == BinaryOperator::Comma) {
1405 OS << "... , ";
1406 Helper->handledStmt(B->getRHS(),OS);
1407 OS << '\n';
1408 return;
1409 }
1410 }
1411 }
1412
Ted Kremenek411cdee2008-04-16 21:10:48 +00001413 Terminator->printPretty(OS, Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001414
1415 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001416 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001417}
1418
Ted Kremeneka95d3752008-09-13 05:16:45 +00001419void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B,
Ted Kremenek42a509f2007-08-31 21:30:12 +00001420 StmtPrinterHelper* Helper, bool print_edges) {
1421
1422 if (Helper) Helper->setBlockID(B.getBlockID());
1423
Ted Kremenek7dba8602007-08-29 21:56:09 +00001424 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001425 OS << "\n [ B" << B.getBlockID();
1426
1427 if (&B == &cfg->getEntry())
1428 OS << " (ENTRY) ]\n";
1429 else if (&B == &cfg->getExit())
1430 OS << " (EXIT) ]\n";
1431 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001432 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001433 else
1434 OS << " ]\n";
1435
Ted Kremenek9cffe732007-08-29 23:20:49 +00001436 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001437 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001438
1439 if (print_edges)
1440 OS << " ";
1441
Ted Kremenek411cdee2008-04-16 21:10:48 +00001442 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001443 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001444 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001445 OS << "case ";
1446 C->getLHS()->printPretty(OS);
1447 if (C->getRHS()) {
1448 OS << " ... ";
1449 C->getRHS()->printPretty(OS);
1450 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001451 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001452 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001453 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001454 else
1455 assert(false && "Invalid label statement in CFGBlock.");
1456
Ted Kremenek9cffe732007-08-29 23:20:49 +00001457 OS << ":\n";
1458 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001459
Ted Kremenekfddd5182007-08-21 21:42:03 +00001460 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001461 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001462
1463 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1464 I != E ; ++I, ++j ) {
1465
Ted Kremenek9cffe732007-08-29 23:20:49 +00001466 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001467 if (print_edges)
1468 OS << " ";
1469
Ted Kremeneka95d3752008-09-13 05:16:45 +00001470 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001471
1472 if (Helper)
1473 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001474
1475 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001476 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001477
Ted Kremenek9cffe732007-08-29 23:20:49 +00001478 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001479 if (B.getTerminator()) {
1480 if (print_edges)
1481 OS << " ";
1482
Ted Kremenek9cffe732007-08-29 23:20:49 +00001483 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001484
1485 if (Helper) Helper->setBlockID(-1);
1486
1487 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1488 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001489 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001490 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001491
Ted Kremenek9cffe732007-08-29 23:20:49 +00001492 if (print_edges) {
1493 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001494 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001495 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001496
Ted Kremenek42a509f2007-08-31 21:30:12 +00001497 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1498 I != E; ++I, ++i) {
1499
1500 if (i == 8 || (i-8) == 0)
1501 OS << "\n ";
1502
Ted Kremenek9cffe732007-08-29 23:20:49 +00001503 OS << " B" << (*I)->getBlockID();
1504 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001505
1506 OS << '\n';
1507
1508 // Print the successors of this block.
1509 OS << " Successors (" << B.succ_size() << "):";
1510 i = 0;
1511
1512 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1513 I != E; ++I, ++i) {
1514
1515 if (i == 8 || (i-8) % 10 == 0)
1516 OS << "\n ";
1517
1518 OS << " B" << (*I)->getBlockID();
1519 }
1520
Ted Kremenek9cffe732007-08-29 23:20:49 +00001521 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001522 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001523}
1524
1525} // end anonymous namespace
1526
1527/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001528void CFG::dump() const { print(llvm::errs()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001529
1530/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001531void CFG::print(llvm::raw_ostream& OS) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001532
1533 StmtPrinterHelper Helper(this);
1534
1535 // Print the entry block.
1536 print_block(OS, this, getEntry(), &Helper, true);
1537
1538 // Iterate through the CFGBlocks and print them one by one.
1539 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1540 // Skip the entry block, because we already printed it.
1541 if (&(*I) == &getEntry() || &(*I) == &getExit())
1542 continue;
1543
1544 print_block(OS, this, *I, &Helper, true);
1545 }
1546
1547 // Print the exit block.
1548 print_block(OS, this, getExit(), &Helper, true);
1549}
1550
1551/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001552void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001553
1554/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1555/// Generally this will only be called from CFG::print.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001556void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001557 StmtPrinterHelper Helper(cfg);
1558 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001559}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001560
Ted Kremeneka2925852008-01-30 23:02:42 +00001561/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001562void CFGBlock::printTerminator(llvm::raw_ostream& OS) const {
Ted Kremeneka2925852008-01-30 23:02:42 +00001563 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1564 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1565}
1566
Ted Kremenek411cdee2008-04-16 21:10:48 +00001567Expr* CFGBlock::getTerminatorCondition() {
1568
1569 if (!Terminator)
1570 return NULL;
1571
1572 Expr* E = NULL;
1573
1574 switch (Terminator->getStmtClass()) {
1575 default:
1576 break;
1577
1578 case Stmt::ForStmtClass:
1579 E = cast<ForStmt>(Terminator)->getCond();
1580 break;
1581
1582 case Stmt::WhileStmtClass:
1583 E = cast<WhileStmt>(Terminator)->getCond();
1584 break;
1585
1586 case Stmt::DoStmtClass:
1587 E = cast<DoStmt>(Terminator)->getCond();
1588 break;
1589
1590 case Stmt::IfStmtClass:
1591 E = cast<IfStmt>(Terminator)->getCond();
1592 break;
1593
1594 case Stmt::ChooseExprClass:
1595 E = cast<ChooseExpr>(Terminator)->getCond();
1596 break;
1597
1598 case Stmt::IndirectGotoStmtClass:
1599 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1600 break;
1601
1602 case Stmt::SwitchStmtClass:
1603 E = cast<SwitchStmt>(Terminator)->getCond();
1604 break;
1605
1606 case Stmt::ConditionalOperatorClass:
1607 E = cast<ConditionalOperator>(Terminator)->getCond();
1608 break;
1609
1610 case Stmt::BinaryOperatorClass: // '&&' and '||'
1611 E = cast<BinaryOperator>(Terminator)->getLHS();
1612 break;
1613 }
1614
1615 return E ? E->IgnoreParens() : NULL;
1616}
1617
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001618bool CFGBlock::hasBinaryBranchTerminator() const {
1619
1620 if (!Terminator)
1621 return false;
1622
1623 Expr* E = NULL;
1624
1625 switch (Terminator->getStmtClass()) {
1626 default:
1627 return false;
1628
1629 case Stmt::ForStmtClass:
1630 case Stmt::WhileStmtClass:
1631 case Stmt::DoStmtClass:
1632 case Stmt::IfStmtClass:
1633 case Stmt::ChooseExprClass:
1634 case Stmt::ConditionalOperatorClass:
1635 case Stmt::BinaryOperatorClass:
1636 return true;
1637 }
1638
1639 return E ? E->IgnoreParens() : NULL;
1640}
1641
Ted Kremeneka2925852008-01-30 23:02:42 +00001642
Ted Kremenek7dba8602007-08-29 21:56:09 +00001643//===----------------------------------------------------------------------===//
1644// CFG Graphviz Visualization
1645//===----------------------------------------------------------------------===//
1646
Ted Kremenek42a509f2007-08-31 21:30:12 +00001647
1648#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001649static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001650#endif
1651
1652void CFG::viewCFG() const {
1653#ifndef NDEBUG
1654 StmtPrinterHelper H(this);
1655 GraphHelper = &H;
1656 llvm::ViewGraph(this,"CFG");
1657 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001658#endif
1659}
1660
Ted Kremenek7dba8602007-08-29 21:56:09 +00001661namespace llvm {
1662template<>
1663struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1664 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1665
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001666#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001667 std::string OutSStr;
1668 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001669 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001670 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001671
1672 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1673
1674 // Process string output to make it nicer...
1675 for (unsigned i = 0; i != OutStr.length(); ++i)
1676 if (OutStr[i] == '\n') { // Left justify
1677 OutStr[i] = '\\';
1678 OutStr.insert(OutStr.begin()+i+1, 'l');
1679 }
1680
1681 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001682#else
1683 return "";
1684#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001685 }
1686};
1687} // end namespace llvm