blob: ffc42bb6e1c34408cd995db104cce5ce983ca1fb [file] [log] [blame]
Ted Kremenek97f75312007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenek97f75312007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
Steve Naroff9ed3e772008-05-29 21:12:08 +000016#include "clang/AST/ExprObjC.h"
Ted Kremenek95e854d2007-08-21 22:06:14 +000017#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000018#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000019#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000020#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000021#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000022#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000023#include "llvm/Support/Compiler.h"
Ted Kremenekd058a9c2008-04-28 18:00:46 +000024#include <llvm/Support/Allocator.h>
Ted Kremenek97f75312007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000027#include <sstream>
Ted Kremenek5ee98a72008-01-11 00:40:29 +000028
Ted Kremenek97f75312007-08-21 21:42:03 +000029using namespace clang;
30
31namespace {
32
Ted Kremenekd6e50602007-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 Kremenek98cee3a2008-01-08 18:15:10 +000036struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000037 SaveAndRestore(T& x) : X(x), old_value(x) {}
38 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000039 T get() { return old_value; }
40
Ted Kremenekd6e50602007-08-23 21:26:19 +000041 T& X;
42 T old_value;
43};
Ted Kremenek97f75312007-08-21 21:42:03 +000044
Ted Kremeneka3195a32008-08-04 22:51:42 +000045/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek97f75312007-08-21 21:42:03 +000046/// The builder is stateful: an instance of the builder should be used to only
47/// construct a single CFG.
48///
49/// Example usage:
50///
51/// CFGBuilder builder;
52/// CFG* cfg = builder.BuildAST(stmt1);
53///
Ted Kremenek95e854d2007-08-21 22:06:14 +000054/// CFG construction is done via a recursive walk of an AST.
55/// We actually parse the AST in reverse order so that the successor
56/// of a basic block is constructed prior to its predecessor. This
57/// allows us to nicely capture implicit fall-throughs without extra
58/// basic blocks.
59///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000060class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000061 CFG* cfg;
62 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000063 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000064 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000065 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +000066 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +000067 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +000068
Ted Kremenek0edd3a92007-08-28 19:26:49 +000069 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +000070 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
71 LabelMapTy LabelMap;
72
Ted Kremenek0edd3a92007-08-28 19:26:49 +000073 // A list of blocks that end with a "goto" that must be backpatched to
74 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +000075 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +000076 BackpatchBlocksTy BackpatchBlocks;
77
Ted Kremenek0edd3a92007-08-28 19:26:49 +000078 // A list of labels whose address has been taken (for indirect gotos).
79 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
80 LabelSetTy AddressTakenLabels;
81
Ted Kremenek97f75312007-08-21 21:42:03 +000082public:
Ted Kremenek4db5b452007-08-23 16:51:22 +000083 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +000084 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +000085 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +000086 // Create an empty CFG.
87 cfg = new CFG();
88 }
89
90 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +000091
Ted Kremenek73543912007-08-23 21:42:29 +000092 // buildCFG - Used by external clients to construct the CFG.
93 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +000094
Ted Kremenek73543912007-08-23 21:42:29 +000095 // Visitors to walk an AST and construct the CFG. Called by
96 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +000097
Ted Kremenek73543912007-08-23 21:42:29 +000098 CFGBlock* VisitStmt(Stmt* Statement);
99 CFGBlock* VisitNullStmt(NullStmt* Statement);
100 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
101 CFGBlock* VisitIfStmt(IfStmt* I);
102 CFGBlock* VisitReturnStmt(ReturnStmt* R);
103 CFGBlock* VisitLabelStmt(LabelStmt* L);
104 CFGBlock* VisitGotoStmt(GotoStmt* G);
105 CFGBlock* VisitForStmt(ForStmt* F);
106 CFGBlock* VisitWhileStmt(WhileStmt* W);
107 CFGBlock* VisitDoStmt(DoStmt* D);
108 CFGBlock* VisitContinueStmt(ContinueStmt* C);
109 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000110 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
111 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000112 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000113 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000114
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000115 // FIXME: Add support for ObjC-specific control-flow structures.
116
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000117 // NYS == Not Yet Supported
118 CFGBlock* NYS() {
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000119 badCFG = true;
120 return Block;
121 }
122
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000123 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
124 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
125 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
126 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
127 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
128
129 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
130 return NYS();
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000131 }
132
Ted Kremenek73543912007-08-23 21:42:29 +0000133private:
134 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000135 CFGBlock* addStmt(Stmt* Terminator);
136 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
137 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000138 CFGBlock* WalkAST_VisitDeclSubExprs(StmtIterator& I);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000139 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +0000140 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000141
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000142 bool badCFG;
Ted Kremenek97f75312007-08-21 21:42:03 +0000143};
Ted Kremenek73543912007-08-23 21:42:29 +0000144
145/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
146/// represent an arbitrary statement. Examples include a single expression
147/// or a function body (compound statement). The ownership of the returned
148/// CFG is transferred to the caller. If CFG construction fails, this method
149/// returns NULL.
150CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000151 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000152 if (!Statement) return NULL;
153
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000154 badCFG = false;
155
Ted Kremenek73543912007-08-23 21:42:29 +0000156 // Create an empty block that will serve as the exit block for the CFG.
157 // Since this is the first block added to the CFG, it will be implicitly
158 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000159 Succ = createBlock();
160 assert (Succ == &cfg->getExit());
161 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000162
163 // Visit the statements and create the CFG.
Ted Kremenekfa38c7a2008-02-27 17:33:02 +0000164 CFGBlock* B = Visit(Statement);
165 if (!B) B = Succ;
166
167 if (B) {
Ted Kremenek73543912007-08-23 21:42:29 +0000168 // Finalize the last constructed block. This usually involves
169 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000170 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000171
172 // Backpatch the gotos whose label -> block mappings we didn't know
173 // when we encountered them.
174 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
175 E = BackpatchBlocks.end(); I != E; ++I ) {
176
177 CFGBlock* B = *I;
178 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
179 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
180
181 // If there is no target for the goto, then we are looking at an
182 // incomplete AST. Handle this by not registering a successor.
183 if (LI == LabelMap.end()) continue;
184
185 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000186 }
Ted Kremenek73543912007-08-23 21:42:29 +0000187
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000188 // Add successors to the Indirect Goto Dispatch block (if we have one).
189 if (CFGBlock* B = cfg->getIndirectGotoBlock())
190 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
191 E = AddressTakenLabels.end(); I != E; ++I ) {
192
193 // Lookup the target block.
194 LabelMapTy::iterator LI = LabelMap.find(*I);
195
196 // If there is no target block that contains label, then we are looking
197 // at an incomplete AST. Handle this by not registering a successor.
198 if (LI == LabelMap.end()) continue;
199
200 B->addSuccessor(LI->second);
201 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000202
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000203 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000204 }
205
206 // Create an empty entry block that has no predecessors.
207 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000208
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000209 if (badCFG) {
210 delete cfg;
211 cfg = NULL;
212 return NULL;
213 }
214
Ted Kremenek680fcb82007-09-26 21:23:31 +0000215 // NULL out cfg so that repeated calls to the builder will fail and that
216 // the ownership of the constructed CFG is passed to the caller.
217 CFG* t = cfg;
218 cfg = NULL;
219 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000220}
221
222/// createBlock - Used to lazily create blocks that are connected
223/// to the current (global) succcessor.
224CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000225 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000226 if (add_successor && Succ) B->addSuccessor(Succ);
227 return B;
228}
229
230/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000231/// we must reverse the statements because they have been inserted
232/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000233void CFGBuilder::FinishBlock(CFGBlock* B) {
234 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000235 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000236}
237
Ted Kremenek65cfa562007-08-27 21:27:44 +0000238/// addStmt - Used to add statements/expressions to the current CFGBlock
239/// "Block". This method calls WalkAST on the passed statement to see if it
240/// contains any short-circuit expressions. If so, it recursively creates
241/// the necessary blocks for such expressions. It returns the "topmost" block
242/// of the created blocks, or the original value of "Block" when this method
243/// was called if no additional blocks are created.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000244CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000245 if (!Block) Block = createBlock();
Ted Kremenek79f0a632008-04-16 21:10:48 +0000246 return WalkAST(Terminator,true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000247}
248
249/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000250/// add extra blocks for ternary operators, &&, and ||. We also
251/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000252CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
253 switch (Terminator->getStmtClass()) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000254 case Stmt::ConditionalOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000255 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000256
257 // Create the confluence block that will "merge" the results
258 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000259 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
260 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000261 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000262
263 // Create a block for the LHS expression if there is an LHS expression.
264 // A GCC extension allows LHS to be NULL, causing the condition to
265 // be the value that is returned instead.
266 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000267 Succ = ConfluenceBlock;
268 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000269 CFGBlock* LHSBlock = NULL;
270 if (C->getLHS()) {
271 LHSBlock = Visit(C->getLHS());
272 FinishBlock(LHSBlock);
273 Block = NULL;
274 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000275
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000276 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000277 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000278 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000279 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000280
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000281 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000282 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000283
284 if (LHSBlock)
285 Block->addSuccessor(LHSBlock);
286 else {
287 // If we have no LHS expression, add the ConfluenceBlock as a direct
288 // successor for the block containing the condition. Moreover,
289 // we need to reverse the order of the predecessors in the
290 // ConfluenceBlock because the RHSBlock will have been added to
291 // the succcessors already, and we want the first predecessor to the
292 // the block containing the expression for the case when the ternary
293 // expression evaluates to true.
294 Block->addSuccessor(ConfluenceBlock);
295 assert (ConfluenceBlock->pred_size() == 2);
296 std::reverse(ConfluenceBlock->pred_begin(),
297 ConfluenceBlock->pred_end());
298 }
299
Ted Kremenek65cfa562007-08-27 21:27:44 +0000300 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000301
Ted Kremenek65cfa562007-08-27 21:27:44 +0000302 Block->setTerminator(C);
303 return addStmt(C->getCond());
304 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000305
306 case Stmt::ChooseExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000307 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek7f788422007-08-31 17:03:41 +0000308
309 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
310 ConfluenceBlock->appendStmt(C);
311 FinishBlock(ConfluenceBlock);
312
313 Succ = ConfluenceBlock;
314 Block = NULL;
315 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000316 FinishBlock(LHSBlock);
317
Ted Kremenek7f788422007-08-31 17:03:41 +0000318 Succ = ConfluenceBlock;
319 Block = NULL;
320 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000321 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000322
323 Block = createBlock(false);
324 Block->addSuccessor(LHSBlock);
325 Block->addSuccessor(RHSBlock);
326 Block->setTerminator(C);
327 return addStmt(C->getCond());
328 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000329
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000330 case Stmt::DeclStmtClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000331 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
332 Block->appendStmt(Terminator);
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000333
334 StmtIterator I(D);
335 return WalkAST_VisitDeclSubExprs(I);
336 }
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000337
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000338 case Stmt::AddrLabelExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000339 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000340 AddressTakenLabels.insert(A->getLabel());
341
Ted Kremenek79f0a632008-04-16 21:10:48 +0000342 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000343 return Block;
344 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000345
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000346 case Stmt::StmtExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000347 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremeneke822b622007-08-28 18:14:37 +0000348
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000349 case Stmt::UnaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000350 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000351
352 // sizeof(expressions). For such expressions,
353 // the subexpression is not really evaluated, so
354 // we don't care about control-flow within the sizeof.
355 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000356 Block->appendStmt(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000357 return Block;
358 }
359
360 break;
361 }
362
Ted Kremenekcfaae762007-08-27 21:54:41 +0000363 case Stmt::BinaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000364 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000365
366 if (B->isLogicalOp()) { // && or ||
367 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
368 ConfluenceBlock->appendStmt(B);
369 FinishBlock(ConfluenceBlock);
370
371 // create the block evaluating the LHS
372 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000373 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000374
375 // create the block evaluating the RHS
376 Succ = ConfluenceBlock;
377 Block = NULL;
378 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000379
380 // Now link the LHSBlock with RHSBlock.
381 if (B->getOpcode() == BinaryOperator::LOr) {
382 LHSBlock->addSuccessor(ConfluenceBlock);
383 LHSBlock->addSuccessor(RHSBlock);
384 }
385 else {
386 assert (B->getOpcode() == BinaryOperator::LAnd);
387 LHSBlock->addSuccessor(RHSBlock);
388 LHSBlock->addSuccessor(ConfluenceBlock);
389 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000390
391 // Generate the blocks for evaluating the LHS.
392 Block = LHSBlock;
393 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000394 }
395 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
396 Block->appendStmt(B);
397 addStmt(B->getRHS());
398 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000399 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000400
401 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000402 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000403
404 case Stmt::ParenExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000405 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000406
Ted Kremenek65cfa562007-08-27 21:27:44 +0000407 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000408 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000409 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000410
Ted Kremenek79f0a632008-04-16 21:10:48 +0000411 if (AlwaysAddStmt) Block->appendStmt(Terminator);
412 return WalkAST_VisitChildren(Terminator);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000413}
414
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000415/// WalkAST_VisitDeclSubExprs - Utility method to handle Decls contained in
416/// DeclStmts. Because the initialization code (and sometimes the
417/// the type declarations) for DeclStmts can contain arbitrary expressions,
418/// we must linearize declarations to handle arbitrary control-flow induced by
419/// those expressions.
420CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExprs(StmtIterator& I) {
Ted Kremenekf4e35622007-11-18 20:06:01 +0000421 if (I == StmtIterator())
422 return Block;
423
Ted Kremenek79f0a632008-04-16 21:10:48 +0000424 Stmt* Terminator = *I;
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000425 ++I;
Ted Kremenekf4e35622007-11-18 20:06:01 +0000426 WalkAST_VisitDeclSubExprs(I);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000427
428 // Optimization: Don't create separate block-level statements for literals.
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000429
Ted Kremenek79f0a632008-04-16 21:10:48 +0000430 switch (Terminator->getStmtClass()) {
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000431 case Stmt::IntegerLiteralClass:
432 case Stmt::CharacterLiteralClass:
433 case Stmt::StringLiteralClass:
434 break;
435
436 // All other cases.
437
438 default:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000439 Block = addStmt(Terminator);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000440 }
441
Ted Kremeneke822b622007-08-28 18:14:37 +0000442 return Block;
443}
444
Ted Kremenek65cfa562007-08-27 21:27:44 +0000445/// WalkAST_VisitChildren - Utility method to call WalkAST on the
446/// children of a Stmt.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000447CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000448 CFGBlock* B = Block;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000449 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000450 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000451 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000452
453 return B;
454}
455
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000456/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
457/// expressions (a GCC extension).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000458CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
459 Block->appendStmt(Terminator);
460 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000461}
462
Ted Kremenek73543912007-08-23 21:42:29 +0000463/// VisitStmt - Handle statements with no branching control flow.
464CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
465 // We cannot assume that we are in the middle of a basic block, since
466 // the CFG might only be constructed for this single statement. If
467 // we have no current basic block, just create one lazily.
468 if (!Block) Block = createBlock();
469
470 // Simply add the statement to the current block. We actually
471 // insert statements in reverse order; this order is reversed later
472 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000473 addStmt(Statement);
474
Ted Kremenek73543912007-08-23 21:42:29 +0000475 return Block;
476}
477
478CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
479 return Block;
480}
481
482CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000483
484 CFGBlock* LastBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000485
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000486 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
487 I != E; ++I ) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000488 LastBlock = Visit(*I);
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000489 }
490
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000491 return LastBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000492}
493
494CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
495 // We may see an if statement in the middle of a basic block, or
496 // it may be the first statement we are processing. In either case,
497 // we create a new basic block. First, we create the blocks for
498 // the then...else statements, and then we create the block containing
499 // the if statement. If we were in the middle of a block, we
500 // stop processing that block and reverse its statements. That block
501 // is then the implicit successor for the "then" and "else" clauses.
502
503 // The block we were proccessing is now finished. Make it the
504 // successor block.
505 if (Block) {
506 Succ = Block;
507 FinishBlock(Block);
508 }
509
510 // Process the false branch. NULL out Block so that the recursive
511 // call to Visit will create a new basic block.
512 // Null out Block so that all successor
513 CFGBlock* ElseBlock = Succ;
514
515 if (Stmt* Else = I->getElse()) {
516 SaveAndRestore<CFGBlock*> sv(Succ);
517
518 // NULL out Block so that the recursive call to Visit will
519 // create a new basic block.
520 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000521 ElseBlock = Visit(Else);
522
523 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
524 ElseBlock = sv.get();
525 else if (Block)
526 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000527 }
528
529 // Process the true branch. NULL out Block so that the recursive
530 // call to Visit will create a new basic block.
531 // Null out Block so that all successor
532 CFGBlock* ThenBlock;
533 {
534 Stmt* Then = I->getThen();
535 assert (Then);
536 SaveAndRestore<CFGBlock*> sv(Succ);
537 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000538 ThenBlock = Visit(Then);
539
540 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
541 ThenBlock = sv.get();
542 else if (Block)
543 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000544 }
545
546 // Now create a new block containing the if statement.
547 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000548
549 // Set the terminator of the new block to the If statement.
550 Block->setTerminator(I);
551
552 // Now add the successors.
553 Block->addSuccessor(ThenBlock);
554 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000555
556 // Add the condition as the last statement in the new block. This
557 // may create new blocks as the condition may contain control-flow. Any
558 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000559 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000560}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000561
Ted Kremenek73543912007-08-23 21:42:29 +0000562
563CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
564 // If we were in the middle of a block we stop processing that block
565 // and reverse its statements.
566 //
567 // NOTE: If a "return" appears in the middle of a block, this means
568 // that the code afterwards is DEAD (unreachable). We still
569 // keep a basic block for that code; a simple "mark-and-sweep"
570 // from the entry block will be able to report such dead
571 // blocks.
572 if (Block) FinishBlock(Block);
573
574 // Create the new block.
575 Block = createBlock(false);
576
577 // The Exit block is the only successor.
578 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000579
580 // Add the return statement to the block. This may create new blocks
581 // if R contains control-flow (short-circuit operations).
582 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000583}
584
585CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
586 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek82e8a192008-03-15 07:45:02 +0000587 Visit(L->getSubStmt());
588 CFGBlock* LabelBlock = Block;
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000589
590 if (!LabelBlock) // This can happen when the body is empty, i.e.
591 LabelBlock=createBlock(); // scopes that only contains NullStmts.
592
Ted Kremenek73543912007-08-23 21:42:29 +0000593 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
594 LabelMap[ L ] = LabelBlock;
595
596 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000597 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000598 // label (and we have already processed the substatement) there is no
599 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000600 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000601 FinishBlock(LabelBlock);
602
603 // We set Block to NULL to allow lazy creation of a new block
604 // (if necessary);
605 Block = NULL;
606
607 // This block is now the implicit successor of other blocks.
608 Succ = LabelBlock;
609
610 return LabelBlock;
611}
612
613CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
614 // Goto is a control-flow statement. Thus we stop processing the
615 // current block and create a new one.
616 if (Block) FinishBlock(Block);
617 Block = createBlock(false);
618 Block->setTerminator(G);
619
620 // If we already know the mapping to the label block add the
621 // successor now.
622 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
623
624 if (I == LabelMap.end())
625 // We will need to backpatch this block later.
626 BackpatchBlocks.push_back(Block);
627 else
628 Block->addSuccessor(I->second);
629
630 return Block;
631}
632
633CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
634 // "for" is a control-flow statement. Thus we stop processing the
635 // current block.
636
637 CFGBlock* LoopSuccessor = NULL;
638
639 if (Block) {
640 FinishBlock(Block);
641 LoopSuccessor = Block;
642 }
643 else LoopSuccessor = Succ;
644
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000645 // Because of short-circuit evaluation, the condition of the loop
646 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
647 // blocks that evaluate the condition.
648 CFGBlock* ExitConditionBlock = createBlock(false);
649 CFGBlock* EntryConditionBlock = ExitConditionBlock;
650
651 // Set the terminator for the "exit" condition block.
652 ExitConditionBlock->setTerminator(F);
653
654 // Now add the actual condition to the condition block. Because the
655 // condition itself may contain control-flow, new blocks may be created.
656 if (Stmt* C = F->getCond()) {
657 Block = ExitConditionBlock;
658 EntryConditionBlock = addStmt(C);
659 if (Block) FinishBlock(EntryConditionBlock);
660 }
Ted Kremenek73543912007-08-23 21:42:29 +0000661
662 // The condition block is the implicit successor for the loop body as
663 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000664 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000665
666 // Now create the loop body.
667 {
668 assert (F->getBody());
669
670 // Save the current values for Block, Succ, and continue and break targets
671 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
672 save_continue(ContinueTargetBlock),
673 save_break(BreakTargetBlock);
674
675 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000676 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000677
678 // All breaks should go to the code following the loop.
679 BreakTargetBlock = LoopSuccessor;
680
Ted Kremenek390b9762007-08-30 18:39:40 +0000681 // Create a new block to contain the (bottom) of the loop body.
682 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000683
684 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000685 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000686
687 // Now populate the body block, and in the process create new blocks
688 // as we walk the body of the loop.
689 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000690
691 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000692 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000693 else if (Block)
694 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000695
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000696 // This new body block is a successor to our "exit" condition block.
697 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000698 }
699
700 // Link up the condition block with the code that follows the loop.
701 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000702 ExitConditionBlock->addSuccessor(LoopSuccessor);
703
Ted Kremenek73543912007-08-23 21:42:29 +0000704 // If the loop contains initialization, create a new block for those
705 // statements. This block can also contain statements that precede
706 // the loop.
707 if (Stmt* I = F->getInit()) {
708 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000709 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000710 }
711 else {
712 // There is no loop initialization. We are thus basically a while
713 // loop. NULL out Block to force lazy block construction.
714 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000715 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000716 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000717 }
718}
719
720CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
721 // "while" 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;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000731
732 // 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(W);
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 // Thus we update "Succ" after adding the condition.
744 if (Stmt* C = W->getCond()) {
745 Block = ExitConditionBlock;
746 EntryConditionBlock = addStmt(C);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000747 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000748 if (Block) FinishBlock(EntryConditionBlock);
749 }
Ted Kremenek73543912007-08-23 21:42:29 +0000750
751 // The condition block is the implicit successor for the loop body as
752 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000753 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000754
755 // Process the loop body.
756 {
757 assert (W->getBody());
758
759 // Save the current values for Block, Succ, and continue and break targets
760 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
761 save_continue(ContinueTargetBlock),
762 save_break(BreakTargetBlock);
763
764 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000765 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000766
767 // All breaks should go to the code following the loop.
768 BreakTargetBlock = LoopSuccessor;
769
770 // NULL out Block to force lazy instantiation of blocks for the body.
771 Block = NULL;
772
773 // Create the body. The returned block is the entry to the loop body.
774 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000775
776 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000777 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000778 else if (Block)
779 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000780
781 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000782 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000783 }
784
785 // Link up the condition block with the code that follows the loop.
786 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000787 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000788
789 // There can be no more statements in the condition block
790 // since we loop back to this block. NULL out Block to force
791 // lazy creation of another block.
792 Block = NULL;
793
794 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000795 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000796 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000797}
798
799CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
800 // "do...while" is a control-flow statement. Thus we stop processing the
801 // current block.
802
803 CFGBlock* LoopSuccessor = NULL;
804
805 if (Block) {
806 FinishBlock(Block);
807 LoopSuccessor = Block;
808 }
809 else LoopSuccessor = Succ;
810
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000811 // Because of short-circuit evaluation, the condition of the loop
812 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
813 // blocks that evaluate the condition.
814 CFGBlock* ExitConditionBlock = createBlock(false);
815 CFGBlock* EntryConditionBlock = ExitConditionBlock;
816
817 // Set the terminator for the "exit" condition block.
818 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000819
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000820 // Now add the actual condition to the condition block. Because the
821 // condition itself may contain control-flow, new blocks may be created.
822 if (Stmt* C = D->getCond()) {
823 Block = ExitConditionBlock;
824 EntryConditionBlock = addStmt(C);
825 if (Block) FinishBlock(EntryConditionBlock);
826 }
Ted Kremenek73543912007-08-23 21:42:29 +0000827
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000828 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000829 Succ = EntryConditionBlock;
830
Ted Kremenek73543912007-08-23 21:42:29 +0000831 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000832 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000833 {
834 assert (D->getBody());
835
836 // Save the current values for Block, Succ, and continue and break targets
837 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
838 save_continue(ContinueTargetBlock),
839 save_break(BreakTargetBlock);
840
841 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000842 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000843
844 // All breaks should go to the code following the loop.
845 BreakTargetBlock = LoopSuccessor;
846
847 // NULL out Block to force lazy instantiation of blocks for the body.
848 Block = NULL;
849
850 // Create the body. The returned block is the entry to the loop body.
851 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000852
Ted Kremenek390b9762007-08-30 18:39:40 +0000853 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000854 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000855 else if (Block)
856 FinishBlock(BodyBlock);
857
Ted Kremenek73543912007-08-23 21:42:29 +0000858 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000859 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000860 }
861
862 // Link up the condition block with the code that follows the loop.
863 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000864 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000865
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000866 // There can be no more statements in the body block(s)
867 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000868 // lazy creation of another block.
869 Block = NULL;
870
871 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000872 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000873 return BodyBlock;
874}
875
876CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
877 // "continue" is a control-flow statement. Thus we stop processing the
878 // current block.
879 if (Block) FinishBlock(Block);
880
881 // Now create a new block that ends with the continue statement.
882 Block = createBlock(false);
883 Block->setTerminator(C);
884
885 // If there is no target for the continue, then we are looking at an
886 // incomplete AST. Handle this by not registering a successor.
887 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
888
889 return Block;
890}
891
892CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
893 // "break" is a control-flow statement. Thus we stop processing the
894 // current block.
895 if (Block) FinishBlock(Block);
896
897 // Now create a new block that ends with the continue statement.
898 Block = createBlock(false);
899 Block->setTerminator(B);
900
901 // If there is no target for the break, then we are looking at an
902 // incomplete AST. Handle this by not registering a successor.
903 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
904
905 return Block;
906}
907
Ted Kremenek79f0a632008-04-16 21:10:48 +0000908CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek73543912007-08-23 21:42:29 +0000909 // "switch" is a control-flow statement. Thus we stop processing the
910 // current block.
911 CFGBlock* SwitchSuccessor = NULL;
912
913 if (Block) {
914 FinishBlock(Block);
915 SwitchSuccessor = Block;
916 }
917 else SwitchSuccessor = Succ;
918
919 // Save the current "switch" context.
920 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000921 save_break(BreakTargetBlock),
922 save_default(DefaultCaseBlock);
923
924 // Set the "default" case to be the block after the switch statement.
925 // If the switch statement contains a "default:", this value will
926 // be overwritten with the block for that code.
927 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000928
Ted Kremenek73543912007-08-23 21:42:29 +0000929 // Create a new block that will contain the switch statement.
930 SwitchTerminatedBlock = createBlock(false);
931
Ted Kremenek73543912007-08-23 21:42:29 +0000932 // Now process the switch body. The code after the switch is the implicit
933 // successor.
934 Succ = SwitchSuccessor;
935 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000936
937 // When visiting the body, the case statements should automatically get
938 // linked up to the switch. We also don't keep a pointer to the body,
939 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000940 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000941 Block = NULL;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000942 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000943 if (Block) FinishBlock(BodyBlock);
944
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000945 // If we have no "default:" case, the default transition is to the
946 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000947 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000948
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000949 // Add the terminator and condition in the switch block.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000950 SwitchTerminatedBlock->setTerminator(Terminator);
951 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +0000952 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000953
Ted Kremenek79f0a632008-04-16 21:10:48 +0000954 return addStmt(Terminator->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +0000955}
956
Ted Kremenek79f0a632008-04-16 21:10:48 +0000957CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenek97bc3422008-02-13 22:05:39 +0000958 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +0000959 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +0000960
Ted Kremenek79f0a632008-04-16 21:10:48 +0000961 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek44659d82007-08-30 18:48:11 +0000962 CFGBlock* CaseBlock = Block;
963 if (!CaseBlock) CaseBlock = createBlock();
964
Ted Kremenek97bc3422008-02-13 22:05:39 +0000965 // Cases statements partition blocks, so this is the top of
966 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000967 CaseBlock->setLabel(Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +0000968 FinishBlock(CaseBlock);
969
970 // Add this block to the list of successors for the block with the
971 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000972 assert (SwitchTerminatedBlock);
973 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000974
975 // We set Block to NULL to allow lazy creation of a new block (if necessary)
976 Block = NULL;
977
978 // This block is now the implicit successor of other blocks.
979 Succ = CaseBlock;
980
Ted Kremenek82e8a192008-03-15 07:45:02 +0000981 return CaseBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000982}
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000983
Ted Kremenek79f0a632008-04-16 21:10:48 +0000984CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
985 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek97bc3422008-02-13 22:05:39 +0000986 DefaultCaseBlock = Block;
987 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
988
989 // Default statements partition blocks, so this is the top of
990 // the basic block we were processing (the "default:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000991 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek97bc3422008-02-13 22:05:39 +0000992 FinishBlock(DefaultCaseBlock);
993
994 // Unlike case statements, we don't add the default block to the
995 // successors for the switch statement immediately. This is done
996 // when we finish processing the switch statement. This allows for
997 // the default case (including a fall-through to the code after the
998 // switch statement) to always be the last successor of a switch-terminated
999 // block.
1000
1001 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1002 Block = NULL;
1003
1004 // This block is now the implicit successor of other blocks.
1005 Succ = DefaultCaseBlock;
1006
1007 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001008}
Ted Kremenek73543912007-08-23 21:42:29 +00001009
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001010CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1011 // Lazily create the indirect-goto dispatch block if there isn't one
1012 // already.
1013 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1014
1015 if (!IBlock) {
1016 IBlock = createBlock(false);
1017 cfg->setIndirectGotoBlock(IBlock);
1018 }
1019
1020 // IndirectGoto is a control-flow statement. Thus we stop processing the
1021 // current block and create a new one.
1022 if (Block) FinishBlock(Block);
1023 Block = createBlock(false);
1024 Block->setTerminator(I);
1025 Block->addSuccessor(IBlock);
1026 return addStmt(I->getTarget());
1027}
1028
Ted Kremenek73543912007-08-23 21:42:29 +00001029
Ted Kremenekd6e50602007-08-23 21:26:19 +00001030} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +00001031
1032/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1033/// block has no successors or predecessors. If this is the first block
1034/// created in the CFG, it is automatically set to be the Entry and Exit
1035/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001036CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001037 bool first_block = begin() == end();
1038
1039 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001040 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001041
1042 // If this is the first block, set it as the Entry and Exit.
1043 if (first_block) Entry = Exit = &front();
1044
1045 // Return the block.
1046 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001047}
1048
Ted Kremenek4db5b452007-08-23 16:51:22 +00001049/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1050/// CFG is returned to the caller.
1051CFG* CFG::buildCFG(Stmt* Statement) {
1052 CFGBuilder Builder;
1053 return Builder.buildCFG(Statement);
1054}
1055
1056/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001057void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1058
Ted Kremenek3a819822007-10-01 19:33:33 +00001059//===----------------------------------------------------------------------===//
1060// CFG: Queries for BlkExprs.
1061//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001062
Ted Kremenek3a819822007-10-01 19:33:33 +00001063namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001064 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001065}
1066
Ted Kremenek79f0a632008-04-16 21:10:48 +00001067static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1068 if (!Terminator)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001069 return;
1070
Ted Kremenek79f0a632008-04-16 21:10:48 +00001071 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001072 if (!*I) continue;
1073
1074 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1075 if (B->isAssignmentOp()) Set.insert(B);
1076
1077 FindSubExprAssignments(*I, Set);
1078 }
1079}
1080
Ted Kremenek3a819822007-10-01 19:33:33 +00001081static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1082 BlkExprMapTy* M = new BlkExprMapTy();
1083
Ted Kremenekc6fda602008-01-26 00:03:27 +00001084 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek79f0a632008-04-16 21:10:48 +00001085 // only assignments that we want to *possibly* register as a block-level
1086 // expression. Basically, if an assignment occurs both in a subexpression
1087 // and at the block-level, it is a block-level expression.
Ted Kremenekc6fda602008-01-26 00:03:27 +00001088 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1089
Ted Kremenek3a819822007-10-01 19:33:33 +00001090 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1091 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001092 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001093
Ted Kremenek79f0a632008-04-16 21:10:48 +00001094 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1095
1096 // Iterate over the statements again on identify the Expr* and Stmt* at
1097 // the block-level that are block-level expressions.
1098
Ted Kremenekc6fda602008-01-26 00:03:27 +00001099 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek79f0a632008-04-16 21:10:48 +00001100 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001101
Ted Kremenek79f0a632008-04-16 21:10:48 +00001102 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001103 // Assignment expressions that are not nested within another
1104 // expression are really "statements" whose value is never
1105 // used by another expression.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001106 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenekc6fda602008-01-26 00:03:27 +00001107 continue;
1108 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001109 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001110 // Special handling for statement expressions. The last statement
1111 // in the statement expression is also a block-level expr.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001112 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001113 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001114 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001115 (*M)[C->body_back()] = x;
1116 }
1117 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001118
Ted Kremenekc6fda602008-01-26 00:03:27 +00001119 unsigned x = M->size();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001120 (*M)[Exp] = x;
Ted Kremenekc6fda602008-01-26 00:03:27 +00001121 }
1122
Ted Kremenek79f0a632008-04-16 21:10:48 +00001123 // Look at terminators. The condition is a block-level expression.
1124
1125 Expr* Exp = I->getTerminatorCondition();
1126
1127 if (Exp && M->find(Exp) == M->end()) {
1128 unsigned x = M->size();
1129 (*M)[Exp] = x;
1130 }
1131 }
1132
Ted Kremenek3a819822007-10-01 19:33:33 +00001133 return M;
1134}
1135
Ted Kremenekab6c5902008-01-17 20:48:37 +00001136CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1137 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001138 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1139
1140 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001141 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001142
1143 if (I == M->end()) return CFG::BlkExprNumTy();
1144 else return CFG::BlkExprNumTy(I->second);
1145}
1146
1147unsigned CFG::getNumBlkExprs() {
1148 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1149 return M->size();
1150 else {
1151 // We assume callers interested in the number of BlkExprs will want
1152 // the map constructed if it doesn't already exist.
1153 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1154 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1155 }
1156}
1157
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001158//===----------------------------------------------------------------------===//
1159// Internal Block-Edge Set; used for modeling persistent <CFGBlock*,CFGBlock*>
1160// pairs for use with ProgramPoint.
1161//===----------------------------------------------------------------------===//
1162
1163typedef std::pair<CFGBlock*,CFGBlock*> BPairTy;
1164
1165namespace llvm {
1166 template<> struct FoldingSetTrait<BPairTy*> {
1167 static void Profile(const BPairTy* X, FoldingSetNodeID& profile) {
1168 profile.AddPointer(X->first);
1169 profile.AddPointer(X->second);
1170 }
1171 };
1172}
1173
1174typedef llvm::FoldingSetNodeWrapper<BPairTy*> PersistPairTy;
1175typedef llvm::FoldingSet<PersistPairTy> BlkEdgeSetTy;
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001176
1177const std::pair<CFGBlock*,CFGBlock*>*
1178CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1179
Ted Kremenekce668af2008-05-29 21:52:26 +00001180 if (!BlkEdgeSet)
1181 BlkEdgeSet = new BlkEdgeSetTy();
1182
1183 BlkEdgeSetTy* p = static_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001184
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001185 // Profile the edges.
1186 llvm::FoldingSetNodeID profile;
1187 void* InsertPos;
1188
1189 profile.AddPointer(B1);
1190 profile.AddPointer(B2);
1191
1192 PersistPairTy* V = p->FindNodeOrInsertPos(profile, InsertPos);
1193
1194 if (!V) {
1195 assert (llvm::AlignOf<BPairTy>::Alignment_LessEqual_8Bytes);
1196
1197 // Allocate the pair, forcing an 8-byte alignment.
Ted Kremenek1f62aa82008-08-06 22:22:32 +00001198 BPairTy* pair = (BPairTy*) Alloc.Allocate(sizeof(*pair), 8);
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001199
1200 new (pair) BPairTy(const_cast<CFGBlock*>(B1),
1201 const_cast<CFGBlock*>(B2));
1202
1203 // Allocate the meta data to store the pair in the FoldingSet.
Ted Kremenek1f62aa82008-08-06 22:22:32 +00001204 PersistPairTy* ppair = (PersistPairTy*) Alloc.Allocate<PersistPairTy>();
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001205 new (ppair) PersistPairTy(pair);
1206
1207 p->InsertNode(ppair, InsertPos);
1208
1209 return pair;
1210 }
1211
1212 return V->getValue();
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001213}
1214
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001215//===----------------------------------------------------------------------===//
1216// Cleanup: CFG dstor.
1217//===----------------------------------------------------------------------===//
1218
Ted Kremenek3a819822007-10-01 19:33:33 +00001219CFG::~CFG() {
1220 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001221 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001222}
1223
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001224//===----------------------------------------------------------------------===//
1225// CFG pretty printing
1226//===----------------------------------------------------------------------===//
1227
Ted Kremenekd8313202007-08-22 18:22:34 +00001228namespace {
1229
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001230class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001231
Ted Kremenek08176a52007-08-31 21:30:12 +00001232 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1233 StmtMapTy StmtMap;
1234 signed CurrentBlock;
1235 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001236
Ted Kremenek73543912007-08-23 21:42:29 +00001237public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001238
Ted Kremenek08176a52007-08-31 21:30:12 +00001239 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1240 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1241 unsigned j = 1;
1242 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1243 BI != BEnd; ++BI, ++j )
1244 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1245 }
1246 }
1247
1248 virtual ~StmtPrinterHelper() {}
1249
1250 void setBlockID(signed i) { CurrentBlock = i; }
1251 void setStmtID(unsigned i) { CurrentStmt = i; }
1252
Ted Kremenek79f0a632008-04-16 21:10:48 +00001253 virtual bool handledStmt(Stmt* Terminator, std::ostream& OS) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001254
Ted Kremenek79f0a632008-04-16 21:10:48 +00001255 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek08176a52007-08-31 21:30:12 +00001256
1257 if (I == StmtMap.end())
1258 return false;
1259
1260 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1261 && I->second.second == CurrentStmt)
1262 return false;
1263
Ted Kremenek86afc042007-08-31 22:26:13 +00001264 OS << "[B" << I->second.first << "." << I->second.second << "]";
1265 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001266 }
1267};
1268
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001269class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1270 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1271
Ted Kremenek08176a52007-08-31 21:30:12 +00001272 std::ostream& OS;
1273 StmtPrinterHelper* Helper;
1274public:
1275 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1276 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001277
1278 void VisitIfStmt(IfStmt* I) {
1279 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001280 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001281 }
1282
1283 // Default case.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001284 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001285
1286 void VisitForStmt(ForStmt* F) {
1287 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001288 if (F->getInit()) OS << "...";
1289 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001290 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001291 OS << "; ";
1292 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001293 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001294 }
1295
1296 void VisitWhileStmt(WhileStmt* W) {
1297 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001298 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001299 }
1300
1301 void VisitDoStmt(DoStmt* D) {
1302 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001303 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001304 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001305
Ted Kremenek79f0a632008-04-16 21:10:48 +00001306 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +00001307 OS << "switch ";
Ted Kremenek79f0a632008-04-16 21:10:48 +00001308 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001309 }
1310
Ted Kremenek621e1592007-08-31 21:49:40 +00001311 void VisitConditionalOperator(ConditionalOperator* C) {
1312 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001313 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001314 }
1315
Ted Kremenek2025cc92007-08-31 22:29:13 +00001316 void VisitChooseExpr(ChooseExpr* C) {
1317 OS << "__builtin_choose_expr( ";
1318 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001319 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001320 }
1321
Ted Kremenek86afc042007-08-31 22:26:13 +00001322 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1323 OS << "goto *";
1324 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001325 }
1326
Ted Kremenek621e1592007-08-31 21:49:40 +00001327 void VisitBinaryOperator(BinaryOperator* B) {
1328 if (!B->isLogicalOp()) {
1329 VisitExpr(B);
1330 return;
1331 }
1332
1333 B->getLHS()->printPretty(OS,Helper);
1334
1335 switch (B->getOpcode()) {
1336 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001337 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001338 return;
1339 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001340 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001341 return;
1342 default:
1343 assert(false && "Invalid logical operator.");
1344 }
1345 }
1346
Ted Kremenekcfaae762007-08-27 21:54:41 +00001347 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001348 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001349 }
Ted Kremenek73543912007-08-23 21:42:29 +00001350};
Ted Kremenek08176a52007-08-31 21:30:12 +00001351
1352
Ted Kremenek79f0a632008-04-16 21:10:48 +00001353void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001354 if (Helper) {
1355 // special printing for statement-expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001356 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001357 CompoundStmt* Sub = SE->getSubStmt();
1358
1359 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001360 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001361 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001362 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001363 return;
1364 }
1365 }
1366
1367 // special printing for comma expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001368 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001369 if (B->getOpcode() == BinaryOperator::Comma) {
1370 OS << "... , ";
1371 Helper->handledStmt(B->getRHS(),OS);
1372 OS << '\n';
1373 return;
1374 }
1375 }
1376 }
1377
Ted Kremenek79f0a632008-04-16 21:10:48 +00001378 Terminator->printPretty(OS, Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001379
1380 // Expressions need a newline.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001381 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek86afc042007-08-31 22:26:13 +00001382}
1383
Ted Kremenek08176a52007-08-31 21:30:12 +00001384void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1385 StmtPrinterHelper* Helper, bool print_edges) {
1386
1387 if (Helper) Helper->setBlockID(B.getBlockID());
1388
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001389 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001390 OS << "\n [ B" << B.getBlockID();
1391
1392 if (&B == &cfg->getEntry())
1393 OS << " (ENTRY) ]\n";
1394 else if (&B == &cfg->getExit())
1395 OS << " (EXIT) ]\n";
1396 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001397 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001398 else
1399 OS << " ]\n";
1400
Ted Kremenekec055e12007-08-29 23:20:49 +00001401 // Print the label of this block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001402 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001403
1404 if (print_edges)
1405 OS << " ";
1406
Ted Kremenek79f0a632008-04-16 21:10:48 +00001407 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001408 OS << L->getName();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001409 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001410 OS << "case ";
1411 C->getLHS()->printPretty(OS);
1412 if (C->getRHS()) {
1413 OS << " ... ";
1414 C->getRHS()->printPretty(OS);
1415 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001416 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001417 else if (isa<DefaultStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001418 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001419 else
1420 assert(false && "Invalid label statement in CFGBlock.");
1421
Ted Kremenekec055e12007-08-29 23:20:49 +00001422 OS << ":\n";
1423 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001424
Ted Kremenek97f75312007-08-21 21:42:03 +00001425 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001426 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001427
1428 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1429 I != E ; ++I, ++j ) {
1430
Ted Kremenekec055e12007-08-29 23:20:49 +00001431 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001432 if (print_edges)
1433 OS << " ";
1434
1435 OS << std::setw(3) << j << ": ";
1436
1437 if (Helper)
1438 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001439
1440 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001441 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001442
Ted Kremenekec055e12007-08-29 23:20:49 +00001443 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001444 if (B.getTerminator()) {
1445 if (print_edges)
1446 OS << " ";
1447
Ted Kremenekec055e12007-08-29 23:20:49 +00001448 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001449
1450 if (Helper) Helper->setBlockID(-1);
1451
1452 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1453 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001454 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001455 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001456
Ted Kremenekec055e12007-08-29 23:20:49 +00001457 if (print_edges) {
1458 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001459 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001460 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001461
Ted Kremenek08176a52007-08-31 21:30:12 +00001462 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1463 I != E; ++I, ++i) {
1464
1465 if (i == 8 || (i-8) == 0)
1466 OS << "\n ";
1467
Ted Kremenekec055e12007-08-29 23:20:49 +00001468 OS << " B" << (*I)->getBlockID();
1469 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001470
1471 OS << '\n';
1472
1473 // Print the successors of this block.
1474 OS << " Successors (" << B.succ_size() << "):";
1475 i = 0;
1476
1477 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1478 I != E; ++I, ++i) {
1479
1480 if (i == 8 || (i-8) % 10 == 0)
1481 OS << "\n ";
1482
1483 OS << " B" << (*I)->getBlockID();
1484 }
1485
Ted Kremenekec055e12007-08-29 23:20:49 +00001486 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001487 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001488}
1489
1490} // end anonymous namespace
1491
1492/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001493void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001494
1495/// print - A simple pretty printer of a CFG that outputs to an ostream.
1496void CFG::print(std::ostream& OS) const {
1497
1498 StmtPrinterHelper Helper(this);
1499
1500 // Print the entry block.
1501 print_block(OS, this, getEntry(), &Helper, true);
1502
1503 // Iterate through the CFGBlocks and print them one by one.
1504 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1505 // Skip the entry block, because we already printed it.
1506 if (&(*I) == &getEntry() || &(*I) == &getExit())
1507 continue;
1508
1509 print_block(OS, this, *I, &Helper, true);
1510 }
1511
1512 // Print the exit block.
1513 print_block(OS, this, getExit(), &Helper, true);
1514}
1515
1516/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001517void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001518
1519/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1520/// Generally this will only be called from CFG::print.
1521void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1522 StmtPrinterHelper Helper(cfg);
1523 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001524}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001525
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001526/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1527void CFGBlock::printTerminator(std::ostream& OS) const {
1528 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1529 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1530}
1531
Ted Kremenek79f0a632008-04-16 21:10:48 +00001532Expr* CFGBlock::getTerminatorCondition() {
1533
1534 if (!Terminator)
1535 return NULL;
1536
1537 Expr* E = NULL;
1538
1539 switch (Terminator->getStmtClass()) {
1540 default:
1541 break;
1542
1543 case Stmt::ForStmtClass:
1544 E = cast<ForStmt>(Terminator)->getCond();
1545 break;
1546
1547 case Stmt::WhileStmtClass:
1548 E = cast<WhileStmt>(Terminator)->getCond();
1549 break;
1550
1551 case Stmt::DoStmtClass:
1552 E = cast<DoStmt>(Terminator)->getCond();
1553 break;
1554
1555 case Stmt::IfStmtClass:
1556 E = cast<IfStmt>(Terminator)->getCond();
1557 break;
1558
1559 case Stmt::ChooseExprClass:
1560 E = cast<ChooseExpr>(Terminator)->getCond();
1561 break;
1562
1563 case Stmt::IndirectGotoStmtClass:
1564 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1565 break;
1566
1567 case Stmt::SwitchStmtClass:
1568 E = cast<SwitchStmt>(Terminator)->getCond();
1569 break;
1570
1571 case Stmt::ConditionalOperatorClass:
1572 E = cast<ConditionalOperator>(Terminator)->getCond();
1573 break;
1574
1575 case Stmt::BinaryOperatorClass: // '&&' and '||'
1576 E = cast<BinaryOperator>(Terminator)->getLHS();
1577 break;
1578 }
1579
1580 return E ? E->IgnoreParens() : NULL;
1581}
1582
Ted Kremenekbdbd1b52008-05-16 16:06:00 +00001583bool CFGBlock::hasBinaryBranchTerminator() const {
1584
1585 if (!Terminator)
1586 return false;
1587
1588 Expr* E = NULL;
1589
1590 switch (Terminator->getStmtClass()) {
1591 default:
1592 return false;
1593
1594 case Stmt::ForStmtClass:
1595 case Stmt::WhileStmtClass:
1596 case Stmt::DoStmtClass:
1597 case Stmt::IfStmtClass:
1598 case Stmt::ChooseExprClass:
1599 case Stmt::ConditionalOperatorClass:
1600 case Stmt::BinaryOperatorClass:
1601 return true;
1602 }
1603
1604 return E ? E->IgnoreParens() : NULL;
1605}
1606
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001607
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001608//===----------------------------------------------------------------------===//
1609// CFG Graphviz Visualization
1610//===----------------------------------------------------------------------===//
1611
Ted Kremenek08176a52007-08-31 21:30:12 +00001612
1613#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001614static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001615#endif
1616
1617void CFG::viewCFG() const {
1618#ifndef NDEBUG
1619 StmtPrinterHelper H(this);
1620 GraphHelper = &H;
1621 llvm::ViewGraph(this,"CFG");
1622 GraphHelper = NULL;
Ted Kremenek08176a52007-08-31 21:30:12 +00001623#endif
1624}
1625
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001626namespace llvm {
1627template<>
1628struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1629 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1630
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001631#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001632 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001633 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001634 std::string OutStr = Out.str();
1635
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 Kaiser752a0052007-09-16 00:28:28 +00001646#else
1647 return "";
1648#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001649 }
1650};
1651} // end namespace llvm