use std::collections::HashMap;
pub struct RegisterAllocator {
register_map: HashMap<u8, String>,
next_temp: usize,
spilled_registers: Vec<u8>,
}
impl RegisterAllocator {
#[inline] pub fn new() -> Self {
Self {
register_map: HashMap::new(),
next_temp: 0usize,
spilled_registers: Vec::new(),
}
}
#[inline] pub fn allocate_register(&mut self, ppc_reg: u8) -> String {
self.register_map
.entry(ppc_reg)
.or_insert_with(|| {
let name: String = format!("r{}", ppc_reg);
self.next_temp = self.next_temp.wrapping_add(1);
name
})
.clone()
}
#[inline] pub fn spill_register(&mut self, reg: u8) -> String {
let stack_var: String = format!("spilled_r{}", reg);
self.spilled_registers.push(reg);
stack_var
}
}
impl Default for RegisterAllocator {
#[inline] fn default() -> Self {
Self::new()
}
}