1//===- 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_IR_CFG_H
16#define LLVM_IR_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->user_begin()) {
48    advancePastNonTerminators();
49  }
50  inline PredIterator(Ptr *bb, bool) : It(bb->user_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::user_iterator> pred_iterator;
85typedef PredIterator<const BasicBlock,
86                     Value::const_user_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::random_access_iterator_tag, BB_,
105                                          int, BB_ *, BB_ *> {
106  typedef std::iterator<std::random_access_iterator_tag, BB_, int, BB_ *, BB_ *>
107  super;
108
109public:
110  typedef typename super::pointer pointer;
111  typedef typename super::reference reference;
112
113private:
114  const Term_ Term;
115  unsigned idx;
116  typedef SuccIterator<Term_, BB_> Self;
117
118  inline bool index_is_valid(int idx) {
119    return idx >= 0 && (unsigned) idx < Term->getNumSuccessors();
120  }
121
122  /// \brief Proxy object to allow write access in operator[]
123  class SuccessorProxy {
124    Self it;
125
126  public:
127    explicit SuccessorProxy(const Self &it) : it(it) {}
128
129    SuccessorProxy &operator=(SuccessorProxy r) {
130      *this = reference(r);
131      return *this;
132    }
133
134    SuccessorProxy &operator=(reference r) {
135      it.Term->setSuccessor(it.idx, r);
136      return *this;
137    }
138
139    operator reference() const { return *it; }
140  };
141
142public:
143  explicit inline SuccIterator(Term_ T) : Term(T), idx(0) {// begin iterator
144  }
145  inline SuccIterator(Term_ T, bool)                       // end iterator
146    : Term(T) {
147    if (Term)
148      idx = Term->getNumSuccessors();
149    else
150      // Term == NULL happens, if a basic block is not fully constructed and
151      // consequently getTerminator() returns NULL. In this case we construct a
152      // SuccIterator which describes a basic block that has zero successors.
153      // Defining SuccIterator for incomplete and malformed CFGs is especially
154      // useful for debugging.
155      idx = 0;
156  }
157
158  inline const Self &operator=(const Self &I) {
159    assert(Term == I.Term &&"Cannot assign iterators to two different blocks!");
160    idx = I.idx;
161    return *this;
162  }
163
164  /// getSuccessorIndex - This is used to interface between code that wants to
165  /// operate on terminator instructions directly.
166  unsigned getSuccessorIndex() const { return idx; }
167
168  inline bool operator==(const Self& x) const { return idx == x.idx; }
169  inline bool operator!=(const Self& x) const { return !operator==(x); }
170
171  inline reference operator*() const { return Term->getSuccessor(idx); }
172  inline pointer operator->() const { return operator*(); }
173
174  inline Self& operator++() { ++idx; return *this; } // Preincrement
175
176  inline Self operator++(int) { // Postincrement
177    Self tmp = *this; ++*this; return tmp;
178  }
179
180  inline Self& operator--() { --idx; return *this; }  // Predecrement
181  inline Self operator--(int) { // Postdecrement
182    Self tmp = *this; --*this; return tmp;
183  }
184
185  inline bool operator<(const Self& x) const {
186    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
187    return idx < x.idx;
188  }
189
190  inline bool operator<=(const Self& x) const {
191    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
192    return idx <= x.idx;
193  }
194  inline bool operator>=(const Self& x) const {
195    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
196    return idx >= x.idx;
197  }
198
199  inline bool operator>(const Self& x) const {
200    assert(Term == x.Term && "Cannot compare iterators of different blocks!");
201    return idx > x.idx;
202  }
203
204  inline Self& operator+=(int Right) {
205    unsigned new_idx = idx + Right;
206    assert(index_is_valid(new_idx) && "Iterator index out of bound");
207    idx = new_idx;
208    return *this;
209  }
210
211  inline Self operator+(int Right) const {
212    Self tmp = *this;
213    tmp += Right;
214    return tmp;
215  }
216
217  inline Self& operator-=(int Right) {
218    return operator+=(-Right);
219  }
220
221  inline Self operator-(int Right) const {
222    return operator+(-Right);
223  }
224
225  inline int operator-(const Self& x) const {
226    assert(Term == x.Term && "Cannot work on iterators of different blocks!");
227    int distance = idx - x.idx;
228    return distance;
229  }
230
231  inline SuccessorProxy operator[](int offset) {
232   Self tmp = *this;
233   tmp += offset;
234   return SuccessorProxy(tmp);
235  }
236
237  /// Get the source BB of this iterator.
238  inline BB_ *getSource() {
239    assert(Term && "Source not available, if basic block was malformed");
240    return Term->getParent();
241  }
242};
243
244typedef SuccIterator<TerminatorInst*, BasicBlock> succ_iterator;
245typedef SuccIterator<const TerminatorInst*,
246                     const BasicBlock> succ_const_iterator;
247
248inline succ_iterator succ_begin(BasicBlock *BB) {
249  return succ_iterator(BB->getTerminator());
250}
251inline succ_const_iterator succ_begin(const BasicBlock *BB) {
252  return succ_const_iterator(BB->getTerminator());
253}
254inline succ_iterator succ_end(BasicBlock *BB) {
255  return succ_iterator(BB->getTerminator(), true);
256}
257inline succ_const_iterator succ_end(const BasicBlock *BB) {
258  return succ_const_iterator(BB->getTerminator(), true);
259}
260
261template <typename T, typename U> struct isPodLike<SuccIterator<T, U> > {
262  static const bool value = isPodLike<T>::value;
263};
264
265
266
267//===--------------------------------------------------------------------===//
268// GraphTraits specializations for basic block graphs (CFGs)
269//===--------------------------------------------------------------------===//
270
271// Provide specializations of GraphTraits to be able to treat a function as a
272// graph of basic blocks...
273
274template <> struct GraphTraits<BasicBlock*> {
275  typedef BasicBlock NodeType;
276  typedef succ_iterator ChildIteratorType;
277
278  static NodeType *getEntryNode(BasicBlock *BB) { return BB; }
279  static inline ChildIteratorType child_begin(NodeType *N) {
280    return succ_begin(N);
281  }
282  static inline ChildIteratorType child_end(NodeType *N) {
283    return succ_end(N);
284  }
285};
286
287template <> struct GraphTraits<const BasicBlock*> {
288  typedef const BasicBlock NodeType;
289  typedef succ_const_iterator ChildIteratorType;
290
291  static NodeType *getEntryNode(const BasicBlock *BB) { return BB; }
292
293  static inline ChildIteratorType child_begin(NodeType *N) {
294    return succ_begin(N);
295  }
296  static inline ChildIteratorType child_end(NodeType *N) {
297    return succ_end(N);
298  }
299};
300
301// Provide specializations of GraphTraits to be able to treat a function as a
302// graph of basic blocks... and to walk it in inverse order.  Inverse order for
303// a function is considered to be when traversing the predecessor edges of a BB
304// instead of the successor edges.
305//
306template <> struct GraphTraits<Inverse<BasicBlock*> > {
307  typedef BasicBlock NodeType;
308  typedef pred_iterator ChildIteratorType;
309  static NodeType *getEntryNode(Inverse<BasicBlock *> G) { return G.Graph; }
310  static inline ChildIteratorType child_begin(NodeType *N) {
311    return pred_begin(N);
312  }
313  static inline ChildIteratorType child_end(NodeType *N) {
314    return pred_end(N);
315  }
316};
317
318template <> struct GraphTraits<Inverse<const BasicBlock*> > {
319  typedef const BasicBlock NodeType;
320  typedef const_pred_iterator ChildIteratorType;
321  static NodeType *getEntryNode(Inverse<const BasicBlock*> G) {
322    return G.Graph;
323  }
324  static inline ChildIteratorType child_begin(NodeType *N) {
325    return pred_begin(N);
326  }
327  static inline ChildIteratorType child_end(NodeType *N) {
328    return pred_end(N);
329  }
330};
331
332
333
334//===--------------------------------------------------------------------===//
335// GraphTraits specializations for function basic block graphs (CFGs)
336//===--------------------------------------------------------------------===//
337
338// Provide specializations of GraphTraits to be able to treat a function as a
339// graph of basic blocks... these are the same as the basic block iterators,
340// except that the root node is implicitly the first node of the function.
341//
342template <> struct GraphTraits<Function*> : public GraphTraits<BasicBlock*> {
343  static NodeType *getEntryNode(Function *F) { return &F->getEntryBlock(); }
344
345  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
346  typedef Function::iterator nodes_iterator;
347  static nodes_iterator nodes_begin(Function *F) { return F->begin(); }
348  static nodes_iterator nodes_end  (Function *F) { return F->end(); }
349  static size_t         size       (Function *F) { return F->size(); }
350};
351template <> struct GraphTraits<const Function*> :
352  public GraphTraits<const BasicBlock*> {
353  static NodeType *getEntryNode(const Function *F) {return &F->getEntryBlock();}
354
355  // nodes_iterator/begin/end - Allow iteration over all nodes in the graph
356  typedef Function::const_iterator nodes_iterator;
357  static nodes_iterator nodes_begin(const Function *F) { return F->begin(); }
358  static nodes_iterator nodes_end  (const Function *F) { return F->end(); }
359  static size_t         size       (const Function *F) { return F->size(); }
360};
361
362
363// Provide specializations of GraphTraits to be able to treat a function as a
364// graph of basic blocks... and to walk it in inverse order.  Inverse order for
365// a function is considered to be when traversing the predecessor edges of a BB
366// instead of the successor edges.
367//
368template <> struct GraphTraits<Inverse<Function*> > :
369  public GraphTraits<Inverse<BasicBlock*> > {
370  static NodeType *getEntryNode(Inverse<Function*> G) {
371    return &G.Graph->getEntryBlock();
372  }
373};
374template <> struct GraphTraits<Inverse<const Function*> > :
375  public GraphTraits<Inverse<const BasicBlock*> > {
376  static NodeType *getEntryNode(Inverse<const Function *> G) {
377    return &G.Graph->getEntryBlock();
378  }
379};
380
381} // End llvm namespace
382
383#endif
384