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