1 // Copyright 2014 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.
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.
12 use rustc::mir::repr::*;
13 use rustc::ty::{self, TyCtxt};
15 use std::io::{self, Write};
16 use syntax::ast::NodeId;
18 /// Write a graphviz DOT graph of a list of MIRs.
19 pub fn write_mir_graphviz<'a, 'b, 'tcx, W, I>(tcx: TyCtxt<'b, 'tcx, 'tcx>,
22 where W: Write, I: Iterator<Item=(&'a NodeId, &'a Mir<'a>)> {
23 for (&nodeid, mir) in iter {
24 writeln!(w, "digraph Mir_{} {{", nodeid)?;
26 // Global graph properties
27 writeln!(w, r#" graph [fontname="monospace"];"#)?;
28 writeln!(w, r#" node [fontname="monospace"];"#)?;
29 writeln!(w, r#" edge [fontname="monospace"];"#)?;
32 write_graph_label(tcx, nodeid, mir, w)?;
35 for block in mir.all_basic_blocks() {
36 write_node(block, mir, w)?;
40 for source in mir.all_basic_blocks() {
41 write_edges(source, mir, w)?;
48 /// Write a graphviz HTML-styled label for the given basic block, with
49 /// all necessary escaping already performed. (This is suitable for
50 /// emitting directly, as is done in this module, or for use with the
51 /// LabelText::HtmlStr from libgraphviz.)
53 /// `init` and `fini` are callbacks for emitting additional rows of
54 /// data (using HTML enclosed with `<tr>` in the emitted text).
55 pub fn write_node_label<W: Write, INIT, FINI>(block: BasicBlock,
60 fini: FINI) -> io::Result<()>
61 where INIT: Fn(&mut W) -> io::Result<()>,
62 FINI: Fn(&mut W) -> io::Result<()>
64 let data = mir.basic_block_data(block);
66 write!(w, r#"<table border="0" cellborder="1" cellspacing="0">"#)?;
68 // Basic block number at the top.
69 write!(w, r#"<tr><td {attrs} colspan="{colspan}">{blk}</td></tr>"#,
70 attrs=r#"bgcolor="gray" align="center""#,
76 // List of statements in the middle.
77 if !data.statements.is_empty() {
78 write!(w, r#"<tr><td align="left" balign="left">"#)?;
79 for statement in &data.statements {
80 write!(w, "{}<br/>", escape(statement))?;
82 write!(w, "</td></tr>")?;
85 // Terminator head at the bottom, not including the list of successor blocks. Those will be
86 // displayed as labels on the edges between blocks.
87 let mut terminator_head = String::new();
88 data.terminator().kind.fmt_head(&mut terminator_head).unwrap();
89 write!(w, r#"<tr><td align="left">{}</td></tr>"#, dot::escape_html(&terminator_head))?;
94 writeln!(w, "</table>")
97 /// Write a graphviz DOT node for the given basic block.
98 fn write_node<W: Write>(block: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
99 // Start a new node with the label to follow, in one of DOT's pseudo-HTML tables.
100 write!(w, r#" {} [shape="none", label=<"#, node(block))?;
101 write_node_label(block, mir, w, 1, |_| Ok(()), |_| Ok(()))?;
102 // Close the node label and the node itself.
106 /// Write graphviz DOT edges with labels between the given basic block and all of its successors.
107 fn write_edges<W: Write>(source: BasicBlock, mir: &Mir, w: &mut W) -> io::Result<()> {
108 let terminator = &mir.basic_block_data(source).terminator();
109 let labels = terminator.kind.fmt_successor_labels();
111 for (&target, label) in terminator.successors().iter().zip(labels) {
112 writeln!(w, r#" {} -> {} [label="{}"];"#, node(source), node(target), label)?;
118 /// Write the graphviz DOT label for the overall graph. This is essentially a block of text that
119 /// will appear below the graph, showing the type of the `fn` this MIR represents and the types of
120 /// all the variables and temporaries.
121 fn write_graph_label<'a, 'tcx, W: Write>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
126 write!(w, " label=<fn {}(", dot::escape_html(&tcx.node_path_str(nid)))?;
128 // fn argument types.
129 for (i, arg) in mir.arg_decls.iter().enumerate() {
133 write!(w, "{:?}: {}", Lvalue::Arg(i as u32), escape(&arg.ty))?;
136 write!(w, ") -> ")?;
139 match mir.return_ty {
140 ty::FnOutput::FnConverging(ty) => write!(w, "{}", escape(ty))?,
141 ty::FnOutput::FnDiverging => write!(w, "!")?,
144 write!(w, r#"<br align="left"/>"#)?;
146 // User variable types (including the user's name in a comment).
147 for (i, var) in mir.var_decls.iter().enumerate() {
149 if var.mutability == Mutability::Mut {
152 write!(w, r#"{:?}: {}; // {}<br align="left"/>"#,
153 Lvalue::Var(i as u32), escape(&var.ty), var.name)?;
156 // Compiler-introduced temporary types.
157 for (i, temp) in mir.temp_decls.iter().enumerate() {
158 write!(w, r#"let mut {:?}: {};<br align="left"/>"#,
159 Lvalue::Temp(i as u32), escape(&temp.ty))?;
165 fn node(block: BasicBlock) -> String {
166 format!("bb{}", block.index())
169 fn escape<T: Debug>(t: &T) -> String {
170 dot::escape_html(&format!("{:?}", t))