1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
use lib::llvm::{llvm, UseRef, ValueRef};
use middle::trans::basic_block::BasicBlock;
use middle::trans::common::Block;
use libc::c_uint;
pub struct Value(pub ValueRef);
macro_rules! opt_val ( ($e:expr) => (
unsafe {
match $e {
p if p.is_not_null() => Some(Value(p)),
_ => None
}
}
))
impl Value {
pub fn get(&self) -> ValueRef {
let Value(v) = *self; v
}
pub fn get_parent(self) -> Option<BasicBlock> {
unsafe {
match llvm::LLVMGetInstructionParent(self.get()) {
p if p.is_not_null() => Some(BasicBlock(p)),
_ => None
}
}
}
pub fn erase_from_parent(self) {
unsafe {
llvm::LLVMInstructionEraseFromParent(self.get());
}
}
pub fn get_dominating_store(self, bcx: &Block) -> Option<Value> {
match self.get_single_user().and_then(|user| user.as_store_inst()) {
Some(store) => {
store.get_parent().and_then(|store_bb| {
let mut bb = BasicBlock(bcx.llbb);
let mut ret = Some(store);
while bb.get() != store_bb.get() {
match bb.get_single_predecessor() {
Some(pred) => bb = pred,
None => { ret = None; break }
}
}
ret
})
}
_ => None
}
}
pub fn get_first_use(self) -> Option<Use> {
unsafe {
match llvm::LLVMGetFirstUse(self.get()) {
u if u.is_not_null() => Some(Use(u)),
_ => None
}
}
}
pub fn has_no_uses(self) -> bool {
self.get_first_use().is_none()
}
pub fn get_single_user(self) -> Option<Value> {
let mut iter = self.user_iter();
match (iter.next(), iter.next()) {
(Some(first), None) => Some(first),
_ => None
}
}
pub fn user_iter(self) -> Users {
Users {
next: self.get_first_use()
}
}
pub fn get_operand(self, i: uint) -> Option<Value> {
opt_val!(llvm::LLVMGetOperand(self.get(), i as c_uint))
}
pub fn as_store_inst(self) -> Option<Value> {
opt_val!(llvm::LLVMIsAStoreInst(self.get()))
}
pub fn is_a_terminator_inst(self) -> bool {
unsafe {
llvm::LLVMIsATerminatorInst(self.get()).is_not_null()
}
}
}
pub struct Use(UseRef);
impl Use {
pub fn get(&self) -> UseRef {
let Use(v) = *self; v
}
pub fn get_user(self) -> Value {
unsafe {
Value(llvm::LLVMGetUser(self.get()))
}
}
pub fn get_next_use(self) -> Option<Use> {
unsafe {
match llvm::LLVMGetNextUse(self.get()) {
u if u.is_not_null() => Some(Use(u)),
_ => None
}
}
}
}
pub struct Users {
next: Option<Use>
}
impl Iterator<Value> for Users {
fn next(&mut self) -> Option<Value> {
let current = self.next;
self.next = current.and_then(|u| u.get_next_use());
current.map(|u| u.get_user())
}
}