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
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
use std::collections::{BTreeMap, HashMap};
use crate::{
block::{Block, BlockIterator, Label},
constant::Constant,
context::Context,
error::IrError,
irtype::Type,
metadata::MetadataIndex,
module::Module,
pointer::{Pointer, PointerContent},
value::Value,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct Function(pub generational_arena::Index);
#[doc(hidden)]
pub struct FunctionContent {
pub name: String,
pub arguments: Vec<(String, Value)>,
pub return_type: Type,
pub blocks: Vec<Block>,
pub is_public: bool,
pub selector: Option<[u8; 4]>,
pub local_storage: BTreeMap<String, Pointer>,
next_label_idx: u64,
}
impl Function {
pub fn new(
context: &mut Context,
module: Module,
name: String,
args: Vec<(String, Type, Option<MetadataIndex>)>,
return_type: Type,
selector: Option<[u8; 4]>,
is_public: bool,
) -> Function {
let arguments = args
.into_iter()
.map(|(name, ty, span_md_idx)| (name, Value::new_argument(context, ty, span_md_idx)))
.collect();
let content = FunctionContent {
name,
arguments,
return_type,
blocks: Vec::new(),
is_public,
selector,
local_storage: BTreeMap::new(),
next_label_idx: 0,
};
let func = Function(context.functions.insert(content));
context.modules[module.0].functions.push(func);
let entry_block = Block::new(context, func, Some("entry".to_owned()));
context
.functions
.get_mut(func.0)
.unwrap()
.blocks
.push(entry_block);
func
}
pub fn create_block(&self, context: &mut Context, label: Option<Label>) -> Block {
let block = Block::new(context, *self, label);
let func = context.functions.get_mut(self.0).unwrap();
func.blocks.push(block);
block
}
pub fn create_block_before(
&self,
context: &mut Context,
other: &Block,
label: Option<Label>,
) -> Result<Block, IrError> {
let new_block = Block::new(context, *self, label);
let func = context.functions.get_mut(self.0).unwrap();
func.blocks
.iter()
.position(|block| block == other)
.map(|idx| {
func.blocks.insert(idx, new_block);
new_block
})
.ok_or_else(|| {
let label = &context.blocks[other.0].label;
IrError::MissingBlock(label.clone())
})
}
pub fn create_block_after(
&self,
context: &mut Context,
other: &Block,
label: Option<Label>,
) -> Result<Block, IrError> {
let new_block = Block::new(context, *self, label);
let func = context.functions.get_mut(self.0).unwrap();
func.blocks
.iter()
.position(|block| block == other)
.map(|idx| {
func.blocks.insert(idx + 1, new_block);
new_block
})
.ok_or_else(|| {
let label = &context.blocks[other.0].label;
IrError::MissingBlock(label.clone())
})
}
pub fn get_unique_label(&self, context: &mut Context, hint: Option<String>) -> String {
match hint {
Some(hint) => {
if context.functions[self.0]
.blocks
.iter()
.any(|block| context.blocks[block.0].label == hint)
{
let idx = self.get_next_label_idx(context);
self.get_unique_label(context, Some(format!("{}{}", hint, idx)))
} else {
hint
}
}
None => {
let idx = self.get_next_label_idx(context);
self.get_unique_label(context, Some(format!("block{}", idx)))
}
}
}
fn get_next_label_idx(&self, context: &mut Context) -> u64 {
let func = context.functions.get_mut(self.0).unwrap();
let idx = func.next_label_idx;
func.next_label_idx += 1;
idx
}
pub fn get_name<'a>(&self, context: &'a Context) -> &'a str {
&context.functions[self.0].name
}
pub fn get_entry_block(&self, context: &Context) -> Block {
context.functions[self.0].blocks[0]
}
pub fn has_selector(&self, context: &Context) -> bool {
context.functions[self.0].selector.is_some()
}
pub fn get_selector(&self, context: &Context) -> Option<[u8; 4]> {
context.functions[self.0].selector
}
pub fn get_arg(&self, context: &Context, name: &str) -> Option<Value> {
context.functions[self.0]
.arguments
.iter()
.find_map(|(arg_name, val)| if arg_name == name { Some(val) } else { None })
.copied()
}
pub fn lookup_arg_name<'a>(&self, context: &'a Context, value: &Value) -> Option<&'a String> {
context.functions[self.0]
.arguments
.iter()
.find_map(|(name, arg_val)| if arg_val == value { Some(name) } else { None })
}
pub fn args_iter<'a>(&self, context: &'a Context) -> impl Iterator<Item = &'a (String, Value)> {
context.functions[self.0].arguments.iter()
}
pub fn get_local_ptr(&self, context: &Context, name: &str) -> Option<Pointer> {
context.functions[self.0].local_storage.get(name).copied()
}
pub fn lookup_local_name<'a>(&self, context: &'a Context, ptr: &Pointer) -> Option<&'a String> {
context.functions[self.0]
.local_storage
.iter()
.find_map(|(name, local_ptr)| if local_ptr == ptr { Some(name) } else { None })
}
pub fn new_local_ptr(
&self,
context: &mut Context,
name: String,
local_type: Type,
is_mutable: bool,
initializer: Option<Constant>,
) -> Result<Pointer, IrError> {
let ptr = Pointer::new(context, local_type, is_mutable, initializer);
let func = context.functions.get_mut(self.0).unwrap();
func.local_storage
.insert(name.clone(), ptr)
.map(|_| Err(IrError::FunctionLocalClobbered(func.name.clone(), name)))
.unwrap_or(Ok(ptr))
}
pub fn new_unique_local_ptr(
&self,
context: &mut Context,
name: String,
local_type: Type,
is_mutable: bool,
initializer: Option<Constant>,
) -> Pointer {
let func = &context.functions[self.0];
let new_name = if func.local_storage.contains_key(&name) {
(0..)
.find_map(|n| {
let candidate = format!("{}{}", name, n);
if func.local_storage.contains_key(&candidate) {
None
} else {
Some(candidate)
}
})
.unwrap()
} else {
name
};
self.new_local_ptr(context, new_name, local_type, is_mutable, initializer)
.unwrap()
}
pub fn locals_iter<'a>(
&self,
context: &'a Context,
) -> impl Iterator<Item = (&'a String, &'a Pointer)> {
context.functions[self.0].local_storage.iter()
}
pub fn merge_locals_from(
&self,
context: &mut Context,
other: Function,
) -> Result<HashMap<Pointer, Pointer>, IrError> {
let mut ptr_map = HashMap::new();
let old_ptrs: Vec<(String, Pointer, PointerContent)> = context.functions[other.0]
.local_storage
.iter()
.map(|(name, ptr)| (name.clone(), *ptr, context.pointers[ptr.0].clone()))
.collect();
for (name, old_ptr, old_ptr_content) in old_ptrs {
let new_ptr = self.new_unique_local_ptr(
context,
name.clone(),
old_ptr_content.ty,
old_ptr_content.is_mutable,
old_ptr_content.initializer,
);
ptr_map.insert(old_ptr, new_ptr);
}
Ok(ptr_map)
}
pub fn block_iter(&self, context: &Context) -> BlockIterator {
BlockIterator::new(context, self)
}
pub fn instruction_iter<'a>(
&self,
context: &'a Context,
) -> impl Iterator<Item = (Block, Value)> + 'a {
context.functions[self.0]
.blocks
.iter()
.flat_map(move |block| {
context.blocks[block.0]
.instructions
.iter()
.map(move |ins_val| (*block, *ins_val))
})
}
pub fn replace_value(
&self,
context: &mut Context,
old_val: Value,
new_val: Value,
starting_block: Option<Block>,
) {
let mut block_iter = self.block_iter(context).peekable();
if let Some(ref starting_block) = starting_block {
while block_iter
.next_if(|block| block != starting_block)
.is_some()
{}
}
for block in block_iter {
block.replace_value(context, old_val, new_val);
}
}
}
pub struct FunctionIterator {
functions: Vec<generational_arena::Index>,
next: usize,
}
impl FunctionIterator {
pub fn new(context: &Context, module: &Module) -> FunctionIterator {
FunctionIterator {
functions: context.modules[module.0]
.functions
.iter()
.map(|func| func.0)
.collect(),
next: 0,
}
}
}
impl Iterator for FunctionIterator {
type Item = Function;
fn next(&mut self) -> Option<Function> {
if self.next < self.functions.len() {
let idx = self.next;
self.next += 1;
Some(Function(self.functions[idx]))
} else {
None
}
}
}