1//===-- llvm/Support/CFG.h - Process LLVM structures as graphs --*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines specializations of GraphTraits that allow Function and
11// BasicBlock graphs to be treated as proper graphs for generic algorithms.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_SUPPORT_CFG_H
16#define LLVM_SUPPORT_CFG_H
17
18#include "llvm/ADT/GraphTraits.h"
19#include "llvm/Function.h"
20#include "llvm/InstrTypes.h"
21
22namespace llvm {
23
24//===----------------------------------------------------------------------===//
25// BasicBlock pred_iterator definition
26//===----------------------------------------------------------------------===//
27
28template <class Ptr, class USE_iterator> // Predecessor Iterator
29class PredIterator : public std::iterator<std::forward_iterator_tag,
30                                          Ptr, ptrdiff_t> {
31  typedef std::iterator<std::forward_iterator_tag, Ptr, ptrdiff_t> super;
32  typedef PredIterator<Ptr, USE_iterator> Self;
33  USE_iterator It;
34
35  inline void advancePastNonTerminators() {
36    // Loop to ignore non terminator uses (for example BlockAddresses).
37    while (!It.atEnd() && !isa<TerminatorInst>(*It))
38      ++It;
39  }
40
41public:
42  typedef typename super::pointer pointer;
43
44  PredIterator() {}
45  explicit inline PredIterator(Ptr *bb) : It(bb->use_begin()) {
46    advancePastNonTerminators();
47  }
48  inline PredIterator(Ptr *bb, bool) : It(bb->use_end()) {}
49
50  inline bool operator==(const Self& x) const { return It == x.It; }
51  inline bool operator!=(const Self& x) const { return !operator==(x); }
52
53  inline pointer operator*() const {
54    assert(!It.atEnd() && "pred_iterator out of range!");
55    return cast<TerminatorInst>(*It)->getParent();
56  }
57  inline pointer *operator->() const { return &operator*(); }
58
59  inline Self& operator++() {   // Preincrement
60    assert(!It.atEnd() && "pred_iterator out of range!");
61    ++It; advancePastNonTerminators();
62    return *this;
63  }
64
65  inline Self operator++(int) { // Postincrement
66    Self tmp = *this; ++*this; return tmp;
67  }
68
69  /// getOperandNo - Return the operand number in the predecessor's
70  /// terminator of the successor.
71  unsigned getOperandNo() const {
72    return It.getOperandNo();
73  }
74
75  /// getUse - Return the operand Use in the predecessor's terminator
76  /// of the successor.
77  Use &getUse() const {
78    return It.getUse();
79  }
80};
81
82typedef PredIterator<BasicBlock, Value::use_iterator> pred_iterator;
83typedef PredIterator<const BasicBlock,
84                     Value::const_use_iterator> const_pred_iterator;
85
86inline pred_iterator pred_begin(BasicBlock *BB) { return pred_iterator(BB); }
87inline const_pred_iterator pred_begin(const BasicBlock *BB) {
88  return const_pred_iterator(BB);
89}
90inline pred_iterator pred_end(BasicBlock *BB) { return pred_iterator(BB, true);}
91inline const_pred_iterator pred_end(const BasicBlock *BB) {
92  return const_pred_iterator(BB, true);
93}
94
95
96
97//===----------------------------------------------------------------------===//
98// BasicBlock succ_iterator definition
99//===----------------------------------------------------------------------===//
100
101template <class Term_, class BB_>           // Successor Iterator
102class SuccIterator : public std::iterator<std::bidirectional_iterator_tag,
103                                          BB_, ptrdiff_t> {
104  const Term_ Term;
105  unsigned idx;
106  typedef std::iterator<std::bidirectional_iterator_tag, BB_, ptrdiff_t> super;
107  typedef SuccIterator<Term_, BB_> Self;
108
109  inline bool index_is_valid(int idx) {
110    return idx >= 0 && (unsigned) idx < Term->getNumSuccessors();
111  }
112
113public:
114  typedef typename super::pointer pointer;
115  // TODO: This can be random access iterator, only operator[] missing.
116
117  explicit inline SuccIterator(Term_ T) : Term(T), idx(0) {// begin iterator
118  }
119  inline SuccIterator(Term_ T, bool)                       // end iterator
120    : Term(T) {
121    if (Term)
122      idx = Term->getNumSuccessors();
123    else
124      // Term == NULL happens, if a basic block is not fully constructed and
125      // consequently getTerminator() returns NULL. In this case we construct a
126      // SuccIterator which describes a basic block that has zero successors.
127      // Defining SuccIterator for incomplete and malformed CFGs is especially
128      // useful for debugging.
129      idx = 0;
130  }
131
132  inline const Self &operator=(const Self &I) {
133    assert(Term == I.Term &&"Cannot assign iterators to two different blocks!");
134    idx = I.idx;
135    return *this;
136  }
137
138  /// getSuccessorIndex - This is used to interface between code that wants to
139  /// operate on terminator instructions directly.
140  unsigned getSuccessorIndex() const { return idx; }
141
142  inline bool operator==(const Self& x) const { return idx == x.idx; }
143  inline bool operator!=(const Self& x) const { return !operator==(x); }
144
145  inline pointer operator*() const { return Term->getSuccessor(idx); }
146  inline pointer operator->() const { return operator*(); }
147
148  inline Self& operator++() { ++idx; return *this; } // Preincrement
149
150  inline Self operator++(int) { // Postincrement
151    Self tmp = *this; ++*this; return tmp;
152  }
153
154  inline Self& operator--() { --idx; return *this; }  // Predecrement
155  inline Self operator--(int) { // Postdecrement
156    Self tmp = *this; --*this; return tmp;
157  }
158
159  inline bool operator<(const Self& x) const {
160    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
161    return idx < x.idx;
162  }
163
164  inline bool operator<=(const Self& x) const {
165    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
166    return idx <= x.idx;
167  }
168  inline bool operator>=(const Self& x) const {
169    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
170    return idx >= x.idx;
171  }
172
173  inline bool operator>(const Self& x) const {
174    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
175    return idx > x.idx;
176  }
177
178  inline Self& operator+=(int Right) {
179    unsigned new_idx = idx + Right;
180    assert(index_is_valid(new_idx) && "Iterator index out of bound");
181    idx = new_idx;
182    return *this;
183  }
184
185  inline Self operator+(int Right) {
186    Self tmp = *this;
187    tmp += Right;
188    return tmp;
189  }
190
191  inline Self& operator-=(int Right) {
192    return operator+=(-Right);
193  }
194
195  inline Self operator-(int Right) {
196    return operator+(-Right);
197  }
198
199  inline int operator-(const Self& x) {
200    assert(Term == x.Term && "Cannot work on iterators of different blocks!");
201    int distance = idx - x.idx;
202    return distance;
203  }
204
205  // This works for read access, however write access is difficult as changes
206  // to Term are only possible with Term->setSuccessor(idx). Pointers that can
207  // be modified are not available.
208  //
209  // inline pointer operator[](int offset) {
210  //  Self tmp = *this;
211  //  tmp += offset;
212  //  return tmp.operator*();
213  // }
214
215  /// Get the source BB of this iterator.
216  inline BB_ *getSource() {
217    assert(Term && "Source not available, if basic block was malformed");
218    return Term->getParent();
219  }
220};
221
222typedef SuccIterator<TerminatorInst*, BasicBlock> succ_iterator;
223typedef SuccIterator<const TerminatorInst*,
224                     const BasicBlock> succ_const_iterator;
225
226inline succ_iterator succ_begin(BasicBlock *BB) {
227  return succ_iterator(BB->getTerminator());
228}
229inline succ_const_iterator succ_begin(const BasicBlock *BB) {
230  return succ_const_iterator(BB->getTerminator());
231}
232inline succ_iterator succ_end(BasicBlock *BB) {
233  return succ_iterator(BB->getTerminator(), true);
234}
235inline succ_const_iterator succ_end(const BasicBlock *BB) {
236  return succ_const_iterator(BB->getTerminator(), true);
237}
238
239
240
241//===--------------------------------------------------------------------===//
242// GraphTraits specializations for basic block graphs (CFGs)
243//===--------------------------------------------------------------------===//
244
245// Provide specializations of GraphTraits to be able to treat a function as a
246// graph of basic blocks...
247
248template <> struct GraphTraits<BasicBlock*> {
249  typedef BasicBlock NodeType;
250  typedef succ_iterator ChildIteratorType;
251
252  static NodeType *getEntryNode(BasicBlock *BB) { return BB; }
253  static inline ChildIteratorType child_begin(NodeType *N) {
254    return succ_begin(N);
255  }
256  static inline ChildIteratorType child_end(NodeType *N) {
257    return succ_end(N);
258  }
259};
260
261template <> struct GraphTraits<const BasicBlock*> {
262  typedef const BasicBlock NodeType;
263  typedef succ_const_iterator ChildIteratorType;
264
265  static NodeType *getEntryNode(const BasicBlock *BB) { return BB; }
266
267  static inline ChildIteratorType child_begin(NodeType *N) {
268    return succ_begin(N);
269  }
270  static inline ChildIteratorType child_end(NodeType *N) {
271    return succ_end(N);
272  }
273};
274
275// Provide specializations of GraphTraits to be able to treat a function as a
276// graph of basic blocks... and to walk it in inverse order.  Inverse order for
277// a function is considered to be when traversing the predecessor edges of a BB
278// instead of the successor edges.
279//
280template <> struct GraphTraits<Inverse<BasicBlock*> > {
281  typedef BasicBlock NodeType;
282  typedef pred_iterator ChildIteratorType;
283  static NodeType *getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
284  static inline ChildIteratorType child_begin(NodeType *N) {
285    return pred_begin(N);
286  }
287  static inline ChildIteratorType child_end(NodeType *N) {
288    return pred_end(N);
289  }
290};
291
292template <> struct GraphTraits<Inverse<const BasicBlock*> > {
293  typedef const BasicBlock NodeType;
294  typedef const_pred_iterator ChildIteratorType;
295  static NodeType *getEntryNode(Inverse<const BasicBlock*> G) {
296    return G.Graph;
297  }
298  static inline ChildIteratorType child_begin(NodeType *N) {
299    return pred_begin(N);
300  }
301  static inline ChildIteratorType child_end(NodeType *N) {
302    return pred_end(N);
303  }
304};
305
306
307
308//===--------------------------------------------------------------------===//
309// GraphTraits specializations for function basic block graphs (CFGs)
310//===--------------------------------------------------------------------===//
311
312// Provide specializations of GraphTraits to be able to treat a function as a
313// graph of basic blocks... these are the same as the basic block iterators,
314// except that the root node is implicitly the first node of the function.
315//
316template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
317  static NodeType *getEntryNode(Function *F) { return &F->getEntryBlock(); }
318
319  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
320  typedef Function::iterator nodes_iterator;
321  static nodes_iterator nodes_begin(Function *F) { return F->begin(); }
322  static nodes_iterator nodes_end  (Function *F) { return F->end(); }
323  static unsigned       size       (Function *F) { return F->size(); }
324};
325template <> struct GraphTraits<const Function*> :
326  public GraphTraits<const BasicBlock*> {
327  static NodeType *getEntryNode(const Function *F) {return &F->getEntryBlock();}
328
329  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
330  typedef Function::const_iterator nodes_iterator;
331  static nodes_iterator nodes_begin(const Function *F) { return F->begin(); }
332  static nodes_iterator nodes_end  (const Function *F) { return F->end(); }
333  static unsigned       size       (const Function *F) { return F->size(); }
334};
335
336
337// Provide specializations of GraphTraits to be able to treat a function as a
338// graph of basic blocks... and to walk it in inverse order.  Inverse order for
339// a function is considered to be when traversing the predecessor edges of a BB
340// instead of the successor edges.
341//
342template <> struct GraphTraits<Inverse<Function*> > :
343  public GraphTraits<Inverse<BasicBlock*> > {
344  static NodeType *getEntryNode(Inverse<Function*> G) {
345    return &G.Graph->getEntryBlock();
346  }
347};
348template <> struct GraphTraits<Inverse<const Function*> > :
349  public GraphTraits<Inverse<const BasicBlock*> > {
350  static NodeType *getEntryNode(Inverse<const Function *> G) {
351    return &G.Graph->getEntryBlock();
352  }
353};
354
355} // End llvm namespace
356
357#endif
358