Skip to content

Commit ebeee0e

Browse files
committed
Auto merge of #38092 - pnkfelix:mir-stats, r=nikomatsakis
Adds `-Z mir-stats`, which is similar to `-Z hir-stats`. Adds `-Z mir-stats`, which is similar to `-Z hir-stats`. Some notes: * This code attempts to present the breakdown of each variant for every enum in the MIR. This is meant to guide decisions about how to revise representations e.g. when to box payloads for rare variants to shrink the size of the enum overall. * I left out the "Total:" line that hir-stats presents, because this implementation uses the MIR Visitor infrastructure, and the memory usage of structures directly embedded in other structures (e.g. the `func: Operand` in a `TerminatorKind:Call`) is not distinguished from similar structures allocated in a `Vec` (e.g. the `args: Vec<Operand>` in a `TerminatorKind::Call`). This means that a naive summation of all the accumulated sizes is misleading, because it will double-count the contribution of the `Operand` of the `func` as well as the size of the whole `TerminatorKind`. * I did consider abandoning the MIR Visitor and instead hand-coding a traversal that distinguished embedded storage from indirect storage. But such code would be fragile; better to just require people to take care when interpreting the presented results. * This traverses the `mir.promoted` rvalues to capture stats for MIR stored there, even though the MIR visitor super_mir method does not do so. (I did not observe any promoted mir being newly traversed when compiling the rustc crate, however.) * It might be nice to try to unify this code with hir-stats. Then again, the reporting portion is the only common code (I think), and it is small compared to the visitors in hir-stats and mir-stats.
2 parents 341f084 + ff1ba6a commit ebeee0e

File tree

4 files changed

+335
-1
lines changed

4 files changed

+335
-1
lines changed

src/librustc/session/config.rs

+2
Original file line numberDiff line numberDiff line change
@@ -926,6 +926,8 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
926926
"print some performance-related statistics"),
927927
hir_stats: bool = (false, parse_bool, [UNTRACKED],
928928
"print some statistics about AST and HIR"),
929+
mir_stats: bool = (false, parse_bool, [UNTRACKED],
930+
"print some statistics about MIR"),
929931
}
930932

931933
pub fn default_lib_output() -> CrateType {

src/librustc_driver/driver.rs

+13-1
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ use rustc_privacy;
3737
use rustc_plugin::registry::Registry;
3838
use rustc_plugin as plugin;
3939
use rustc_passes::{ast_validation, no_asm, loops, consts, rvalues,
40-
static_recursion, hir_stats};
40+
static_recursion, hir_stats, mir_stats};
4141
use rustc_const_eval::check_match;
4242
use super::Compilation;
4343

@@ -932,6 +932,10 @@ pub fn phase_3_run_analysis_passes<'tcx, F, R>(sess: &'tcx Session,
932932
"MIR dump",
933933
|| mir::mir_map::build_mir_for_crate(tcx));
934934

935+
if sess.opts.debugging_opts.mir_stats {
936+
mir_stats::print_mir_stats(tcx, "PRE CLEANUP MIR STATS");
937+
}
938+
935939
time(time_passes, "MIR cleanup and validation", || {
936940
let mut passes = sess.mir_passes.borrow_mut();
937941
// Push all the built-in validation passes.
@@ -1000,6 +1004,10 @@ pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
10001004
"resolving dependency formats",
10011005
|| dependency_format::calculate(&tcx.sess));
10021006

1007+
if tcx.sess.opts.debugging_opts.mir_stats {
1008+
mir_stats::print_mir_stats(tcx, "PRE OPTIMISATION MIR STATS");
1009+
}
1010+
10031011
// Run the passes that transform the MIR into a more suitable form for translation to LLVM
10041012
// code.
10051013
time(time_passes, "MIR optimisations", || {
@@ -1028,6 +1036,10 @@ pub fn phase_4_translate_to_llvm<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
10281036
passes.run_passes(tcx);
10291037
});
10301038

1039+
if tcx.sess.opts.debugging_opts.mir_stats {
1040+
mir_stats::print_mir_stats(tcx, "POST OPTIMISATION MIR STATS");
1041+
}
1042+
10311043
let translation =
10321044
time(time_passes,
10331045
"translation",

src/librustc_passes/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ pub mod ast_validation;
4646
pub mod consts;
4747
pub mod hir_stats;
4848
pub mod loops;
49+
pub mod mir_stats;
4950
pub mod no_asm;
5051
pub mod rvalues;
5152
pub mod static_recursion;

src/librustc_passes/mir_stats.rs

+319
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,319 @@
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+
// The visitors in this module collect sizes and counts of the most important
12+
// pieces of MIR. The resulting numbers are good approximations but not
13+
// completely accurate (some things might be counted twice, others missed).
14+
15+
use rustc_const_math::{ConstUsize};
16+
use rustc::middle::const_val::{ConstVal};
17+
use rustc::mir::{AggregateKind, AssertMessage, BasicBlock, BasicBlockData};
18+
use rustc::mir::{Constant, Literal, Location, LocalDecl};
19+
use rustc::mir::{Lvalue, LvalueElem, LvalueProjection};
20+
use rustc::mir::{Mir, Operand, ProjectionElem};
21+
use rustc::mir::{Rvalue, SourceInfo, Statement, StatementKind};
22+
use rustc::mir::{Terminator, TerminatorKind, TypedConstVal, VisibilityScope, VisibilityScopeData};
23+
use rustc::mir::visit as mir_visit;
24+
use rustc::mir::visit::Visitor;
25+
use rustc::ty::{ClosureSubsts, TyCtxt};
26+
use rustc::util::common::to_readable_str;
27+
use rustc::util::nodemap::{FxHashMap};
28+
29+
struct NodeData {
30+
count: usize,
31+
size: usize,
32+
}
33+
34+
struct StatCollector<'a, 'tcx: 'a> {
35+
_tcx: TyCtxt<'a, 'tcx, 'tcx>,
36+
data: FxHashMap<&'static str, NodeData>,
37+
}
38+
39+
pub fn print_mir_stats<'tcx, 'a>(tcx: TyCtxt<'a, 'tcx, 'tcx>, title: &str) {
40+
let mut collector = StatCollector {
41+
_tcx: tcx,
42+
data: FxHashMap(),
43+
};
44+
// For debugging instrumentation like this, we don't need to worry
45+
// about maintaining the dep graph.
46+
let _ignore = tcx.dep_graph.in_ignore();
47+
let mir_map = tcx.mir_map.borrow();
48+
for def_id in mir_map.keys() {
49+
let mir = mir_map.get(&def_id).unwrap();
50+
collector.visit_mir(&mir.borrow());
51+
}
52+
collector.print(title);
53+
}
54+
55+
impl<'a, 'tcx> StatCollector<'a, 'tcx> {
56+
57+
fn record_with_size(&mut self, label: &'static str, node_size: usize) {
58+
let entry = self.data.entry(label).or_insert(NodeData {
59+
count: 0,
60+
size: 0,
61+
});
62+
63+
entry.count += 1;
64+
entry.size = node_size;
65+
}
66+
67+
fn record<T>(&mut self, label: &'static str, node: &T) {
68+
self.record_with_size(label, ::std::mem::size_of_val(node));
69+
}
70+
71+
fn print(&self, title: &str) {
72+
let mut stats: Vec<_> = self.data.iter().collect();
73+
74+
stats.sort_by_key(|&(_, ref d)| d.count * d.size);
75+
76+
println!("\n{}\n", title);
77+
78+
println!("{:<32}{:>18}{:>14}{:>14}",
79+
"Name", "Accumulated Size", "Count", "Item Size");
80+
println!("------------------------------------------------------------------------------");
81+
82+
for (label, data) in stats {
83+
println!("{:<32}{:>18}{:>14}{:>14}",
84+
label,
85+
to_readable_str(data.count * data.size),
86+
to_readable_str(data.count),
87+
to_readable_str(data.size));
88+
}
89+
println!("------------------------------------------------------------------------------");
90+
}
91+
}
92+
93+
impl<'a, 'tcx> mir_visit::Visitor<'tcx> for StatCollector<'a, 'tcx> {
94+
fn visit_mir(&mut self, mir: &Mir<'tcx>) {
95+
self.record("Mir", mir);
96+
97+
// since the `super_mir` method does not traverse the MIR of
98+
// promoted rvalues, (but we still want to gather statistics
99+
// on the structures represented there) we manually traverse
100+
// the promoted rvalues here.
101+
for promoted_mir in &mir.promoted {
102+
self.visit_mir(promoted_mir);
103+
}
104+
105+
self.super_mir(mir);
106+
}
107+
108+
fn visit_basic_block_data(&mut self,
109+
block: BasicBlock,
110+
data: &BasicBlockData<'tcx>) {
111+
self.record("BasicBlockData", data);
112+
self.super_basic_block_data(block, data);
113+
}
114+
115+
fn visit_visibility_scope_data(&mut self,
116+
scope_data: &VisibilityScopeData) {
117+
self.record("VisibilityScopeData", scope_data);
118+
self.super_visibility_scope_data(scope_data);
119+
}
120+
121+
fn visit_statement(&mut self,
122+
block: BasicBlock,
123+
statement: &Statement<'tcx>,
124+
location: Location) {
125+
self.record("Statement", statement);
126+
self.record(match statement.kind {
127+
StatementKind::Assign(..) => "StatementKind::Assign",
128+
StatementKind::SetDiscriminant { .. } => "StatementKind::SetDiscriminant",
129+
StatementKind::StorageLive(..) => "StatementKind::StorageLive",
130+
StatementKind::StorageDead(..) => "StatementKind::StorageDead",
131+
StatementKind::Nop => "StatementKind::Nop",
132+
}, &statement.kind);
133+
self.super_statement(block, statement, location);
134+
}
135+
136+
fn visit_terminator(&mut self,
137+
block: BasicBlock,
138+
terminator: &Terminator<'tcx>,
139+
location: Location) {
140+
self.record("Terminator", terminator);
141+
self.super_terminator(block, terminator, location);
142+
}
143+
144+
fn visit_terminator_kind(&mut self,
145+
block: BasicBlock,
146+
kind: &TerminatorKind<'tcx>,
147+
location: Location) {
148+
self.record("TerminatorKind", kind);
149+
self.record(match *kind {
150+
TerminatorKind::Goto { .. } => "TerminatorKind::Goto",
151+
TerminatorKind::If { .. } => "TerminatorKind::If",
152+
TerminatorKind::Switch { .. } => "TerminatorKind::Switch",
153+
TerminatorKind::SwitchInt { .. } => "TerminatorKind::SwitchInt",
154+
TerminatorKind::Resume => "TerminatorKind::Resume",
155+
TerminatorKind::Return => "TerminatorKind::Return",
156+
TerminatorKind::Unreachable => "TerminatorKind::Unreachable",
157+
TerminatorKind::Drop { .. } => "TerminatorKind::Drop",
158+
TerminatorKind::DropAndReplace { .. } => "TerminatorKind::DropAndReplace",
159+
TerminatorKind::Call { .. } => "TerminatorKind::Call",
160+
TerminatorKind::Assert { .. } => "TerminatorKind::Assert",
161+
}, kind);
162+
self.super_terminator_kind(block, kind, location);
163+
}
164+
165+
fn visit_assert_message(&mut self,
166+
msg: &AssertMessage<'tcx>,
167+
location: Location) {
168+
self.record("AssertMessage", msg);
169+
self.record(match *msg {
170+
AssertMessage::BoundsCheck { .. } => "AssertMessage::BoundsCheck",
171+
AssertMessage::Math(..) => "AssertMessage::Math",
172+
}, msg);
173+
self.super_assert_message(msg, location);
174+
}
175+
176+
fn visit_rvalue(&mut self,
177+
rvalue: &Rvalue<'tcx>,
178+
location: Location) {
179+
self.record("Rvalue", rvalue);
180+
let rvalue_kind = match *rvalue {
181+
Rvalue::Use(..) => "Rvalue::Use",
182+
Rvalue::Repeat(..) => "Rvalue::Repeat",
183+
Rvalue::Ref(..) => "Rvalue::Ref",
184+
Rvalue::Len(..) => "Rvalue::Len",
185+
Rvalue::Cast(..) => "Rvalue::Cast",
186+
Rvalue::BinaryOp(..) => "Rvalue::BinaryOp",
187+
Rvalue::CheckedBinaryOp(..) => "Rvalue::CheckedBinaryOp",
188+
Rvalue::UnaryOp(..) => "Rvalue::UnaryOp",
189+
Rvalue::Box(..) => "Rvalue::Box",
190+
Rvalue::Aggregate(ref kind, ref _operands) => {
191+
// AggregateKind is not distinguished by visit API, so
192+
// record it. (`super_rvalue` handles `_operands`.)
193+
self.record(match *kind {
194+
AggregateKind::Array => "AggregateKind::Array",
195+
AggregateKind::Tuple => "AggregateKind::Tuple",
196+
AggregateKind::Adt(..) => "AggregateKind::Adt",
197+
AggregateKind::Closure(..) => "AggregateKind::Closure",
198+
}, kind);
199+
200+
"Rvalue::Aggregate"
201+
}
202+
Rvalue::InlineAsm { .. } => "Rvalue::InlineAsm",
203+
};
204+
self.record(rvalue_kind, rvalue);
205+
self.super_rvalue(rvalue, location);
206+
}
207+
208+
fn visit_operand(&mut self,
209+
operand: &Operand<'tcx>,
210+
location: Location) {
211+
self.record("Operand", operand);
212+
self.record(match *operand {
213+
Operand::Consume(..) => "Operand::Consume",
214+
Operand::Constant(..) => "Operand::Constant",
215+
}, operand);
216+
self.super_operand(operand, location);
217+
}
218+
219+
fn visit_lvalue(&mut self,
220+
lvalue: &Lvalue<'tcx>,
221+
context: mir_visit::LvalueContext<'tcx>,
222+
location: Location) {
223+
self.record("Lvalue", lvalue);
224+
self.record(match *lvalue {
225+
Lvalue::Local(..) => "Lvalue::Local",
226+
Lvalue::Static(..) => "Lvalue::Static",
227+
Lvalue::Projection(..) => "Lvalue::Projection",
228+
}, lvalue);
229+
self.super_lvalue(lvalue, context, location);
230+
}
231+
232+
fn visit_projection(&mut self,
233+
lvalue: &LvalueProjection<'tcx>,
234+
context: mir_visit::LvalueContext<'tcx>,
235+
location: Location) {
236+
self.record("LvalueProjection", lvalue);
237+
self.super_projection(lvalue, context, location);
238+
}
239+
240+
fn visit_projection_elem(&mut self,
241+
lvalue: &LvalueElem<'tcx>,
242+
context: mir_visit::LvalueContext<'tcx>,
243+
location: Location) {
244+
self.record("LvalueElem", lvalue);
245+
self.record(match *lvalue {
246+
ProjectionElem::Deref => "LvalueElem::Deref",
247+
ProjectionElem::Subslice { .. } => "LvalueElem::Subslice",
248+
ProjectionElem::Field(..) => "LvalueElem::Field",
249+
ProjectionElem::Index(..) => "LvalueElem::Index",
250+
ProjectionElem::ConstantIndex { .. } => "LvalueElem::ConstantIndex",
251+
ProjectionElem::Downcast(..) => "LvalueElem::Downcast",
252+
}, lvalue);
253+
self.super_projection_elem(lvalue, context, location);
254+
}
255+
256+
fn visit_constant(&mut self,
257+
constant: &Constant<'tcx>,
258+
location: Location) {
259+
self.record("Constant", constant);
260+
self.super_constant(constant, location);
261+
}
262+
263+
fn visit_literal(&mut self,
264+
literal: &Literal<'tcx>,
265+
location: Location) {
266+
self.record("Literal", literal);
267+
self.record(match *literal {
268+
Literal::Item { .. } => "Literal::Item",
269+
Literal::Value { .. } => "Literal::Value",
270+
Literal::Promoted { .. } => "Literal::Promoted",
271+
}, literal);
272+
self.super_literal(literal, location);
273+
}
274+
275+
fn visit_source_info(&mut self,
276+
source_info: &SourceInfo) {
277+
self.record("SourceInfo", source_info);
278+
self.super_source_info(source_info);
279+
}
280+
281+
fn visit_closure_substs(&mut self,
282+
substs: &ClosureSubsts<'tcx>) {
283+
self.record("ClosureSubsts", substs);
284+
self.super_closure_substs(substs);
285+
}
286+
287+
fn visit_const_val(&mut self,
288+
const_val: &ConstVal,
289+
_: Location) {
290+
self.record("ConstVal", const_val);
291+
self.super_const_val(const_val);
292+
}
293+
294+
fn visit_const_usize(&mut self,
295+
const_usize: &ConstUsize,
296+
_: Location) {
297+
self.record("ConstUsize", const_usize);
298+
self.super_const_usize(const_usize);
299+
}
300+
301+
fn visit_typed_const_val(&mut self,
302+
val: &TypedConstVal<'tcx>,
303+
location: Location) {
304+
self.record("TypedConstVal", val);
305+
self.super_typed_const_val(val, location);
306+
}
307+
308+
fn visit_local_decl(&mut self,
309+
local_decl: &LocalDecl<'tcx>) {
310+
self.record("LocalDecl", local_decl);
311+
self.super_local_decl(local_decl);
312+
}
313+
314+
fn visit_visibility_scope(&mut self,
315+
scope: &VisibilityScope) {
316+
self.record("VisiblityScope", scope);
317+
self.super_visibility_scope(scope);
318+
}
319+
}

0 commit comments

Comments
 (0)