blob: 0231c982f4151d57c2f2c67ddf0658436b36add8 [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"
Ted Kremenek95e854d2007-08-21 22:06:14 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek08176a52007-08-31 21:30:12 +000017#include "clang/AST/PrettyPrinter.h"
Ted Kremenekc5de2222007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek0edd3a92007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
Ted Kremenek56c939e2007-12-17 19:35:20 +000021#include "llvm/Support/Streams.h"
Ted Kremenek98cee3a2008-01-08 18:15:10 +000022#include "llvm/Support/Compiler.h"
Ted Kremenekd058a9c2008-04-28 18:00:46 +000023#include <llvm/Support/Allocator.h>
Ted Kremenek97f75312007-08-21 21:42:03 +000024#include <iomanip>
25#include <algorithm>
Ted Kremenekb3bb91b2007-08-29 21:56:09 +000026#include <sstream>
Ted Kremenek5ee98a72008-01-11 00:40:29 +000027
Ted Kremenek97f75312007-08-21 21:42:03 +000028using namespace clang;
29
30namespace {
31
Ted Kremenekd6e50602007-08-23 21:26:19 +000032// SaveAndRestore - A utility class that uses RIIA to save and restore
33// the value of a variable.
34template<typename T>
Ted Kremenek98cee3a2008-01-08 18:15:10 +000035struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekd6e50602007-08-23 21:26:19 +000036 SaveAndRestore(T& x) : X(x), old_value(x) {}
37 ~SaveAndRestore() { X = old_value; }
Ted Kremenek44db7872007-08-30 18:13:31 +000038 T get() { return old_value; }
39
Ted Kremenekd6e50602007-08-23 21:26:19 +000040 T& X;
41 T old_value;
42};
Ted Kremenek97f75312007-08-21 21:42:03 +000043
Ted Kremenek0865a992008-08-06 23:20:50 +000044static SourceLocation GetEndLoc(ScopedDecl* D) {
45 if (VarDecl* VD = dyn_cast<VarDecl>(D))
46 if (Expr* Ex = VD->getInit())
47 return Ex->getSourceRange().getEnd();
48
49 return D->getLocation();
50}
51
52class VISIBILITY_HIDDEN UnaryDeclStmt : public DeclStmt {
53 Stmt* Ex;
54public:
55 UnaryDeclStmt(ScopedDecl* D)
56 : DeclStmt(D, D->getLocation(), GetEndLoc(D)), Ex(0) {
57 if (VarDecl* VD = dyn_cast<VarDecl>(D))
58 Ex = VD->getInit();
59 }
60
61 virtual ~UnaryDeclStmt() {}
62 virtual void Destroy(ASTContext& Ctx) { assert(false && "Do not call"); }
63
64 virtual child_iterator child_begin() {
65 return Ex ? &Ex : 0;
66 }
67 virtual child_iterator child_end() {
68 return Ex ? &Ex + 1 : 0;
69 }
70 virtual decl_iterator decl_begin() {
71 return getDecl();
72 }
73 virtual decl_iterator decl_end() {
74 ScopedDecl* D = getDecl();
75 return D ? D->getNextDeclarator() : 0;
76 }
77};
78
Ted Kremeneka3195a32008-08-04 22:51:42 +000079/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenek97f75312007-08-21 21:42:03 +000080/// The builder is stateful: an instance of the builder should be used to only
81/// construct a single CFG.
82///
83/// Example usage:
84///
85/// CFGBuilder builder;
86/// CFG* cfg = builder.BuildAST(stmt1);
87///
Ted Kremenek95e854d2007-08-21 22:06:14 +000088/// CFG construction is done via a recursive walk of an AST.
89/// We actually parse the AST in reverse order so that the successor
90/// of a basic block is constructed prior to its predecessor. This
91/// allows us to nicely capture implicit fall-throughs without extra
92/// basic blocks.
93///
Ted Kremenek98cee3a2008-01-08 18:15:10 +000094class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenek97f75312007-08-21 21:42:03 +000095 CFG* cfg;
96 CFGBlock* Block;
Ted Kremenek97f75312007-08-21 21:42:03 +000097 CFGBlock* Succ;
Ted Kremenekf511d672007-08-22 21:36:54 +000098 CFGBlock* ContinueTargetBlock;
Ted Kremenekf308d372007-08-22 21:51:58 +000099 CFGBlock* BreakTargetBlock;
Ted Kremeneke809ebf2007-08-23 18:43:24 +0000100 CFGBlock* SwitchTerminatedBlock;
Ted Kremenek97bc3422008-02-13 22:05:39 +0000101 CFGBlock* DefaultCaseBlock;
Ted Kremenek97f75312007-08-21 21:42:03 +0000102
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000103 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenekc5de2222007-08-21 23:26:17 +0000104 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
105 LabelMapTy LabelMap;
106
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000107 // A list of blocks that end with a "goto" that must be backpatched to
108 // their resolved targets upon completion of CFG construction.
Ted Kremenekf5392b72007-08-22 15:40:58 +0000109 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenekc5de2222007-08-21 23:26:17 +0000110 BackpatchBlocksTy BackpatchBlocks;
111
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000112 // A list of labels whose address has been taken (for indirect gotos).
113 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
114 LabelSetTy AddressTakenLabels;
115
Ted Kremenek97f75312007-08-21 21:42:03 +0000116public:
Ted Kremenek4db5b452007-08-23 16:51:22 +0000117 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenekf308d372007-08-22 21:51:58 +0000118 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000119 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenek97f75312007-08-21 21:42:03 +0000120 // Create an empty CFG.
121 cfg = new CFG();
122 }
123
124 ~CFGBuilder() { delete cfg; }
Ted Kremenek97f75312007-08-21 21:42:03 +0000125
Ted Kremenek73543912007-08-23 21:42:29 +0000126 // buildCFG - Used by external clients to construct the CFG.
127 CFG* buildCFG(Stmt* Statement);
Ted Kremenek95e854d2007-08-21 22:06:14 +0000128
Ted Kremenek73543912007-08-23 21:42:29 +0000129 // Visitors to walk an AST and construct the CFG. Called by
130 // buildCFG. Do not call directly!
Ted Kremenekd8313202007-08-22 18:22:34 +0000131
Ted Kremenek73543912007-08-23 21:42:29 +0000132 CFGBlock* VisitStmt(Stmt* Statement);
133 CFGBlock* VisitNullStmt(NullStmt* Statement);
134 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
135 CFGBlock* VisitIfStmt(IfStmt* I);
136 CFGBlock* VisitReturnStmt(ReturnStmt* R);
137 CFGBlock* VisitLabelStmt(LabelStmt* L);
138 CFGBlock* VisitGotoStmt(GotoStmt* G);
139 CFGBlock* VisitForStmt(ForStmt* F);
140 CFGBlock* VisitWhileStmt(WhileStmt* W);
141 CFGBlock* VisitDoStmt(DoStmt* D);
142 CFGBlock* VisitContinueStmt(ContinueStmt* C);
143 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000144 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
145 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000146 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000147 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenek97f75312007-08-21 21:42:03 +0000148
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000149 // FIXME: Add support for ObjC-specific control-flow structures.
150
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000151 // NYS == Not Yet Supported
152 CFGBlock* NYS() {
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000153 badCFG = true;
154 return Block;
155 }
156
Ted Kremenekd058a9c2008-04-28 18:00:46 +0000157 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
158 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
159 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
160 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
161 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
162
163 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
164 return NYS();
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000165 }
166
Ted Kremenek73543912007-08-23 21:42:29 +0000167private:
168 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000169 CFGBlock* addStmt(Stmt* Terminator);
170 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
171 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenek0865a992008-08-06 23:20:50 +0000172 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek79f0a632008-04-16 21:10:48 +0000173 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +0000174 void FinishBlock(CFGBlock* B);
Ted Kremenekd8313202007-08-22 18:22:34 +0000175
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000176 bool badCFG;
Ted Kremenek97f75312007-08-21 21:42:03 +0000177};
Ted Kremenek73543912007-08-23 21:42:29 +0000178
179/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
180/// represent an arbitrary statement. Examples include a single expression
181/// or a function body (compound statement). The ownership of the returned
182/// CFG is transferred to the caller. If CFG construction fails, this method
183/// returns NULL.
184CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000185 assert (cfg);
Ted Kremenek73543912007-08-23 21:42:29 +0000186 if (!Statement) return NULL;
187
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000188 badCFG = false;
189
Ted Kremenek73543912007-08-23 21:42:29 +0000190 // Create an empty block that will serve as the exit block for the CFG.
191 // Since this is the first block added to the CFG, it will be implicitly
192 // registered as the exit block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000193 Succ = createBlock();
194 assert (Succ == &cfg->getExit());
195 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenek73543912007-08-23 21:42:29 +0000196
197 // Visit the statements and create the CFG.
Ted Kremenekfa38c7a2008-02-27 17:33:02 +0000198 CFGBlock* B = Visit(Statement);
199 if (!B) B = Succ;
200
201 if (B) {
Ted Kremenek73543912007-08-23 21:42:29 +0000202 // Finalize the last constructed block. This usually involves
203 // reversing the order of the statements in the block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000204 if (Block) FinishBlock(B);
Ted Kremenek73543912007-08-23 21:42:29 +0000205
206 // Backpatch the gotos whose label -> block mappings we didn't know
207 // when we encountered them.
208 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
209 E = BackpatchBlocks.end(); I != E; ++I ) {
210
211 CFGBlock* B = *I;
212 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
213 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
214
215 // If there is no target for the goto, then we are looking at an
216 // incomplete AST. Handle this by not registering a successor.
217 if (LI == LabelMap.end()) continue;
218
219 B->addSuccessor(LI->second);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000220 }
Ted Kremenek73543912007-08-23 21:42:29 +0000221
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000222 // Add successors to the Indirect Goto Dispatch block (if we have one).
223 if (CFGBlock* B = cfg->getIndirectGotoBlock())
224 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
225 E = AddressTakenLabels.end(); I != E; ++I ) {
226
227 // Lookup the target block.
228 LabelMapTy::iterator LI = LabelMap.find(*I);
229
230 // If there is no target block that contains label, then we are looking
231 // at an incomplete AST. Handle this by not registering a successor.
232 if (LI == LabelMap.end()) continue;
233
234 B->addSuccessor(LI->second);
235 }
Ted Kremenek680fcb82007-09-26 21:23:31 +0000236
Ted Kremenek844cb4d2007-09-17 16:18:02 +0000237 Succ = B;
Ted Kremenek680fcb82007-09-26 21:23:31 +0000238 }
239
240 // Create an empty entry block that has no predecessors.
241 cfg->setEntry(createBlock());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000242
Ted Kremenek4c69b3a2008-03-13 03:04:22 +0000243 if (badCFG) {
244 delete cfg;
245 cfg = NULL;
246 return NULL;
247 }
248
Ted Kremenek680fcb82007-09-26 21:23:31 +0000249 // NULL out cfg so that repeated calls to the builder will fail and that
250 // the ownership of the constructed CFG is passed to the caller.
251 CFG* t = cfg;
252 cfg = NULL;
253 return t;
Ted Kremenek73543912007-08-23 21:42:29 +0000254}
255
256/// createBlock - Used to lazily create blocks that are connected
257/// to the current (global) succcessor.
258CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek14594572007-09-05 20:02:05 +0000259 CFGBlock* B = cfg->createBlock();
Ted Kremenek73543912007-08-23 21:42:29 +0000260 if (add_successor && Succ) B->addSuccessor(Succ);
261 return B;
262}
263
264/// FinishBlock - When the last statement has been added to the block,
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000265/// we must reverse the statements because they have been inserted
266/// in reverse order.
Ted Kremenek73543912007-08-23 21:42:29 +0000267void CFGBuilder::FinishBlock(CFGBlock* B) {
268 assert (B);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000269 B->reverseStmts();
Ted Kremenek73543912007-08-23 21:42:29 +0000270}
271
Ted Kremenek65cfa562007-08-27 21:27:44 +0000272/// addStmt - Used to add statements/expressions to the current CFGBlock
273/// "Block". This method calls WalkAST on the passed statement to see if it
274/// contains any short-circuit expressions. If so, it recursively creates
275/// the necessary blocks for such expressions. It returns the "topmost" block
276/// of the created blocks, or the original value of "Block" when this method
277/// was called if no additional blocks are created.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000278CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenek390b9762007-08-30 18:39:40 +0000279 if (!Block) Block = createBlock();
Ted Kremenek79f0a632008-04-16 21:10:48 +0000280 return WalkAST(Terminator,true);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000281}
282
283/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremeneke822b622007-08-28 18:14:37 +0000284/// add extra blocks for ternary operators, &&, and ||. We also
285/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000286CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
287 switch (Terminator->getStmtClass()) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000288 case Stmt::ConditionalOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000289 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000290
291 // Create the confluence block that will "merge" the results
292 // of the ternary expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000293 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
294 ConfluenceBlock->appendStmt(C);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000295 FinishBlock(ConfluenceBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000296
297 // Create a block for the LHS expression if there is an LHS expression.
298 // A GCC extension allows LHS to be NULL, causing the condition to
299 // be the value that is returned instead.
300 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000301 Succ = ConfluenceBlock;
302 Block = NULL;
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000303 CFGBlock* LHSBlock = NULL;
304 if (C->getLHS()) {
305 LHSBlock = Visit(C->getLHS());
306 FinishBlock(LHSBlock);
307 Block = NULL;
308 }
Ted Kremenek65cfa562007-08-27 21:27:44 +0000309
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000310 // Create the block for the RHS expression.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000311 Succ = ConfluenceBlock;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000312 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000313 FinishBlock(RHSBlock);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000314
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000315 // Create the block that will contain the condition.
Ted Kremenek65cfa562007-08-27 21:27:44 +0000316 Block = createBlock(false);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000317
318 if (LHSBlock)
319 Block->addSuccessor(LHSBlock);
320 else {
321 // If we have no LHS expression, add the ConfluenceBlock as a direct
322 // successor for the block containing the condition. Moreover,
323 // we need to reverse the order of the predecessors in the
324 // ConfluenceBlock because the RHSBlock will have been added to
325 // the succcessors already, and we want the first predecessor to the
326 // the block containing the expression for the case when the ternary
327 // expression evaluates to true.
328 Block->addSuccessor(ConfluenceBlock);
329 assert (ConfluenceBlock->pred_size() == 2);
330 std::reverse(ConfluenceBlock->pred_begin(),
331 ConfluenceBlock->pred_end());
332 }
333
Ted Kremenek65cfa562007-08-27 21:27:44 +0000334 Block->addSuccessor(RHSBlock);
Ted Kremenekc0980cd2007-11-26 18:20:26 +0000335
Ted Kremenek65cfa562007-08-27 21:27:44 +0000336 Block->setTerminator(C);
337 return addStmt(C->getCond());
338 }
Ted Kremenek7f788422007-08-31 17:03:41 +0000339
340 case Stmt::ChooseExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000341 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek7f788422007-08-31 17:03:41 +0000342
343 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
344 ConfluenceBlock->appendStmt(C);
345 FinishBlock(ConfluenceBlock);
346
347 Succ = ConfluenceBlock;
348 Block = NULL;
349 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000350 FinishBlock(LHSBlock);
351
Ted Kremenek7f788422007-08-31 17:03:41 +0000352 Succ = ConfluenceBlock;
353 Block = NULL;
354 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekd11620d2007-09-11 21:29:43 +0000355 FinishBlock(RHSBlock);
Ted Kremenek7f788422007-08-31 17:03:41 +0000356
357 Block = createBlock(false);
358 Block->addSuccessor(LHSBlock);
359 Block->addSuccessor(RHSBlock);
360 Block->setTerminator(C);
361 return addStmt(C->getCond());
362 }
Ted Kremenek666a6af2007-08-28 16:18:58 +0000363
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000364 case Stmt::DeclStmtClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000365 ScopedDecl* D = cast<DeclStmt>(Terminator)->getDecl();
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000366
Ted Kremenek0865a992008-08-06 23:20:50 +0000367 if (!D->getNextDeclarator()) {
368 Block->appendStmt(Terminator);
369 return WalkAST_VisitDeclSubExpr(D);
370 }
371 else {
372 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
373 BufTy Buf;
374 CFGBlock* B = 0;
375 do { Buf.push_back(D); D = D->getNextDeclarator(); } while (D);
376 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
377 // Get the alignment of UnaryDeclStmt, padding out to >=8 bytes.
378 unsigned A = llvm::AlignOf<UnaryDeclStmt>::Alignment < 8
379 ? 8 : llvm::AlignOf<UnaryDeclStmt>::Alignment;
380
381 // Allocate the UnaryDeclStmt using the BumpPtrAllocator. It will
382 // get automatically freed with the CFG.
383 void* Mem = cfg->getAllocator().Allocate(sizeof(UnaryDeclStmt), A);
384 // Append the fake DeclStmt to block.
385 Block->appendStmt(new (Mem) UnaryDeclStmt(*I));
386 B = WalkAST_VisitDeclSubExpr(*I);
387 }
388 return B;
389 }
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000390 }
Ted Kremenek0865a992008-08-06 23:20:50 +0000391
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000392 case Stmt::AddrLabelExprClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000393 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000394 AddressTakenLabels.insert(A->getLabel());
395
Ted Kremenek79f0a632008-04-16 21:10:48 +0000396 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek0edd3a92007-08-28 19:26:49 +0000397 return Block;
398 }
Ted Kremenekd11620d2007-09-11 21:29:43 +0000399
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000400 case Stmt::StmtExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000401 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremeneke822b622007-08-28 18:14:37 +0000402
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000403 case Stmt::UnaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000404 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000405
406 // sizeof(expressions). For such expressions,
407 // the subexpression is not really evaluated, so
408 // we don't care about control-flow within the sizeof.
409 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000410 Block->appendStmt(Terminator);
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000411 return Block;
412 }
413
414 break;
415 }
416
Ted Kremenekcfaae762007-08-27 21:54:41 +0000417 case Stmt::BinaryOperatorClass: {
Ted Kremenek79f0a632008-04-16 21:10:48 +0000418 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000419
420 if (B->isLogicalOp()) { // && or ||
421 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
422 ConfluenceBlock->appendStmt(B);
423 FinishBlock(ConfluenceBlock);
424
425 // create the block evaluating the LHS
426 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekb2348522007-12-21 19:49:00 +0000427 LHSBlock->setTerminator(B);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000428
429 // create the block evaluating the RHS
430 Succ = ConfluenceBlock;
431 Block = NULL;
432 CFGBlock* RHSBlock = Visit(B->getRHS());
Ted Kremenekb2348522007-12-21 19:49:00 +0000433
434 // Now link the LHSBlock with RHSBlock.
435 if (B->getOpcode() == BinaryOperator::LOr) {
436 LHSBlock->addSuccessor(ConfluenceBlock);
437 LHSBlock->addSuccessor(RHSBlock);
438 }
439 else {
440 assert (B->getOpcode() == BinaryOperator::LAnd);
441 LHSBlock->addSuccessor(RHSBlock);
442 LHSBlock->addSuccessor(ConfluenceBlock);
443 }
Ted Kremenekcfaae762007-08-27 21:54:41 +0000444
445 // Generate the blocks for evaluating the LHS.
446 Block = LHSBlock;
447 return addStmt(B->getLHS());
Ted Kremeneke822b622007-08-28 18:14:37 +0000448 }
449 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
450 Block->appendStmt(B);
451 addStmt(B->getRHS());
452 return addStmt(B->getLHS());
Ted Kremenek3a819822007-10-01 19:33:33 +0000453 }
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000454
455 break;
Ted Kremenekcfaae762007-08-27 21:54:41 +0000456 }
Ted Kremeneka9ba5cc2008-02-26 02:37:08 +0000457
458 case Stmt::ParenExprClass:
Ted Kremenek79f0a632008-04-16 21:10:48 +0000459 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenekcfaae762007-08-27 21:54:41 +0000460
Ted Kremenek65cfa562007-08-27 21:27:44 +0000461 default:
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000462 break;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000463 };
Ted Kremenekd1a80f72007-12-13 22:44:18 +0000464
Ted Kremenek79f0a632008-04-16 21:10:48 +0000465 if (AlwaysAddStmt) Block->appendStmt(Terminator);
466 return WalkAST_VisitChildren(Terminator);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000467}
468
Ted Kremenek0865a992008-08-06 23:20:50 +0000469/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
470/// for initializers in Decls.
471CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
472 VarDecl* VD = dyn_cast<VarDecl>(D);
473
474 if (!VD)
Ted Kremenekf4e35622007-11-18 20:06:01 +0000475 return Block;
476
Ted Kremenek0865a992008-08-06 23:20:50 +0000477 Expr* Init = VD->getInit();
Ted Kremenek7c6c0fd2007-10-30 21:48:34 +0000478
Ted Kremenek0865a992008-08-06 23:20:50 +0000479 if (!Init)
480 return Block;
481
482 // Optimization: Don't create separate block-level statements for literals.
483 switch (Init->getStmtClass()) {
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000484 case Stmt::IntegerLiteralClass:
485 case Stmt::CharacterLiteralClass:
486 case Stmt::StringLiteralClass:
487 break;
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000488 default:
Ted Kremenek0865a992008-08-06 23:20:50 +0000489 Block = addStmt(Init);
Ted Kremenek4ad64e82008-02-29 22:32:24 +0000490 }
491
Ted Kremeneke822b622007-08-28 18:14:37 +0000492 return Block;
493}
494
Ted Kremenek65cfa562007-08-27 21:27:44 +0000495/// WalkAST_VisitChildren - Utility method to call WalkAST on the
496/// children of a Stmt.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000497CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +0000498 CFGBlock* B = Block;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000499 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek65cfa562007-08-27 21:27:44 +0000500 I != E; ++I)
Ted Kremenek680fcb82007-09-26 21:23:31 +0000501 if (*I) B = WalkAST(*I);
Ted Kremenek65cfa562007-08-27 21:27:44 +0000502
503 return B;
504}
505
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000506/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
507/// expressions (a GCC extension).
Ted Kremenek79f0a632008-04-16 21:10:48 +0000508CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
509 Block->appendStmt(Terminator);
510 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek6fca3e02007-08-28 18:30:10 +0000511}
512
Ted Kremenek73543912007-08-23 21:42:29 +0000513/// VisitStmt - Handle statements with no branching control flow.
514CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
515 // We cannot assume that we are in the middle of a basic block, since
516 // the CFG might only be constructed for this single statement. If
517 // we have no current basic block, just create one lazily.
518 if (!Block) Block = createBlock();
519
520 // Simply add the statement to the current block. We actually
521 // insert statements in reverse order; this order is reversed later
522 // when processing the containing element in the AST.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000523 addStmt(Statement);
524
Ted Kremenek73543912007-08-23 21:42:29 +0000525 return Block;
526}
527
528CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
529 return Block;
530}
531
532CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000533
534 CFGBlock* LastBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000535
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000536 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
537 I != E; ++I ) {
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000538 LastBlock = Visit(*I);
Ted Kremenekfeb0e992008-02-26 00:22:58 +0000539 }
540
Ted Kremenek92e3ff92008-03-17 17:19:44 +0000541 return LastBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000542}
543
544CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
545 // We may see an if statement in the middle of a basic block, or
546 // it may be the first statement we are processing. In either case,
547 // we create a new basic block. First, we create the blocks for
548 // the then...else statements, and then we create the block containing
549 // the if statement. If we were in the middle of a block, we
550 // stop processing that block and reverse its statements. That block
551 // is then the implicit successor for the "then" and "else" clauses.
552
553 // The block we were proccessing is now finished. Make it the
554 // successor block.
555 if (Block) {
556 Succ = Block;
557 FinishBlock(Block);
558 }
559
560 // Process the false branch. NULL out Block so that the recursive
561 // call to Visit will create a new basic block.
562 // Null out Block so that all successor
563 CFGBlock* ElseBlock = Succ;
564
565 if (Stmt* Else = I->getElse()) {
566 SaveAndRestore<CFGBlock*> sv(Succ);
567
568 // NULL out Block so that the recursive call to Visit will
569 // create a new basic block.
570 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000571 ElseBlock = Visit(Else);
572
573 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
574 ElseBlock = sv.get();
575 else if (Block)
576 FinishBlock(ElseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000577 }
578
579 // Process the true branch. NULL out Block so that the recursive
580 // call to Visit will create a new basic block.
581 // Null out Block so that all successor
582 CFGBlock* ThenBlock;
583 {
584 Stmt* Then = I->getThen();
585 assert (Then);
586 SaveAndRestore<CFGBlock*> sv(Succ);
587 Block = NULL;
Ted Kremenek44db7872007-08-30 18:13:31 +0000588 ThenBlock = Visit(Then);
589
590 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
591 ThenBlock = sv.get();
592 else if (Block)
593 FinishBlock(ThenBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000594 }
595
596 // Now create a new block containing the if statement.
597 Block = createBlock(false);
Ted Kremenek73543912007-08-23 21:42:29 +0000598
599 // Set the terminator of the new block to the If statement.
600 Block->setTerminator(I);
601
602 // Now add the successors.
603 Block->addSuccessor(ThenBlock);
604 Block->addSuccessor(ElseBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000605
606 // Add the condition as the last statement in the new block. This
607 // may create new blocks as the condition may contain control-flow. Any
608 // newly created blocks will be pointed to be "Block".
Ted Kremenek1eaa6712008-01-30 23:02:42 +0000609 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenek73543912007-08-23 21:42:29 +0000610}
Ted Kremenekd11620d2007-09-11 21:29:43 +0000611
Ted Kremenek73543912007-08-23 21:42:29 +0000612
613CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
614 // If we were in the middle of a block we stop processing that block
615 // and reverse its statements.
616 //
617 // NOTE: If a "return" appears in the middle of a block, this means
618 // that the code afterwards is DEAD (unreachable). We still
619 // keep a basic block for that code; a simple "mark-and-sweep"
620 // from the entry block will be able to report such dead
621 // blocks.
622 if (Block) FinishBlock(Block);
623
624 // Create the new block.
625 Block = createBlock(false);
626
627 // The Exit block is the only successor.
628 Block->addSuccessor(&cfg->getExit());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000629
630 // Add the return statement to the block. This may create new blocks
631 // if R contains control-flow (short-circuit operations).
632 return addStmt(R);
Ted Kremenek73543912007-08-23 21:42:29 +0000633}
634
635CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
636 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek82e8a192008-03-15 07:45:02 +0000637 Visit(L->getSubStmt());
638 CFGBlock* LabelBlock = Block;
Ted Kremenek9b0d1b62007-08-30 18:20:57 +0000639
640 if (!LabelBlock) // This can happen when the body is empty, i.e.
641 LabelBlock=createBlock(); // scopes that only contains NullStmts.
642
Ted Kremenek73543912007-08-23 21:42:29 +0000643 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
644 LabelMap[ L ] = LabelBlock;
645
646 // Labels partition blocks, so this is the end of the basic block
Ted Kremenekec055e12007-08-29 23:20:49 +0000647 // we were processing (L is the block's label). Because this is
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000648 // label (and we have already processed the substatement) there is no
649 // extra control-flow to worry about.
Ted Kremenekec055e12007-08-29 23:20:49 +0000650 LabelBlock->setLabel(L);
Ted Kremenek73543912007-08-23 21:42:29 +0000651 FinishBlock(LabelBlock);
652
653 // We set Block to NULL to allow lazy creation of a new block
654 // (if necessary);
655 Block = NULL;
656
657 // This block is now the implicit successor of other blocks.
658 Succ = LabelBlock;
659
660 return LabelBlock;
661}
662
663CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
664 // Goto is a control-flow statement. Thus we stop processing the
665 // current block and create a new one.
666 if (Block) FinishBlock(Block);
667 Block = createBlock(false);
668 Block->setTerminator(G);
669
670 // If we already know the mapping to the label block add the
671 // successor now.
672 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
673
674 if (I == LabelMap.end())
675 // We will need to backpatch this block later.
676 BackpatchBlocks.push_back(Block);
677 else
678 Block->addSuccessor(I->second);
679
680 return Block;
681}
682
683CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
684 // "for" is a control-flow statement. Thus we stop processing the
685 // current block.
686
687 CFGBlock* LoopSuccessor = NULL;
688
689 if (Block) {
690 FinishBlock(Block);
691 LoopSuccessor = Block;
692 }
693 else LoopSuccessor = Succ;
694
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000695 // Because of short-circuit evaluation, the condition of the loop
696 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
697 // blocks that evaluate the condition.
698 CFGBlock* ExitConditionBlock = createBlock(false);
699 CFGBlock* EntryConditionBlock = ExitConditionBlock;
700
701 // Set the terminator for the "exit" condition block.
702 ExitConditionBlock->setTerminator(F);
703
704 // Now add the actual condition to the condition block. Because the
705 // condition itself may contain control-flow, new blocks may be created.
706 if (Stmt* C = F->getCond()) {
707 Block = ExitConditionBlock;
708 EntryConditionBlock = addStmt(C);
709 if (Block) FinishBlock(EntryConditionBlock);
710 }
Ted Kremenek73543912007-08-23 21:42:29 +0000711
712 // The condition block is the implicit successor for the loop body as
713 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000714 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000715
716 // Now create the loop body.
717 {
718 assert (F->getBody());
719
720 // Save the current values for Block, Succ, and continue and break targets
721 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
722 save_continue(ContinueTargetBlock),
723 save_break(BreakTargetBlock);
724
725 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000726 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000727
728 // All breaks should go to the code following the loop.
729 BreakTargetBlock = LoopSuccessor;
730
Ted Kremenek390b9762007-08-30 18:39:40 +0000731 // Create a new block to contain the (bottom) of the loop body.
732 Block = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000733
734 // If we have increment code, insert it at the end of the body block.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000735 if (Stmt* I = F->getInc()) Block = addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000736
737 // Now populate the body block, and in the process create new blocks
738 // as we walk the body of the loop.
739 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000740
741 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000742 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000743 else if (Block)
744 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000745
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000746 // This new body block is a successor to our "exit" condition block.
747 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000748 }
749
750 // Link up the condition block with the code that follows the loop.
751 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000752 ExitConditionBlock->addSuccessor(LoopSuccessor);
753
Ted Kremenek73543912007-08-23 21:42:29 +0000754 // If the loop contains initialization, create a new block for those
755 // statements. This block can also contain statements that precede
756 // the loop.
757 if (Stmt* I = F->getInit()) {
758 Block = createBlock();
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000759 return addStmt(I);
Ted Kremenek73543912007-08-23 21:42:29 +0000760 }
761 else {
762 // There is no loop initialization. We are thus basically a while
763 // loop. NULL out Block to force lazy block construction.
764 Block = NULL;
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000765 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000766 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000767 }
768}
769
770CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
771 // "while" is a control-flow statement. Thus we stop processing the
772 // current block.
773
774 CFGBlock* LoopSuccessor = NULL;
775
776 if (Block) {
777 FinishBlock(Block);
778 LoopSuccessor = Block;
779 }
780 else LoopSuccessor = Succ;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000781
782 // Because of short-circuit evaluation, the condition of the loop
783 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
784 // blocks that evaluate the condition.
785 CFGBlock* ExitConditionBlock = createBlock(false);
786 CFGBlock* EntryConditionBlock = ExitConditionBlock;
787
788 // Set the terminator for the "exit" condition block.
789 ExitConditionBlock->setTerminator(W);
790
791 // Now add the actual condition to the condition block. Because the
792 // condition itself may contain control-flow, new blocks may be created.
793 // Thus we update "Succ" after adding the condition.
794 if (Stmt* C = W->getCond()) {
795 Block = ExitConditionBlock;
796 EntryConditionBlock = addStmt(C);
Ted Kremenekd0c87602008-02-27 00:28:17 +0000797 assert (Block == EntryConditionBlock);
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000798 if (Block) FinishBlock(EntryConditionBlock);
799 }
Ted Kremenek73543912007-08-23 21:42:29 +0000800
801 // The condition block is the implicit successor for the loop body as
802 // well as any code above the loop.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000803 Succ = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000804
805 // Process the loop body.
806 {
807 assert (W->getBody());
808
809 // Save the current values for Block, Succ, and continue and break targets
810 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
811 save_continue(ContinueTargetBlock),
812 save_break(BreakTargetBlock);
813
814 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000815 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000816
817 // All breaks should go to the code following the loop.
818 BreakTargetBlock = LoopSuccessor;
819
820 // NULL out Block to force lazy instantiation of blocks for the body.
821 Block = NULL;
822
823 // Create the body. The returned block is the entry to the loop body.
824 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenek390b9762007-08-30 18:39:40 +0000825
826 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000827 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenek390b9762007-08-30 18:39:40 +0000828 else if (Block)
829 FinishBlock(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000830
831 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000832 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000833 }
834
835 // Link up the condition block with the code that follows the loop.
836 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000837 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000838
839 // There can be no more statements in the condition block
840 // since we loop back to this block. NULL out Block to force
841 // lazy creation of another block.
842 Block = NULL;
843
844 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000845 Succ = EntryConditionBlock;
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000846 return EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000847}
848
849CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
850 // "do...while" is a control-flow statement. Thus we stop processing the
851 // current block.
852
853 CFGBlock* LoopSuccessor = NULL;
854
855 if (Block) {
856 FinishBlock(Block);
857 LoopSuccessor = Block;
858 }
859 else LoopSuccessor = Succ;
860
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000861 // Because of short-circuit evaluation, the condition of the loop
862 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
863 // blocks that evaluate the condition.
864 CFGBlock* ExitConditionBlock = createBlock(false);
865 CFGBlock* EntryConditionBlock = ExitConditionBlock;
866
867 // Set the terminator for the "exit" condition block.
868 ExitConditionBlock->setTerminator(D);
Ted Kremenek73543912007-08-23 21:42:29 +0000869
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000870 // Now add the actual condition to the condition block. Because the
871 // condition itself may contain control-flow, new blocks may be created.
872 if (Stmt* C = D->getCond()) {
873 Block = ExitConditionBlock;
874 EntryConditionBlock = addStmt(C);
875 if (Block) FinishBlock(EntryConditionBlock);
876 }
Ted Kremenek73543912007-08-23 21:42:29 +0000877
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000878 // The condition block is the implicit successor for the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000879 Succ = EntryConditionBlock;
880
Ted Kremenek73543912007-08-23 21:42:29 +0000881 // Process the loop body.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000882 CFGBlock* BodyBlock = NULL;
Ted Kremenek73543912007-08-23 21:42:29 +0000883 {
884 assert (D->getBody());
885
886 // Save the current values for Block, Succ, and continue and break targets
887 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
888 save_continue(ContinueTargetBlock),
889 save_break(BreakTargetBlock);
890
891 // All continues within this loop should go to the condition block
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000892 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000893
894 // All breaks should go to the code following the loop.
895 BreakTargetBlock = LoopSuccessor;
896
897 // NULL out Block to force lazy instantiation of blocks for the body.
898 Block = NULL;
899
900 // Create the body. The returned block is the entry to the loop body.
901 BodyBlock = Visit(D->getBody());
Ted Kremenek73543912007-08-23 21:42:29 +0000902
Ted Kremenek390b9762007-08-30 18:39:40 +0000903 if (!BodyBlock)
Ted Kremenekd0c87602008-02-27 00:28:17 +0000904 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenek390b9762007-08-30 18:39:40 +0000905 else if (Block)
906 FinishBlock(BodyBlock);
907
Ted Kremenek73543912007-08-23 21:42:29 +0000908 // Add the loop body entry as a successor to the condition.
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000909 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenek73543912007-08-23 21:42:29 +0000910 }
911
912 // Link up the condition block with the code that follows the loop.
913 // (the false branch).
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000914 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenek73543912007-08-23 21:42:29 +0000915
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000916 // There can be no more statements in the body block(s)
917 // since we loop back to the body. NULL out Block to force
Ted Kremenek73543912007-08-23 21:42:29 +0000918 // lazy creation of another block.
919 Block = NULL;
920
921 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek9ff572c2008-02-27 07:20:00 +0000922 Succ = BodyBlock;
Ted Kremenek73543912007-08-23 21:42:29 +0000923 return BodyBlock;
924}
925
926CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
927 // "continue" is a control-flow statement. Thus we stop processing the
928 // current block.
929 if (Block) FinishBlock(Block);
930
931 // Now create a new block that ends with the continue statement.
932 Block = createBlock(false);
933 Block->setTerminator(C);
934
935 // If there is no target for the continue, then we are looking at an
936 // incomplete AST. Handle this by not registering a successor.
937 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
938
939 return Block;
940}
941
942CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
943 // "break" is a control-flow statement. Thus we stop processing the
944 // current block.
945 if (Block) FinishBlock(Block);
946
947 // Now create a new block that ends with the continue statement.
948 Block = createBlock(false);
949 Block->setTerminator(B);
950
951 // If there is no target for the break, then we are looking at an
952 // incomplete AST. Handle this by not registering a successor.
953 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
954
955 return Block;
956}
957
Ted Kremenek79f0a632008-04-16 21:10:48 +0000958CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek73543912007-08-23 21:42:29 +0000959 // "switch" is a control-flow statement. Thus we stop processing the
960 // current block.
961 CFGBlock* SwitchSuccessor = NULL;
962
963 if (Block) {
964 FinishBlock(Block);
965 SwitchSuccessor = Block;
966 }
967 else SwitchSuccessor = Succ;
968
969 // Save the current "switch" context.
970 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenek97bc3422008-02-13 22:05:39 +0000971 save_break(BreakTargetBlock),
972 save_default(DefaultCaseBlock);
973
974 // Set the "default" case to be the block after the switch statement.
975 // If the switch statement contains a "default:", this value will
976 // be overwritten with the block for that code.
977 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000978
Ted Kremenek73543912007-08-23 21:42:29 +0000979 // Create a new block that will contain the switch statement.
980 SwitchTerminatedBlock = createBlock(false);
981
Ted Kremenek73543912007-08-23 21:42:29 +0000982 // Now process the switch body. The code after the switch is the implicit
983 // successor.
984 Succ = SwitchSuccessor;
985 BreakTargetBlock = SwitchSuccessor;
Ted Kremenek73543912007-08-23 21:42:29 +0000986
987 // When visiting the body, the case statements should automatically get
988 // linked up to the switch. We also don't keep a pointer to the body,
989 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek79f0a632008-04-16 21:10:48 +0000990 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000991 Block = NULL;
Ted Kremenek79f0a632008-04-16 21:10:48 +0000992 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000993 if (Block) FinishBlock(BodyBlock);
994
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000995 // If we have no "default:" case, the default transition is to the
996 // code following the switch body.
Ted Kremenek97bc3422008-02-13 22:05:39 +0000997 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenekc07a8af2008-02-13 21:46:34 +0000998
Ted Kremenekcfee50c2007-08-27 19:46:09 +0000999 // Add the terminator and condition in the switch block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001000 SwitchTerminatedBlock->setTerminator(Terminator);
1001 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenek73543912007-08-23 21:42:29 +00001002 Block = SwitchTerminatedBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001003
Ted Kremenek79f0a632008-04-16 21:10:48 +00001004 return addStmt(Terminator->getCond());
Ted Kremenek73543912007-08-23 21:42:29 +00001005}
1006
Ted Kremenek79f0a632008-04-16 21:10:48 +00001007CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenek97bc3422008-02-13 22:05:39 +00001008 // CaseStmts are essentially labels, so they are the
Ted Kremenek73543912007-08-23 21:42:29 +00001009 // first statement in a block.
Ted Kremenek44659d82007-08-30 18:48:11 +00001010
Ted Kremenek79f0a632008-04-16 21:10:48 +00001011 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek44659d82007-08-30 18:48:11 +00001012 CFGBlock* CaseBlock = Block;
1013 if (!CaseBlock) CaseBlock = createBlock();
1014
Ted Kremenek97bc3422008-02-13 22:05:39 +00001015 // Cases statements partition blocks, so this is the top of
1016 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +00001017 CaseBlock->setLabel(Terminator);
Ted Kremenek73543912007-08-23 21:42:29 +00001018 FinishBlock(CaseBlock);
1019
1020 // Add this block to the list of successors for the block with the
1021 // switch statement.
Ted Kremenek97bc3422008-02-13 22:05:39 +00001022 assert (SwitchTerminatedBlock);
1023 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenek73543912007-08-23 21:42:29 +00001024
1025 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1026 Block = NULL;
1027
1028 // This block is now the implicit successor of other blocks.
1029 Succ = CaseBlock;
1030
Ted Kremenek82e8a192008-03-15 07:45:02 +00001031 return CaseBlock;
Ted Kremenek73543912007-08-23 21:42:29 +00001032}
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001033
Ted Kremenek79f0a632008-04-16 21:10:48 +00001034CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1035 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek97bc3422008-02-13 22:05:39 +00001036 DefaultCaseBlock = Block;
1037 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1038
1039 // Default statements partition blocks, so this is the top of
1040 // the basic block we were processing (the "default:" is the label).
Ted Kremenek79f0a632008-04-16 21:10:48 +00001041 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenek97bc3422008-02-13 22:05:39 +00001042 FinishBlock(DefaultCaseBlock);
1043
1044 // Unlike case statements, we don't add the default block to the
1045 // successors for the switch statement immediately. This is done
1046 // when we finish processing the switch statement. This allows for
1047 // the default case (including a fall-through to the code after the
1048 // switch statement) to always be the last successor of a switch-terminated
1049 // block.
1050
1051 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1052 Block = NULL;
1053
1054 // This block is now the implicit successor of other blocks.
1055 Succ = DefaultCaseBlock;
1056
1057 return DefaultCaseBlock;
Ted Kremenekc07a8af2008-02-13 21:46:34 +00001058}
Ted Kremenek73543912007-08-23 21:42:29 +00001059
Ted Kremenek0edd3a92007-08-28 19:26:49 +00001060CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1061 // Lazily create the indirect-goto dispatch block if there isn't one
1062 // already.
1063 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1064
1065 if (!IBlock) {
1066 IBlock = createBlock(false);
1067 cfg->setIndirectGotoBlock(IBlock);
1068 }
1069
1070 // IndirectGoto is a control-flow statement. Thus we stop processing the
1071 // current block and create a new one.
1072 if (Block) FinishBlock(Block);
1073 Block = createBlock(false);
1074 Block->setTerminator(I);
1075 Block->addSuccessor(IBlock);
1076 return addStmt(I->getTarget());
1077}
1078
Ted Kremenek73543912007-08-23 21:42:29 +00001079
Ted Kremenekd6e50602007-08-23 21:26:19 +00001080} // end anonymous namespace
Ted Kremenek4db5b452007-08-23 16:51:22 +00001081
1082/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1083/// block has no successors or predecessors. If this is the first block
1084/// created in the CFG, it is automatically set to be the Entry and Exit
1085/// of the CFG.
Ted Kremenek14594572007-09-05 20:02:05 +00001086CFGBlock* CFG::createBlock() {
Ted Kremenek4db5b452007-08-23 16:51:22 +00001087 bool first_block = begin() == end();
1088
1089 // Create the block.
Ted Kremenek14594572007-09-05 20:02:05 +00001090 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek4db5b452007-08-23 16:51:22 +00001091
1092 // If this is the first block, set it as the Entry and Exit.
1093 if (first_block) Entry = Exit = &front();
1094
1095 // Return the block.
1096 return &front();
Ted Kremenek97f75312007-08-21 21:42:03 +00001097}
1098
Ted Kremenek4db5b452007-08-23 16:51:22 +00001099/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1100/// CFG is returned to the caller.
1101CFG* CFG::buildCFG(Stmt* Statement) {
1102 CFGBuilder Builder;
1103 return Builder.buildCFG(Statement);
1104}
1105
1106/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenek97f75312007-08-21 21:42:03 +00001107void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1108
Ted Kremenek3a819822007-10-01 19:33:33 +00001109//===----------------------------------------------------------------------===//
1110// CFG: Queries for BlkExprs.
1111//===----------------------------------------------------------------------===//
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001112
Ted Kremenek3a819822007-10-01 19:33:33 +00001113namespace {
Ted Kremenekab6c5902008-01-17 20:48:37 +00001114 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek3a819822007-10-01 19:33:33 +00001115}
1116
Ted Kremenek79f0a632008-04-16 21:10:48 +00001117static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1118 if (!Terminator)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001119 return;
1120
Ted Kremenek79f0a632008-04-16 21:10:48 +00001121 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001122 if (!*I) continue;
1123
1124 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1125 if (B->isAssignmentOp()) Set.insert(B);
1126
1127 FindSubExprAssignments(*I, Set);
1128 }
1129}
1130
Ted Kremenek3a819822007-10-01 19:33:33 +00001131static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1132 BlkExprMapTy* M = new BlkExprMapTy();
1133
Ted Kremenekc6fda602008-01-26 00:03:27 +00001134 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek79f0a632008-04-16 21:10:48 +00001135 // only assignments that we want to *possibly* register as a block-level
1136 // expression. Basically, if an assignment occurs both in a subexpression
1137 // and at the block-level, it is a block-level expression.
Ted Kremenekc6fda602008-01-26 00:03:27 +00001138 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1139
Ted Kremenek3a819822007-10-01 19:33:33 +00001140 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1141 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenekc6fda602008-01-26 00:03:27 +00001142 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001143
Ted Kremenek79f0a632008-04-16 21:10:48 +00001144 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1145
1146 // Iterate over the statements again on identify the Expr* and Stmt* at
1147 // the block-level that are block-level expressions.
1148
Ted Kremenekc6fda602008-01-26 00:03:27 +00001149 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek79f0a632008-04-16 21:10:48 +00001150 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001151
Ted Kremenek79f0a632008-04-16 21:10:48 +00001152 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001153 // Assignment expressions that are not nested within another
1154 // expression are really "statements" whose value is never
1155 // used by another expression.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001156 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenekc6fda602008-01-26 00:03:27 +00001157 continue;
1158 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001159 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001160 // Special handling for statement expressions. The last statement
1161 // in the statement expression is also a block-level expr.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001162 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001163 if (!C->body_empty()) {
Ted Kremenekc6fda602008-01-26 00:03:27 +00001164 unsigned x = M->size();
Ted Kremenekab6c5902008-01-17 20:48:37 +00001165 (*M)[C->body_back()] = x;
1166 }
1167 }
Ted Kremenek5b4eb172008-01-25 23:22:27 +00001168
Ted Kremenekc6fda602008-01-26 00:03:27 +00001169 unsigned x = M->size();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001170 (*M)[Exp] = x;
Ted Kremenekc6fda602008-01-26 00:03:27 +00001171 }
1172
Ted Kremenek79f0a632008-04-16 21:10:48 +00001173 // Look at terminators. The condition is a block-level expression.
1174
1175 Expr* Exp = I->getTerminatorCondition();
1176
1177 if (Exp && M->find(Exp) == M->end()) {
1178 unsigned x = M->size();
1179 (*M)[Exp] = x;
1180 }
1181 }
1182
Ted Kremenek3a819822007-10-01 19:33:33 +00001183 return M;
1184}
1185
Ted Kremenekab6c5902008-01-17 20:48:37 +00001186CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1187 assert(S != NULL);
Ted Kremenek3a819822007-10-01 19:33:33 +00001188 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1189
1190 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenekab6c5902008-01-17 20:48:37 +00001191 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek3a819822007-10-01 19:33:33 +00001192
1193 if (I == M->end()) return CFG::BlkExprNumTy();
1194 else return CFG::BlkExprNumTy(I->second);
1195}
1196
1197unsigned CFG::getNumBlkExprs() {
1198 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1199 return M->size();
1200 else {
1201 // We assume callers interested in the number of BlkExprs will want
1202 // the map constructed if it doesn't already exist.
1203 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1204 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1205 }
1206}
1207
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001208//===----------------------------------------------------------------------===//
1209// Internal Block-Edge Set; used for modeling persistent <CFGBlock*,CFGBlock*>
1210// pairs for use with ProgramPoint.
1211//===----------------------------------------------------------------------===//
1212
1213typedef std::pair<CFGBlock*,CFGBlock*> BPairTy;
1214
1215namespace llvm {
1216 template<> struct FoldingSetTrait<BPairTy*> {
1217 static void Profile(const BPairTy* X, FoldingSetNodeID& profile) {
1218 profile.AddPointer(X->first);
1219 profile.AddPointer(X->second);
1220 }
1221 };
1222}
1223
1224typedef llvm::FoldingSetNodeWrapper<BPairTy*> PersistPairTy;
1225typedef llvm::FoldingSet<PersistPairTy> BlkEdgeSetTy;
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001226
1227const std::pair<CFGBlock*,CFGBlock*>*
1228CFG::getBlockEdgeImpl(const CFGBlock* B1, const CFGBlock* B2) {
1229
Ted Kremenekce668af2008-05-29 21:52:26 +00001230 if (!BlkEdgeSet)
1231 BlkEdgeSet = new BlkEdgeSetTy();
1232
1233 BlkEdgeSetTy* p = static_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001234
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001235 // Profile the edges.
1236 llvm::FoldingSetNodeID profile;
1237 void* InsertPos;
1238
1239 profile.AddPointer(B1);
1240 profile.AddPointer(B2);
1241
1242 PersistPairTy* V = p->FindNodeOrInsertPos(profile, InsertPos);
1243
1244 if (!V) {
1245 assert (llvm::AlignOf<BPairTy>::Alignment_LessEqual_8Bytes);
1246
1247 // Allocate the pair, forcing an 8-byte alignment.
Ted Kremenek1f62aa82008-08-06 22:22:32 +00001248 BPairTy* pair = (BPairTy*) Alloc.Allocate(sizeof(*pair), 8);
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001249
1250 new (pair) BPairTy(const_cast<CFGBlock*>(B1),
1251 const_cast<CFGBlock*>(B2));
1252
1253 // Allocate the meta data to store the pair in the FoldingSet.
Ted Kremenek1f62aa82008-08-06 22:22:32 +00001254 PersistPairTy* ppair = (PersistPairTy*) Alloc.Allocate<PersistPairTy>();
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001255 new (ppair) PersistPairTy(pair);
1256
1257 p->InsertNode(ppair, InsertPos);
1258
1259 return pair;
1260 }
1261
1262 return V->getValue();
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001263}
1264
Ted Kremenekd058a9c2008-04-28 18:00:46 +00001265//===----------------------------------------------------------------------===//
1266// Cleanup: CFG dstor.
1267//===----------------------------------------------------------------------===//
1268
Ted Kremenek3a819822007-10-01 19:33:33 +00001269CFG::~CFG() {
1270 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
Ted Kremenek5ee98a72008-01-11 00:40:29 +00001271 delete reinterpret_cast<BlkEdgeSetTy*>(BlkEdgeSet);
Ted Kremenek3a819822007-10-01 19:33:33 +00001272}
1273
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001274//===----------------------------------------------------------------------===//
1275// CFG pretty printing
1276//===----------------------------------------------------------------------===//
1277
Ted Kremenekd8313202007-08-22 18:22:34 +00001278namespace {
1279
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001280class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek86afc042007-08-31 22:26:13 +00001281
Ted Kremenek08176a52007-08-31 21:30:12 +00001282 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1283 StmtMapTy StmtMap;
1284 signed CurrentBlock;
1285 unsigned CurrentStmt;
Ted Kremenek86afc042007-08-31 22:26:13 +00001286
Ted Kremenek73543912007-08-23 21:42:29 +00001287public:
Ted Kremenek86afc042007-08-31 22:26:13 +00001288
Ted Kremenek08176a52007-08-31 21:30:12 +00001289 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1290 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1291 unsigned j = 1;
1292 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1293 BI != BEnd; ++BI, ++j )
1294 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1295 }
1296 }
1297
1298 virtual ~StmtPrinterHelper() {}
1299
1300 void setBlockID(signed i) { CurrentBlock = i; }
1301 void setStmtID(unsigned i) { CurrentStmt = i; }
1302
Ted Kremenek79f0a632008-04-16 21:10:48 +00001303 virtual bool handledStmt(Stmt* Terminator, std::ostream& OS) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001304
Ted Kremenek79f0a632008-04-16 21:10:48 +00001305 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek08176a52007-08-31 21:30:12 +00001306
1307 if (I == StmtMap.end())
1308 return false;
1309
1310 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1311 && I->second.second == CurrentStmt)
1312 return false;
1313
Ted Kremenek86afc042007-08-31 22:26:13 +00001314 OS << "[B" << I->second.first << "." << I->second.second << "]";
1315 return true;
Ted Kremenek08176a52007-08-31 21:30:12 +00001316 }
1317};
1318
Ted Kremenek98cee3a2008-01-08 18:15:10 +00001319class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1320 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1321
Ted Kremenek08176a52007-08-31 21:30:12 +00001322 std::ostream& OS;
1323 StmtPrinterHelper* Helper;
1324public:
1325 CFGBlockTerminatorPrint(std::ostream& os, StmtPrinterHelper* helper)
1326 : OS(os), Helper(helper) {}
Ted Kremenek73543912007-08-23 21:42:29 +00001327
1328 void VisitIfStmt(IfStmt* I) {
1329 OS << "if ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001330 I->getCond()->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001331 }
1332
1333 // Default case.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001334 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenek73543912007-08-23 21:42:29 +00001335
1336 void VisitForStmt(ForStmt* F) {
1337 OS << "for (" ;
Ted Kremenek23a1d662007-08-30 21:28:02 +00001338 if (F->getInit()) OS << "...";
1339 OS << "; ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001340 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek23a1d662007-08-30 21:28:02 +00001341 OS << "; ";
1342 if (F->getInc()) OS << "...";
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001343 OS << ")";
Ted Kremenek73543912007-08-23 21:42:29 +00001344 }
1345
1346 void VisitWhileStmt(WhileStmt* W) {
1347 OS << "while " ;
Ted Kremenek08176a52007-08-31 21:30:12 +00001348 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenek73543912007-08-23 21:42:29 +00001349 }
1350
1351 void VisitDoStmt(DoStmt* D) {
1352 OS << "do ... while ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001353 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001354 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001355
Ted Kremenek79f0a632008-04-16 21:10:48 +00001356 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek65cfa562007-08-27 21:27:44 +00001357 OS << "switch ";
Ted Kremenek79f0a632008-04-16 21:10:48 +00001358 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek65cfa562007-08-27 21:27:44 +00001359 }
1360
Ted Kremenek621e1592007-08-31 21:49:40 +00001361 void VisitConditionalOperator(ConditionalOperator* C) {
1362 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001363 OS << " ? ... : ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001364 }
1365
Ted Kremenek2025cc92007-08-31 22:29:13 +00001366 void VisitChooseExpr(ChooseExpr* C) {
1367 OS << "__builtin_choose_expr( ";
1368 C->getCond()->printPretty(OS,Helper);
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001369 OS << " )";
Ted Kremenek2025cc92007-08-31 22:29:13 +00001370 }
1371
Ted Kremenek86afc042007-08-31 22:26:13 +00001372 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1373 OS << "goto *";
1374 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001375 }
1376
Ted Kremenek621e1592007-08-31 21:49:40 +00001377 void VisitBinaryOperator(BinaryOperator* B) {
1378 if (!B->isLogicalOp()) {
1379 VisitExpr(B);
1380 return;
1381 }
1382
1383 B->getLHS()->printPretty(OS,Helper);
1384
1385 switch (B->getOpcode()) {
1386 case BinaryOperator::LOr:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001387 OS << " || ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001388 return;
1389 case BinaryOperator::LAnd:
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001390 OS << " && ...";
Ted Kremenek621e1592007-08-31 21:49:40 +00001391 return;
1392 default:
1393 assert(false && "Invalid logical operator.");
1394 }
1395 }
1396
Ted Kremenekcfaae762007-08-27 21:54:41 +00001397 void VisitExpr(Expr* E) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001398 E->printPretty(OS,Helper);
Ted Kremenekcfaae762007-08-27 21:54:41 +00001399 }
Ted Kremenek73543912007-08-23 21:42:29 +00001400};
Ted Kremenek08176a52007-08-31 21:30:12 +00001401
1402
Ted Kremenek79f0a632008-04-16 21:10:48 +00001403void print_stmt(std::ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001404 if (Helper) {
1405 // special printing for statement-expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001406 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001407 CompoundStmt* Sub = SE->getSubStmt();
1408
1409 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001410 OS << "({ ... ; ";
Ted Kremenek256a2592007-10-29 20:41:04 +00001411 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek16e3b9a2007-08-31 22:47:06 +00001412 OS << " })\n";
Ted Kremenek86afc042007-08-31 22:26:13 +00001413 return;
1414 }
1415 }
1416
1417 // special printing for comma expressions.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001418 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek86afc042007-08-31 22:26:13 +00001419 if (B->getOpcode() == BinaryOperator::Comma) {
1420 OS << "... , ";
1421 Helper->handledStmt(B->getRHS(),OS);
1422 OS << '\n';
1423 return;
1424 }
1425 }
1426 }
1427
Ted Kremenek79f0a632008-04-16 21:10:48 +00001428 Terminator->printPretty(OS, Helper);
Ted Kremenek86afc042007-08-31 22:26:13 +00001429
1430 // Expressions need a newline.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001431 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek86afc042007-08-31 22:26:13 +00001432}
1433
Ted Kremenek08176a52007-08-31 21:30:12 +00001434void print_block(std::ostream& OS, const CFG* cfg, const CFGBlock& B,
1435 StmtPrinterHelper* Helper, bool print_edges) {
1436
1437 if (Helper) Helper->setBlockID(B.getBlockID());
1438
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001439 // Print the header.
Ted Kremenek08176a52007-08-31 21:30:12 +00001440 OS << "\n [ B" << B.getBlockID();
1441
1442 if (&B == &cfg->getEntry())
1443 OS << " (ENTRY) ]\n";
1444 else if (&B == &cfg->getExit())
1445 OS << " (EXIT) ]\n";
1446 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001447 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek08176a52007-08-31 21:30:12 +00001448 else
1449 OS << " ]\n";
1450
Ted Kremenekec055e12007-08-29 23:20:49 +00001451 // Print the label of this block.
Ted Kremenek79f0a632008-04-16 21:10:48 +00001452 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek08176a52007-08-31 21:30:12 +00001453
1454 if (print_edges)
1455 OS << " ";
1456
Ted Kremenek79f0a632008-04-16 21:10:48 +00001457 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001458 OS << L->getName();
Ted Kremenek79f0a632008-04-16 21:10:48 +00001459 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenekec055e12007-08-29 23:20:49 +00001460 OS << "case ";
1461 C->getLHS()->printPretty(OS);
1462 if (C->getRHS()) {
1463 OS << " ... ";
1464 C->getRHS()->printPretty(OS);
1465 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001466 }
Ted Kremenek79f0a632008-04-16 21:10:48 +00001467 else if (isa<DefaultStmt>(Terminator))
Ted Kremenekec055e12007-08-29 23:20:49 +00001468 OS << "default";
Ted Kremenek08176a52007-08-31 21:30:12 +00001469 else
1470 assert(false && "Invalid label statement in CFGBlock.");
1471
Ted Kremenekec055e12007-08-29 23:20:49 +00001472 OS << ":\n";
1473 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001474
Ted Kremenek97f75312007-08-21 21:42:03 +00001475 // Iterate through the statements in the block and print them.
Ted Kremenek97f75312007-08-21 21:42:03 +00001476 unsigned j = 1;
Ted Kremenek08176a52007-08-31 21:30:12 +00001477
1478 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1479 I != E ; ++I, ++j ) {
1480
Ted Kremenekec055e12007-08-29 23:20:49 +00001481 // Print the statement # in the basic block and the statement itself.
Ted Kremenek08176a52007-08-31 21:30:12 +00001482 if (print_edges)
1483 OS << " ";
1484
1485 OS << std::setw(3) << j << ": ";
1486
1487 if (Helper)
1488 Helper->setStmtID(j);
Ted Kremenek86afc042007-08-31 22:26:13 +00001489
1490 print_stmt(OS,Helper,*I);
Ted Kremenek97f75312007-08-21 21:42:03 +00001491 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001492
Ted Kremenekec055e12007-08-29 23:20:49 +00001493 // Print the terminator of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001494 if (B.getTerminator()) {
1495 if (print_edges)
1496 OS << " ";
1497
Ted Kremenekec055e12007-08-29 23:20:49 +00001498 OS << " T: ";
Ted Kremenek08176a52007-08-31 21:30:12 +00001499
1500 if (Helper) Helper->setBlockID(-1);
1501
1502 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1503 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001504 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001505 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001506
Ted Kremenekec055e12007-08-29 23:20:49 +00001507 if (print_edges) {
1508 // Print the predecessors of this block.
Ted Kremenek08176a52007-08-31 21:30:12 +00001509 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenekec055e12007-08-29 23:20:49 +00001510 unsigned i = 0;
Ted Kremenekec055e12007-08-29 23:20:49 +00001511
Ted Kremenek08176a52007-08-31 21:30:12 +00001512 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1513 I != E; ++I, ++i) {
1514
1515 if (i == 8 || (i-8) == 0)
1516 OS << "\n ";
1517
Ted Kremenekec055e12007-08-29 23:20:49 +00001518 OS << " B" << (*I)->getBlockID();
1519 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001520
1521 OS << '\n';
1522
1523 // Print the successors of this block.
1524 OS << " Successors (" << B.succ_size() << "):";
1525 i = 0;
1526
1527 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1528 I != E; ++I, ++i) {
1529
1530 if (i == 8 || (i-8) % 10 == 0)
1531 OS << "\n ";
1532
1533 OS << " B" << (*I)->getBlockID();
1534 }
1535
Ted Kremenekec055e12007-08-29 23:20:49 +00001536 OS << '\n';
Ted Kremenek97f75312007-08-21 21:42:03 +00001537 }
Ted Kremenek08176a52007-08-31 21:30:12 +00001538}
1539
1540} // end anonymous namespace
1541
1542/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001543void CFG::dump() const { print(*llvm::cerr.stream()); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001544
1545/// print - A simple pretty printer of a CFG that outputs to an ostream.
1546void CFG::print(std::ostream& OS) const {
1547
1548 StmtPrinterHelper Helper(this);
1549
1550 // Print the entry block.
1551 print_block(OS, this, getEntry(), &Helper, true);
1552
1553 // Iterate through the CFGBlocks and print them one by one.
1554 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1555 // Skip the entry block, because we already printed it.
1556 if (&(*I) == &getEntry() || &(*I) == &getExit())
1557 continue;
1558
1559 print_block(OS, this, *I, &Helper, true);
1560 }
1561
1562 // Print the exit block.
1563 print_block(OS, this, getExit(), &Helper, true);
1564}
1565
1566/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremenek56c939e2007-12-17 19:35:20 +00001567void CFGBlock::dump(const CFG* cfg) const { print(*llvm::cerr.stream(), cfg); }
Ted Kremenek08176a52007-08-31 21:30:12 +00001568
1569/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1570/// Generally this will only be called from CFG::print.
1571void CFGBlock::print(std::ostream& OS, const CFG* cfg) const {
1572 StmtPrinterHelper Helper(cfg);
1573 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek4db5b452007-08-23 16:51:22 +00001574}
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001575
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001576/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
1577void CFGBlock::printTerminator(std::ostream& OS) const {
1578 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1579 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1580}
1581
Ted Kremenek79f0a632008-04-16 21:10:48 +00001582Expr* CFGBlock::getTerminatorCondition() {
1583
1584 if (!Terminator)
1585 return NULL;
1586
1587 Expr* E = NULL;
1588
1589 switch (Terminator->getStmtClass()) {
1590 default:
1591 break;
1592
1593 case Stmt::ForStmtClass:
1594 E = cast<ForStmt>(Terminator)->getCond();
1595 break;
1596
1597 case Stmt::WhileStmtClass:
1598 E = cast<WhileStmt>(Terminator)->getCond();
1599 break;
1600
1601 case Stmt::DoStmtClass:
1602 E = cast<DoStmt>(Terminator)->getCond();
1603 break;
1604
1605 case Stmt::IfStmtClass:
1606 E = cast<IfStmt>(Terminator)->getCond();
1607 break;
1608
1609 case Stmt::ChooseExprClass:
1610 E = cast<ChooseExpr>(Terminator)->getCond();
1611 break;
1612
1613 case Stmt::IndirectGotoStmtClass:
1614 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1615 break;
1616
1617 case Stmt::SwitchStmtClass:
1618 E = cast<SwitchStmt>(Terminator)->getCond();
1619 break;
1620
1621 case Stmt::ConditionalOperatorClass:
1622 E = cast<ConditionalOperator>(Terminator)->getCond();
1623 break;
1624
1625 case Stmt::BinaryOperatorClass: // '&&' and '||'
1626 E = cast<BinaryOperator>(Terminator)->getLHS();
1627 break;
1628 }
1629
1630 return E ? E->IgnoreParens() : NULL;
1631}
1632
Ted Kremenekbdbd1b52008-05-16 16:06:00 +00001633bool CFGBlock::hasBinaryBranchTerminator() const {
1634
1635 if (!Terminator)
1636 return false;
1637
1638 Expr* E = NULL;
1639
1640 switch (Terminator->getStmtClass()) {
1641 default:
1642 return false;
1643
1644 case Stmt::ForStmtClass:
1645 case Stmt::WhileStmtClass:
1646 case Stmt::DoStmtClass:
1647 case Stmt::IfStmtClass:
1648 case Stmt::ChooseExprClass:
1649 case Stmt::ConditionalOperatorClass:
1650 case Stmt::BinaryOperatorClass:
1651 return true;
1652 }
1653
1654 return E ? E->IgnoreParens() : NULL;
1655}
1656
Ted Kremenek1eaa6712008-01-30 23:02:42 +00001657
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001658//===----------------------------------------------------------------------===//
1659// CFG Graphviz Visualization
1660//===----------------------------------------------------------------------===//
1661
Ted Kremenek08176a52007-08-31 21:30:12 +00001662
1663#ifndef NDEBUG
Chris Lattner26002172007-09-17 06:16:32 +00001664static StmtPrinterHelper* GraphHelper;
Ted Kremenek08176a52007-08-31 21:30:12 +00001665#endif
1666
1667void CFG::viewCFG() const {
1668#ifndef NDEBUG
1669 StmtPrinterHelper H(this);
1670 GraphHelper = &H;
1671 llvm::ViewGraph(this,"CFG");
1672 GraphHelper = NULL;
Ted Kremenek08176a52007-08-31 21:30:12 +00001673#endif
1674}
1675
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001676namespace llvm {
1677template<>
1678struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1679 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1680
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001681#ifndef NDEBUG
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001682 std::ostringstream Out;
Ted Kremenek08176a52007-08-31 21:30:12 +00001683 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001684 std::string OutStr = Out.str();
1685
1686 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1687
1688 // Process string output to make it nicer...
1689 for (unsigned i = 0; i != OutStr.length(); ++i)
1690 if (OutStr[i] == '\n') { // Left justify
1691 OutStr[i] = '\\';
1692 OutStr.insert(OutStr.begin()+i+1, 'l');
1693 }
1694
1695 return OutStr;
Hartmut Kaiser752a0052007-09-16 00:28:28 +00001696#else
1697 return "";
1698#endif
Ted Kremenekb3bb91b2007-08-29 21:56:09 +00001699 }
1700};
1701} // end namespace llvm