]> git.lizzy.rs Git - rust.git/blob - src/pretty_clif.rs
Rustup to rustc 1.37.0-nightly (2887008e0 2019-06-12)
[rust.git] / src / pretty_clif.rs
1 use std::borrow::Cow;
2 use std::collections::HashMap;
3 use std::fmt;
4
5 use cranelift::codegen::{
6     entity::SecondaryMap,
7     ir::{
8         self,
9         entities::AnyEntity,
10         function::DisplayFunctionAnnotations,
11     },
12     write::{FuncWriter, PlainWriter},
13     ValueLabelsRanges,
14 };
15
16 use crate::prelude::*;
17
18 /// This module provides the [CommentWriter] which makes it possible
19 /// to add comments to the written cranelift ir.
20 ///
21 /// # Example
22 ///
23 /// ```clif
24 /// test compile
25 /// target x86_64
26 ///
27 /// function u0:0(i64, i64, i64) system_v {
28 /// ; symbol _ZN119_$LT$example..IsNotEmpty$u20$as$u20$mini_core..FnOnce$LT$$LP$$RF$$u27$a$u20$$RF$$u27$b$u20$$u5b$u16$u5d$$C$$RP$$GT$$GT$9call_once17he85059d5e6a760a0E
29 /// ; instance Instance { def: Item(DefId(0/0:29 ~ example[8787]::{{impl}}[0]::call_once[0])), substs: [ReErased, ReErased] }
30 /// ; sig ([IsNotEmpty, (&&[u16],)]; c_variadic: false)->(u8, u8)
31 ///
32 /// ; ssa {_2: NOT_SSA, _4: NOT_SSA, _0: NOT_SSA, _3: (empty), _1: NOT_SSA}
33 /// ; msg   loc.idx    param    pass mode            ssa flags  ty
34 /// ; ret    _0      = v0       ByRef                NOT_SSA    (u8, u8)
35 /// ; arg    _1      = v1       ByRef                NOT_SSA    IsNotEmpty
36 /// ; arg    _2.0    = v2       ByVal(types::I64)    NOT_SSA    &&[u16]
37 ///
38 ///     ss0 = explicit_slot 0 ; _1: IsNotEmpty size=0 align=1,8
39 ///     ss1 = explicit_slot 8 ; _2: (&&[u16],) size=8 align=8,8
40 ///     ss2 = explicit_slot 8 ; _4: (&&[u16],) size=8 align=8,8
41 ///     sig0 = (i64, i64, i64) system_v
42 ///     sig1 = (i64, i64, i64) system_v
43 ///     fn0 = colocated u0:6 sig1 ; Instance { def: Item(DefId(0/0:31 ~ example[8787]::{{impl}}[1]::call_mut[0])), substs: [ReErased, ReErased] }
44 ///
45 /// ebb0(v0: i64, v1: i64, v2: i64):
46 ///     v3 = stack_addr.i64 ss0
47 ///     v4 = stack_addr.i64 ss1
48 ///     store v2, v4
49 ///     v5 = stack_addr.i64 ss2
50 ///     jump ebb1
51 ///
52 /// ebb1:
53 ///     nop
54 /// ; _3 = &mut _1
55 /// ; _4 = _2
56 ///     v6 = load.i64 v4
57 ///     store v6, v5
58 /// ;
59 /// ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
60 ///     v7 = load.i64 v5
61 ///     call fn0(v0, v3, v7)
62 ///     jump ebb2
63 ///
64 /// ebb2:
65 ///     nop
66 /// ;
67 /// ; return
68 ///     return
69 /// }
70 /// ```
71
72 #[derive(Debug)]
73 pub struct CommentWriter {
74     global_comments: Vec<String>,
75     entity_comments: HashMap<AnyEntity, String>,
76     inst_comments: HashMap<Inst, String>,
77 }
78
79 impl CommentWriter {
80     pub fn new<'a, 'tcx: 'a>(tcx: TyCtxt<'tcx, 'tcx>, instance: Instance<'tcx>) -> Self {
81         CommentWriter {
82             global_comments: vec![
83                 format!("symbol {}", tcx.symbol_name(instance).as_str()),
84                 format!("instance {:?}", instance),
85                 format!("sig {:?}", tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &instance.fn_sig(tcx))),
86                 String::new(),
87             ],
88             entity_comments: HashMap::new(),
89             inst_comments: HashMap::new(),
90         }
91     }
92 }
93
94 impl<'a> FuncWriter for &'a CommentWriter {
95     fn write_preamble(
96         &mut self,
97         w: &mut dyn fmt::Write,
98         func: &Function,
99         reg_info: Option<&isa::RegInfo>,
100     ) -> Result<bool, fmt::Error> {
101         for comment in &self.global_comments {
102             if !comment.is_empty() {
103                 writeln!(w, "; {}", comment)?;
104             } else {
105                 writeln!(w, "")?;
106             }
107         }
108         if !self.global_comments.is_empty() {
109             writeln!(w, "")?;
110         }
111
112         self.super_preamble(w, func, reg_info)
113     }
114
115     fn write_entity_definition(
116         &mut self,
117         w: &mut dyn fmt::Write,
118         _func: &Function,
119         entity: AnyEntity,
120         value: &dyn fmt::Display,
121     ) -> fmt::Result {
122         write!(w, "    {} = {}", entity, value)?;
123
124         if let Some(comment) = self.entity_comments.get(&entity) {
125             writeln!(w, " ; {}", comment.replace('\n', "\n; "))
126         } else {
127             writeln!(w, "")
128         }
129     }
130
131     fn write_ebb_header(
132         &mut self,
133         w: &mut dyn fmt::Write,
134         func: &Function,
135         isa: Option<&dyn isa::TargetIsa>,
136         ebb: Ebb,
137         indent: usize,
138     ) -> fmt::Result {
139         PlainWriter.write_ebb_header(w, func, isa, ebb, indent)
140     }
141
142     fn write_instruction(
143         &mut self,
144         w: &mut dyn fmt::Write,
145         func: &Function,
146         aliases: &SecondaryMap<Value, Vec<Value>>,
147         isa: Option<&dyn isa::TargetIsa>,
148         inst: Inst,
149         indent: usize,
150     ) -> fmt::Result {
151         PlainWriter.write_instruction(w, func, aliases, isa, inst, indent)?;
152         if let Some(comment) = self.inst_comments.get(&inst) {
153             writeln!(w, "; {}", comment.replace('\n', "\n; "))?;
154         }
155         Ok(())
156     }
157 }
158
159 #[cfg(debug_assertions)]
160 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
161     pub fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
162         self.clif_comments.global_comments.push(comment.into());
163     }
164
165     pub fn add_entity_comment<'s, S: Into<Cow<'s, str>>, E: Into<AnyEntity>>(
166         &mut self,
167         entity: E,
168         comment: S,
169     ) {
170         use std::collections::hash_map::Entry;
171         match self.clif_comments.entity_comments.entry(entity.into()) {
172             Entry::Occupied(mut occ) => {
173                 occ.get_mut().push('\n');
174                 occ.get_mut().push_str(comment.into().as_ref());
175             }
176             Entry::Vacant(vac) => {
177                 vac.insert(comment.into().into_owned());
178             }
179         }
180     }
181
182     pub fn add_comment<'s, S: Into<Cow<'s, str>>>(&mut self, inst: Inst, comment: S) {
183         use std::collections::hash_map::Entry;
184         match self.clif_comments.inst_comments.entry(inst) {
185             Entry::Occupied(mut occ) => {
186                 occ.get_mut().push('\n');
187                 occ.get_mut().push_str(comment.into().as_ref());
188             }
189             Entry::Vacant(vac) => {
190                 vac.insert(comment.into().into_owned());
191             }
192         }
193     }
194 }
195
196 pub fn write_clif_file<'a, 'tcx: 'a>(
197     tcx: TyCtxt<'tcx, 'tcx>,
198     postfix: &str,
199     instance: Instance<'tcx>,
200     func: &ir::Function,
201     mut clif_comments: &CommentWriter,
202     value_ranges: Option<&ValueLabelsRanges>,
203 ) {
204     use std::io::Write;
205
206     let symbol_name = tcx.symbol_name(instance).as_str();
207     let clif_file_name = format!(
208         "{}/{}__{}.{}.clif",
209         concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
210         tcx.crate_name(LOCAL_CRATE),
211         symbol_name,
212         postfix,
213     );
214
215     let mut clif = String::new();
216     cranelift::codegen::write::decorate_function(
217         &mut clif_comments,
218         &mut clif,
219         &func,
220         &DisplayFunctionAnnotations {
221             isa: Some(&*crate::build_isa(tcx.sess)),
222             value_ranges,
223         },
224     )
225     .unwrap();
226
227     match ::std::fs::File::create(clif_file_name) {
228         Ok(mut file) => {
229             let target_triple = crate::target_triple(tcx.sess);
230             writeln!(file, "test compile").unwrap();
231             writeln!(file, "set is_pic").unwrap();
232             writeln!(file, "target {}", target_triple).unwrap();
233             writeln!(file, "").unwrap();
234             file.write(clif.as_bytes()).unwrap();
235         }
236         Err(e) => {
237             tcx.sess.warn(&format!("err opening clif file: {:?}", e));
238         }
239     }
240 }
241
242 impl<'a, 'tcx: 'a, B: Backend + 'a> fmt::Debug for FunctionCx<'a, 'tcx, B> {
243     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
244         writeln!(f, "{:?}", self.instance.substs)?;
245         writeln!(f, "{:?}", self.local_map)?;
246
247         let mut clif = String::new();
248         ::cranelift::codegen::write::decorate_function(
249             &mut &self.clif_comments,
250             &mut clif,
251             &self.bcx.func,
252             // FIXME use DisplayFunctionAnnotations::default() instead
253             &DisplayFunctionAnnotations {
254                 isa: None,
255                 value_ranges: None,
256             },
257         )
258         .unwrap();
259         writeln!(f, "\n{}", clif)
260     }
261 }