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