Method.h no longer includes BasicBlock.h
[oota-llvm.git] / include / llvm / Analysis / ConstantsScanner.h
1 //==-- llvm/Analysis/ConstantsScanner.h - Iterate over constants -*- C++ -*-==//
2 //
3 // This class implements an iterator to walk through the constants referenced by
4 // a method.  This is used by the Bytecode & Assembly writers to build constant
5 // pools.
6 //
7 //===----------------------------------------------------------------------===//
8
9 #ifndef LLVM_ANALYSIS_CONSTANTSSCANNER_H
10 #define LLVM_ANALYSIS_CONSTANTSSCANNER_H
11
12 #include "llvm/Support/InstIterator.h"
13 #include "llvm/Instruction.h"
14 #include <iterator>
15 class Constant;
16
17 class constant_iterator
18   : public std::forward_iterator<const Constant, ptrdiff_t> {
19   const_inst_iterator InstI;                // Method instruction iterator
20   unsigned OpIdx;                           // Operand index
21
22   typedef constant_iterator _Self;
23
24   inline bool isAtConstant() const {
25     assert(!InstI.atEnd() && OpIdx < InstI->getNumOperands() &&
26            "isAtConstant called with invalid arguments!");
27     return isa<Constant>(InstI->getOperand(OpIdx));
28   }
29
30 public:
31   inline constant_iterator(const Method *M) : InstI(inst_begin(M)), OpIdx(0) {
32     // Advance to first constant... if we are not already at constant or end
33     if (InstI != inst_end(M) &&                            // InstI is valid?
34         (InstI->getNumOperands() == 0 || !isAtConstant())) // Not at constant?
35       operator++();
36   }
37
38   inline constant_iterator(const Method *M, bool)   // end ctor
39     : InstI(inst_end(M)), OpIdx(0) {
40   }
41
42   inline bool operator==(const _Self& x) const { return OpIdx == x.OpIdx && 
43                                                         InstI == x.InstI; }
44   inline bool operator!=(const _Self& x) const { return !operator==(x); }
45
46   inline pointer operator*() const {
47     assert(isAtConstant() && "Dereferenced an iterator at the end!");
48     return cast<Constant>(InstI->getOperand(OpIdx));
49   }
50   inline pointer operator->() const { return operator*(); }
51
52   inline _Self& operator++() {   // Preincrement implementation
53     ++OpIdx;
54     do {
55       unsigned NumOperands = InstI->getNumOperands();
56       while (OpIdx < NumOperands && !isAtConstant()) {
57         ++OpIdx;
58       }
59
60       if (OpIdx < NumOperands) return *this;  // Found a constant!
61       ++InstI;
62       OpIdx = 0;
63     } while (!InstI.atEnd());
64
65     return *this;  // At the end of the method
66   }
67
68   inline _Self operator++(int) { // Postincrement
69     _Self tmp = *this; ++*this; return tmp; 
70   }
71
72   inline bool atEnd() const { return InstI.atEnd(); }
73 };
74
75 inline constant_iterator constant_begin(const Method *M) {
76   return constant_iterator(M);
77 }
78
79 inline constant_iterator constant_end(const Method *M) {
80   return constant_iterator(M, true);
81 }
82
83 #endif