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