1 use crate::bitset::BitSet;
2 use crate::ir;
3 use crate::isa::TargetIsa;
4 use alloc::vec::Vec;
5 
6 type Num = u32;
7 const NUM_BITS: usize = core::mem::size_of::<Num>() * 8;
8 
9 /// A stack map is a bitmap with one bit per machine word on the stack. Stack
10 /// maps are created at `safepoint` instructions and record all live reference
11 /// values that are on the stack. All slot kinds, except `OutgoingArg` are
12 /// captured in a stack map. The `OutgoingArg`'s will be captured in the callee
13 /// function as `IncomingArg`'s.
14 ///
15 /// The first value in the bitmap is of the lowest addressed slot on the stack.
16 /// As all stacks in Isa's supported by Cranelift grow down, this means that
17 /// first value is of the top of the stack and values proceed down the stack.
18 #[derive(Clone, Debug)]
19 pub struct Stackmap {
20     bitmap: Vec<BitSet<Num>>,
21     mapped_words: u32,
22 }
23 
24 impl Stackmap {
25     /// Create a stackmap based on where references are located on a function's stack.
from_values( args: &[ir::entities::Value], func: &ir::Function, isa: &dyn TargetIsa, ) -> Self26     pub fn from_values(
27         args: &[ir::entities::Value],
28         func: &ir::Function,
29         isa: &dyn TargetIsa,
30     ) -> Self {
31         let loc = &func.locations;
32         let mut live_ref_in_stack_slot = crate::HashSet::new();
33         // References can be in registers, and live registers values are pushed onto the stack before calls and traps.
34         // TODO: Implement register maps. If a register containing a reference is spilled and reused after a safepoint,
35         // it could contain a stale reference value if the garbage collector relocated the value.
36         for val in args {
37             if let Some(value_loc) = loc.get(*val) {
38                 match *value_loc {
39                     ir::ValueLoc::Stack(stack_slot) => {
40                         live_ref_in_stack_slot.insert(stack_slot);
41                     }
42                     _ => {}
43                 }
44             }
45         }
46 
47         let stack = &func.stack_slots;
48         let info = func.stack_slots.layout_info.unwrap();
49 
50         // Refer to the doc comment for `Stackmap` above to understand the
51         // bitmap representation used here.
52         let map_size = (info.frame_size + info.inbound_args_size) as usize;
53         let word_size = isa.pointer_bytes() as usize;
54         let num_words = map_size / word_size;
55 
56         let mut vec = alloc::vec::Vec::with_capacity(num_words);
57         vec.resize(num_words, false);
58 
59         for (ss, ssd) in stack.iter() {
60             if !live_ref_in_stack_slot.contains(&ss)
61                 || ssd.kind == ir::stackslot::StackSlotKind::OutgoingArg
62             {
63                 continue;
64             }
65 
66             debug_assert!(ssd.size as usize == word_size);
67             let bytes_from_bottom = info.frame_size as i32 + ssd.offset.unwrap();
68             let words_from_bottom = (bytes_from_bottom as usize) / word_size;
69             vec[words_from_bottom] = true;
70         }
71 
72         Self::from_slice(&vec)
73     }
74 
75     /// Create a vec of Bitsets from a slice of bools.
from_slice(vec: &[bool]) -> Self76     pub fn from_slice(vec: &[bool]) -> Self {
77         let len = vec.len();
78         let num_word = len / NUM_BITS + (len % NUM_BITS != 0) as usize;
79         let mut bitmap = Vec::with_capacity(num_word);
80 
81         for segment in vec.chunks(NUM_BITS) {
82             let mut curr_word = 0;
83             for (i, set) in segment.iter().enumerate() {
84                 if *set {
85                     curr_word |= 1 << i;
86                 }
87             }
88             bitmap.push(BitSet(curr_word));
89         }
90         Self {
91             mapped_words: len as u32,
92             bitmap,
93         }
94     }
95 
96     /// Returns a specified bit.
get_bit(&self, bit_index: usize) -> bool97     pub fn get_bit(&self, bit_index: usize) -> bool {
98         assert!(bit_index < NUM_BITS * self.bitmap.len());
99         let word_index = bit_index / NUM_BITS;
100         let word_offset = (bit_index % NUM_BITS) as u8;
101         self.bitmap[word_index].contains(word_offset)
102     }
103 
104     /// Returns the raw bitmap that represents this stack map.
as_slice(&self) -> &[BitSet<u32>]105     pub fn as_slice(&self) -> &[BitSet<u32>] {
106         &self.bitmap
107     }
108 
109     /// Returns the number of words represented by this stack map.
mapped_words(&self) -> u32110     pub fn mapped_words(&self) -> u32 {
111         self.mapped_words
112     }
113 }
114 
115 #[cfg(test)]
116 mod tests {
117     use super::*;
118 
119     #[test]
stackmaps()120     fn stackmaps() {
121         let vec: Vec<bool> = Vec::new();
122         assert!(Stackmap::from_slice(&vec).bitmap.is_empty());
123 
124         let mut vec: [bool; NUM_BITS] = Default::default();
125         let set_true_idx = [5, 7, 24, 31];
126 
127         for &idx in &set_true_idx {
128             vec[idx] = true;
129         }
130 
131         let mut vec = vec.to_vec();
132         assert_eq!(
133             vec![BitSet::<Num>(2164261024)],
134             Stackmap::from_slice(&vec).bitmap
135         );
136 
137         vec.push(false);
138         vec.push(true);
139         let res = Stackmap::from_slice(&vec);
140         assert_eq!(
141             vec![BitSet::<Num>(2164261024), BitSet::<Num>(2)],
142             res.bitmap
143         );
144 
145         assert!(res.get_bit(5));
146         assert!(res.get_bit(31));
147         assert!(res.get_bit(33));
148         assert!(!res.get_bit(1));
149     }
150 }
151