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