]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_session/src/code_stats.rs
Auto merge of #97870 - eggyal:inplace_fold_spec, r=wesleywiser
[rust.git] / compiler / rustc_session / src / code_stats.rs
1 use rustc_data_structures::fx::FxHashSet;
2 use rustc_data_structures::sync::Lock;
3 use rustc_span::Symbol;
4 use rustc_target::abi::{Align, Size};
5 use std::cmp::{self, Ordering};
6
7 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
8 pub struct VariantInfo {
9     pub name: Option<Symbol>,
10     pub kind: SizeKind,
11     pub size: u64,
12     pub align: u64,
13     pub fields: Vec<FieldInfo>,
14 }
15
16 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
17 pub enum SizeKind {
18     Exact,
19     Min,
20 }
21
22 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
23 pub struct FieldInfo {
24     pub name: Symbol,
25     pub offset: u64,
26     pub size: u64,
27     pub align: u64,
28 }
29
30 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
31 pub enum DataTypeKind {
32     Struct,
33     Union,
34     Enum,
35     Closure,
36 }
37
38 #[derive(PartialEq, Eq, Hash, Debug)]
39 pub struct TypeSizeInfo {
40     pub kind: DataTypeKind,
41     pub type_description: String,
42     pub align: u64,
43     pub overall_size: u64,
44     pub packed: bool,
45     pub opt_discr_size: Option<u64>,
46     pub variants: Vec<VariantInfo>,
47 }
48
49 #[derive(Default)]
50 pub struct CodeStats {
51     type_sizes: Lock<FxHashSet<TypeSizeInfo>>,
52 }
53
54 impl CodeStats {
55     pub fn record_type_size<S: ToString>(
56         &self,
57         kind: DataTypeKind,
58         type_desc: S,
59         align: Align,
60         overall_size: Size,
61         packed: bool,
62         opt_discr_size: Option<Size>,
63         mut variants: Vec<VariantInfo>,
64     ) {
65         // Sort variants so the largest ones are shown first. A stable sort is
66         // used here so that source code order is preserved for all variants
67         // that have the same size.
68         variants.sort_by(|info1, info2| info2.size.cmp(&info1.size));
69         let info = TypeSizeInfo {
70             kind,
71             type_description: type_desc.to_string(),
72             align: align.bytes(),
73             overall_size: overall_size.bytes(),
74             packed,
75             opt_discr_size: opt_discr_size.map(|s| s.bytes()),
76             variants,
77         };
78         self.type_sizes.borrow_mut().insert(info);
79     }
80
81     pub fn print_type_sizes(&self) {
82         let type_sizes = self.type_sizes.borrow();
83         let mut sorted: Vec<_> = type_sizes.iter().collect();
84
85         // Primary sort: large-to-small.
86         // Secondary sort: description (dictionary order)
87         sorted.sort_by(|info1, info2| {
88             // (reversing cmp order to get large-to-small ordering)
89             match info2.overall_size.cmp(&info1.overall_size) {
90                 Ordering::Equal => info1.type_description.cmp(&info2.type_description),
91                 other => other,
92             }
93         });
94
95         for info in sorted {
96             let TypeSizeInfo { type_description, overall_size, align, kind, variants, .. } = info;
97             println!(
98                 "print-type-size type: `{type_description}`: {overall_size} bytes, alignment: {align} bytes"
99             );
100             let indent = "    ";
101
102             let discr_size = if let Some(discr_size) = info.opt_discr_size {
103                 println!("print-type-size {indent}discriminant: {discr_size} bytes");
104                 discr_size
105             } else {
106                 0
107             };
108
109             // We start this at discr_size (rather than 0) because
110             // things like C-enums do not have variants but we still
111             // want the max_variant_size at the end of the loop below
112             // to reflect the presence of the discriminant.
113             let mut max_variant_size = discr_size;
114
115             let struct_like = match kind {
116                 DataTypeKind::Struct | DataTypeKind::Closure => true,
117                 DataTypeKind::Enum | DataTypeKind::Union => false,
118             };
119             for (i, variant_info) in variants.into_iter().enumerate() {
120                 let VariantInfo { ref name, kind: _, align: _, size, ref fields } = *variant_info;
121                 let indent = if !struct_like {
122                     let name = match name.as_ref() {
123                         Some(name) => name.to_string(),
124                         None => i.to_string(),
125                     };
126                     println!(
127                         "print-type-size {indent}variant `{name}`: {diff} bytes",
128                         diff = size - discr_size
129                     );
130                     "        "
131                 } else {
132                     assert!(i < 1);
133                     "    "
134                 };
135                 max_variant_size = cmp::max(max_variant_size, size);
136
137                 let mut min_offset = discr_size;
138
139                 // We want to print fields by increasing offset. We also want
140                 // zero-sized fields before non-zero-sized fields, otherwise
141                 // the loop below goes wrong; hence the `f.size` in the sort
142                 // key.
143                 let mut fields = fields.clone();
144                 fields.sort_by_key(|f| (f.offset, f.size));
145
146                 for field in fields {
147                     let FieldInfo { ref name, offset, size, align } = field;
148
149                     if offset > min_offset {
150                         let pad = offset - min_offset;
151                         println!("print-type-size {indent}padding: {pad} bytes");
152                     }
153
154                     if offset < min_offset {
155                         // If this happens it's probably a union.
156                         println!(
157                             "print-type-size {indent}field `.{name}`: {size} bytes, \
158                                   offset: {offset} bytes, \
159                                   alignment: {align} bytes"
160                         );
161                     } else if info.packed || offset == min_offset {
162                         println!("print-type-size {indent}field `.{name}`: {size} bytes");
163                     } else {
164                         // Include field alignment in output only if it caused padding injection
165                         println!(
166                             "print-type-size {indent}field `.{name}`: {size} bytes, \
167                                   alignment: {align} bytes"
168                         );
169                     }
170
171                     min_offset = offset + size;
172                 }
173             }
174
175             match overall_size.checked_sub(max_variant_size) {
176                 None => panic!("max_variant_size {max_variant_size} > {overall_size} overall_size"),
177                 Some(diff @ 1..) => println!("print-type-size {indent}end padding: {diff} bytes"),
178                 Some(0) => {}
179             }
180         }
181     }
182 }