]> git.lizzy.rs Git - rust.git/blob - src/librustc/session/code_stats.rs
Rollup merge of #40521 - TimNN:panic-free-shift, r=alexcrichton
[rust.git] / src / librustc / session / code_stats.rs
1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use ty::AdtKind;
12 use ty::layout::{Align, Size};
13
14 use rustc_data_structures::fx::{FxHashSet};
15
16 use std::cmp::{self, Ordering};
17
18 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
19 pub struct VariantInfo {
20     pub name: Option<String>,
21     pub kind: SizeKind,
22     pub size: u64,
23     pub align: u64,
24     pub fields: Vec<FieldInfo>,
25 }
26
27 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
28 pub enum SizeKind {
29     Exact,
30     Min,
31 }
32
33 #[derive(Clone, PartialEq, Eq, Hash, Debug)]
34 pub struct FieldInfo {
35     pub name: String,
36     pub offset: u64,
37     pub size: u64,
38     pub align: u64,
39 }
40
41 impl From<AdtKind> for DataTypeKind {
42     fn from(kind: AdtKind) -> Self {
43         match kind {
44             AdtKind::Struct => DataTypeKind::Struct,
45             AdtKind::Enum => DataTypeKind::Enum,
46             AdtKind::Union => DataTypeKind::Union,
47         }
48     }
49 }
50
51 #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)]
52 pub enum DataTypeKind {
53     Struct,
54     Union,
55     Enum,
56     Closure,
57 }
58
59 #[derive(PartialEq, Eq, Hash, Debug)]
60 pub struct TypeSizeInfo {
61     pub kind: DataTypeKind,
62     pub type_description: String,
63     pub align: u64,
64     pub overall_size: u64,
65     pub opt_discr_size: Option<u64>,
66     pub variants: Vec<VariantInfo>,
67 }
68
69 #[derive(PartialEq, Eq, Debug)]
70 pub struct CodeStats {
71     type_sizes: FxHashSet<TypeSizeInfo>,
72 }
73
74 impl CodeStats {
75     pub fn new() -> Self { CodeStats { type_sizes: FxHashSet() } }
76
77     pub fn record_type_size<S: ToString>(&mut self,
78                                          kind: DataTypeKind,
79                                          type_desc: S,
80                                          align: Align,
81                                          overall_size: Size,
82                                          opt_discr_size: Option<Size>,
83                                          variants: Vec<VariantInfo>) {
84         let info = TypeSizeInfo {
85             kind: kind,
86             type_description: type_desc.to_string(),
87             align: align.abi(),
88             overall_size: overall_size.bytes(),
89             opt_discr_size: opt_discr_size.map(|s| s.bytes()),
90             variants: variants,
91         };
92         self.type_sizes.insert(info);
93     }
94
95     pub fn print_type_sizes(&self) {
96         let mut sorted: Vec<_> = self.type_sizes.iter().collect();
97
98         // Primary sort: large-to-small.
99         // Secondary sort: description (dictionary order)
100         sorted.sort_by(|info1, info2| {
101             // (reversing cmp order to get large-to-small ordering)
102             match info2.overall_size.cmp(&info1.overall_size) {
103                 Ordering::Equal => info1.type_description.cmp(&info2.type_description),
104                 other => other,
105             }
106         });
107
108         for info in &sorted {
109             println!("print-type-size type: `{}`: {} bytes, alignment: {} bytes",
110                      info.type_description, info.overall_size, info.align);
111             let indent = "    ";
112
113             let discr_size = if let Some(discr_size) = info.opt_discr_size {
114                 println!("print-type-size {}discriminant: {} bytes",
115                          indent, discr_size);
116                 discr_size
117             } else {
118                 0
119             };
120
121             // We start this at discr_size (rather than 0) because
122             // things like C-enums do not have variants but we still
123             // want the max_variant_size at the end of the loop below
124             // to reflect the presence of the discriminant.
125             let mut max_variant_size = discr_size;
126
127             let struct_like = match info.kind {
128                 DataTypeKind::Struct | DataTypeKind::Closure => true,
129                 DataTypeKind::Enum | DataTypeKind::Union => false,
130             };
131             for (i, variant_info) in info.variants.iter().enumerate() {
132                 let VariantInfo { ref name, kind: _, align: _, size, ref fields } = *variant_info;
133                 let indent = if !struct_like {
134                     let name = match name.as_ref() {
135                         Some(name) => format!("{}", name),
136                         None => format!("{}", i),
137                     };
138                     println!("print-type-size {}variant `{}`: {} bytes",
139                              indent, name, size - discr_size);
140                     "        "
141                 } else {
142                     assert!(i < 1);
143                     "    "
144                 };
145                 max_variant_size = cmp::max(max_variant_size, size);
146
147                 let mut min_offset = discr_size;
148
149                 // We want to print fields by increasing offset.
150                 let mut fields = fields.clone();
151                 fields.sort_by_key(|f| f.offset);
152
153                 for field in fields.iter() {
154                     let FieldInfo { ref name, offset, size, align } = *field;
155
156                     // Include field alignment in output only if it caused padding injection
157                     if min_offset != offset {
158                         let pad = offset - min_offset;
159                         println!("print-type-size {}padding: {} bytes",
160                                  indent, pad);
161                         println!("print-type-size {}field `.{}`: {} bytes, alignment: {} bytes",
162                                  indent, name, size, align);
163                     } else {
164                         println!("print-type-size {}field `.{}`: {} bytes",
165                                  indent, name, size);
166                     }
167
168                     min_offset = offset + size;
169                 }
170             }
171
172             assert!(max_variant_size <= info.overall_size,
173                     "max_variant_size {} !<= {} overall_size",
174                     max_variant_size, info.overall_size);
175             if max_variant_size < info.overall_size {
176                 println!("print-type-size {}end padding: {} bytes",
177                          indent, info.overall_size - max_variant_size);
178             }
179         }
180     }
181 }