1 //==- llvm/Analysis/ConstantsScanner.h - Iterate over constants -*- 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 class implements an iterator to walk through the constants referenced by
11 // a method. This is used by the Bitcode & Assembly writers to build constant
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_ANALYSIS_CONSTANTSSCANNER_H
17 #define LLVM_ANALYSIS_CONSTANTSSCANNER_H
19 #include "llvm/IR/InstIterator.h"
25 class constant_iterator : public std::iterator<std::forward_iterator_tag,
26 const Constant, ptrdiff_t> {
27 const_inst_iterator InstI; // Method instruction iterator
28 unsigned OpIdx; // Operand index
30 bool isAtConstant() const {
31 assert(!InstI.atEnd() && OpIdx < InstI->getNumOperands() &&
32 "isAtConstant called with invalid arguments!");
33 return isa<Constant>(InstI->getOperand(OpIdx));
37 constant_iterator(const Function *F) : InstI(inst_begin(F)), OpIdx(0) {
38 // Advance to first constant... if we are not already at constant or end
39 if (InstI != inst_end(F) && // InstI is valid?
40 (InstI->getNumOperands() == 0 || !isAtConstant())) // Not at constant?
44 constant_iterator(const Function *F, bool) // end ctor
48 bool operator==(const constant_iterator &x) const {
49 return OpIdx == x.OpIdx && InstI == x.InstI;
51 bool operator!=(const constant_iterator &x) const { return !(*this == x); }
53 pointer operator*() const {
54 assert(isAtConstant() && "Dereferenced an iterator at the end!");
55 return cast<Constant>(InstI->getOperand(OpIdx));
57 pointer operator->() const { return **this; }
59 constant_iterator &operator++() { // Preincrement implementation
62 unsigned NumOperands = InstI->getNumOperands();
63 while (OpIdx < NumOperands && !isAtConstant()) {
67 if (OpIdx < NumOperands) return *this; // Found a constant!
70 } while (!InstI.atEnd());
72 return *this; // At the end of the method
75 onstant_iterator operator++(int) { // Postincrement
76 constant_iterator tmp = *this;
81 bool atEnd() const { return InstI.atEnd(); }
84 inline constant_iterator constant_begin(const Function *F) {
85 return constant_iterator(F);
88 inline constant_iterator constant_end(const Function *F) {
89 return constant_iterator(F, true);
92 } // End llvm namespace