blob: b18f90497f06a520d66dcd140e4b85864e320bc9 [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 Kremenekd4fdee32007-08-23 21:42:29 +0000168private:
169 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000170 CFGBlock* addStmt(Stmt* Terminator);
171 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
172 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000173 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000174 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000175 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000176
Ted Kremenek4102af92008-03-13 03:04:22 +0000177 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000178};
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000179
180/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
181/// represent an arbitrary statement. Examples include a single expression
182/// or a function body (compound statement). The ownership of the returned
183/// CFG is transferred to the caller. If CFG construction fails, this method
184/// returns NULL.
185CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000186 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000187 if (!Statement) return NULL;
188
Ted Kremenek4102af92008-03-13 03:04:22 +0000189 badCFG = false;
190
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000191 // Create an empty block that will serve as the exit block for the CFG.
192 // Since this is the first block added to the CFG, it will be implicitly
193 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000194 Succ = createBlock();
195 assert (Succ == &cfg->getExit());
196 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000197
198 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000199 CFGBlock* B = Visit(Statement);
200 if (!B) B = Succ;
201
202 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000203 // Finalize the last constructed block. This usually involves
204 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000205 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000206
207 // Backpatch the gotos whose label -> block mappings we didn't know
208 // when we encountered them.
209 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
210 E = BackpatchBlocks.end(); I != E; ++I ) {
211
212 CFGBlock* B = *I;
213 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
214 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
215
216 // If there is no target for the goto, then we are looking at an
217 // incomplete AST. Handle this by not registering a successor.
218 if (LI == LabelMap.end()) continue;
219
220 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000221 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000222
Ted Kremenek19bb3562007-08-28 19:26:49 +0000223 // Add successors to the Indirect Goto Dispatch block (if we have one).
224 if (CFGBlock* B = cfg->getIndirectGotoBlock())
225 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
226 E = AddressTakenLabels.end(); I != E; ++I ) {
227
228 // Lookup the target block.
229 LabelMapTy::iterator LI = LabelMap.find(*I);
230
231 // If there is no target block that contains label, then we are looking
232 // at an incomplete AST. Handle this by not registering a successor.
233 if (LI == LabelMap.end()) continue;
234
235 B->addSuccessor(LI->second);
236 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000237
Ted Kremenek94b33162007-09-17 16:18:02 +0000238 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000239 }
240
241 // Create an empty entry block that has no predecessors.
242 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000243
Ted Kremenek4102af92008-03-13 03:04:22 +0000244 if (badCFG) {
245 delete cfg;
246 cfg = NULL;
247 return NULL;
248 }
249
Ted Kremenek322f58d2007-09-26 21:23:31 +0000250 // NULL out cfg so that repeated calls to the builder will fail and that
251 // the ownership of the constructed CFG is passed to the caller.
252 CFG* t = cfg;
253 cfg = NULL;
254 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000255}
256
257/// createBlock - Used to lazily create blocks that are connected
258/// to the current (global) succcessor.
259CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000260 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000261 if (add_successor && Succ) B->addSuccessor(Succ);
262 return B;
263}
264
265/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000266/// we must reverse the statements because they have been inserted
267/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000268void CFGBuilder::FinishBlock(CFGBlock* B) {
269 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000270 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000271}
272
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000273/// addStmt - Used to add statements/expressions to the current CFGBlock
274/// "Block". This method calls WalkAST on the passed statement to see if it
275/// contains any short-circuit expressions. If so, it recursively creates
276/// the necessary blocks for such expressions. It returns the "topmost" block
277/// of the created blocks, or the original value of "Block" when this method
278/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000279CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000280 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000281 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000282}
283
284/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000285/// add extra blocks for ternary operators, &&, and ||. We also
286/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000287CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
288 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000289 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000290 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000291
292 // Create the confluence block that will "merge" the results
293 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000294 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
295 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000296 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000297
298 // Create a block for the LHS expression if there is an LHS expression.
299 // A GCC extension allows LHS to be NULL, causing the condition to
300 // be the value that is returned instead.
301 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000302 Succ = ConfluenceBlock;
303 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000304 CFGBlock* LHSBlock = NULL;
305 if (C->getLHS()) {
306 LHSBlock = Visit(C->getLHS());
307 FinishBlock(LHSBlock);
308 Block = NULL;
309 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000310
Ted Kremenekecc04c92007-11-26 18:20:26 +0000311 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000312 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000313 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000314 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000315
Ted Kremenekecc04c92007-11-26 18:20:26 +0000316 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000317 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000318
319 if (LHSBlock)
320 Block->addSuccessor(LHSBlock);
321 else {
322 // If we have no LHS expression, add the ConfluenceBlock as a direct
323 // successor for the block containing the condition. Moreover,
324 // we need to reverse the order of the predecessors in the
325 // ConfluenceBlock because the RHSBlock will have been added to
326 // the succcessors already, and we want the first predecessor to the
327 // the block containing the expression for the case when the ternary
328 // expression evaluates to true.
329 Block->addSuccessor(ConfluenceBlock);
330 assert (ConfluenceBlock->pred_size() == 2);
331 std::reverse(ConfluenceBlock->pred_begin(),
332 ConfluenceBlock->pred_end());
333 }
334
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000335 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000336
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000337 Block->setTerminator(C);
338 return addStmt(C->getCond());
339 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000340
341 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000342 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000343
344 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
345 ConfluenceBlock->appendStmt(C);
346 FinishBlock(ConfluenceBlock);
347
348 Succ = ConfluenceBlock;
349 Block = NULL;
350 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000351 FinishBlock(LHSBlock);
352
Ted Kremenek49a436d2007-08-31 17:03:41 +0000353 Succ = ConfluenceBlock;
354 Block = NULL;
355 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000356 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000357
358 Block = createBlock(false);
359 Block->addSuccessor(LHSBlock);
360 Block->addSuccessor(RHSBlock);
361 Block->setTerminator(C);
362 return addStmt(C->getCond());
363 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000364
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000365 case Stmt::DeclStmtClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000366 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000367
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000368 if (!D->getNextDeclarator()) {
369 Block->appendStmt(Terminator);
370 return WalkAST_VisitDeclSubExpr(D);
371 }
372 else {
373 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
374 BufTy Buf;
375 CFGBlock* B = 0;
376 do { Buf.push_back(D); D = D->getNextDeclarator(); } while (D);
377 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
378 // Get the alignment of UnaryDeclStmt, padding out to >=8 bytes.
379 unsigned A = llvm::AlignOf<UnaryDeclStmt>::Alignment < 8
380 ? 8 : llvm::AlignOf<UnaryDeclStmt>::Alignment;
381
382 // Allocate the UnaryDeclStmt using the BumpPtrAllocator. It will
383 // get automatically freed with the CFG.
384 void* Mem = cfg->getAllocator().Allocate(sizeof(UnaryDeclStmt), A);
385 // Append the fake DeclStmt to block.
386 Block->appendStmt(new (Mem) UnaryDeclStmt(*I));
387 B = WalkAST_VisitDeclSubExpr(*I);
388 }
389 return B;
390 }
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000391 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000392
Ted Kremenek19bb3562007-08-28 19:26:49 +0000393 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000394 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000395 AddressTakenLabels.insert(A->getLabel());
396
Ted Kremenek411cdee2008-04-16 21:10:48 +0000397 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000398 return Block;
399 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000400
Ted Kremenek15c27a82007-08-28 18:30:10 +0000401 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000402 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000403
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000404 case Stmt::UnaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000405 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000406
407 // sizeof(expressions). For such expressions,
408 // the subexpression is not really evaluated, so
409 // we don't care about control-flow within the sizeof.
410 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000411 Block->appendStmt(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000412 return Block;
413 }
414
415 break;
416 }
417
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000418 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000419 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000420
421 if (B->isLogicalOp()) { // && or ||
422 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
423 ConfluenceBlock->appendStmt(B);
424 FinishBlock(ConfluenceBlock);
425
426 // create the block evaluating the LHS
427 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000428 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000429
430 // create the block evaluating the RHS
431 Succ = ConfluenceBlock;
432 Block = NULL;
433 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekafe54332007-12-21 19:49:00 +0000434
435 // Now link the LHSBlock with RHSBlock.
436 if (B->getOpcode() == BinaryOperator::LOr) {
437 LHSBlock->addSuccessor(ConfluenceBlock);
438 LHSBlock->addSuccessor(RHSBlock);
439 }
440 else {
441 assert (B->getOpcode() == BinaryOperator::LAnd);
442 LHSBlock->addSuccessor(RHSBlock);
443 LHSBlock->addSuccessor(ConfluenceBlock);
444 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000445
446 // Generate the blocks for evaluating the LHS.
447 Block = LHSBlock;
448 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000449 }
450 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
451 Block->appendStmt(B);
452 addStmt(B->getRHS());
453 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000454 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000455
456 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000457 }
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000458
459 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000460 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000461
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000462 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000463 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000464 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000465
Ted Kremenek411cdee2008-04-16 21:10:48 +0000466 if (AlwaysAddStmt) Block->appendStmt(Terminator);
467 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000468}
469
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000470/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
471/// for initializers in Decls.
472CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
473 VarDecl* VD = dyn_cast<VarDecl>(D);
474
475 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000476 return Block;
477
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000478 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000479
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000480 if (!Init)
481 return Block;
482
483 // Optimization: Don't create separate block-level statements for literals.
484 switch (Init->getStmtClass()) {
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000485 case Stmt::IntegerLiteralClass:
486 case Stmt::CharacterLiteralClass:
487 case Stmt::StringLiteralClass:
488 break;
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000489 default:
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000490 Block = addStmt(Init);
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000491 }
492
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000493 return Block;
494}
495
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000496/// WalkAST_VisitChildren - Utility method to call WalkAST on the
497/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000498CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000499 CFGBlock* B = Block;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000500 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000501 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000502 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000503
504 return B;
505}
506
Ted Kremenek15c27a82007-08-28 18:30:10 +0000507/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
508/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000509CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
510 Block->appendStmt(Terminator);
511 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000512}
513
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000514/// VisitStmt - Handle statements with no branching control flow.
515CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
516 // We cannot assume that we are in the middle of a basic block, since
517 // the CFG might only be constructed for this single statement. If
518 // we have no current basic block, just create one lazily.
519 if (!Block) Block = createBlock();
520
521 // Simply add the statement to the current block. We actually
522 // insert statements in reverse order; this order is reversed later
523 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000524 addStmt(Statement);
525
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000526 return Block;
527}
528
529CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
530 return Block;
531}
532
533CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000534
535 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000536
Ted Kremenekd34066c2008-02-26 00:22:58 +0000537 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
538 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000539 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000540 }
541
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000542 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000543}
544
545CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
546 // We may see an if statement in the middle of a basic block, or
547 // it may be the first statement we are processing. In either case,
548 // we create a new basic block. First, we create the blocks for
549 // the then...else statements, and then we create the block containing
550 // the if statement. If we were in the middle of a block, we
551 // stop processing that block and reverse its statements. That block
552 // is then the implicit successor for the "then" and "else" clauses.
553
554 // The block we were proccessing is now finished. Make it the
555 // successor block.
556 if (Block) {
557 Succ = Block;
558 FinishBlock(Block);
559 }
560
561 // Process the false branch. NULL out Block so that the recursive
562 // call to Visit will create a new basic block.
563 // Null out Block so that all successor
564 CFGBlock* ElseBlock = Succ;
565
566 if (Stmt* Else = I->getElse()) {
567 SaveAndRestore<CFGBlock*> sv(Succ);
568
569 // NULL out Block so that the recursive call to Visit will
570 // create a new basic block.
571 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000572 ElseBlock = Visit(Else);
573
574 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
575 ElseBlock = sv.get();
576 else if (Block)
577 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000578 }
579
580 // Process the true branch. NULL out Block so that the recursive
581 // call to Visit will create a new basic block.
582 // Null out Block so that all successor
583 CFGBlock* ThenBlock;
584 {
585 Stmt* Then = I->getThen();
586 assert (Then);
587 SaveAndRestore<CFGBlock*> sv(Succ);
588 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000589 ThenBlock = Visit(Then);
590
591 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
592 ThenBlock = sv.get();
593 else if (Block)
594 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000595 }
596
597 // Now create a new block containing the if statement.
598 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000599
600 // Set the terminator of the new block to the If statement.
601 Block->setTerminator(I);
602
603 // Now add the successors.
604 Block->addSuccessor(ThenBlock);
605 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000606
607 // Add the condition as the last statement in the new block. This
608 // may create new blocks as the condition may contain control-flow. Any
609 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000610 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000611}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000612
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000613
614CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
615 // If we were in the middle of a block we stop processing that block
616 // and reverse its statements.
617 //
618 // NOTE: If a "return" appears in the middle of a block, this means
619 // that the code afterwards is DEAD (unreachable). We still
620 // keep a basic block for that code; a simple "mark-and-sweep"
621 // from the entry block will be able to report such dead
622 // blocks.
623 if (Block) FinishBlock(Block);
624
625 // Create the new block.
626 Block = createBlock(false);
627
628 // The Exit block is the only successor.
629 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000630
631 // Add the return statement to the block. This may create new blocks
632 // if R contains control-flow (short-circuit operations).
633 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000634}
635
636CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
637 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000638 Visit(L->getSubStmt());
639 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000640
641 if (!LabelBlock) // This can happen when the body is empty, i.e.
642 LabelBlock=createBlock(); // scopes that only contains NullStmts.
643
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000644 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
645 LabelMap[ L ] = LabelBlock;
646
647 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000648 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000649 // label (and we have already processed the substatement) there is no
650 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000651 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000652 FinishBlock(LabelBlock);
653
654 // We set Block to NULL to allow lazy creation of a new block
655 // (if necessary);
656 Block = NULL;
657
658 // This block is now the implicit successor of other blocks.
659 Succ = LabelBlock;
660
661 return LabelBlock;
662}
663
664CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
665 // Goto is a control-flow statement. Thus we stop processing the
666 // current block and create a new one.
667 if (Block) FinishBlock(Block);
668 Block = createBlock(false);
669 Block->setTerminator(G);
670
671 // If we already know the mapping to the label block add the
672 // successor now.
673 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
674
675 if (I == LabelMap.end())
676 // We will need to backpatch this block later.
677 BackpatchBlocks.push_back(Block);
678 else
679 Block->addSuccessor(I->second);
680
681 return Block;
682}
683
684CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
685 // "for" is a control-flow statement. Thus we stop processing the
686 // current block.
687
688 CFGBlock* LoopSuccessor = NULL;
689
690 if (Block) {
691 FinishBlock(Block);
692 LoopSuccessor = Block;
693 }
694 else LoopSuccessor = Succ;
695
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000696 // Because of short-circuit evaluation, the condition of the loop
697 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
698 // blocks that evaluate the condition.
699 CFGBlock* ExitConditionBlock = createBlock(false);
700 CFGBlock* EntryConditionBlock = ExitConditionBlock;
701
702 // Set the terminator for the "exit" condition block.
703 ExitConditionBlock->setTerminator(F);
704
705 // Now add the actual condition to the condition block. Because the
706 // condition itself may contain control-flow, new blocks may be created.
707 if (Stmt* C = F->getCond()) {
708 Block = ExitConditionBlock;
709 EntryConditionBlock = addStmt(C);
710 if (Block) FinishBlock(EntryConditionBlock);
711 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000712
713 // The condition block is the implicit successor for the loop body as
714 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000715 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000716
717 // Now create the loop body.
718 {
719 assert (F->getBody());
720
721 // Save the current values for Block, Succ, and continue and break targets
722 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
723 save_continue(ContinueTargetBlock),
724 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000725
Ted Kremenekaf603f72007-08-30 18:39:40 +0000726 // Create a new block to contain the (bottom) of the loop body.
727 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000728
Ted Kremeneke9334502008-09-04 21:48:47 +0000729 if (Stmt* I = F->getInc()) {
730 // Generate increment code in its own basic block. This is the target
731 // of continue statements.
732 Succ = addStmt(I);
733 Block = 0;
734 ContinueTargetBlock = Succ;
735 }
736 else {
737 // No increment code. Continues should go the the entry condition block.
738 ContinueTargetBlock = EntryConditionBlock;
739 }
740
741 // All breaks should go to the code following the loop.
742 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000743
744 // Now populate the body block, and in the process create new blocks
745 // as we walk the body of the loop.
746 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000747
748 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000749 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000750 else if (Block)
751 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000752
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000753 // This new body block is a successor to our "exit" condition block.
754 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000755 }
756
757 // Link up the condition block with the code that follows the loop.
758 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000759 ExitConditionBlock->addSuccessor(LoopSuccessor);
760
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000761 // If the loop contains initialization, create a new block for those
762 // statements. This block can also contain statements that precede
763 // the loop.
764 if (Stmt* I = F->getInit()) {
765 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000766 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000767 }
768 else {
769 // There is no loop initialization. We are thus basically a while
770 // loop. NULL out Block to force lazy block construction.
771 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000772 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000773 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000774 }
775}
776
777CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
778 // "while" is a control-flow statement. Thus we stop processing the
779 // current block.
780
781 CFGBlock* LoopSuccessor = NULL;
782
783 if (Block) {
784 FinishBlock(Block);
785 LoopSuccessor = Block;
786 }
787 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000788
789 // Because of short-circuit evaluation, the condition of the loop
790 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
791 // blocks that evaluate the condition.
792 CFGBlock* ExitConditionBlock = createBlock(false);
793 CFGBlock* EntryConditionBlock = ExitConditionBlock;
794
795 // Set the terminator for the "exit" condition block.
796 ExitConditionBlock->setTerminator(W);
797
798 // Now add the actual condition to the condition block. Because the
799 // condition itself may contain control-flow, new blocks may be created.
800 // Thus we update "Succ" after adding the condition.
801 if (Stmt* C = W->getCond()) {
802 Block = ExitConditionBlock;
803 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000804 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000805 if (Block) FinishBlock(EntryConditionBlock);
806 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000807
808 // The condition block is the implicit successor for the loop body as
809 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000810 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000811
812 // Process the loop body.
813 {
814 assert (W->getBody());
815
816 // Save the current values for Block, Succ, and continue and break targets
817 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
818 save_continue(ContinueTargetBlock),
819 save_break(BreakTargetBlock);
820
821 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000822 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000823
824 // All breaks should go to the code following the loop.
825 BreakTargetBlock = LoopSuccessor;
826
827 // NULL out Block to force lazy instantiation of blocks for the body.
828 Block = NULL;
829
830 // Create the body. The returned block is the entry to the loop body.
831 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000832
833 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000834 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000835 else if (Block)
836 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000837
838 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000839 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000840 }
841
842 // Link up the condition block with the code that follows the loop.
843 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000844 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000845
846 // There can be no more statements in the condition block
847 // since we loop back to this block. NULL out Block to force
848 // lazy creation of another block.
849 Block = NULL;
850
851 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000852 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000853 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000854}
855
856CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
857 // "do...while" is a control-flow statement. Thus we stop processing the
858 // current block.
859
860 CFGBlock* LoopSuccessor = NULL;
861
862 if (Block) {
863 FinishBlock(Block);
864 LoopSuccessor = Block;
865 }
866 else LoopSuccessor = Succ;
867
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000868 // Because of short-circuit evaluation, the condition of the loop
869 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
870 // blocks that evaluate the condition.
871 CFGBlock* ExitConditionBlock = createBlock(false);
872 CFGBlock* EntryConditionBlock = ExitConditionBlock;
873
874 // Set the terminator for the "exit" condition block.
875 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000876
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000877 // Now add the actual condition to the condition block. Because the
878 // condition itself may contain control-flow, new blocks may be created.
879 if (Stmt* C = D->getCond()) {
880 Block = ExitConditionBlock;
881 EntryConditionBlock = addStmt(C);
882 if (Block) FinishBlock(EntryConditionBlock);
883 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000884
Ted Kremenek54827132008-02-27 07:20:00 +0000885 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000886 Succ = EntryConditionBlock;
887
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000888 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000889 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000890 {
891 assert (D->getBody());
892
893 // Save the current values for Block, Succ, and continue and break targets
894 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
895 save_continue(ContinueTargetBlock),
896 save_break(BreakTargetBlock);
897
898 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000899 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000900
901 // All breaks should go to the code following the loop.
902 BreakTargetBlock = LoopSuccessor;
903
904 // NULL out Block to force lazy instantiation of blocks for the body.
905 Block = NULL;
906
907 // Create the body. The returned block is the entry to the loop body.
908 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000909
Ted Kremenekaf603f72007-08-30 18:39:40 +0000910 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000911 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000912 else if (Block)
913 FinishBlock(BodyBlock);
914
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000915 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000916 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000917 }
918
919 // Link up the condition block with the code that follows the loop.
920 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000921 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000922
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000923 // There can be no more statements in the body block(s)
924 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000925 // lazy creation of another block.
926 Block = NULL;
927
928 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000929 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000930 return BodyBlock;
931}
932
933CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
934 // "continue" is a control-flow statement. Thus we stop processing the
935 // current block.
936 if (Block) FinishBlock(Block);
937
938 // Now create a new block that ends with the continue statement.
939 Block = createBlock(false);
940 Block->setTerminator(C);
941
942 // If there is no target for the continue, then we are looking at an
943 // incomplete AST. Handle this by not registering a successor.
944 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
945
946 return Block;
947}
948
949CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
950 // "break" is a control-flow statement. Thus we stop processing the
951 // current block.
952 if (Block) FinishBlock(Block);
953
954 // Now create a new block that ends with the continue statement.
955 Block = createBlock(false);
956 Block->setTerminator(B);
957
958 // If there is no target for the break, then we are looking at an
959 // incomplete AST. Handle this by not registering a successor.
960 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
961
962 return Block;
963}
964
Ted Kremenek411cdee2008-04-16 21:10:48 +0000965CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000966 // "switch" is a control-flow statement. Thus we stop processing the
967 // current block.
968 CFGBlock* SwitchSuccessor = NULL;
969
970 if (Block) {
971 FinishBlock(Block);
972 SwitchSuccessor = Block;
973 }
974 else SwitchSuccessor = Succ;
975
976 // Save the current "switch" context.
977 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +0000978 save_break(BreakTargetBlock),
979 save_default(DefaultCaseBlock);
980
981 // Set the "default" case to be the block after the switch statement.
982 // If the switch statement contains a "default:", this value will
983 // be overwritten with the block for that code.
984 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +0000985
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000986 // Create a new block that will contain the switch statement.
987 SwitchTerminatedBlock = createBlock(false);
988
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000989 // Now process the switch body. The code after the switch is the implicit
990 // successor.
991 Succ = SwitchSuccessor;
992 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000993
994 // When visiting the body, the case statements should automatically get
995 // linked up to the switch. We also don't keep a pointer to the body,
996 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000997 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000998 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000999 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001000 if (Block) FinishBlock(BodyBlock);
1001
Ted Kremenek295222c2008-02-13 21:46:34 +00001002 // If we have no "default:" case, the default transition is to the
1003 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001004 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001005
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001006 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001007 SwitchTerminatedBlock->setTerminator(Terminator);
1008 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001009 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001010
Ted Kremenek411cdee2008-04-16 21:10:48 +00001011 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001012}
1013
Ted Kremenek411cdee2008-04-16 21:10:48 +00001014CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001015 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001016 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001017
Ted Kremenek411cdee2008-04-16 21:10:48 +00001018 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001019 CFGBlock* CaseBlock = Block;
1020 if (!CaseBlock) CaseBlock = createBlock();
1021
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001022 // Cases statements partition blocks, so this is the top of
1023 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001024 CaseBlock->setLabel(Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001025 FinishBlock(CaseBlock);
1026
1027 // Add this block to the list of successors for the block with the
1028 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001029 assert (SwitchTerminatedBlock);
1030 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001031
1032 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1033 Block = NULL;
1034
1035 // This block is now the implicit successor of other blocks.
1036 Succ = CaseBlock;
1037
Ted Kremenek2677ea82008-03-15 07:45:02 +00001038 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001039}
Ted Kremenek295222c2008-02-13 21:46:34 +00001040
Ted Kremenek411cdee2008-04-16 21:10:48 +00001041CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1042 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001043 DefaultCaseBlock = Block;
1044 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1045
1046 // Default statements partition blocks, so this is the top of
1047 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001048 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001049 FinishBlock(DefaultCaseBlock);
1050
1051 // Unlike case statements, we don't add the default block to the
1052 // successors for the switch statement immediately. This is done
1053 // when we finish processing the switch statement. This allows for
1054 // the default case (including a fall-through to the code after the
1055 // switch statement) to always be the last successor of a switch-terminated
1056 // block.
1057
1058 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1059 Block = NULL;
1060
1061 // This block is now the implicit successor of other blocks.
1062 Succ = DefaultCaseBlock;
1063
1064 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001065}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001066
Ted Kremenek19bb3562007-08-28 19:26:49 +00001067CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1068 // Lazily create the indirect-goto dispatch block if there isn't one
1069 // already.
1070 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1071
1072 if (!IBlock) {
1073 IBlock = createBlock(false);
1074 cfg->setIndirectGotoBlock(IBlock);
1075 }
1076
1077 // IndirectGoto is a control-flow statement. Thus we stop processing the
1078 // current block and create a new one.
1079 if (Block) FinishBlock(Block);
1080 Block = createBlock(false);
1081 Block->setTerminator(I);
1082 Block->addSuccessor(IBlock);
1083 return addStmt(I->getTarget());
1084}
1085
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001086
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001087} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001088
1089/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1090/// block has no successors or predecessors. If this is the first block
1091/// created in the CFG, it is automatically set to be the Entry and Exit
1092/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001093CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001094 bool first_block = begin() == end();
1095
1096 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001097 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001098
1099 // If this is the first block, set it as the Entry and Exit.
1100 if (first_block) Entry = Exit = &front();
1101
1102 // Return the block.
1103 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001104}
1105
Ted Kremenek026473c2007-08-23 16:51:22 +00001106/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1107/// CFG is returned to the caller.
1108CFG* CFG::buildCFG(Stmt* Statement) {
1109 CFGBuilder Builder;
1110 return Builder.buildCFG(Statement);
1111}
1112
1113/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001114void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1115
Ted Kremenek63f58872007-10-01 19:33:33 +00001116//===----------------------------------------------------------------------===//
1117// CFG: Queries for BlkExprs.
1118//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001119
Ted Kremenek63f58872007-10-01 19:33:33 +00001120namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001121 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001122}
1123
Ted Kremenek411cdee2008-04-16 21:10:48 +00001124static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1125 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001126 return;
1127
Ted Kremenek411cdee2008-04-16 21:10:48 +00001128 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001129 if (!*I) continue;
1130
1131 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1132 if (B->isAssignmentOp()) Set.insert(B);
1133
1134 FindSubExprAssignments(*I, Set);
1135 }
1136}
1137
Ted Kremenek63f58872007-10-01 19:33:33 +00001138static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1139 BlkExprMapTy* M = new BlkExprMapTy();
1140
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001141 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001142 // only assignments that we want to *possibly* register as a block-level
1143 // expression. Basically, if an assignment occurs both in a subexpression
1144 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001145 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1146
Ted Kremenek63f58872007-10-01 19:33:33 +00001147 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1148 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001149 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001150
Ted Kremenek411cdee2008-04-16 21:10:48 +00001151 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1152
1153 // Iterate over the statements again on identify the Expr* and Stmt* at
1154 // the block-level that are block-level expressions.
1155
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001156 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001157 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001158
Ted Kremenek411cdee2008-04-16 21:10:48 +00001159 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001160 // Assignment expressions that are not nested within another
1161 // expression are really "statements" whose value is never
1162 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001163 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001164 continue;
1165 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001166 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001167 // Special handling for statement expressions. The last statement
1168 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001169 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001170 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001171 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001172 (*M)[C->body_back()] = x;
1173 }
1174 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001175
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001176 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001177 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001178 }
1179
Ted Kremenek411cdee2008-04-16 21:10:48 +00001180 // Look at terminators. The condition is a block-level expression.
1181
1182 Expr* Exp = I->getTerminatorCondition();
1183
1184 if (Exp && M->find(Exp) == M->end()) {
1185 unsigned x = M->size();
1186 (*M)[Exp] = x;
1187 }
1188 }
1189
Ted Kremenek63f58872007-10-01 19:33:33 +00001190 return M;
1191}
1192
Ted Kremenek86946742008-01-17 20:48:37 +00001193CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1194 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001195 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1196
1197 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001198 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001199
1200 if (I == M->end()) return CFG::BlkExprNumTy();
1201 else return CFG::BlkExprNumTy(I->second);
1202}
1203
1204unsigned CFG::getNumBlkExprs() {
1205 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1206 return M->size();
1207 else {
1208 // We assume callers interested in the number of BlkExprs will want
1209 // the map constructed if it doesn't already exist.
1210 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1211 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1212 }
1213}
1214
Ted Kremenek274f4332008-04-28 18:00:46 +00001215//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001216// Cleanup: CFG dstor.
1217//===----------------------------------------------------------------------===//
1218
Ted Kremenek63f58872007-10-01 19:33:33 +00001219CFG::~CFG() {
1220 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1221}
1222
Ted Kremenek7dba8602007-08-29 21:56:09 +00001223//===----------------------------------------------------------------------===//
1224// CFG pretty printing
1225//===----------------------------------------------------------------------===//
1226
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001227namespace {
1228
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001229class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001230
Ted Kremenek42a509f2007-08-31 21:30:12 +00001231 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1232 StmtMapTy StmtMap;
1233 signed CurrentBlock;
1234 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001235
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001236public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001237
Ted Kremenek42a509f2007-08-31 21:30:12 +00001238 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1239 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1240 unsigned j = 1;
1241 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1242 BI != BEnd; ++BI, ++j )
1243 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1244 }
1245 }
1246
1247 virtual ~StmtPrinterHelper() {}
1248
1249 void setBlockID(signed i) { CurrentBlock = i; }
1250 void setStmtID(unsigned i) { CurrentStmt = i; }
1251
Ted Kremeneka95d3752008-09-13 05:16:45 +00001252 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001253
Ted Kremenek411cdee2008-04-16 21:10:48 +00001254 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001255
1256 if (I == StmtMap.end())
1257 return false;
1258
1259 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1260 && I->second.second == CurrentStmt)
1261 return false;
1262
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001263 OS << "[B" << I->second.first << "." << I->second.second << "]";
1264 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001265 }
1266};
1267
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001268class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1269 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1270
Ted Kremeneka95d3752008-09-13 05:16:45 +00001271 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001272 StmtPrinterHelper* Helper;
1273public:
Ted Kremeneka95d3752008-09-13 05:16:45 +00001274 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper)
Ted Kremenek42a509f2007-08-31 21:30:12 +00001275 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001276
1277 void VisitIfStmt(IfStmt* I) {
1278 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001279 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001280 }
1281
1282 // Default case.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001283 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001284
1285 void VisitForStmt(ForStmt* F) {
1286 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001287 if (F->getInit()) OS << "...";
1288 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001289 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001290 OS << "; ";
1291 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001292 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001293 }
1294
1295 void VisitWhileStmt(WhileStmt* W) {
1296 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001297 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001298 }
1299
1300 void VisitDoStmt(DoStmt* D) {
1301 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001302 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001303 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001304
Ted Kremenek411cdee2008-04-16 21:10:48 +00001305 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001306 OS << "switch ";
Ted Kremenek411cdee2008-04-16 21:10:48 +00001307 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001308 }
1309
Ted Kremenek805e9a82007-08-31 21:49:40 +00001310 void VisitConditionalOperator(ConditionalOperator* C) {
1311 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001312 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001313 }
1314
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001315 void VisitChooseExpr(ChooseExpr* C) {
1316 OS << "__builtin_choose_expr( ";
1317 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001318 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001319 }
1320
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001321 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1322 OS << "goto *";
1323 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001324 }
1325
Ted Kremenek805e9a82007-08-31 21:49:40 +00001326 void VisitBinaryOperator(BinaryOperator* B) {
1327 if (!B->isLogicalOp()) {
1328 VisitExpr(B);
1329 return;
1330 }
1331
1332 B->getLHS()->printPretty(OS,Helper);
1333
1334 switch (B->getOpcode()) {
1335 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001336 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001337 return;
1338 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001339 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001340 return;
1341 default:
1342 assert(false && "Invalid logical operator.");
1343 }
1344 }
1345
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001346 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001347 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001348 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001349};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001350
1351
Ted Kremeneka95d3752008-09-13 05:16:45 +00001352void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001353 if (Helper) {
1354 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001355 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001356 CompoundStmt* Sub = SE->getSubStmt();
1357
1358 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001359 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001360 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001361 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001362 return;
1363 }
1364 }
1365
1366 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001367 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001368 if (B->getOpcode() == BinaryOperator::Comma) {
1369 OS << "... , ";
1370 Helper->handledStmt(B->getRHS(),OS);
1371 OS << '\n';
1372 return;
1373 }
1374 }
1375 }
1376
Ted Kremenek411cdee2008-04-16 21:10:48 +00001377 Terminator->printPretty(OS, Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001378
1379 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001380 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001381}
1382
Ted Kremeneka95d3752008-09-13 05:16:45 +00001383void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B,
Ted Kremenek42a509f2007-08-31 21:30:12 +00001384 StmtPrinterHelper* Helper, bool print_edges) {
1385
1386 if (Helper) Helper->setBlockID(B.getBlockID());
1387
Ted Kremenek7dba8602007-08-29 21:56:09 +00001388 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001389 OS << "\n [ B" << B.getBlockID();
1390
1391 if (&B == &cfg->getEntry())
1392 OS << " (ENTRY) ]\n";
1393 else if (&B == &cfg->getExit())
1394 OS << " (EXIT) ]\n";
1395 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001396 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001397 else
1398 OS << " ]\n";
1399
Ted Kremenek9cffe732007-08-29 23:20:49 +00001400 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001401 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001402
1403 if (print_edges)
1404 OS << " ";
1405
Ted Kremenek411cdee2008-04-16 21:10:48 +00001406 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001407 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001408 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001409 OS << "case ";
1410 C->getLHS()->printPretty(OS);
1411 if (C->getRHS()) {
1412 OS << " ... ";
1413 C->getRHS()->printPretty(OS);
1414 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001415 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001416 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001417 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001418 else
1419 assert(false && "Invalid label statement in CFGBlock.");
1420
Ted Kremenek9cffe732007-08-29 23:20:49 +00001421 OS << ":\n";
1422 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001423
Ted Kremenekfddd5182007-08-21 21:42:03 +00001424 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001425 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001426
1427 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1428 I != E ; ++I, ++j ) {
1429
Ted Kremenek9cffe732007-08-29 23:20:49 +00001430 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001431 if (print_edges)
1432 OS << " ";
1433
Ted Kremeneka95d3752008-09-13 05:16:45 +00001434 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001435
1436 if (Helper)
1437 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001438
1439 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001440 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001441
Ted Kremenek9cffe732007-08-29 23:20:49 +00001442 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001443 if (B.getTerminator()) {
1444 if (print_edges)
1445 OS << " ";
1446
Ted Kremenek9cffe732007-08-29 23:20:49 +00001447 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001448
1449 if (Helper) Helper->setBlockID(-1);
1450
1451 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1452 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001453 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001454 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001455
Ted Kremenek9cffe732007-08-29 23:20:49 +00001456 if (print_edges) {
1457 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001458 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001459 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001460
Ted Kremenek42a509f2007-08-31 21:30:12 +00001461 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1462 I != E; ++I, ++i) {
1463
1464 if (i == 8 || (i-8) == 0)
1465 OS << "\n ";
1466
Ted Kremenek9cffe732007-08-29 23:20:49 +00001467 OS << " B" << (*I)->getBlockID();
1468 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001469
1470 OS << '\n';
1471
1472 // Print the successors of this block.
1473 OS << " Successors (" << B.succ_size() << "):";
1474 i = 0;
1475
1476 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1477 I != E; ++I, ++i) {
1478
1479 if (i == 8 || (i-8) % 10 == 0)
1480 OS << "\n ";
1481
1482 OS << " B" << (*I)->getBlockID();
1483 }
1484
Ted Kremenek9cffe732007-08-29 23:20:49 +00001485 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001486 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001487}
1488
1489} // end anonymous namespace
1490
1491/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001492void CFG::dump() const { print(llvm::errs()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001493
1494/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001495void CFG::print(llvm::raw_ostream& OS) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001496
1497 StmtPrinterHelper Helper(this);
1498
1499 // Print the entry block.
1500 print_block(OS, this, getEntry(), &Helper, true);
1501
1502 // Iterate through the CFGBlocks and print them one by one.
1503 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1504 // Skip the entry block, because we already printed it.
1505 if (&(*I) == &getEntry() || &(*I) == &getExit())
1506 continue;
1507
1508 print_block(OS, this, *I, &Helper, true);
1509 }
1510
1511 // Print the exit block.
1512 print_block(OS, this, getExit(), &Helper, true);
1513}
1514
1515/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001516void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001517
1518/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1519/// Generally this will only be called from CFG::print.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001520void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001521 StmtPrinterHelper Helper(cfg);
1522 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001523}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001524
Ted Kremeneka2925852008-01-30 23:02:42 +00001525/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001526void CFGBlock::printTerminator(llvm::raw_ostream& OS) const {
Ted Kremeneka2925852008-01-30 23:02:42 +00001527 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1528 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1529}
1530
Ted Kremenek411cdee2008-04-16 21:10:48 +00001531Expr* CFGBlock::getTerminatorCondition() {
1532
1533 if (!Terminator)
1534 return NULL;
1535
1536 Expr* E = NULL;
1537
1538 switch (Terminator->getStmtClass()) {
1539 default:
1540 break;
1541
1542 case Stmt::ForStmtClass:
1543 E = cast<ForStmt>(Terminator)->getCond();
1544 break;
1545
1546 case Stmt::WhileStmtClass:
1547 E = cast<WhileStmt>(Terminator)->getCond();
1548 break;
1549
1550 case Stmt::DoStmtClass:
1551 E = cast<DoStmt>(Terminator)->getCond();
1552 break;
1553
1554 case Stmt::IfStmtClass:
1555 E = cast<IfStmt>(Terminator)->getCond();
1556 break;
1557
1558 case Stmt::ChooseExprClass:
1559 E = cast<ChooseExpr>(Terminator)->getCond();
1560 break;
1561
1562 case Stmt::IndirectGotoStmtClass:
1563 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1564 break;
1565
1566 case Stmt::SwitchStmtClass:
1567 E = cast<SwitchStmt>(Terminator)->getCond();
1568 break;
1569
1570 case Stmt::ConditionalOperatorClass:
1571 E = cast<ConditionalOperator>(Terminator)->getCond();
1572 break;
1573
1574 case Stmt::BinaryOperatorClass: // '&&' and '||'
1575 E = cast<BinaryOperator>(Terminator)->getLHS();
1576 break;
1577 }
1578
1579 return E ? E->IgnoreParens() : NULL;
1580}
1581
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001582bool CFGBlock::hasBinaryBranchTerminator() const {
1583
1584 if (!Terminator)
1585 return false;
1586
1587 Expr* E = NULL;
1588
1589 switch (Terminator->getStmtClass()) {
1590 default:
1591 return false;
1592
1593 case Stmt::ForStmtClass:
1594 case Stmt::WhileStmtClass:
1595 case Stmt::DoStmtClass:
1596 case Stmt::IfStmtClass:
1597 case Stmt::ChooseExprClass:
1598 case Stmt::ConditionalOperatorClass:
1599 case Stmt::BinaryOperatorClass:
1600 return true;
1601 }
1602
1603 return E ? E->IgnoreParens() : NULL;
1604}
1605
Ted Kremeneka2925852008-01-30 23:02:42 +00001606
Ted Kremenek7dba8602007-08-29 21:56:09 +00001607//===----------------------------------------------------------------------===//
1608// CFG Graphviz Visualization
1609//===----------------------------------------------------------------------===//
1610
Ted Kremenek42a509f2007-08-31 21:30:12 +00001611
1612#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001613static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001614#endif
1615
1616void CFG::viewCFG() const {
1617#ifndef NDEBUG
1618 StmtPrinterHelper H(this);
1619 GraphHelper = &H;
1620 llvm::ViewGraph(this,"CFG");
1621 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001622#endif
1623}
1624
Ted Kremenek7dba8602007-08-29 21:56:09 +00001625namespace llvm {
1626template<>
1627struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1628 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1629
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001630#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001631 std::string OutSStr;
1632 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001633 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001634 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001635
1636 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1637
1638 // Process string output to make it nicer...
1639 for (unsigned i = 0; i != OutStr.length(); ++i)
1640 if (OutStr[i] == '\n') { // Left justify
1641 OutStr[i] = '\\';
1642 OutStr.insert(OutStr.begin()+i+1, 'l');
1643 }
1644
1645 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001646#else
1647 return "";
1648#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001649 }
1650};
1651} // end namespace llvm