diff --git a/zjit/src/distribution.rs b/zjit/src/distribution.rs index 1d8149dbd35fe2..472f1ce163a71b 100644 --- a/zjit/src/distribution.rs +++ b/zjit/src/distribution.rs @@ -2,14 +2,21 @@ use crate::options::NumProfiles; +#[derive(Debug, Clone)] +enum Buckets { + Empty, + Single(T), + Multiple(Vec), +} + /// This implementation was inspired by the type feedback module from Google's S6, which was /// written in C++ for use with Python. This is a new implementation in Rust created for use with /// Ruby instead of Python. #[derive(Debug, Clone)] pub struct Distribution { - /// buckets and counts have the same length - /// `buckets[0]` is always the most common item - buckets: [T; N], + /// Store the common monomorphic case inline. Allocate only for polymorphic profiles. + buckets: Buckets, + /// `counts[0]` corresponds to the most common item. counts: [NumProfiles; N], /// if there is no more room, increment the fallback other: NumProfiles, @@ -18,40 +25,113 @@ pub struct Distribution { impl Distribution { pub fn new() -> Self { - Self { buckets: [Default::default(); N], counts: [0; N], other: 0 } + Self { + buckets: Buckets::Empty, + counts: [0; N], + other: 0, + } } pub fn observe(&mut self, item: T) { - for (bucket, count) in self.buckets.iter_mut().zip(self.counts.iter_mut()) { - if *bucket == item || *count == 0 { - *bucket = item; - *count = count.saturating_add(1); - // Keep the most frequent item at the front - self.bubble_up(); + if matches!(&self.buckets, Buckets::Empty) { + if N == 0 { + self.other = self.other.saturating_add(1); + } else { + self.buckets = Buckets::Single(item); + self.counts[0] = 1; + } + return; + } + + if let Buckets::Single(existing) = &self.buckets { + let existing = *existing; + if existing == item { + self.counts[0] = self.counts[0].saturating_add(1); + } else if N == 1 { + self.other = self.other.saturating_add(1); return; + } else { + let buckets = vec![existing, item]; + self.buckets = Buckets::Multiple(buckets); + self.counts[1] = 1; } + self.bubble_up(); + return; } - self.other = self.other.saturating_add(1); + + let Buckets::Multiple(buckets) = &self.buckets else { + unreachable!("empty distributions are handled above"); + }; + let existing_index = buckets.iter().position(|&bucket| bucket == item); + if let Some(index) = existing_index { + self.counts[index] = self.counts[index].saturating_add(1); + } else if buckets.len() == N { + self.other = self.other.saturating_add(1); + return; + } else { + let index = buckets.len(); + let Buckets::Multiple(buckets) = &mut self.buckets else { + unreachable!() + }; + buckets.reserve_exact(1); + buckets.push(item); + self.counts[index] = 1; + } + + // Keep the most frequent item at the front. + self.bubble_up(); } /// Keep the highest counted bucket at index 0 fn bubble_up(&mut self) { - if N == 0 { return; } - let max_index = self.counts.into_iter().enumerate().max_by_key(|(_, val)| *val).unwrap().0; + let bucket_count = match &self.buckets { + Buckets::Empty => 0, + Buckets::Single(_) => 1, + Buckets::Multiple(buckets) => buckets.len(), + }; + if bucket_count < 2 { + return; + } + + let max_index = self.counts[..bucket_count] + .iter() + .enumerate() + .max_by_key(|(_, val)| **val) + .unwrap() + .0; if max_index != 0 { self.counts.swap(0, max_index); - self.buckets.swap(0, max_index); + let Buckets::Multiple(buckets) = &mut self.buckets else { + unreachable!() + }; + buckets.swap(0, max_index); + } + } + + fn len(&self) -> usize { + match &self.buckets { + Buckets::Empty => 0, + Buckets::Single(_) => 1, + Buckets::Multiple(buckets) => buckets.len(), } } pub fn each_item(&self) -> impl Iterator + '_ { - self.buckets.iter().zip(self.counts.iter()) - .filter_map(|(&bucket, &count)| if count > 0 { Some(bucket) } else { None }) + let buckets: &[T] = match &self.buckets { + Buckets::Empty => &[], + Buckets::Single(bucket) => std::slice::from_ref(bucket), + Buckets::Multiple(buckets) => buckets, + }; + buckets.iter().copied() } pub fn each_item_mut(&mut self) -> impl Iterator + '_ { - self.buckets.iter_mut().zip(self.counts.iter()) - .filter_map(|(bucket, &count)| if count > 0 { Some(bucket) } else { None }) + let buckets: &mut [T] = match &mut self.buckets { + Buckets::Empty => &mut [], + Buckets::Single(bucket) => std::slice::from_mut(bucket), + Buckets::Multiple(buckets) => buckets, + }; + buckets.iter_mut() } } @@ -82,7 +162,10 @@ const SKEW_THRESHOLD: f64 = 0.75; impl DistributionSummary { pub fn empty() -> Self { - Self { kind: DistributionKind::Empty, buckets: [Default::default(); N] } + Self { + kind: DistributionKind::Empty, + buckets: [Default::default(); N], + } } pub fn new(dist: &Distribution) -> Self { @@ -93,27 +176,32 @@ impl Distributi assert!(first_count >= count, "First count should be the largest"); } } - let num_seen = dist.counts.iter().map(|&c| usize::from(c)).sum::() + usize::from(dist.other); + let num_seen = + dist.counts.iter().map(|&c| usize::from(c)).sum::() + usize::from(dist.other); let kind = if dist.other == 0 { // Seen <= N types total - if dist.counts[0] == 0 { + if dist.len() == 0 { DistributionKind::Empty - } else if dist.counts[1] == 0 { + } else if dist.len() == 1 { DistributionKind::Monomorphic - } else if (dist.counts[0] as f64)/(num_seen as f64) >= SKEW_THRESHOLD { + } else if (dist.counts[0] as f64) / (num_seen as f64) >= SKEW_THRESHOLD { DistributionKind::SkewedPolymorphic } else { DistributionKind::Polymorphic } } else { // Seen > N types total; considered megamorphic - if (dist.counts[0] as f64)/(num_seen as f64) >= SKEW_THRESHOLD { + if (dist.counts[0] as f64) / (num_seen as f64) >= SKEW_THRESHOLD { DistributionKind::SkewedMegamorphic } else { DistributionKind::Megamorphic } }; - Self { kind, buckets: dist.buckets } + let mut buckets = [Default::default(); N]; + for (bucket, item) in buckets.iter_mut().zip(dist.each_item()) { + *bucket = item; + } + Self { kind, buckets } } pub fn is_monomorphic(&self) -> bool { @@ -153,6 +241,7 @@ mod distribution_tests { #[test] fn start_empty() { let dist = Distribution::::new(); + assert_eq!(dist.len(), 0); assert_eq!(dist.other, 0); assert!(dist.counts.iter().all(|&b| b == 0)); } @@ -161,9 +250,10 @@ mod distribution_tests { fn observe_adds_record() { let mut dist = Distribution::::new(); dist.observe(10); - assert_eq!(dist.buckets[0], 10); + assert_eq!(dist.each_item().next(), Some(10)); assert_eq!(dist.counts[0], 1); assert_eq!(dist.other, 0); + assert!(matches!(dist.buckets, Buckets::Single(10))); } #[test] @@ -171,7 +261,7 @@ mod distribution_tests { let mut dist = Distribution::::new(); dist.observe(10); dist.observe(10); - assert_eq!(dist.buckets[0], 10); + assert_eq!(dist.each_item().next(), Some(10)); assert_eq!(dist.counts[0], 2); assert_eq!(dist.other, 0); } @@ -184,18 +274,55 @@ mod distribution_tests { dist.observe(11); dist.observe(11); dist.observe(11); - assert_eq!(dist.buckets[0], 11); + assert_eq!(dist.each_item().next(), Some(11)); assert_eq!(dist.counts[0], 3); - assert_eq!(dist.buckets[1], 10); + assert_eq!(dist.each_item().nth(1), Some(10)); assert_eq!(dist.counts[1], 2); assert_eq!(dist.other, 0); + assert!(matches!(dist.buckets, Buckets::Multiple(_))); + } + + #[test] + fn tied_counts_keep_the_latest_item_first() { + let mut dist = Distribution::::new(); + dist.observe(10); + dist.observe(11); + assert_eq!(dist.each_item().collect::>(), vec![11, 10]); + assert_eq!(dist.counts[..2], [1, 1]); + } + + #[test] + fn one_bucket_keeps_tracking_its_item_after_overflow() { + let mut dist = Distribution::::new(); + dist.observe(10); + dist.observe(20); + dist.observe(10); + assert_eq!(dist.each_item().collect::>(), vec![10]); + assert_eq!(dist.counts, [2]); + assert_eq!(dist.other, 1); + } + + #[test] + fn each_item_mut_visits_inline_and_heap_buckets() { + let mut dist = Distribution::::new(); + dist.observe(10); + for item in dist.each_item_mut() { + *item += 1; + } + assert_eq!(dist.each_item().collect::>(), vec![11]); + + dist.observe(20); + for item in dist.each_item_mut() { + *item += 1; + } + assert_eq!(dist.each_item().collect::>(), vec![21, 12]); } #[test] fn observe_with_max_increments_other() { let mut dist = Distribution::::new(); dist.observe(10); - assert!(dist.buckets.is_empty()); + assert_eq!(dist.len(), 0); assert!(dist.counts.is_empty()); assert_eq!(dist.other, 1); } @@ -215,6 +342,7 @@ mod distribution_tests { let summary = DistributionSummary::new(&dist); assert_eq!(summary.kind, DistributionKind::Monomorphic); assert_eq!(summary.buckets[0], 10); + assert_eq!(summary.buckets(), &[10, 0, 0, 0]); } #[test] @@ -283,4 +411,12 @@ mod distribution_tests { assert_eq!(summary.kind, DistributionKind::SkewedMegamorphic); assert_eq!(summary.buckets[0], 12); } + + #[test] + fn distribution_header_is_smaller_than_fixed_bucket_storage() { + type ProfileType = [usize; 2]; + let old_fixed_size = + std::mem::size_of::() * 8 + std::mem::size_of::() * 9; + assert!(std::mem::size_of::>() < old_fixed_size,); + } }