blob: 2a79355a6363ddbc71390a6e2be831a26a4805a3 [file] [log] [blame]
Ted Kremenekfddd5182007-08-21 21:42:03 +00001//===--- CFG.cpp - Classes for representing and building CFGs----*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Ted Kremenekfddd5182007-08-21 21:42:03 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the CFG and CFGBuilder classes for representing and
11// building Control-Flow Graphs (CFGs) from ASTs.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/AST/CFG.h"
Ted Kremenekc310e932007-08-21 22:06:14 +000016#include "clang/AST/StmtVisitor.h"
Ted Kremenek42a509f2007-08-31 21:30:12 +000017#include "clang/AST/PrettyPrinter.h"
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000018#include "llvm/ADT/DenseMap.h"
Ted Kremenek19bb3562007-08-28 19:26:49 +000019#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek7dba8602007-08-29 21:56:09 +000020#include "llvm/Support/GraphWriter.h"
Ted Kremenek7e3a89d2007-12-17 19:35:20 +000021#include "llvm/Support/Streams.h"
Ted Kremenek6fa9b882008-01-08 18:15:10 +000022#include "llvm/Support/Compiler.h"
Ted Kremenek274f4332008-04-28 18:00:46 +000023#include <llvm/Support/Allocator.h>
Ted Kremeneka95d3752008-09-13 05:16:45 +000024#include <llvm/Support/Format.h>
Ted Kremenekfddd5182007-08-21 21:42:03 +000025#include <iomanip>
26#include <algorithm>
Ted Kremenek7dba8602007-08-29 21:56:09 +000027#include <sstream>
Ted Kremenek83c01da2008-01-11 00:40:29 +000028
Ted Kremenekfddd5182007-08-21 21:42:03 +000029using namespace clang;
30
31namespace {
32
Ted Kremenekbefef2f2007-08-23 21:26:19 +000033// SaveAndRestore - A utility class that uses RIIA to save and restore
34// the value of a variable.
35template<typename T>
Ted Kremenek6fa9b882008-01-08 18:15:10 +000036struct VISIBILITY_HIDDEN SaveAndRestore {
Ted Kremenekbefef2f2007-08-23 21:26:19 +000037 SaveAndRestore(T& x) : X(x), old_value(x) {}
38 ~SaveAndRestore() { X = old_value; }
Ted Kremenekb6f7b722007-08-30 18:13:31 +000039 T get() { return old_value; }
40
Ted Kremenekbefef2f2007-08-23 21:26:19 +000041 T& X;
42 T old_value;
43};
Ted Kremenekfddd5182007-08-21 21:42:03 +000044
Ted Kremenekc7eb9032008-08-06 23:20:50 +000045static SourceLocation GetEndLoc(ScopedDecl* D) {
46 if (VarDecl* VD = dyn_cast<VarDecl>(D))
47 if (Expr* Ex = VD->getInit())
48 return Ex->getSourceRange().getEnd();
49
50 return D->getLocation();
51}
52
Ted Kremeneka34ea072008-08-04 22:51:42 +000053/// CFGBuilder - This class implements CFG construction from an AST.
Ted Kremenekfddd5182007-08-21 21:42:03 +000054/// The builder is stateful: an instance of the builder should be used to only
55/// construct a single CFG.
56///
57/// Example usage:
58///
59/// CFGBuilder builder;
60/// CFG* cfg = builder.BuildAST(stmt1);
61///
Ted Kremenekc310e932007-08-21 22:06:14 +000062/// CFG construction is done via a recursive walk of an AST.
63/// We actually parse the AST in reverse order so that the successor
64/// of a basic block is constructed prior to its predecessor. This
65/// allows us to nicely capture implicit fall-throughs without extra
66/// basic blocks.
67///
Ted Kremenek6fa9b882008-01-08 18:15:10 +000068class VISIBILITY_HIDDEN CFGBuilder : public StmtVisitor<CFGBuilder,CFGBlock*> {
Ted Kremenekfddd5182007-08-21 21:42:03 +000069 CFG* cfg;
70 CFGBlock* Block;
Ted Kremenekfddd5182007-08-21 21:42:03 +000071 CFGBlock* Succ;
Ted Kremenekbf15b272007-08-22 21:36:54 +000072 CFGBlock* ContinueTargetBlock;
Ted Kremenek8a294712007-08-22 21:51:58 +000073 CFGBlock* BreakTargetBlock;
Ted Kremenekb5c13b02007-08-23 18:43:24 +000074 CFGBlock* SwitchTerminatedBlock;
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000075 CFGBlock* DefaultCaseBlock;
Ted Kremenekfddd5182007-08-21 21:42:03 +000076
Ted Kremenek19bb3562007-08-28 19:26:49 +000077 // LabelMap records the mapping from Label expressions to their blocks.
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000078 typedef llvm::DenseMap<LabelStmt*,CFGBlock*> LabelMapTy;
79 LabelMapTy LabelMap;
80
Ted Kremenek19bb3562007-08-28 19:26:49 +000081 // A list of blocks that end with a "goto" that must be backpatched to
82 // their resolved targets upon completion of CFG construction.
Ted Kremenek4a2b8a12007-08-22 15:40:58 +000083 typedef std::vector<CFGBlock*> BackpatchBlocksTy;
Ted Kremenek0cebe3e2007-08-21 23:26:17 +000084 BackpatchBlocksTy BackpatchBlocks;
85
Ted Kremenek19bb3562007-08-28 19:26:49 +000086 // A list of labels whose address has been taken (for indirect gotos).
87 typedef llvm::SmallPtrSet<LabelStmt*,5> LabelSetTy;
88 LabelSetTy AddressTakenLabels;
89
Ted Kremenekfddd5182007-08-21 21:42:03 +000090public:
Ted Kremenek026473c2007-08-23 16:51:22 +000091 explicit CFGBuilder() : cfg(NULL), Block(NULL), Succ(NULL),
Ted Kremenek8a294712007-08-22 21:51:58 +000092 ContinueTargetBlock(NULL), BreakTargetBlock(NULL),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +000093 SwitchTerminatedBlock(NULL), DefaultCaseBlock(NULL) {
Ted Kremenekfddd5182007-08-21 21:42:03 +000094 // Create an empty CFG.
95 cfg = new CFG();
96 }
97
98 ~CFGBuilder() { delete cfg; }
Ted Kremenekfddd5182007-08-21 21:42:03 +000099
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000100 // buildCFG - Used by external clients to construct the CFG.
101 CFG* buildCFG(Stmt* Statement);
Ted Kremenekc310e932007-08-21 22:06:14 +0000102
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000103 // Visitors to walk an AST and construct the CFG. Called by
104 // buildCFG. Do not call directly!
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000105
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000106 CFGBlock* VisitStmt(Stmt* Statement);
107 CFGBlock* VisitNullStmt(NullStmt* Statement);
108 CFGBlock* VisitCompoundStmt(CompoundStmt* C);
109 CFGBlock* VisitIfStmt(IfStmt* I);
110 CFGBlock* VisitReturnStmt(ReturnStmt* R);
111 CFGBlock* VisitLabelStmt(LabelStmt* L);
112 CFGBlock* VisitGotoStmt(GotoStmt* G);
113 CFGBlock* VisitForStmt(ForStmt* F);
114 CFGBlock* VisitWhileStmt(WhileStmt* W);
115 CFGBlock* VisitDoStmt(DoStmt* D);
116 CFGBlock* VisitContinueStmt(ContinueStmt* C);
117 CFGBlock* VisitBreakStmt(BreakStmt* B);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000118 CFGBlock* VisitSwitchStmt(SwitchStmt* Terminator);
119 CFGBlock* VisitCaseStmt(CaseStmt* Terminator);
Ted Kremenek295222c2008-02-13 21:46:34 +0000120 CFGBlock* VisitDefaultStmt(DefaultStmt* D);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000121 CFGBlock* VisitIndirectGotoStmt(IndirectGotoStmt* I);
Ted Kremenekfddd5182007-08-21 21:42:03 +0000122
Ted Kremenek4102af92008-03-13 03:04:22 +0000123 // FIXME: Add support for ObjC-specific control-flow structures.
124
Ted Kremenek274f4332008-04-28 18:00:46 +0000125 // NYS == Not Yet Supported
126 CFGBlock* NYS() {
Ted Kremenek4102af92008-03-13 03:04:22 +0000127 badCFG = true;
128 return Block;
129 }
130
Ted Kremenek274f4332008-04-28 18:00:46 +0000131 CFGBlock* VisitObjCForCollectionStmt(ObjCForCollectionStmt* S){ return NYS();}
132 CFGBlock* VisitObjCAtTryStmt(ObjCAtTryStmt* S) { return NYS(); }
133 CFGBlock* VisitObjCAtCatchStmt(ObjCAtCatchStmt* S) { return NYS(); }
134 CFGBlock* VisitObjCAtFinallyStmt(ObjCAtFinallyStmt* S) { return NYS(); }
135 CFGBlock* VisitObjCAtThrowStmt(ObjCAtThrowStmt* S) { return NYS(); }
136
137 CFGBlock* VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt* S){
138 return NYS();
Ted Kremenek4102af92008-03-13 03:04:22 +0000139 }
140
Ted Kremenek00c0a302008-09-26 18:17:07 +0000141 // Blocks.
142 CFGBlock* VisitBlockExpr(BlockExpr* E) { return NYS(); }
143 CFGBlock* VisitBlockDeclRefExpr(BlockDeclRefExpr* E) { return NYS(); }
144
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000145private:
146 CFGBlock* createBlock(bool add_successor = true);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000147 CFGBlock* addStmt(Stmt* Terminator);
148 CFGBlock* WalkAST(Stmt* Terminator, bool AlwaysAddStmt);
149 CFGBlock* WalkAST_VisitChildren(Stmt* Terminator);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000150 CFGBlock* WalkAST_VisitDeclSubExpr(ScopedDecl* D);
Ted Kremenek411cdee2008-04-16 21:10:48 +0000151 CFGBlock* WalkAST_VisitStmtExpr(StmtExpr* Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000152 void FinishBlock(CFGBlock* B);
Ted Kremeneke8ee26b2007-08-22 18:22:34 +0000153
Ted Kremenek4102af92008-03-13 03:04:22 +0000154 bool badCFG;
Ted Kremenekfddd5182007-08-21 21:42:03 +0000155};
Ted Kremenek610a09e2008-09-26 22:58:57 +0000156
157static VariableArrayType* FindVA(Type* t) {
158 while (ArrayType* vt = dyn_cast<ArrayType>(t)) {
159 if (VariableArrayType* vat = dyn_cast<VariableArrayType>(vt))
160 if (vat->getSizeExpr())
161 return vat;
162
163 t = vt->getElementType().getTypePtr();
164 }
165
166 return 0;
167}
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000168
169/// BuildCFG - Constructs a CFG from an AST (a Stmt*). The AST can
170/// represent an arbitrary statement. Examples include a single expression
171/// or a function body (compound statement). The ownership of the returned
172/// CFG is transferred to the caller. If CFG construction fails, this method
173/// returns NULL.
174CFG* CFGBuilder::buildCFG(Stmt* Statement) {
Ted Kremenek19bb3562007-08-28 19:26:49 +0000175 assert (cfg);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000176 if (!Statement) return NULL;
177
Ted Kremenek4102af92008-03-13 03:04:22 +0000178 badCFG = false;
179
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000180 // Create an empty block that will serve as the exit block for the CFG.
181 // Since this is the first block added to the CFG, it will be implicitly
182 // registered as the exit block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000183 Succ = createBlock();
184 assert (Succ == &cfg->getExit());
185 Block = NULL; // the EXIT block is empty. Create all other blocks lazily.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000186
187 // Visit the statements and create the CFG.
Ted Kremenek0d99ecf2008-02-27 17:33:02 +0000188 CFGBlock* B = Visit(Statement);
189 if (!B) B = Succ;
190
191 if (B) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000192 // Finalize the last constructed block. This usually involves
193 // reversing the order of the statements in the block.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000194 if (Block) FinishBlock(B);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000195
196 // Backpatch the gotos whose label -> block mappings we didn't know
197 // when we encountered them.
198 for (BackpatchBlocksTy::iterator I = BackpatchBlocks.begin(),
199 E = BackpatchBlocks.end(); I != E; ++I ) {
200
201 CFGBlock* B = *I;
202 GotoStmt* G = cast<GotoStmt>(B->getTerminator());
203 LabelMapTy::iterator LI = LabelMap.find(G->getLabel());
204
205 // If there is no target for the goto, then we are looking at an
206 // incomplete AST. Handle this by not registering a successor.
207 if (LI == LabelMap.end()) continue;
208
209 B->addSuccessor(LI->second);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000210 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000211
Ted Kremenek19bb3562007-08-28 19:26:49 +0000212 // Add successors to the Indirect Goto Dispatch block (if we have one).
213 if (CFGBlock* B = cfg->getIndirectGotoBlock())
214 for (LabelSetTy::iterator I = AddressTakenLabels.begin(),
215 E = AddressTakenLabels.end(); I != E; ++I ) {
216
217 // Lookup the target block.
218 LabelMapTy::iterator LI = LabelMap.find(*I);
219
220 // If there is no target block that contains label, then we are looking
221 // at an incomplete AST. Handle this by not registering a successor.
222 if (LI == LabelMap.end()) continue;
223
224 B->addSuccessor(LI->second);
225 }
Ted Kremenek322f58d2007-09-26 21:23:31 +0000226
Ted Kremenek94b33162007-09-17 16:18:02 +0000227 Succ = B;
Ted Kremenek322f58d2007-09-26 21:23:31 +0000228 }
229
230 // Create an empty entry block that has no predecessors.
231 cfg->setEntry(createBlock());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000232
Ted Kremenek4102af92008-03-13 03:04:22 +0000233 if (badCFG) {
234 delete cfg;
235 cfg = NULL;
236 return NULL;
237 }
238
Ted Kremenek322f58d2007-09-26 21:23:31 +0000239 // NULL out cfg so that repeated calls to the builder will fail and that
240 // the ownership of the constructed CFG is passed to the caller.
241 CFG* t = cfg;
242 cfg = NULL;
243 return t;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000244}
245
246/// createBlock - Used to lazily create blocks that are connected
247/// to the current (global) succcessor.
248CFGBlock* CFGBuilder::createBlock(bool add_successor) {
Ted Kremenek94382522007-09-05 20:02:05 +0000249 CFGBlock* B = cfg->createBlock();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000250 if (add_successor && Succ) B->addSuccessor(Succ);
251 return B;
252}
253
254/// FinishBlock - When the last statement has been added to the block,
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000255/// we must reverse the statements because they have been inserted
256/// in reverse order.
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000257void CFGBuilder::FinishBlock(CFGBlock* B) {
258 assert (B);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000259 B->reverseStmts();
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000260}
261
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000262/// addStmt - Used to add statements/expressions to the current CFGBlock
263/// "Block". This method calls WalkAST on the passed statement to see if it
264/// contains any short-circuit expressions. If so, it recursively creates
265/// the necessary blocks for such expressions. It returns the "topmost" block
266/// of the created blocks, or the original value of "Block" when this method
267/// was called if no additional blocks are created.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000268CFGBlock* CFGBuilder::addStmt(Stmt* Terminator) {
Ted Kremenekaf603f72007-08-30 18:39:40 +0000269 if (!Block) Block = createBlock();
Ted Kremenek411cdee2008-04-16 21:10:48 +0000270 return WalkAST(Terminator,true);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000271}
272
273/// WalkAST - Used by addStmt to walk the subtree of a statement and
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000274/// add extra blocks for ternary operators, &&, and ||. We also
275/// process "," and DeclStmts (which may contain nested control-flow).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000276CFGBlock* CFGBuilder::WalkAST(Stmt* Terminator, bool AlwaysAddStmt = false) {
277 switch (Terminator->getStmtClass()) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000278 case Stmt::ConditionalOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000279 ConditionalOperator* C = cast<ConditionalOperator>(Terminator);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000280
281 // Create the confluence block that will "merge" the results
282 // of the ternary expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000283 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
284 ConfluenceBlock->appendStmt(C);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000285 FinishBlock(ConfluenceBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000286
287 // Create a block for the LHS expression if there is an LHS expression.
288 // A GCC extension allows LHS to be NULL, causing the condition to
289 // be the value that is returned instead.
290 // e.g: x ?: y is shorthand for: x ? x : y;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000291 Succ = ConfluenceBlock;
292 Block = NULL;
Ted Kremenekecc04c92007-11-26 18:20:26 +0000293 CFGBlock* LHSBlock = NULL;
294 if (C->getLHS()) {
295 LHSBlock = Visit(C->getLHS());
296 FinishBlock(LHSBlock);
297 Block = NULL;
298 }
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000299
Ted Kremenekecc04c92007-11-26 18:20:26 +0000300 // Create the block for the RHS expression.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000301 Succ = ConfluenceBlock;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000302 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000303 FinishBlock(RHSBlock);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000304
Ted Kremenekecc04c92007-11-26 18:20:26 +0000305 // Create the block that will contain the condition.
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000306 Block = createBlock(false);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000307
308 if (LHSBlock)
309 Block->addSuccessor(LHSBlock);
310 else {
311 // If we have no LHS expression, add the ConfluenceBlock as a direct
312 // successor for the block containing the condition. Moreover,
313 // we need to reverse the order of the predecessors in the
314 // ConfluenceBlock because the RHSBlock will have been added to
315 // the succcessors already, and we want the first predecessor to the
316 // the block containing the expression for the case when the ternary
317 // expression evaluates to true.
318 Block->addSuccessor(ConfluenceBlock);
319 assert (ConfluenceBlock->pred_size() == 2);
320 std::reverse(ConfluenceBlock->pred_begin(),
321 ConfluenceBlock->pred_end());
322 }
323
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000324 Block->addSuccessor(RHSBlock);
Ted Kremenekecc04c92007-11-26 18:20:26 +0000325
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000326 Block->setTerminator(C);
327 return addStmt(C->getCond());
328 }
Ted Kremenek49a436d2007-08-31 17:03:41 +0000329
330 case Stmt::ChooseExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000331 ChooseExpr* C = cast<ChooseExpr>(Terminator);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000332
333 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
334 ConfluenceBlock->appendStmt(C);
335 FinishBlock(ConfluenceBlock);
336
337 Succ = ConfluenceBlock;
338 Block = NULL;
339 CFGBlock* LHSBlock = Visit(C->getLHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000340 FinishBlock(LHSBlock);
341
Ted Kremenek49a436d2007-08-31 17:03:41 +0000342 Succ = ConfluenceBlock;
343 Block = NULL;
344 CFGBlock* RHSBlock = Visit(C->getRHS());
Ted Kremenekf50ec102007-09-11 21:29:43 +0000345 FinishBlock(RHSBlock);
Ted Kremenek49a436d2007-08-31 17:03:41 +0000346
347 Block = createBlock(false);
348 Block->addSuccessor(LHSBlock);
349 Block->addSuccessor(RHSBlock);
350 Block->setTerminator(C);
351 return addStmt(C->getCond());
352 }
Ted Kremenek7926f7c2007-08-28 16:18:58 +0000353
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000354 case Stmt::DeclStmtClass: {
Ted Kremenek53061c82008-10-06 20:56:19 +0000355 DeclStmt *DS = cast<DeclStmt>(Terminator);
356 if (DS->hasSolitaryDecl()) {
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000357 Block->appendStmt(Terminator);
Ted Kremenek53061c82008-10-06 20:56:19 +0000358 return WalkAST_VisitDeclSubExpr(DS->getSolitaryDecl());
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000359 }
360 else {
361 typedef llvm::SmallVector<ScopedDecl*,10> BufTy;
362 BufTy Buf;
363 CFGBlock* B = 0;
Ted Kremenek53061c82008-10-06 20:56:19 +0000364
365 // FIXME: Add a reverse iterator for DeclStmt to avoid this
366 // extra copy.
367 for (DeclStmt::decl_iterator DI=DS->decl_begin(), DE=DS->decl_end();
368 DI != DE; ++DI)
369 Buf.push_back(*DI);
370
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000371 for (BufTy::reverse_iterator I=Buf.rbegin(), E=Buf.rend(); I!=E; ++I) {
Ted Kremenek8ffb1592008-10-07 23:09:49 +0000372 // Get the alignment of the new DeclStmt, padding out to >=8 bytes.
373 unsigned A = llvm::AlignOf<DeclStmt>::Alignment < 8
374 ? 8 : llvm::AlignOf<DeclStmt>::Alignment;
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000375
Ted Kremenek8ffb1592008-10-07 23:09:49 +0000376 // Allocate the DeclStmt using the BumpPtrAllocator. It will
377 // get automatically freed with the CFG. Note that even though
378 // we are using a DeclGroupOwningRef that wraps a singe Decl*,
379 // that Decl* will not get deallocated because the destroy method
380 // of DG is never called.
381 DeclGroupOwningRef DG(*I);
382 ScopedDecl* D = *I;
383 void* Mem = cfg->getAllocator().Allocate(sizeof(DeclStmt), A);
384
385 DeclStmt* DS = new (Mem) DeclStmt(DG, D->getLocation(),
386 GetEndLoc(D));
387
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000388 // Append the fake DeclStmt to block.
Ted Kremenek8ffb1592008-10-07 23:09:49 +0000389 Block->appendStmt(DS);
390 B = WalkAST_VisitDeclSubExpr(D);
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000391 }
392 return B;
393 }
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000394 }
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000395
Ted Kremenek19bb3562007-08-28 19:26:49 +0000396 case Stmt::AddrLabelExprClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000397 AddrLabelExpr* A = cast<AddrLabelExpr>(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000398 AddressTakenLabels.insert(A->getLabel());
399
Ted Kremenek411cdee2008-04-16 21:10:48 +0000400 if (AlwaysAddStmt) Block->appendStmt(Terminator);
Ted Kremenek19bb3562007-08-28 19:26:49 +0000401 return Block;
402 }
Ted Kremenekf50ec102007-09-11 21:29:43 +0000403
Ted Kremenek15c27a82007-08-28 18:30:10 +0000404 case Stmt::StmtExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000405 return WalkAST_VisitStmtExpr(cast<StmtExpr>(Terminator));
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000406
Ted Kremenek610a09e2008-09-26 22:58:57 +0000407 case Stmt::SizeOfAlignOfTypeExprClass: {
408 SizeOfAlignOfTypeExpr* E = cast<SizeOfAlignOfTypeExpr>(Terminator);
409
410 // VLA types have expressions that must be evaluated.
411 for (VariableArrayType* VA = FindVA(E->getArgumentType().getTypePtr());
412 VA != 0; VA = FindVA(VA->getElementType().getTypePtr()))
413 addStmt(VA->getSizeExpr());
414
415 return Block;
416 }
417
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000418 case Stmt::UnaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000419 UnaryOperator* U = cast<UnaryOperator>(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000420
421 // sizeof(expressions). For such expressions,
422 // the subexpression is not really evaluated, so
423 // we don't care about control-flow within the sizeof.
424 if (U->getOpcode() == UnaryOperator::SizeOf) {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000425 Block->appendStmt(Terminator);
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000426 return Block;
427 }
428
429 break;
430 }
431
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000432 case Stmt::BinaryOperatorClass: {
Ted Kremenek411cdee2008-04-16 21:10:48 +0000433 BinaryOperator* B = cast<BinaryOperator>(Terminator);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000434
435 if (B->isLogicalOp()) { // && or ||
436 CFGBlock* ConfluenceBlock = (Block) ? Block : createBlock();
437 ConfluenceBlock->appendStmt(B);
438 FinishBlock(ConfluenceBlock);
439
440 // create the block evaluating the LHS
441 CFGBlock* LHSBlock = createBlock(false);
Ted Kremenekafe54332007-12-21 19:49:00 +0000442 LHSBlock->setTerminator(B);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000443
444 // create the block evaluating the RHS
445 Succ = ConfluenceBlock;
446 Block = NULL;
447 CFGBlock* RHSBlock = Visit(B->getRHS());
Zhongxing Xu924d9a82008-10-04 05:48:38 +0000448 FinishBlock(RHSBlock);
Ted Kremenekafe54332007-12-21 19:49:00 +0000449
450 // Now link the LHSBlock with RHSBlock.
451 if (B->getOpcode() == BinaryOperator::LOr) {
452 LHSBlock->addSuccessor(ConfluenceBlock);
453 LHSBlock->addSuccessor(RHSBlock);
454 }
455 else {
456 assert (B->getOpcode() == BinaryOperator::LAnd);
457 LHSBlock->addSuccessor(RHSBlock);
458 LHSBlock->addSuccessor(ConfluenceBlock);
459 }
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000460
461 // Generate the blocks for evaluating the LHS.
462 Block = LHSBlock;
463 return addStmt(B->getLHS());
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000464 }
465 else if (B->getOpcode() == BinaryOperator::Comma) { // ,
466 Block->appendStmt(B);
467 addStmt(B->getRHS());
468 return addStmt(B->getLHS());
Ted Kremenek63f58872007-10-01 19:33:33 +0000469 }
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000470
471 break;
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000472 }
Ted Kremenek00c0a302008-09-26 18:17:07 +0000473
474 // Blocks: No support for blocks ... yet
475 case Stmt::BlockExprClass:
476 case Stmt::BlockDeclRefExprClass:
477 return NYS();
Ted Kremenekf4e15fc2008-02-26 02:37:08 +0000478
479 case Stmt::ParenExprClass:
Ted Kremenek411cdee2008-04-16 21:10:48 +0000480 return WalkAST(cast<ParenExpr>(Terminator)->getSubExpr(), AlwaysAddStmt);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +0000481
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000482 default:
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000483 break;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000484 };
Ted Kremeneka651e0e2007-12-13 22:44:18 +0000485
Ted Kremenek411cdee2008-04-16 21:10:48 +0000486 if (AlwaysAddStmt) Block->appendStmt(Terminator);
487 return WalkAST_VisitChildren(Terminator);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000488}
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000489
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000490/// WalkAST_VisitDeclSubExpr - Utility method to add block-level expressions
491/// for initializers in Decls.
492CFGBlock* CFGBuilder::WalkAST_VisitDeclSubExpr(ScopedDecl* D) {
493 VarDecl* VD = dyn_cast<VarDecl>(D);
494
495 if (!VD)
Ted Kremenekd6603222007-11-18 20:06:01 +0000496 return Block;
497
Ted Kremenekc7eb9032008-08-06 23:20:50 +0000498 Expr* Init = VD->getInit();
Ted Kremenek8f54c1f2007-10-30 21:48:34 +0000499
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000500 if (Init) {
501 // Optimization: Don't create separate block-level statements for literals.
502 switch (Init->getStmtClass()) {
503 case Stmt::IntegerLiteralClass:
504 case Stmt::CharacterLiteralClass:
505 case Stmt::StringLiteralClass:
506 break;
507 default:
508 Block = addStmt(Init);
509 }
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000510 }
Ted Kremenekfcd06f72008-09-26 16:26:36 +0000511
512 // If the type of VD is a VLA, then we must process its size expressions.
513 for (VariableArrayType* VA = FindVA(VD->getType().getTypePtr()); VA != 0;
514 VA = FindVA(VA->getElementType().getTypePtr()))
515 Block = addStmt(VA->getSizeExpr());
Ted Kremenekae2a98c2008-02-29 22:32:24 +0000516
Ted Kremenekb49e1aa2007-08-28 18:14:37 +0000517 return Block;
518}
519
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000520/// WalkAST_VisitChildren - Utility method to call WalkAST on the
521/// children of a Stmt.
Ted Kremenek411cdee2008-04-16 21:10:48 +0000522CFGBlock* CFGBuilder::WalkAST_VisitChildren(Stmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000523 CFGBlock* B = Block;
Ted Kremenek411cdee2008-04-16 21:10:48 +0000524 for (Stmt::child_iterator I = Terminator->child_begin(), E = Terminator->child_end() ;
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000525 I != E; ++I)
Ted Kremenek322f58d2007-09-26 21:23:31 +0000526 if (*I) B = WalkAST(*I);
Ted Kremenek9da2fb72007-08-27 21:27:44 +0000527
528 return B;
529}
530
Ted Kremenek15c27a82007-08-28 18:30:10 +0000531/// WalkAST_VisitStmtExpr - Utility method to handle (nested) statement
532/// expressions (a GCC extension).
Ted Kremenek411cdee2008-04-16 21:10:48 +0000533CFGBlock* CFGBuilder::WalkAST_VisitStmtExpr(StmtExpr* Terminator) {
534 Block->appendStmt(Terminator);
535 return VisitCompoundStmt(Terminator->getSubStmt());
Ted Kremenek15c27a82007-08-28 18:30:10 +0000536}
537
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000538/// VisitStmt - Handle statements with no branching control flow.
539CFGBlock* CFGBuilder::VisitStmt(Stmt* Statement) {
540 // We cannot assume that we are in the middle of a basic block, since
541 // the CFG might only be constructed for this single statement. If
542 // we have no current basic block, just create one lazily.
543 if (!Block) Block = createBlock();
544
545 // Simply add the statement to the current block. We actually
546 // insert statements in reverse order; this order is reversed later
547 // when processing the containing element in the AST.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000548 addStmt(Statement);
549
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000550 return Block;
551}
552
553CFGBlock* CFGBuilder::VisitNullStmt(NullStmt* Statement) {
554 return Block;
555}
556
557CFGBlock* CFGBuilder::VisitCompoundStmt(CompoundStmt* C) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000558
559 CFGBlock* LastBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000560
Ted Kremenekd34066c2008-02-26 00:22:58 +0000561 for (CompoundStmt::reverse_body_iterator I=C->body_rbegin(), E=C->body_rend();
562 I != E; ++I ) {
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000563 LastBlock = Visit(*I);
Ted Kremenekd34066c2008-02-26 00:22:58 +0000564 }
565
Ted Kremeneka716d7a2008-03-17 17:19:44 +0000566 return LastBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000567}
568
569CFGBlock* CFGBuilder::VisitIfStmt(IfStmt* I) {
570 // We may see an if statement in the middle of a basic block, or
571 // it may be the first statement we are processing. In either case,
572 // we create a new basic block. First, we create the blocks for
573 // the then...else statements, and then we create the block containing
574 // the if statement. If we were in the middle of a block, we
575 // stop processing that block and reverse its statements. That block
576 // is then the implicit successor for the "then" and "else" clauses.
577
578 // The block we were proccessing is now finished. Make it the
579 // successor block.
580 if (Block) {
581 Succ = Block;
582 FinishBlock(Block);
583 }
584
585 // Process the false branch. NULL out Block so that the recursive
586 // call to Visit will create a new basic block.
587 // Null out Block so that all successor
588 CFGBlock* ElseBlock = Succ;
589
590 if (Stmt* Else = I->getElse()) {
591 SaveAndRestore<CFGBlock*> sv(Succ);
592
593 // NULL out Block so that the recursive call to Visit will
594 // create a new basic block.
595 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000596 ElseBlock = Visit(Else);
597
598 if (!ElseBlock) // Can occur when the Else body has all NullStmts.
599 ElseBlock = sv.get();
600 else if (Block)
601 FinishBlock(ElseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000602 }
603
604 // Process the true branch. NULL out Block so that the recursive
605 // call to Visit will create a new basic block.
606 // Null out Block so that all successor
607 CFGBlock* ThenBlock;
608 {
609 Stmt* Then = I->getThen();
610 assert (Then);
611 SaveAndRestore<CFGBlock*> sv(Succ);
612 Block = NULL;
Ted Kremenekb6f7b722007-08-30 18:13:31 +0000613 ThenBlock = Visit(Then);
614
615 if (!ThenBlock) // Can occur when the Then body has all NullStmts.
616 ThenBlock = sv.get();
617 else if (Block)
618 FinishBlock(ThenBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000619 }
620
621 // Now create a new block containing the if statement.
622 Block = createBlock(false);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000623
624 // Set the terminator of the new block to the If statement.
625 Block->setTerminator(I);
626
627 // Now add the successors.
628 Block->addSuccessor(ThenBlock);
629 Block->addSuccessor(ElseBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000630
631 // Add the condition as the last statement in the new block. This
632 // may create new blocks as the condition may contain control-flow. Any
633 // newly created blocks will be pointed to be "Block".
Ted Kremeneka2925852008-01-30 23:02:42 +0000634 return addStmt(I->getCond()->IgnoreParens());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000635}
Ted Kremenekf50ec102007-09-11 21:29:43 +0000636
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000637
638CFGBlock* CFGBuilder::VisitReturnStmt(ReturnStmt* R) {
639 // If we were in the middle of a block we stop processing that block
640 // and reverse its statements.
641 //
642 // NOTE: If a "return" appears in the middle of a block, this means
643 // that the code afterwards is DEAD (unreachable). We still
644 // keep a basic block for that code; a simple "mark-and-sweep"
645 // from the entry block will be able to report such dead
646 // blocks.
647 if (Block) FinishBlock(Block);
648
649 // Create the new block.
650 Block = createBlock(false);
651
652 // The Exit block is the only successor.
653 Block->addSuccessor(&cfg->getExit());
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000654
655 // Add the return statement to the block. This may create new blocks
656 // if R contains control-flow (short-circuit operations).
657 return addStmt(R);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000658}
659
660CFGBlock* CFGBuilder::VisitLabelStmt(LabelStmt* L) {
661 // Get the block of the labeled statement. Add it to our map.
Ted Kremenek2677ea82008-03-15 07:45:02 +0000662 Visit(L->getSubStmt());
663 CFGBlock* LabelBlock = Block;
Ted Kremenek16e4dc82007-08-30 18:20:57 +0000664
665 if (!LabelBlock) // This can happen when the body is empty, i.e.
666 LabelBlock=createBlock(); // scopes that only contains NullStmts.
667
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000668 assert (LabelMap.find(L) == LabelMap.end() && "label already in map");
669 LabelMap[ L ] = LabelBlock;
670
671 // Labels partition blocks, so this is the end of the basic block
Ted Kremenek9cffe732007-08-29 23:20:49 +0000672 // we were processing (L is the block's label). Because this is
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000673 // label (and we have already processed the substatement) there is no
674 // extra control-flow to worry about.
Ted Kremenek9cffe732007-08-29 23:20:49 +0000675 LabelBlock->setLabel(L);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000676 FinishBlock(LabelBlock);
677
678 // We set Block to NULL to allow lazy creation of a new block
679 // (if necessary);
680 Block = NULL;
681
682 // This block is now the implicit successor of other blocks.
683 Succ = LabelBlock;
684
685 return LabelBlock;
686}
687
688CFGBlock* CFGBuilder::VisitGotoStmt(GotoStmt* G) {
689 // Goto is a control-flow statement. Thus we stop processing the
690 // current block and create a new one.
691 if (Block) FinishBlock(Block);
692 Block = createBlock(false);
693 Block->setTerminator(G);
694
695 // If we already know the mapping to the label block add the
696 // successor now.
697 LabelMapTy::iterator I = LabelMap.find(G->getLabel());
698
699 if (I == LabelMap.end())
700 // We will need to backpatch this block later.
701 BackpatchBlocks.push_back(Block);
702 else
703 Block->addSuccessor(I->second);
704
705 return Block;
706}
707
708CFGBlock* CFGBuilder::VisitForStmt(ForStmt* F) {
709 // "for" is a control-flow statement. Thus we stop processing the
710 // current block.
711
712 CFGBlock* LoopSuccessor = NULL;
713
714 if (Block) {
715 FinishBlock(Block);
716 LoopSuccessor = Block;
717 }
718 else LoopSuccessor = Succ;
719
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000720 // Because of short-circuit evaluation, the condition of the loop
721 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
722 // blocks that evaluate the condition.
723 CFGBlock* ExitConditionBlock = createBlock(false);
724 CFGBlock* EntryConditionBlock = ExitConditionBlock;
725
726 // Set the terminator for the "exit" condition block.
727 ExitConditionBlock->setTerminator(F);
728
729 // Now add the actual condition to the condition block. Because the
730 // condition itself may contain control-flow, new blocks may be created.
731 if (Stmt* C = F->getCond()) {
732 Block = ExitConditionBlock;
733 EntryConditionBlock = addStmt(C);
734 if (Block) FinishBlock(EntryConditionBlock);
735 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000736
737 // The condition block is the implicit successor for the loop body as
738 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000739 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000740
741 // Now create the loop body.
742 {
743 assert (F->getBody());
744
745 // Save the current values for Block, Succ, and continue and break targets
746 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
747 save_continue(ContinueTargetBlock),
748 save_break(BreakTargetBlock);
Ted Kremeneke9334502008-09-04 21:48:47 +0000749
Ted Kremenekaf603f72007-08-30 18:39:40 +0000750 // Create a new block to contain the (bottom) of the loop body.
751 Block = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000752
Ted Kremeneke9334502008-09-04 21:48:47 +0000753 if (Stmt* I = F->getInc()) {
754 // Generate increment code in its own basic block. This is the target
755 // of continue statements.
756 Succ = addStmt(I);
757 Block = 0;
758 ContinueTargetBlock = Succ;
759 }
760 else {
761 // No increment code. Continues should go the the entry condition block.
762 ContinueTargetBlock = EntryConditionBlock;
763 }
764
765 // All breaks should go to the code following the loop.
766 BreakTargetBlock = LoopSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000767
768 // Now populate the body block, and in the process create new blocks
769 // as we walk the body of the loop.
770 CFGBlock* BodyBlock = Visit(F->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000771
772 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000773 BodyBlock = EntryConditionBlock; // can happen for "for (...;...; ) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000774 else if (Block)
775 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000776
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000777 // This new body block is a successor to our "exit" condition block.
778 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000779 }
780
781 // Link up the condition block with the code that follows the loop.
782 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000783 ExitConditionBlock->addSuccessor(LoopSuccessor);
784
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000785 // If the loop contains initialization, create a new block for those
786 // statements. This block can also contain statements that precede
787 // the loop.
788 if (Stmt* I = F->getInit()) {
789 Block = createBlock();
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000790 return addStmt(I);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000791 }
792 else {
793 // There is no loop initialization. We are thus basically a while
794 // loop. NULL out Block to force lazy block construction.
795 Block = NULL;
Ted Kremenek54827132008-02-27 07:20:00 +0000796 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000797 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000798 }
799}
800
801CFGBlock* CFGBuilder::VisitWhileStmt(WhileStmt* W) {
802 // "while" is a control-flow statement. Thus we stop processing the
803 // current block.
804
805 CFGBlock* LoopSuccessor = NULL;
806
807 if (Block) {
808 FinishBlock(Block);
809 LoopSuccessor = Block;
810 }
811 else LoopSuccessor = Succ;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000812
813 // Because of short-circuit evaluation, the condition of the loop
814 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
815 // blocks that evaluate the condition.
816 CFGBlock* ExitConditionBlock = createBlock(false);
817 CFGBlock* EntryConditionBlock = ExitConditionBlock;
818
819 // Set the terminator for the "exit" condition block.
820 ExitConditionBlock->setTerminator(W);
821
822 // Now add the actual condition to the condition block. Because the
823 // condition itself may contain control-flow, new blocks may be created.
824 // Thus we update "Succ" after adding the condition.
825 if (Stmt* C = W->getCond()) {
826 Block = ExitConditionBlock;
827 EntryConditionBlock = addStmt(C);
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000828 assert (Block == EntryConditionBlock);
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000829 if (Block) FinishBlock(EntryConditionBlock);
830 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000831
832 // The condition block is the implicit successor for the loop body as
833 // well as any code above the loop.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000834 Succ = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000835
836 // Process the loop body.
837 {
838 assert (W->getBody());
839
840 // Save the current values for Block, Succ, and continue and break targets
841 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
842 save_continue(ContinueTargetBlock),
843 save_break(BreakTargetBlock);
844
845 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000846 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000847
848 // All breaks should go to the code following the loop.
849 BreakTargetBlock = LoopSuccessor;
850
851 // NULL out Block to force lazy instantiation of blocks for the body.
852 Block = NULL;
853
854 // Create the body. The returned block is the entry to the loop body.
855 CFGBlock* BodyBlock = Visit(W->getBody());
Ted Kremenekaf603f72007-08-30 18:39:40 +0000856
857 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000858 BodyBlock = EntryConditionBlock; // can happen for "while(...) ;"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000859 else if (Block)
860 FinishBlock(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000861
862 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000863 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000864 }
865
866 // Link up the condition block with the code that follows the loop.
867 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000868 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000869
870 // There can be no more statements in the condition block
871 // since we loop back to this block. NULL out Block to force
872 // lazy creation of another block.
873 Block = NULL;
874
875 // Return the condition block, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000876 Succ = EntryConditionBlock;
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000877 return EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000878}
879
880CFGBlock* CFGBuilder::VisitDoStmt(DoStmt* D) {
881 // "do...while" is a control-flow statement. Thus we stop processing the
882 // current block.
883
884 CFGBlock* LoopSuccessor = NULL;
885
886 if (Block) {
887 FinishBlock(Block);
888 LoopSuccessor = Block;
889 }
890 else LoopSuccessor = Succ;
891
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000892 // Because of short-circuit evaluation, the condition of the loop
893 // can span multiple basic blocks. Thus we need the "Entry" and "Exit"
894 // blocks that evaluate the condition.
895 CFGBlock* ExitConditionBlock = createBlock(false);
896 CFGBlock* EntryConditionBlock = ExitConditionBlock;
897
898 // Set the terminator for the "exit" condition block.
899 ExitConditionBlock->setTerminator(D);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000900
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000901 // Now add the actual condition to the condition block. Because the
902 // condition itself may contain control-flow, new blocks may be created.
903 if (Stmt* C = D->getCond()) {
904 Block = ExitConditionBlock;
905 EntryConditionBlock = addStmt(C);
906 if (Block) FinishBlock(EntryConditionBlock);
907 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000908
Ted Kremenek54827132008-02-27 07:20:00 +0000909 // The condition block is the implicit successor for the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000910 Succ = EntryConditionBlock;
911
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000912 // Process the loop body.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000913 CFGBlock* BodyBlock = NULL;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000914 {
915 assert (D->getBody());
916
917 // Save the current values for Block, Succ, and continue and break targets
918 SaveAndRestore<CFGBlock*> save_Block(Block), save_Succ(Succ),
919 save_continue(ContinueTargetBlock),
920 save_break(BreakTargetBlock);
921
922 // All continues within this loop should go to the condition block
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000923 ContinueTargetBlock = EntryConditionBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000924
925 // All breaks should go to the code following the loop.
926 BreakTargetBlock = LoopSuccessor;
927
928 // NULL out Block to force lazy instantiation of blocks for the body.
929 Block = NULL;
930
931 // Create the body. The returned block is the entry to the loop body.
932 BodyBlock = Visit(D->getBody());
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000933
Ted Kremenekaf603f72007-08-30 18:39:40 +0000934 if (!BodyBlock)
Ted Kremeneka9d996d2008-02-27 00:28:17 +0000935 BodyBlock = EntryConditionBlock; // can happen for "do ; while(...)"
Ted Kremenekaf603f72007-08-30 18:39:40 +0000936 else if (Block)
937 FinishBlock(BodyBlock);
938
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000939 // Add the loop body entry as a successor to the condition.
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000940 ExitConditionBlock->addSuccessor(BodyBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000941 }
942
943 // Link up the condition block with the code that follows the loop.
944 // (the false branch).
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000945 ExitConditionBlock->addSuccessor(LoopSuccessor);
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000946
Ted Kremenek49af7cb2007-08-27 19:46:09 +0000947 // There can be no more statements in the body block(s)
948 // since we loop back to the body. NULL out Block to force
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000949 // lazy creation of another block.
950 Block = NULL;
951
952 // Return the loop body, which is the dominating block for the loop.
Ted Kremenek54827132008-02-27 07:20:00 +0000953 Succ = BodyBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000954 return BodyBlock;
955}
956
957CFGBlock* CFGBuilder::VisitContinueStmt(ContinueStmt* C) {
958 // "continue" is a control-flow statement. Thus we stop processing the
959 // current block.
960 if (Block) FinishBlock(Block);
961
962 // Now create a new block that ends with the continue statement.
963 Block = createBlock(false);
964 Block->setTerminator(C);
965
966 // If there is no target for the continue, then we are looking at an
967 // incomplete AST. Handle this by not registering a successor.
968 if (ContinueTargetBlock) Block->addSuccessor(ContinueTargetBlock);
969
970 return Block;
971}
972
973CFGBlock* CFGBuilder::VisitBreakStmt(BreakStmt* B) {
974 // "break" is a control-flow statement. Thus we stop processing the
975 // current block.
976 if (Block) FinishBlock(Block);
977
978 // Now create a new block that ends with the continue statement.
979 Block = createBlock(false);
980 Block->setTerminator(B);
981
982 // If there is no target for the break, then we are looking at an
983 // incomplete AST. Handle this by not registering a successor.
984 if (BreakTargetBlock) Block->addSuccessor(BreakTargetBlock);
985
986 return Block;
987}
988
Ted Kremenek411cdee2008-04-16 21:10:48 +0000989CFGBlock* CFGBuilder::VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenekd4fdee32007-08-23 21:42:29 +0000990 // "switch" is a control-flow statement. Thus we stop processing the
991 // current block.
992 CFGBlock* SwitchSuccessor = NULL;
993
994 if (Block) {
995 FinishBlock(Block);
996 SwitchSuccessor = Block;
997 }
998 else SwitchSuccessor = Succ;
999
1000 // Save the current "switch" context.
1001 SaveAndRestore<CFGBlock*> save_switch(SwitchTerminatedBlock),
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001002 save_break(BreakTargetBlock),
1003 save_default(DefaultCaseBlock);
1004
1005 // Set the "default" case to be the block after the switch statement.
1006 // If the switch statement contains a "default:", this value will
1007 // be overwritten with the block for that code.
1008 DefaultCaseBlock = SwitchSuccessor;
Ted Kremenek295222c2008-02-13 21:46:34 +00001009
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001010 // Create a new block that will contain the switch statement.
1011 SwitchTerminatedBlock = createBlock(false);
1012
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001013 // Now process the switch body. The code after the switch is the implicit
1014 // successor.
1015 Succ = SwitchSuccessor;
1016 BreakTargetBlock = SwitchSuccessor;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001017
1018 // When visiting the body, the case statements should automatically get
1019 // linked up to the switch. We also don't keep a pointer to the body,
1020 // since all control-flow from the switch goes to case/default statements.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001021 assert (Terminator->getBody() && "switch must contain a non-NULL body");
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001022 Block = NULL;
Ted Kremenek411cdee2008-04-16 21:10:48 +00001023 CFGBlock *BodyBlock = Visit(Terminator->getBody());
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001024 if (Block) FinishBlock(BodyBlock);
1025
Ted Kremenek295222c2008-02-13 21:46:34 +00001026 // If we have no "default:" case, the default transition is to the
1027 // code following the switch body.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001028 SwitchTerminatedBlock->addSuccessor(DefaultCaseBlock);
Ted Kremenek295222c2008-02-13 21:46:34 +00001029
Ted Kremenek49af7cb2007-08-27 19:46:09 +00001030 // Add the terminator and condition in the switch block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001031 SwitchTerminatedBlock->setTerminator(Terminator);
1032 assert (Terminator->getCond() && "switch condition must be non-NULL");
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001033 Block = SwitchTerminatedBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001034
Ted Kremenek411cdee2008-04-16 21:10:48 +00001035 return addStmt(Terminator->getCond());
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001036}
1037
Ted Kremenek411cdee2008-04-16 21:10:48 +00001038CFGBlock* CFGBuilder::VisitCaseStmt(CaseStmt* Terminator) {
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001039 // CaseStmts are essentially labels, so they are the
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001040 // first statement in a block.
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001041
Ted Kremenek411cdee2008-04-16 21:10:48 +00001042 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenek29ccaa12007-08-30 18:48:11 +00001043 CFGBlock* CaseBlock = Block;
1044 if (!CaseBlock) CaseBlock = createBlock();
1045
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001046 // Cases statements partition blocks, so this is the top of
1047 // the basic block we were processing (the "case XXX:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001048 CaseBlock->setLabel(Terminator);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001049 FinishBlock(CaseBlock);
1050
1051 // Add this block to the list of successors for the block with the
1052 // switch statement.
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001053 assert (SwitchTerminatedBlock);
1054 SwitchTerminatedBlock->addSuccessor(CaseBlock);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001055
1056 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1057 Block = NULL;
1058
1059 // This block is now the implicit successor of other blocks.
1060 Succ = CaseBlock;
1061
Ted Kremenek2677ea82008-03-15 07:45:02 +00001062 return CaseBlock;
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001063}
Ted Kremenek295222c2008-02-13 21:46:34 +00001064
Ted Kremenek411cdee2008-04-16 21:10:48 +00001065CFGBlock* CFGBuilder::VisitDefaultStmt(DefaultStmt* Terminator) {
1066 if (Terminator->getSubStmt()) Visit(Terminator->getSubStmt());
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001067 DefaultCaseBlock = Block;
1068 if (!DefaultCaseBlock) DefaultCaseBlock = createBlock();
1069
1070 // Default statements partition blocks, so this is the top of
1071 // the basic block we were processing (the "default:" is the label).
Ted Kremenek411cdee2008-04-16 21:10:48 +00001072 DefaultCaseBlock->setLabel(Terminator);
Ted Kremenekeef5a9a2008-02-13 22:05:39 +00001073 FinishBlock(DefaultCaseBlock);
1074
1075 // Unlike case statements, we don't add the default block to the
1076 // successors for the switch statement immediately. This is done
1077 // when we finish processing the switch statement. This allows for
1078 // the default case (including a fall-through to the code after the
1079 // switch statement) to always be the last successor of a switch-terminated
1080 // block.
1081
1082 // We set Block to NULL to allow lazy creation of a new block (if necessary)
1083 Block = NULL;
1084
1085 // This block is now the implicit successor of other blocks.
1086 Succ = DefaultCaseBlock;
1087
1088 return DefaultCaseBlock;
Ted Kremenek295222c2008-02-13 21:46:34 +00001089}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001090
Ted Kremenek19bb3562007-08-28 19:26:49 +00001091CFGBlock* CFGBuilder::VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1092 // Lazily create the indirect-goto dispatch block if there isn't one
1093 // already.
1094 CFGBlock* IBlock = cfg->getIndirectGotoBlock();
1095
1096 if (!IBlock) {
1097 IBlock = createBlock(false);
1098 cfg->setIndirectGotoBlock(IBlock);
1099 }
1100
1101 // IndirectGoto is a control-flow statement. Thus we stop processing the
1102 // current block and create a new one.
1103 if (Block) FinishBlock(Block);
1104 Block = createBlock(false);
1105 Block->setTerminator(I);
1106 Block->addSuccessor(IBlock);
1107 return addStmt(I->getTarget());
1108}
1109
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001110
Ted Kremenekbefef2f2007-08-23 21:26:19 +00001111} // end anonymous namespace
Ted Kremenek026473c2007-08-23 16:51:22 +00001112
1113/// createBlock - Constructs and adds a new CFGBlock to the CFG. The
1114/// block has no successors or predecessors. If this is the first block
1115/// created in the CFG, it is automatically set to be the Entry and Exit
1116/// of the CFG.
Ted Kremenek94382522007-09-05 20:02:05 +00001117CFGBlock* CFG::createBlock() {
Ted Kremenek026473c2007-08-23 16:51:22 +00001118 bool first_block = begin() == end();
1119
1120 // Create the block.
Ted Kremenek94382522007-09-05 20:02:05 +00001121 Blocks.push_front(CFGBlock(NumBlockIDs++));
Ted Kremenek026473c2007-08-23 16:51:22 +00001122
1123 // If this is the first block, set it as the Entry and Exit.
1124 if (first_block) Entry = Exit = &front();
1125
1126 // Return the block.
1127 return &front();
Ted Kremenekfddd5182007-08-21 21:42:03 +00001128}
1129
Ted Kremenek026473c2007-08-23 16:51:22 +00001130/// buildCFG - Constructs a CFG from an AST. Ownership of the returned
1131/// CFG is returned to the caller.
1132CFG* CFG::buildCFG(Stmt* Statement) {
1133 CFGBuilder Builder;
1134 return Builder.buildCFG(Statement);
1135}
1136
1137/// reverseStmts - Reverses the orders of statements within a CFGBlock.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001138void CFGBlock::reverseStmts() { std::reverse(Stmts.begin(),Stmts.end()); }
1139
Ted Kremenek63f58872007-10-01 19:33:33 +00001140//===----------------------------------------------------------------------===//
1141// CFG: Queries for BlkExprs.
1142//===----------------------------------------------------------------------===//
Ted Kremenek7dba8602007-08-29 21:56:09 +00001143
Ted Kremenek63f58872007-10-01 19:33:33 +00001144namespace {
Ted Kremenek86946742008-01-17 20:48:37 +00001145 typedef llvm::DenseMap<const Stmt*,unsigned> BlkExprMapTy;
Ted Kremenek63f58872007-10-01 19:33:33 +00001146}
1147
Ted Kremenek411cdee2008-04-16 21:10:48 +00001148static void FindSubExprAssignments(Stmt* Terminator, llvm::SmallPtrSet<Expr*,50>& Set) {
1149 if (!Terminator)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001150 return;
1151
Ted Kremenek411cdee2008-04-16 21:10:48 +00001152 for (Stmt::child_iterator I=Terminator->child_begin(), E=Terminator->child_end(); I!=E; ++I) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001153 if (!*I) continue;
1154
1155 if (BinaryOperator* B = dyn_cast<BinaryOperator>(*I))
1156 if (B->isAssignmentOp()) Set.insert(B);
1157
1158 FindSubExprAssignments(*I, Set);
1159 }
1160}
1161
Ted Kremenek63f58872007-10-01 19:33:33 +00001162static BlkExprMapTy* PopulateBlkExprMap(CFG& cfg) {
1163 BlkExprMapTy* M = new BlkExprMapTy();
1164
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001165 // Look for assignments that are used as subexpressions. These are the
Ted Kremenek411cdee2008-04-16 21:10:48 +00001166 // only assignments that we want to *possibly* register as a block-level
1167 // expression. Basically, if an assignment occurs both in a subexpression
1168 // and at the block-level, it is a block-level expression.
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001169 llvm::SmallPtrSet<Expr*,50> SubExprAssignments;
1170
Ted Kremenek63f58872007-10-01 19:33:33 +00001171 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I)
1172 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001173 FindSubExprAssignments(*BI, SubExprAssignments);
Ted Kremenek86946742008-01-17 20:48:37 +00001174
Ted Kremenek411cdee2008-04-16 21:10:48 +00001175 for (CFG::iterator I=cfg.begin(), E=cfg.end(); I != E; ++I) {
1176
1177 // Iterate over the statements again on identify the Expr* and Stmt* at
1178 // the block-level that are block-level expressions.
1179
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001180 for (CFGBlock::iterator BI=I->begin(), EI=I->end(); BI != EI; ++BI)
Ted Kremenek411cdee2008-04-16 21:10:48 +00001181 if (Expr* Exp = dyn_cast<Expr>(*BI)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001182
Ted Kremenek411cdee2008-04-16 21:10:48 +00001183 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001184 // Assignment expressions that are not nested within another
1185 // expression are really "statements" whose value is never
1186 // used by another expression.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001187 if (B->isAssignmentOp() && !SubExprAssignments.count(Exp))
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001188 continue;
1189 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001190 else if (const StmtExpr* Terminator = dyn_cast<StmtExpr>(Exp)) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001191 // Special handling for statement expressions. The last statement
1192 // in the statement expression is also a block-level expr.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001193 const CompoundStmt* C = Terminator->getSubStmt();
Ted Kremenek86946742008-01-17 20:48:37 +00001194 if (!C->body_empty()) {
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001195 unsigned x = M->size();
Ted Kremenek86946742008-01-17 20:48:37 +00001196 (*M)[C->body_back()] = x;
1197 }
1198 }
Ted Kremeneke2dcd782008-01-25 23:22:27 +00001199
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001200 unsigned x = M->size();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001201 (*M)[Exp] = x;
Ted Kremenek33d4aab2008-01-26 00:03:27 +00001202 }
1203
Ted Kremenek411cdee2008-04-16 21:10:48 +00001204 // Look at terminators. The condition is a block-level expression.
1205
1206 Expr* Exp = I->getTerminatorCondition();
1207
1208 if (Exp && M->find(Exp) == M->end()) {
1209 unsigned x = M->size();
1210 (*M)[Exp] = x;
1211 }
1212 }
1213
Ted Kremenek63f58872007-10-01 19:33:33 +00001214 return M;
1215}
1216
Ted Kremenek86946742008-01-17 20:48:37 +00001217CFG::BlkExprNumTy CFG::getBlkExprNum(const Stmt* S) {
1218 assert(S != NULL);
Ted Kremenek63f58872007-10-01 19:33:33 +00001219 if (!BlkExprMap) { BlkExprMap = (void*) PopulateBlkExprMap(*this); }
1220
1221 BlkExprMapTy* M = reinterpret_cast<BlkExprMapTy*>(BlkExprMap);
Ted Kremenek86946742008-01-17 20:48:37 +00001222 BlkExprMapTy::iterator I = M->find(S);
Ted Kremenek63f58872007-10-01 19:33:33 +00001223
1224 if (I == M->end()) return CFG::BlkExprNumTy();
1225 else return CFG::BlkExprNumTy(I->second);
1226}
1227
1228unsigned CFG::getNumBlkExprs() {
1229 if (const BlkExprMapTy* M = reinterpret_cast<const BlkExprMapTy*>(BlkExprMap))
1230 return M->size();
1231 else {
1232 // We assume callers interested in the number of BlkExprs will want
1233 // the map constructed if it doesn't already exist.
1234 BlkExprMap = (void*) PopulateBlkExprMap(*this);
1235 return reinterpret_cast<BlkExprMapTy*>(BlkExprMap)->size();
1236 }
1237}
1238
Ted Kremenek274f4332008-04-28 18:00:46 +00001239//===----------------------------------------------------------------------===//
Ted Kremenek274f4332008-04-28 18:00:46 +00001240// Cleanup: CFG dstor.
1241//===----------------------------------------------------------------------===//
1242
Ted Kremenek63f58872007-10-01 19:33:33 +00001243CFG::~CFG() {
1244 delete reinterpret_cast<const BlkExprMapTy*>(BlkExprMap);
1245}
1246
Ted Kremenek7dba8602007-08-29 21:56:09 +00001247//===----------------------------------------------------------------------===//
1248// CFG pretty printing
1249//===----------------------------------------------------------------------===//
1250
Ted Kremeneke8ee26b2007-08-22 18:22:34 +00001251namespace {
1252
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001253class VISIBILITY_HIDDEN StmtPrinterHelper : public PrinterHelper {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001254
Ted Kremenek42a509f2007-08-31 21:30:12 +00001255 typedef llvm::DenseMap<Stmt*,std::pair<unsigned,unsigned> > StmtMapTy;
1256 StmtMapTy StmtMap;
1257 signed CurrentBlock;
1258 unsigned CurrentStmt;
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001259
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001260public:
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001261
Ted Kremenek42a509f2007-08-31 21:30:12 +00001262 StmtPrinterHelper(const CFG* cfg) : CurrentBlock(0), CurrentStmt(0) {
1263 for (CFG::const_iterator I = cfg->begin(), E = cfg->end(); I != E; ++I ) {
1264 unsigned j = 1;
1265 for (CFGBlock::const_iterator BI = I->begin(), BEnd = I->end() ;
1266 BI != BEnd; ++BI, ++j )
1267 StmtMap[*BI] = std::make_pair(I->getBlockID(),j);
1268 }
1269 }
1270
1271 virtual ~StmtPrinterHelper() {}
1272
1273 void setBlockID(signed i) { CurrentBlock = i; }
1274 void setStmtID(unsigned i) { CurrentStmt = i; }
1275
Ted Kremeneka95d3752008-09-13 05:16:45 +00001276 virtual bool handledStmt(Stmt* Terminator, llvm::raw_ostream& OS) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001277
Ted Kremenek411cdee2008-04-16 21:10:48 +00001278 StmtMapTy::iterator I = StmtMap.find(Terminator);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001279
1280 if (I == StmtMap.end())
1281 return false;
1282
1283 if (CurrentBlock >= 0 && I->second.first == (unsigned) CurrentBlock
1284 && I->second.second == CurrentStmt)
1285 return false;
1286
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001287 OS << "[B" << I->second.first << "." << I->second.second << "]";
1288 return true;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001289 }
1290};
1291
Ted Kremenek6fa9b882008-01-08 18:15:10 +00001292class VISIBILITY_HIDDEN CFGBlockTerminatorPrint
1293 : public StmtVisitor<CFGBlockTerminatorPrint,void> {
1294
Ted Kremeneka95d3752008-09-13 05:16:45 +00001295 llvm::raw_ostream& OS;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001296 StmtPrinterHelper* Helper;
1297public:
Ted Kremeneka95d3752008-09-13 05:16:45 +00001298 CFGBlockTerminatorPrint(llvm::raw_ostream& os, StmtPrinterHelper* helper)
Ted Kremenek42a509f2007-08-31 21:30:12 +00001299 : OS(os), Helper(helper) {}
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001300
1301 void VisitIfStmt(IfStmt* I) {
1302 OS << "if ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001303 I->getCond()->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001304 }
1305
1306 // Default case.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001307 void VisitStmt(Stmt* Terminator) { Terminator->printPretty(OS); }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001308
1309 void VisitForStmt(ForStmt* F) {
1310 OS << "for (" ;
Ted Kremenek535bb202007-08-30 21:28:02 +00001311 if (F->getInit()) OS << "...";
1312 OS << "; ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001313 if (Stmt* C = F->getCond()) C->printPretty(OS,Helper);
Ted Kremenek535bb202007-08-30 21:28:02 +00001314 OS << "; ";
1315 if (F->getInc()) OS << "...";
Ted Kremeneka2925852008-01-30 23:02:42 +00001316 OS << ")";
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001317 }
1318
1319 void VisitWhileStmt(WhileStmt* W) {
1320 OS << "while " ;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001321 if (Stmt* C = W->getCond()) C->printPretty(OS,Helper);
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001322 }
1323
1324 void VisitDoStmt(DoStmt* D) {
1325 OS << "do ... while ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001326 if (Stmt* C = D->getCond()) C->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001327 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001328
Ted Kremenek411cdee2008-04-16 21:10:48 +00001329 void VisitSwitchStmt(SwitchStmt* Terminator) {
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001330 OS << "switch ";
Ted Kremenek411cdee2008-04-16 21:10:48 +00001331 Terminator->getCond()->printPretty(OS,Helper);
Ted Kremenek9da2fb72007-08-27 21:27:44 +00001332 }
1333
Ted Kremenek805e9a82007-08-31 21:49:40 +00001334 void VisitConditionalOperator(ConditionalOperator* C) {
1335 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001336 OS << " ? ... : ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001337 }
1338
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001339 void VisitChooseExpr(ChooseExpr* C) {
1340 OS << "__builtin_choose_expr( ";
1341 C->getCond()->printPretty(OS,Helper);
Ted Kremeneka2925852008-01-30 23:02:42 +00001342 OS << " )";
Ted Kremenekaeddbf62007-08-31 22:29:13 +00001343 }
1344
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001345 void VisitIndirectGotoStmt(IndirectGotoStmt* I) {
1346 OS << "goto *";
1347 I->getTarget()->printPretty(OS,Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001348 }
1349
Ted Kremenek805e9a82007-08-31 21:49:40 +00001350 void VisitBinaryOperator(BinaryOperator* B) {
1351 if (!B->isLogicalOp()) {
1352 VisitExpr(B);
1353 return;
1354 }
1355
1356 B->getLHS()->printPretty(OS,Helper);
1357
1358 switch (B->getOpcode()) {
1359 case BinaryOperator::LOr:
Ted Kremeneka2925852008-01-30 23:02:42 +00001360 OS << " || ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001361 return;
1362 case BinaryOperator::LAnd:
Ted Kremeneka2925852008-01-30 23:02:42 +00001363 OS << " && ...";
Ted Kremenek805e9a82007-08-31 21:49:40 +00001364 return;
1365 default:
1366 assert(false && "Invalid logical operator.");
1367 }
1368 }
1369
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001370 void VisitExpr(Expr* E) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001371 E->printPretty(OS,Helper);
Ted Kremenek0b1d9b72007-08-27 21:54:41 +00001372 }
Ted Kremenekd4fdee32007-08-23 21:42:29 +00001373};
Ted Kremenek42a509f2007-08-31 21:30:12 +00001374
1375
Ted Kremeneka95d3752008-09-13 05:16:45 +00001376void print_stmt(llvm::raw_ostream&OS, StmtPrinterHelper* Helper, Stmt* Terminator) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001377 if (Helper) {
1378 // special printing for statement-expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001379 if (StmtExpr* SE = dyn_cast<StmtExpr>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001380 CompoundStmt* Sub = SE->getSubStmt();
1381
1382 if (Sub->child_begin() != Sub->child_end()) {
Ted Kremenek60266e82007-08-31 22:47:06 +00001383 OS << "({ ... ; ";
Ted Kremenek7a9d9d72007-10-29 20:41:04 +00001384 Helper->handledStmt(*SE->getSubStmt()->body_rbegin(),OS);
Ted Kremenek60266e82007-08-31 22:47:06 +00001385 OS << " })\n";
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001386 return;
1387 }
1388 }
1389
1390 // special printing for comma expressions.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001391 if (BinaryOperator* B = dyn_cast<BinaryOperator>(Terminator)) {
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001392 if (B->getOpcode() == BinaryOperator::Comma) {
1393 OS << "... , ";
1394 Helper->handledStmt(B->getRHS(),OS);
1395 OS << '\n';
1396 return;
1397 }
1398 }
1399 }
1400
Ted Kremenek411cdee2008-04-16 21:10:48 +00001401 Terminator->printPretty(OS, Helper);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001402
1403 // Expressions need a newline.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001404 if (isa<Expr>(Terminator)) OS << '\n';
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001405}
1406
Ted Kremeneka95d3752008-09-13 05:16:45 +00001407void print_block(llvm::raw_ostream& OS, const CFG* cfg, const CFGBlock& B,
Ted Kremenek42a509f2007-08-31 21:30:12 +00001408 StmtPrinterHelper* Helper, bool print_edges) {
1409
1410 if (Helper) Helper->setBlockID(B.getBlockID());
1411
Ted Kremenek7dba8602007-08-29 21:56:09 +00001412 // Print the header.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001413 OS << "\n [ B" << B.getBlockID();
1414
1415 if (&B == &cfg->getEntry())
1416 OS << " (ENTRY) ]\n";
1417 else if (&B == &cfg->getExit())
1418 OS << " (EXIT) ]\n";
1419 else if (&B == cfg->getIndirectGotoBlock())
Ted Kremenek7dba8602007-08-29 21:56:09 +00001420 OS << " (INDIRECT GOTO DISPATCH) ]\n";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001421 else
1422 OS << " ]\n";
1423
Ted Kremenek9cffe732007-08-29 23:20:49 +00001424 // Print the label of this block.
Ted Kremenek411cdee2008-04-16 21:10:48 +00001425 if (Stmt* Terminator = const_cast<Stmt*>(B.getLabel())) {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001426
1427 if (print_edges)
1428 OS << " ";
1429
Ted Kremenek411cdee2008-04-16 21:10:48 +00001430 if (LabelStmt* L = dyn_cast<LabelStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001431 OS << L->getName();
Ted Kremenek411cdee2008-04-16 21:10:48 +00001432 else if (CaseStmt* C = dyn_cast<CaseStmt>(Terminator)) {
Ted Kremenek9cffe732007-08-29 23:20:49 +00001433 OS << "case ";
1434 C->getLHS()->printPretty(OS);
1435 if (C->getRHS()) {
1436 OS << " ... ";
1437 C->getRHS()->printPretty(OS);
1438 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001439 }
Ted Kremenek411cdee2008-04-16 21:10:48 +00001440 else if (isa<DefaultStmt>(Terminator))
Ted Kremenek9cffe732007-08-29 23:20:49 +00001441 OS << "default";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001442 else
1443 assert(false && "Invalid label statement in CFGBlock.");
1444
Ted Kremenek9cffe732007-08-29 23:20:49 +00001445 OS << ":\n";
1446 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001447
Ted Kremenekfddd5182007-08-21 21:42:03 +00001448 // Iterate through the statements in the block and print them.
Ted Kremenekfddd5182007-08-21 21:42:03 +00001449 unsigned j = 1;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001450
1451 for (CFGBlock::const_iterator I = B.begin(), E = B.end() ;
1452 I != E ; ++I, ++j ) {
1453
Ted Kremenek9cffe732007-08-29 23:20:49 +00001454 // Print the statement # in the basic block and the statement itself.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001455 if (print_edges)
1456 OS << " ";
1457
Ted Kremeneka95d3752008-09-13 05:16:45 +00001458 OS << llvm::format("%3d", j) << ": ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001459
1460 if (Helper)
1461 Helper->setStmtID(j);
Ted Kremenek1c29bba2007-08-31 22:26:13 +00001462
1463 print_stmt(OS,Helper,*I);
Ted Kremenekfddd5182007-08-21 21:42:03 +00001464 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001465
Ted Kremenek9cffe732007-08-29 23:20:49 +00001466 // Print the terminator of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001467 if (B.getTerminator()) {
1468 if (print_edges)
1469 OS << " ";
1470
Ted Kremenek9cffe732007-08-29 23:20:49 +00001471 OS << " T: ";
Ted Kremenek42a509f2007-08-31 21:30:12 +00001472
1473 if (Helper) Helper->setBlockID(-1);
1474
1475 CFGBlockTerminatorPrint TPrinter(OS,Helper);
1476 TPrinter.Visit(const_cast<Stmt*>(B.getTerminator()));
Ted Kremeneka2925852008-01-30 23:02:42 +00001477 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001478 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001479
Ted Kremenek9cffe732007-08-29 23:20:49 +00001480 if (print_edges) {
1481 // Print the predecessors of this block.
Ted Kremenek42a509f2007-08-31 21:30:12 +00001482 OS << " Predecessors (" << B.pred_size() << "):";
Ted Kremenek9cffe732007-08-29 23:20:49 +00001483 unsigned i = 0;
Ted Kremenek9cffe732007-08-29 23:20:49 +00001484
Ted Kremenek42a509f2007-08-31 21:30:12 +00001485 for (CFGBlock::const_pred_iterator I = B.pred_begin(), E = B.pred_end();
1486 I != E; ++I, ++i) {
1487
1488 if (i == 8 || (i-8) == 0)
1489 OS << "\n ";
1490
Ted Kremenek9cffe732007-08-29 23:20:49 +00001491 OS << " B" << (*I)->getBlockID();
1492 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001493
1494 OS << '\n';
1495
1496 // Print the successors of this block.
1497 OS << " Successors (" << B.succ_size() << "):";
1498 i = 0;
1499
1500 for (CFGBlock::const_succ_iterator I = B.succ_begin(), E = B.succ_end();
1501 I != E; ++I, ++i) {
1502
1503 if (i == 8 || (i-8) % 10 == 0)
1504 OS << "\n ";
1505
1506 OS << " B" << (*I)->getBlockID();
1507 }
1508
Ted Kremenek9cffe732007-08-29 23:20:49 +00001509 OS << '\n';
Ted Kremenekfddd5182007-08-21 21:42:03 +00001510 }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001511}
1512
1513} // end anonymous namespace
1514
1515/// dump - A simple pretty printer of a CFG that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001516void CFG::dump() const { print(llvm::errs()); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001517
1518/// print - A simple pretty printer of a CFG that outputs to an ostream.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001519void CFG::print(llvm::raw_ostream& OS) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001520
1521 StmtPrinterHelper Helper(this);
1522
1523 // Print the entry block.
1524 print_block(OS, this, getEntry(), &Helper, true);
1525
1526 // Iterate through the CFGBlocks and print them one by one.
1527 for (const_iterator I = Blocks.begin(), E = Blocks.end() ; I != E ; ++I) {
1528 // Skip the entry block, because we already printed it.
1529 if (&(*I) == &getEntry() || &(*I) == &getExit())
1530 continue;
1531
1532 print_block(OS, this, *I, &Helper, true);
1533 }
1534
1535 // Print the exit block.
1536 print_block(OS, this, getExit(), &Helper, true);
1537}
1538
1539/// dump - A simply pretty printer of a CFGBlock that outputs to stderr.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001540void CFGBlock::dump(const CFG* cfg) const { print(llvm::errs(), cfg); }
Ted Kremenek42a509f2007-08-31 21:30:12 +00001541
1542/// print - A simple pretty printer of a CFGBlock that outputs to an ostream.
1543/// Generally this will only be called from CFG::print.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001544void CFGBlock::print(llvm::raw_ostream& OS, const CFG* cfg) const {
Ted Kremenek42a509f2007-08-31 21:30:12 +00001545 StmtPrinterHelper Helper(cfg);
1546 print_block(OS, cfg, *this, &Helper, true);
Ted Kremenek026473c2007-08-23 16:51:22 +00001547}
Ted Kremenek7dba8602007-08-29 21:56:09 +00001548
Ted Kremeneka2925852008-01-30 23:02:42 +00001549/// printTerminator - A simple pretty printer of the terminator of a CFGBlock.
Ted Kremeneka95d3752008-09-13 05:16:45 +00001550void CFGBlock::printTerminator(llvm::raw_ostream& OS) const {
Ted Kremeneka2925852008-01-30 23:02:42 +00001551 CFGBlockTerminatorPrint TPrinter(OS,NULL);
1552 TPrinter.Visit(const_cast<Stmt*>(getTerminator()));
1553}
1554
Ted Kremenek411cdee2008-04-16 21:10:48 +00001555Expr* CFGBlock::getTerminatorCondition() {
1556
1557 if (!Terminator)
1558 return NULL;
1559
1560 Expr* E = NULL;
1561
1562 switch (Terminator->getStmtClass()) {
1563 default:
1564 break;
1565
1566 case Stmt::ForStmtClass:
1567 E = cast<ForStmt>(Terminator)->getCond();
1568 break;
1569
1570 case Stmt::WhileStmtClass:
1571 E = cast<WhileStmt>(Terminator)->getCond();
1572 break;
1573
1574 case Stmt::DoStmtClass:
1575 E = cast<DoStmt>(Terminator)->getCond();
1576 break;
1577
1578 case Stmt::IfStmtClass:
1579 E = cast<IfStmt>(Terminator)->getCond();
1580 break;
1581
1582 case Stmt::ChooseExprClass:
1583 E = cast<ChooseExpr>(Terminator)->getCond();
1584 break;
1585
1586 case Stmt::IndirectGotoStmtClass:
1587 E = cast<IndirectGotoStmt>(Terminator)->getTarget();
1588 break;
1589
1590 case Stmt::SwitchStmtClass:
1591 E = cast<SwitchStmt>(Terminator)->getCond();
1592 break;
1593
1594 case Stmt::ConditionalOperatorClass:
1595 E = cast<ConditionalOperator>(Terminator)->getCond();
1596 break;
1597
1598 case Stmt::BinaryOperatorClass: // '&&' and '||'
1599 E = cast<BinaryOperator>(Terminator)->getLHS();
1600 break;
1601 }
1602
1603 return E ? E->IgnoreParens() : NULL;
1604}
1605
Ted Kremenek9c2535a2008-05-16 16:06:00 +00001606bool CFGBlock::hasBinaryBranchTerminator() const {
1607
1608 if (!Terminator)
1609 return false;
1610
1611 Expr* E = NULL;
1612
1613 switch (Terminator->getStmtClass()) {
1614 default:
1615 return false;
1616
1617 case Stmt::ForStmtClass:
1618 case Stmt::WhileStmtClass:
1619 case Stmt::DoStmtClass:
1620 case Stmt::IfStmtClass:
1621 case Stmt::ChooseExprClass:
1622 case Stmt::ConditionalOperatorClass:
1623 case Stmt::BinaryOperatorClass:
1624 return true;
1625 }
1626
1627 return E ? E->IgnoreParens() : NULL;
1628}
1629
Ted Kremeneka2925852008-01-30 23:02:42 +00001630
Ted Kremenek7dba8602007-08-29 21:56:09 +00001631//===----------------------------------------------------------------------===//
1632// CFG Graphviz Visualization
1633//===----------------------------------------------------------------------===//
1634
Ted Kremenek42a509f2007-08-31 21:30:12 +00001635
1636#ifndef NDEBUG
Chris Lattner00123512007-09-17 06:16:32 +00001637static StmtPrinterHelper* GraphHelper;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001638#endif
1639
1640void CFG::viewCFG() const {
1641#ifndef NDEBUG
1642 StmtPrinterHelper H(this);
1643 GraphHelper = &H;
1644 llvm::ViewGraph(this,"CFG");
1645 GraphHelper = NULL;
Ted Kremenek42a509f2007-08-31 21:30:12 +00001646#endif
1647}
1648
Ted Kremenek7dba8602007-08-29 21:56:09 +00001649namespace llvm {
1650template<>
1651struct DOTGraphTraits<const CFG*> : public DefaultDOTGraphTraits {
1652 static std::string getNodeLabel(const CFGBlock* Node, const CFG* Graph) {
1653
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001654#ifndef NDEBUG
Ted Kremeneka95d3752008-09-13 05:16:45 +00001655 std::string OutSStr;
1656 llvm::raw_string_ostream Out(OutSStr);
Ted Kremenek42a509f2007-08-31 21:30:12 +00001657 print_block(Out,Graph, *Node, GraphHelper, false);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001658 std::string& OutStr = Out.str();
Ted Kremenek7dba8602007-08-29 21:56:09 +00001659
1660 if (OutStr[0] == '\n') OutStr.erase(OutStr.begin());
1661
1662 // Process string output to make it nicer...
1663 for (unsigned i = 0; i != OutStr.length(); ++i)
1664 if (OutStr[i] == '\n') { // Left justify
1665 OutStr[i] = '\\';
1666 OutStr.insert(OutStr.begin()+i+1, 'l');
1667 }
1668
1669 return OutStr;
Hartmut Kaiserbd250b42007-09-16 00:28:28 +00001670#else
1671 return "";
1672#endif
Ted Kremenek7dba8602007-08-29 21:56:09 +00001673 }
1674};
1675} // end namespace llvm