1 //===--- CFG.h - Classes for representing and building CFGs------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the CFG and CFGBuilder classes for representing and
11 // building Control-Flow Graphs (CFGs) from ASTs.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_CFG_H
16 #define LLVM_CLANG_CFG_H
18 #include "llvm/ADT/PointerIntPair.h"
19 #include "llvm/ADT/GraphTraits.h"
20 #include "llvm/Support/Allocator.h"
21 #include "llvm/Support/Casting.h"
22 #include "clang/Analysis/Support/BumpVector.h"
23 #include "clang/Basic/SourceLocation.h"
38 // An element of the CFG for implicit descructor calls implied by the language
41 // Statement that introduces the variable.
43 // A token which ends the scope, return, goto, throw, }.
46 Dtor(Stmt *s, SourceLocation l) : S(s), Loc(l) {
48 SourceLocation getLoc() { return Loc; }
49 Stmt *getStmt() { return S; }
53 /// CFGElement - Represents a top-level expression in a basic block.
55 llvm::PointerIntPair<Stmt *, 2> Data;
57 enum Type { StartScope, EndScope };
58 explicit CFGElement() {}
59 CFGElement(Stmt *S, bool lvalue) : Data(S, lvalue ? 1 : 0) {}
60 CFGElement(Stmt *S, Type t) : Data(S, t == StartScope ? 2 : 3) {}
61 // CFGElement(Dtor *S, Type t) : Data(reinterpret_cast<Stmt*>(S), 4) {}
62 Stmt *getStmt() const { return Data.getPointer(); }
63 bool asLValue() const { return Data.getInt() == 1; }
64 bool asStartScope() const { return Data.getInt() == 2; }
65 bool asEndScope() const { return Data.getInt() == 3; }
66 bool asDtor() const { return Data.getInt() == 4; }
67 operator Stmt*() const { return getStmt(); }
68 operator bool() const { return getStmt() != 0; }
69 operator Dtor*() const { return reinterpret_cast<Dtor*>(getStmt()); }
72 /// CFGBlock - Represents a single basic block in a source-level CFG.
75 /// (1) A set of statements/expressions (which may contain subexpressions).
76 /// (2) A "terminator" statement (not in the set of statements).
77 /// (3) A list of successors and predecessors.
79 /// Terminator: The terminator represents the type of control-flow that occurs
80 /// at the end of the basic block. The terminator is a Stmt* referring to an
81 /// AST node that has control-flow: if-statements, breaks, loops, etc.
82 /// If the control-flow is conditional, the condition expression will appear
83 /// within the set of statements in the block (usually the last statement).
85 /// Predecessors: the order in the set of predecessors is arbitrary.
87 /// Successors: the order in the set of successors is NOT arbitrary. We
88 /// currently have the following orderings based on the terminator:
90 /// Terminator Successor Ordering
91 /// -----------------------------------------------------
92 /// if Then Block; Else Block
93 /// ? operator LHS expression; RHS expression
94 /// &&, || expression that uses result of && or ||, RHS
98 typedef BumpVector<CFGElement> ImplTy;
101 StatementList(BumpVectorContext &C) : Impl(C, 4) {}
103 typedef std::reverse_iterator<ImplTy::iterator> iterator;
104 typedef std::reverse_iterator<ImplTy::const_iterator> const_iterator;
105 typedef ImplTy::iterator reverse_iterator;
106 typedef ImplTy::const_iterator const_reverse_iterator;
108 void push_back(CFGElement e, BumpVectorContext &C) { Impl.push_back(e, C); }
109 CFGElement front() const { return Impl.back(); }
110 CFGElement back() const { return Impl.front(); }
112 iterator begin() { return Impl.rbegin(); }
113 iterator end() { return Impl.rend(); }
114 const_iterator begin() const { return Impl.rbegin(); }
115 const_iterator end() const { return Impl.rend(); }
116 reverse_iterator rbegin() { return Impl.begin(); }
117 reverse_iterator rend() { return Impl.end(); }
118 const_reverse_iterator rbegin() const { return Impl.begin(); }
119 const_reverse_iterator rend() const { return Impl.end(); }
121 CFGElement operator[](size_t i) const {
122 assert(i < Impl.size());
123 return Impl[Impl.size() - 1 - i];
126 size_t size() const { return Impl.size(); }
127 bool empty() const { return Impl.empty(); }
130 /// Stmts - The set of statements in the basic block.
133 /// Label - An (optional) label that prefixes the executable
134 /// statements in the block. When this variable is non-NULL, it is
135 /// either an instance of LabelStmt or SwitchCase.
138 /// Terminator - The terminator for a basic block that
139 /// indicates the type of control-flow that occurs between a block
140 /// and its successors.
143 /// LoopTarget - Some blocks are used to represent the "loop edge" to
144 /// the start of a loop from within the loop body. This Stmt* will be
145 /// refer to the loop statement for such blocks (and be null otherwise).
146 const Stmt *LoopTarget;
148 /// BlockID - A numerical ID assigned to a CFGBlock during construction
152 /// Predecessors/Successors - Keep track of the predecessor / successor
154 typedef BumpVector<CFGBlock*> AdjacentBlocks;
155 AdjacentBlocks Preds;
156 AdjacentBlocks Succs;
159 explicit CFGBlock(unsigned blockid, BumpVectorContext &C)
160 : Stmts(C), Label(NULL), Terminator(NULL), LoopTarget(NULL),
161 BlockID(blockid), Preds(C, 1), Succs(C, 1) {}
164 // Statement iterators
165 typedef StatementList::iterator iterator;
166 typedef StatementList::const_iterator const_iterator;
167 typedef StatementList::reverse_iterator reverse_iterator;
168 typedef StatementList::const_reverse_iterator const_reverse_iterator;
170 CFGElement front() const { return Stmts.front(); }
171 CFGElement back() const { return Stmts.back(); }
173 iterator begin() { return Stmts.begin(); }
174 iterator end() { return Stmts.end(); }
175 const_iterator begin() const { return Stmts.begin(); }
176 const_iterator end() const { return Stmts.end(); }
178 reverse_iterator rbegin() { return Stmts.rbegin(); }
179 reverse_iterator rend() { return Stmts.rend(); }
180 const_reverse_iterator rbegin() const { return Stmts.rbegin(); }
181 const_reverse_iterator rend() const { return Stmts.rend(); }
183 unsigned size() const { return Stmts.size(); }
184 bool empty() const { return Stmts.empty(); }
186 CFGElement operator[](size_t i) const { return Stmts[i]; }
189 typedef AdjacentBlocks::iterator pred_iterator;
190 typedef AdjacentBlocks::const_iterator const_pred_iterator;
191 typedef AdjacentBlocks::reverse_iterator pred_reverse_iterator;
192 typedef AdjacentBlocks::const_reverse_iterator const_pred_reverse_iterator;
194 typedef AdjacentBlocks::iterator succ_iterator;
195 typedef AdjacentBlocks::const_iterator const_succ_iterator;
196 typedef AdjacentBlocks::reverse_iterator succ_reverse_iterator;
197 typedef AdjacentBlocks::const_reverse_iterator const_succ_reverse_iterator;
199 pred_iterator pred_begin() { return Preds.begin(); }
200 pred_iterator pred_end() { return Preds.end(); }
201 const_pred_iterator pred_begin() const { return Preds.begin(); }
202 const_pred_iterator pred_end() const { return Preds.end(); }
204 pred_reverse_iterator pred_rbegin() { return Preds.rbegin(); }
205 pred_reverse_iterator pred_rend() { return Preds.rend(); }
206 const_pred_reverse_iterator pred_rbegin() const { return Preds.rbegin(); }
207 const_pred_reverse_iterator pred_rend() const { return Preds.rend(); }
209 succ_iterator succ_begin() { return Succs.begin(); }
210 succ_iterator succ_end() { return Succs.end(); }
211 const_succ_iterator succ_begin() const { return Succs.begin(); }
212 const_succ_iterator succ_end() const { return Succs.end(); }
214 succ_reverse_iterator succ_rbegin() { return Succs.rbegin(); }
215 succ_reverse_iterator succ_rend() { return Succs.rend(); }
216 const_succ_reverse_iterator succ_rbegin() const { return Succs.rbegin(); }
217 const_succ_reverse_iterator succ_rend() const { return Succs.rend(); }
219 unsigned succ_size() const { return Succs.size(); }
220 bool succ_empty() const { return Succs.empty(); }
222 unsigned pred_size() const { return Preds.size(); }
223 bool pred_empty() const { return Preds.empty(); }
225 // Manipulation of block contents
227 void setTerminator(Stmt* Statement) { Terminator = Statement; }
228 void setLabel(Stmt* Statement) { Label = Statement; }
229 void setLoopTarget(const Stmt *loopTarget) { LoopTarget = loopTarget; }
231 Stmt* getTerminator() { return Terminator; }
232 const Stmt* getTerminator() const { return Terminator; }
234 Stmt* getTerminatorCondition();
236 const Stmt* getTerminatorCondition() const {
237 return const_cast<CFGBlock*>(this)->getTerminatorCondition();
240 const Stmt *getLoopTarget() const { return LoopTarget; }
242 bool hasBinaryBranchTerminator() const;
244 Stmt* getLabel() { return Label; }
245 const Stmt* getLabel() const { return Label; }
249 unsigned getBlockID() const { return BlockID; }
251 void dump(const CFG *cfg, const LangOptions &LO) const;
252 void print(llvm::raw_ostream &OS, const CFG* cfg, const LangOptions &LO) const;
253 void printTerminator(llvm::raw_ostream &OS, const LangOptions &LO) const;
255 void addSuccessor(CFGBlock* Block, BumpVectorContext &C) {
257 Block->Preds.push_back(this, C);
258 Succs.push_back(Block, C);
261 void appendStmt(Stmt* Statement, BumpVectorContext &C, bool asLValue) {
262 Stmts.push_back(CFGElement(Statement, asLValue), C);
264 void StartScope(Stmt* S, BumpVectorContext &C) {
265 Stmts.push_back(CFGElement(S, CFGElement::StartScope), C);
267 void EndScope(Stmt* S, BumpVectorContext &C) {
268 Stmts.push_back(CFGElement(S, CFGElement::EndScope), C);
273 /// CFG - Represents a source-level, intra-procedural CFG that represents the
274 /// control-flow of a Stmt. The Stmt can represent an entire function body,
275 /// or a single expression. A CFG will always contain one empty block that
276 /// represents the Exit point of the CFG. A CFG will also contain a designated
277 /// Entry block. The CFG solely represents control-flow; it consists of
278 /// CFGBlocks which are simply containers of Stmt*'s in the AST the CFG
279 /// was constructed from.
282 //===--------------------------------------------------------------------===//
283 // CFG Construction & Manipulation.
284 //===--------------------------------------------------------------------===//
286 /// buildCFG - Builds a CFG from an AST. The responsibility to free the
287 /// constructed CFG belongs to the caller.
288 static CFG* buildCFG(Stmt* AST, ASTContext *C, bool AddScopes = false);
290 /// createBlock - Create a new block in the CFG. The CFG owns the block;
291 /// the caller should not directly free it.
292 CFGBlock* createBlock();
294 /// setEntry - Set the entry block of the CFG. This is typically used
295 /// only during CFG construction. Most CFG clients expect that the
296 /// entry block has no predecessors and contains no statements.
297 void setEntry(CFGBlock *B) { Entry = B; }
299 /// setIndirectGotoBlock - Set the block used for indirect goto jumps.
300 /// This is typically used only during CFG construction.
301 void setIndirectGotoBlock(CFGBlock* B) { IndirectGotoBlock = B; }
303 //===--------------------------------------------------------------------===//
305 //===--------------------------------------------------------------------===//
307 typedef BumpVector<CFGBlock*> CFGBlockListTy;
308 typedef CFGBlockListTy::iterator iterator;
309 typedef CFGBlockListTy::const_iterator const_iterator;
310 typedef std::reverse_iterator<iterator> reverse_iterator;
311 typedef std::reverse_iterator<const_iterator> const_reverse_iterator;
313 CFGBlock& front() { return *Blocks.front(); }
314 CFGBlock& back() { return *Blocks.back(); }
316 iterator begin() { return Blocks.begin(); }
317 iterator end() { return Blocks.end(); }
318 const_iterator begin() const { return Blocks.begin(); }
319 const_iterator end() const { return Blocks.end(); }
321 reverse_iterator rbegin() { return Blocks.rbegin(); }
322 reverse_iterator rend() { return Blocks.rend(); }
323 const_reverse_iterator rbegin() const { return Blocks.rbegin(); }
324 const_reverse_iterator rend() const { return Blocks.rend(); }
326 CFGBlock& getEntry() { return *Entry; }
327 const CFGBlock& getEntry() const { return *Entry; }
328 CFGBlock& getExit() { return *Exit; }
329 const CFGBlock& getExit() const { return *Exit; }
331 CFGBlock* getIndirectGotoBlock() { return IndirectGotoBlock; }
332 const CFGBlock* getIndirectGotoBlock() const { return IndirectGotoBlock; }
334 //===--------------------------------------------------------------------===//
335 // Member templates useful for various batch operations over CFGs.
336 //===--------------------------------------------------------------------===//
338 template <typename CALLBACK>
339 void VisitBlockStmts(CALLBACK& O) const {
340 for (const_iterator I=begin(), E=end(); I != E; ++I)
341 for (CFGBlock::const_iterator BI=(*I)->begin(), BE=(*I)->end();
346 //===--------------------------------------------------------------------===//
347 // CFG Introspection.
348 //===--------------------------------------------------------------------===//
350 struct BlkExprNumTy {
352 explicit BlkExprNumTy(signed idx) : Idx(idx) {}
353 explicit BlkExprNumTy() : Idx(-1) {}
354 operator bool() const { return Idx >= 0; }
355 operator unsigned() const { assert(Idx >=0); return (unsigned) Idx; }
358 bool isBlkExpr(const Stmt* S) { return getBlkExprNum(S); }
359 BlkExprNumTy getBlkExprNum(const Stmt* S);
360 unsigned getNumBlkExprs();
362 /// getNumBlockIDs - Returns the total number of BlockIDs allocated (which
364 unsigned getNumBlockIDs() const { return NumBlockIDs; }
366 //===--------------------------------------------------------------------===//
367 // CFG Debugging: Pretty-Printing and Visualization.
368 //===--------------------------------------------------------------------===//
370 void viewCFG(const LangOptions &LO) const;
371 void print(llvm::raw_ostream& OS, const LangOptions &LO) const;
372 void dump(const LangOptions &LO) const;
374 //===--------------------------------------------------------------------===//
375 // Internal: constructors and data.
376 //===--------------------------------------------------------------------===//
378 CFG() : Entry(NULL), Exit(NULL), IndirectGotoBlock(NULL), NumBlockIDs(0),
379 BlkExprMap(NULL), Blocks(BlkBVC, 10) {}
383 llvm::BumpPtrAllocator& getAllocator() {
384 return BlkBVC.getAllocator();
387 BumpVectorContext &getBumpVectorContext() {
394 CFGBlock* IndirectGotoBlock; // Special block to contain collective dispatch
395 // for indirect gotos
396 unsigned NumBlockIDs;
398 // BlkExprMap - An opaque pointer to prevent inclusion of DenseMap.h.
399 // It represents a map from Expr* to integers to record the set of
400 // block-level expressions and their "statement number" in the CFG.
403 BumpVectorContext BlkBVC;
405 CFGBlockListTy Blocks;
408 } // end namespace clang
410 //===----------------------------------------------------------------------===//
411 // GraphTraits specializations for CFG basic block graphs (source-level CFGs)
412 //===----------------------------------------------------------------------===//
416 /// Implement simplify_type for CFGElement, so that we can dyn_cast from
417 /// CFGElement to a specific Stmt class.
418 template <> struct simplify_type<const ::clang::CFGElement> {
419 typedef ::clang::Stmt* SimpleType;
420 static SimpleType getSimplifiedValue(const ::clang::CFGElement &Val) {
421 return Val.getStmt();
425 template <> struct simplify_type< ::clang::CFGElement>
426 : public simplify_type<const ::clang::CFGElement> {};
428 // Traits for: CFGBlock
430 template <> struct GraphTraits< ::clang::CFGBlock* > {
431 typedef ::clang::CFGBlock NodeType;
432 typedef ::clang::CFGBlock::succ_iterator ChildIteratorType;
434 static NodeType* getEntryNode(::clang::CFGBlock* BB)
437 static inline ChildIteratorType child_begin(NodeType* N)
438 { return N->succ_begin(); }
440 static inline ChildIteratorType child_end(NodeType* N)
441 { return N->succ_end(); }
444 template <> struct GraphTraits< const ::clang::CFGBlock* > {
445 typedef const ::clang::CFGBlock NodeType;
446 typedef ::clang::CFGBlock::const_succ_iterator ChildIteratorType;
448 static NodeType* getEntryNode(const clang::CFGBlock* BB)
451 static inline ChildIteratorType child_begin(NodeType* N)
452 { return N->succ_begin(); }
454 static inline ChildIteratorType child_end(NodeType* N)
455 { return N->succ_end(); }
458 template <> struct GraphTraits<Inverse<const ::clang::CFGBlock*> > {
459 typedef const ::clang::CFGBlock NodeType;
460 typedef ::clang::CFGBlock::const_pred_iterator ChildIteratorType;
462 static NodeType *getEntryNode(Inverse<const ::clang::CFGBlock*> G)
465 static inline ChildIteratorType child_begin(NodeType* N)
466 { return N->pred_begin(); }
468 static inline ChildIteratorType child_end(NodeType* N)
469 { return N->pred_end(); }
474 template <> struct GraphTraits< ::clang::CFG* >
475 : public GraphTraits< ::clang::CFGBlock* > {
477 typedef ::clang::CFG::iterator nodes_iterator;
479 static NodeType *getEntryNode(::clang::CFG* F) { return &F->getEntry(); }
480 static nodes_iterator nodes_begin(::clang::CFG* F) { return F->begin(); }
481 static nodes_iterator nodes_end(::clang::CFG* F) { return F->end(); }
484 template <> struct GraphTraits<const ::clang::CFG* >
485 : public GraphTraits<const ::clang::CFGBlock* > {
487 typedef ::clang::CFG::const_iterator nodes_iterator;
489 static NodeType *getEntryNode( const ::clang::CFG* F) {
490 return &F->getEntry();
492 static nodes_iterator nodes_begin( const ::clang::CFG* F) {
495 static nodes_iterator nodes_end( const ::clang::CFG* F) {
500 template <> struct GraphTraits<Inverse<const ::clang::CFG*> >
501 : public GraphTraits<Inverse<const ::clang::CFGBlock*> > {
503 typedef ::clang::CFG::const_iterator nodes_iterator;
505 static NodeType *getEntryNode(const ::clang::CFG* F) { return &F->getExit(); }
506 static nodes_iterator nodes_begin(const ::clang::CFG* F) { return F->begin();}
507 static nodes_iterator nodes_end(const ::clang::CFG* F) { return F->end(); }
509 } // end llvm namespace