]> git.lizzy.rs Git - rust.git/blob - src/librustc_borrowck/borrowck/mir/dataflow/graphviz.rs
b15c1873f9bd84506dbe3cd7b3f5946bf83dad59
[rust.git] / src / librustc_borrowck / borrowck / mir / dataflow / graphviz.rs
1 // Copyright 2012-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 //! Hook into libgraphviz for rendering dataflow graphs for MIR.
12
13 use syntax::ast::NodeId;
14 use rustc::mir::{BasicBlock, Mir};
15 use rustc_data_structures::bitslice::bits_to_string;
16 use rustc_data_structures::indexed_set::{IdxSet};
17 use rustc_data_structures::indexed_vec::Idx;
18
19 use dot;
20 use dot::IntoCow;
21
22 use std::fmt::Debug;
23 use std::fs::File;
24 use std::io;
25 use std::io::prelude::*;
26 use std::marker::PhantomData;
27 use std::mem;
28 use std::path::Path;
29
30 use super::super::MirBorrowckCtxtPreDataflow;
31 use super::{BitDenotation, DataflowState};
32
33 impl<O: BitDenotation> DataflowState<O> {
34     fn each_bit<F>(&self, words: &IdxSet<O::Idx>, mut f: F)
35         where F: FnMut(O::Idx) {
36         //! Helper for iterating over the bits in a bitvector.
37
38         let bits_per_block = self.operator.bits_per_block();
39         let usize_bits: usize = mem::size_of::<usize>() * 8;
40
41         for (word_index, &word) in words.words().iter().enumerate() {
42             if word != 0 {
43                 let base_index = word_index * usize_bits;
44                 for offset in 0..usize_bits {
45                     let bit = 1 << offset;
46                     if (word & bit) != 0 {
47                         // NB: we round up the total number of bits
48                         // that we store in any given bit set so that
49                         // it is an even multiple of usize::BITS. This
50                         // means that there may be some stray bits at
51                         // the end that do not correspond to any
52                         // actual value; that's why we first check
53                         // that we are in range of bits_per_block.
54                         let bit_index = base_index + offset as usize;
55                         if bit_index >= bits_per_block {
56                             return;
57                         } else {
58                             f(O::Idx::new(bit_index));
59                         }
60                     }
61                 }
62             }
63         }
64     }
65
66     pub fn interpret_set<'c, P>(&self,
67                                 o: &'c O,
68                                 words: &IdxSet<O::Idx>,
69                                 render_idx: &P)
70                                 -> Vec<&'c Debug>
71         where P: Fn(&O, O::Idx) -> &Debug
72     {
73         let mut v = Vec::new();
74         self.each_bit(words, |i| {
75             v.push(render_idx(o, i));
76         });
77         v
78     }
79 }
80
81 pub trait MirWithFlowState<'tcx> {
82     type BD: BitDenotation;
83     fn node_id(&self) -> NodeId;
84     fn mir(&self) -> &Mir<'tcx>;
85     fn flow_state(&self) -> &DataflowState<Self::BD>;
86 }
87
88 impl<'a, 'tcx: 'a, BD> MirWithFlowState<'tcx> for MirBorrowckCtxtPreDataflow<'a, 'tcx, BD>
89     where 'tcx: 'a, BD: BitDenotation
90 {
91     type BD = BD;
92     fn node_id(&self) -> NodeId { self.node_id }
93     fn mir(&self) -> &Mir<'tcx> { self.flow_state.mir() }
94     fn flow_state(&self) -> &DataflowState<Self::BD> { &self.flow_state.flow_state }
95 }
96
97 struct Graph<'a, 'tcx, MWF:'a, P> where
98     MWF: MirWithFlowState<'tcx>
99 {
100     mbcx: &'a MWF,
101     phantom: PhantomData<&'tcx ()>,
102     render_idx: P,
103 }
104
105 pub fn print_borrowck_graph_to<'a, 'tcx, BD, P>(
106     mbcx: &MirBorrowckCtxtPreDataflow<'a, 'tcx, BD>,
107     path: &Path,
108     render_idx: P)
109     -> io::Result<()>
110     where BD: BitDenotation,
111           P: Fn(&BD, BD::Idx) -> &Debug
112 {
113     let g = Graph { mbcx: mbcx, phantom: PhantomData, render_idx: render_idx };
114     let mut v = Vec::new();
115     dot::render(&g, &mut v)?;
116     debug!("print_borrowck_graph_to path: {} node_id: {}",
117            path.display(), mbcx.node_id);
118     File::create(path).and_then(|mut f| f.write_all(&v))
119 }
120
121 pub type Node = BasicBlock;
122
123 #[derive(Copy, Clone, PartialEq, Eq, Debug)]
124 pub struct Edge { source: BasicBlock, index: usize }
125
126 fn outgoing(mir: &Mir, bb: BasicBlock) -> Vec<Edge> {
127     let succ_len = mir[bb].terminator().successors().len();
128     (0..succ_len).map(|index| Edge { source: bb, index: index}).collect()
129 }
130
131 impl<'a, 'tcx, MWF, P> dot::Labeller<'a> for Graph<'a, 'tcx, MWF, P>
132     where MWF: MirWithFlowState<'tcx>,
133           P: for <'b> Fn(&'b MWF::BD, <MWF::BD as BitDenotation>::Idx) -> &'b Debug,
134 {
135     type Node = Node;
136     type Edge = Edge;
137     fn graph_id(&self) -> dot::Id {
138         dot::Id::new(format!("graph_for_node_{}",
139                              self.mbcx.node_id()))
140             .unwrap()
141     }
142
143     fn node_id(&self, n: &Node) -> dot::Id {
144         dot::Id::new(format!("bb_{}", n.index()))
145             .unwrap()
146     }
147
148     fn node_label(&self, n: &Node) -> dot::LabelText {
149         // A standard MIR label, as generated by write_node_label, is
150         // presented in a single column in a table.
151         //
152         // The code below does a bunch of formatting work to format a
153         // node (i.e. MIR basic-block) label with extra
154         // dataflow-enriched information.  In particular, the goal is
155         // to add extra columns that present the three dataflow
156         // bitvectors, and the data those bitvectors represent.
157         //
158         // It presents it in the following format (where I am
159         // presenting the table rendering via ASCII art, one line per
160         // row of the table, and a chunk size of 3 rather than 5):
161         //
162         // ------  -----------------------  ------------  --------------------
163         //                    [e1, e3, e4]
164         //             [e8, e9] "= ENTRY:"  <ENTRY-BITS>
165         // ------  -----------------------  ------------  --------------------
166         // Left
167         // Most
168         // Column
169         // Is
170         // Just
171         // Normal
172         // Series
173         // Of
174         // MIR
175         // Stmts
176         // ------  -----------------------  ------------  --------------------
177         //           [g1, g4, g5] "= GEN:"  <GEN-BITS>
178         // ------  -----------------------  ------------  --------------------
179         //                         "KILL:"  <KILL-BITS>   "=" [k1, k3, k8]
180         //                                                [k9]
181         // ------  -----------------------  ------------  --------------------
182         //
183         // (In addition, the added dataflow is rendered with a colored
184         // background just so it will stand out compared to the
185         // statements.)
186         let mut v = Vec::new();
187         let i = n.index();
188         let chunk_size = 5;
189         const BG_FLOWCONTENT: &'static str = r#"bgcolor="pink""#;
190         const ALIGN_RIGHT: &'static str = r#"align="right""#;
191         const FACE_MONOSPACE: &'static str = r#"FACE="Courier""#;
192         fn chunked_present_left<W:io::Write>(w: &mut W,
193                                              interpreted: &[&Debug],
194                                              chunk_size: usize)
195                                              -> io::Result<()>
196         {
197             // This function may emit a sequence of <tr>'s, but it
198             // always finishes with an (unfinished)
199             // <tr><td></td><td>
200             //
201             // Thus, after being called, one should finish both the
202             // pending <td> as well as the <tr> itself.
203             let mut seen_one = false;
204             for c in interpreted.chunks(chunk_size) {
205                 if seen_one {
206                     // if not the first row, finish off the previous row
207                     write!(w, "</td><td></td><td></td></tr>")?;
208                 }
209                 write!(w, "<tr><td></td><td {bg} {align}>{objs:?}",
210                        bg = BG_FLOWCONTENT,
211                        align = ALIGN_RIGHT,
212                        objs = c)?;
213                 seen_one = true;
214             }
215             if !seen_one {
216                 write!(w, "<tr><td></td><td {bg} {align}>[]",
217                        bg = BG_FLOWCONTENT,
218                        align = ALIGN_RIGHT)?;
219             }
220             Ok(())
221         }
222         ::rustc_mir::graphviz::write_node_label(
223             *n, self.mbcx.mir(), &mut v, 4,
224             |w| {
225                 let flow = self.mbcx.flow_state();
226                 let entry_interp = flow.interpret_set(&flow.operator,
227                                                       flow.sets.on_entry_set_for(i),
228                                                       &self.render_idx);
229                 chunked_present_left(w, &entry_interp[..], chunk_size)?;
230                 let bits_per_block = flow.sets.bits_per_block();
231                 let entry = flow.sets.on_entry_set_for(i);
232                 debug!("entry set for i={i} bits_per_block: {bpb} entry: {e:?} interp: {ei:?}",
233                        i=i, e=entry, bpb=bits_per_block, ei=entry_interp);
234                 write!(w, "= ENTRY:</td><td {bg}><FONT {face}>{entrybits:?}</FONT></td>\
235                                         <td></td></tr>",
236                        bg = BG_FLOWCONTENT,
237                        face = FACE_MONOSPACE,
238                        entrybits=bits_to_string(entry.words(), bits_per_block))
239             },
240             |w| {
241                 let flow = self.mbcx.flow_state();
242                 let gen_interp =
243                     flow.interpret_set(&flow.operator, flow.sets.gen_set_for(i), &self.render_idx);
244                 let kill_interp =
245                     flow.interpret_set(&flow.operator, flow.sets.kill_set_for(i), &self.render_idx);
246                 chunked_present_left(w, &gen_interp[..], chunk_size)?;
247                 let bits_per_block = flow.sets.bits_per_block();
248                 {
249                     let gen = flow.sets.gen_set_for(i);
250                     debug!("gen set for i={i} bits_per_block: {bpb} gen: {g:?} interp: {gi:?}",
251                            i=i, g=gen, bpb=bits_per_block, gi=gen_interp);
252                     write!(w, " = GEN:</td><td {bg}><FONT {face}>{genbits:?}</FONT></td>\
253                                            <td></td></tr>",
254                            bg = BG_FLOWCONTENT,
255                            face = FACE_MONOSPACE,
256                            genbits=bits_to_string(gen.words(), bits_per_block))?;
257                 }
258
259                 {
260                     let kill = flow.sets.kill_set_for(i);
261                     debug!("kill set for i={i} bits_per_block: {bpb} kill: {k:?} interp: {ki:?}",
262                            i=i, k=kill, bpb=bits_per_block, ki=kill_interp);
263                     write!(w, "<tr><td></td><td {bg} {align}>KILL:</td>\
264                                             <td {bg}><FONT {face}>{killbits:?}</FONT></td>",
265                            bg = BG_FLOWCONTENT,
266                            align = ALIGN_RIGHT,
267                            face = FACE_MONOSPACE,
268                            killbits=bits_to_string(kill.words(), bits_per_block))?;
269                 }
270
271                 // (chunked_present_right)
272                 let mut seen_one = false;
273                 for k in kill_interp.chunks(chunk_size) {
274                     if !seen_one {
275                         // continuation of row; this is fourth <td>
276                         write!(w, "<td {bg}>= {kill:?}</td></tr>",
277                                bg = BG_FLOWCONTENT,
278                                kill=k)?;
279                     } else {
280                         // new row, with indent of three <td>'s
281                         write!(w, "<tr><td></td><td></td><td></td><td {bg}>{kill:?}</td></tr>",
282                                bg = BG_FLOWCONTENT,
283                                kill=k)?;
284                     }
285                     seen_one = true;
286                 }
287                 if !seen_one {
288                     write!(w, "<td {bg}>= []</td></tr>",
289                            bg = BG_FLOWCONTENT)?;
290                 }
291
292                 Ok(())
293             })
294             .unwrap();
295         dot::LabelText::html(String::from_utf8(v).unwrap())
296     }
297
298     fn node_shape(&self, _n: &Node) -> Option<dot::LabelText> {
299         Some(dot::LabelText::label("none"))
300     }
301 }
302
303 impl<'a, 'tcx, MWF, P> dot::GraphWalk<'a> for Graph<'a, 'tcx, MWF, P>
304     where MWF: MirWithFlowState<'tcx>
305 {
306     type Node = Node;
307     type Edge = Edge;
308     fn nodes(&self) -> dot::Nodes<Node> {
309         self.mbcx.mir()
310             .basic_blocks()
311             .indices()
312             .collect::<Vec<_>>()
313             .into_cow()
314     }
315
316     fn edges(&self) -> dot::Edges<Edge> {
317         let mir = self.mbcx.mir();
318         // base initial capacity on assumption every block has at
319         // least one outgoing edge (Which should be true for all
320         // blocks but one, the exit-block).
321         let mut edges = Vec::with_capacity(mir.basic_blocks().len());
322         for bb in mir.basic_blocks().indices() {
323             let outgoing = outgoing(mir, bb);
324             edges.extend(outgoing.into_iter());
325         }
326         edges.into_cow()
327     }
328
329     fn source(&self, edge: &Edge) -> Node {
330         edge.source
331     }
332
333     fn target(&self, edge: &Edge) -> Node {
334         let mir = self.mbcx.mir();
335         mir[edge.source].terminator().successors()[edge.index]
336     }
337 }