]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_cranelift/src/pretty_clif.rs
Merge commit 'dbee13661efa269cb4cd57bb4c6b99a19732b484' into sync_cg_clif-2020-12-27
[rust.git] / compiler / rustc_codegen_cranelift / src / pretty_clif.rs
1 //! This module provides the [CommentWriter] which makes it possible
2 //! to add comments to the written cranelift ir.
3 //!
4 //! # Example
5 //!
6 //! ```clif
7 //! test compile
8 //! target x86_64
9 //!
10 //! function u0:0(i64, i64, i64) system_v {
11 //! ; 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
12 //! ; instance Instance { def: Item(DefId(0/0:29 ~ example[8787]::{{impl}}[0]::call_once[0])), substs: [ReErased, ReErased] }
13 //! ; sig ([IsNotEmpty, (&&[u16],)]; c_variadic: false)->(u8, u8)
14 //!
15 //! ; ssa {_2: NOT_SSA, _4: NOT_SSA, _0: NOT_SSA, _3: (empty), _1: NOT_SSA}
16 //! ; msg   loc.idx    param    pass mode            ssa flags  ty
17 //! ; ret    _0      = v0       ByRef                NOT_SSA    (u8, u8)
18 //! ; arg    _1      = v1       ByRef                NOT_SSA    IsNotEmpty
19 //! ; arg    _2.0    = v2       ByVal(types::I64)    NOT_SSA    &&[u16]
20 //!
21 //!     ss0 = explicit_slot 0 ; _1: IsNotEmpty size=0 align=1,8
22 //!     ss1 = explicit_slot 8 ; _2: (&&[u16],) size=8 align=8,8
23 //!     ss2 = explicit_slot 8 ; _4: (&&[u16],) size=8 align=8,8
24 //!     sig0 = (i64, i64, i64) system_v
25 //!     sig1 = (i64, i64, i64) system_v
26 //!     fn0 = colocated u0:6 sig1 ; Instance { def: Item(DefId(0/0:31 ~ example[8787]::{{impl}}[1]::call_mut[0])), substs: [ReErased, ReErased] }
27 //!
28 //! block0(v0: i64, v1: i64, v2: i64):
29 //!     v3 = stack_addr.i64 ss0
30 //!     v4 = stack_addr.i64 ss1
31 //!     store v2, v4
32 //!     v5 = stack_addr.i64 ss2
33 //!     jump block1
34 //!
35 //! block1:
36 //!     nop
37 //! ; _3 = &mut _1
38 //! ; _4 = _2
39 //!     v6 = load.i64 v4
40 //!     store v6, v5
41 //! ;
42 //! ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
43 //!     v7 = load.i64 v5
44 //!     call fn0(v0, v3, v7)
45 //!     jump block2
46 //!
47 //! block2:
48 //!     nop
49 //! ;
50 //! ; return
51 //!     return
52 //! }
53 //! ```
54
55 use std::fmt;
56 use std::io::Write;
57
58 use cranelift_codegen::{
59     entity::SecondaryMap,
60     ir::{entities::AnyEntity, function::DisplayFunctionAnnotations},
61     write::{FuncWriter, PlainWriter},
62 };
63
64 use rustc_session::config::OutputType;
65
66 use crate::prelude::*;
67
68 #[derive(Debug)]
69 pub(crate) struct CommentWriter {
70     global_comments: Vec<String>,
71     entity_comments: FxHashMap<AnyEntity, String>,
72 }
73
74 impl CommentWriter {
75     pub(crate) fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
76         let global_comments = if cfg!(debug_assertions) {
77             vec![
78                 format!("symbol {}", tcx.symbol_name(instance).name),
79                 format!("instance {:?}", instance),
80                 format!(
81                     "sig {:?}",
82                     tcx.normalize_erasing_late_bound_regions(
83                         ParamEnv::reveal_all(),
84                         crate::abi::fn_sig_for_fn_abi(tcx, instance)
85                     )
86                 ),
87                 String::new(),
88             ]
89         } else {
90             vec![]
91         };
92
93         CommentWriter {
94             global_comments,
95             entity_comments: FxHashMap::default(),
96         }
97     }
98 }
99
100 #[cfg(debug_assertions)]
101 impl CommentWriter {
102     pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
103         self.global_comments.push(comment.into());
104     }
105
106     pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
107         &mut self,
108         entity: E,
109         comment: S,
110     ) {
111         use std::collections::hash_map::Entry;
112         match self.entity_comments.entry(entity.into()) {
113             Entry::Occupied(mut occ) => {
114                 occ.get_mut().push('\n');
115                 occ.get_mut().push_str(comment.as_ref());
116             }
117             Entry::Vacant(vac) => {
118                 vac.insert(comment.into());
119             }
120         }
121     }
122 }
123
124 impl FuncWriter for &'_ CommentWriter {
125     fn write_preamble(
126         &mut self,
127         w: &mut dyn fmt::Write,
128         func: &Function,
129         reg_info: Option<&isa::RegInfo>,
130     ) -> Result<bool, fmt::Error> {
131         for comment in &self.global_comments {
132             if !comment.is_empty() {
133                 writeln!(w, "; {}", comment)?;
134             } else {
135                 writeln!(w)?;
136             }
137         }
138         if !self.global_comments.is_empty() {
139             writeln!(w)?;
140         }
141
142         self.super_preamble(w, func, reg_info)
143     }
144
145     fn write_entity_definition(
146         &mut self,
147         w: &mut dyn fmt::Write,
148         _func: &Function,
149         entity: AnyEntity,
150         value: &dyn fmt::Display,
151     ) -> fmt::Result {
152         write!(w, "    {} = {}", entity, value)?;
153
154         if let Some(comment) = self.entity_comments.get(&entity) {
155             writeln!(w, " ; {}", comment.replace('\n', "\n; "))
156         } else {
157             writeln!(w)
158         }
159     }
160
161     fn write_block_header(
162         &mut self,
163         w: &mut dyn fmt::Write,
164         func: &Function,
165         isa: Option<&dyn isa::TargetIsa>,
166         block: Block,
167         indent: usize,
168     ) -> fmt::Result {
169         PlainWriter.write_block_header(w, func, isa, block, indent)
170     }
171
172     fn write_instruction(
173         &mut self,
174         w: &mut dyn fmt::Write,
175         func: &Function,
176         aliases: &SecondaryMap<Value, Vec<Value>>,
177         isa: Option<&dyn isa::TargetIsa>,
178         inst: Inst,
179         indent: usize,
180     ) -> fmt::Result {
181         PlainWriter.write_instruction(w, func, aliases, isa, inst, indent)?;
182         if let Some(comment) = self.entity_comments.get(&inst.into()) {
183             writeln!(w, "; {}", comment.replace('\n', "\n; "))?;
184         }
185         Ok(())
186     }
187 }
188
189 #[cfg(debug_assertions)]
190 impl<M: Module> FunctionCx<'_, '_, M> {
191     pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
192         self.clif_comments.add_global_comment(comment);
193     }
194
195     pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
196         &mut self,
197         entity: E,
198         comment: S,
199     ) {
200         self.clif_comments.add_comment(entity, comment);
201     }
202 }
203
204 pub(crate) fn should_write_ir(tcx: TyCtxt<'_>) -> bool {
205     cfg!(debug_assertions)
206         || tcx
207             .sess
208             .opts
209             .output_types
210             .contains_key(&OutputType::LlvmAssembly)
211 }
212
213 pub(crate) fn write_ir_file<'tcx>(
214     tcx: TyCtxt<'tcx>,
215     name: &str,
216     write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>,
217 ) {
218     if !should_write_ir(tcx) {
219         return;
220     }
221
222     let clif_output_dir = tcx.output_filenames(LOCAL_CRATE).with_extension("clif");
223
224     match std::fs::create_dir(&clif_output_dir) {
225         Ok(()) => {}
226         Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
227         res @ Err(_) => res.unwrap(),
228     }
229
230     let clif_file_name = clif_output_dir.join(name);
231
232     let res: std::io::Result<()> = try {
233         let mut file = std::fs::File::create(clif_file_name)?;
234         write(&mut file)?;
235     };
236     if let Err(err) = res {
237         tcx.sess.warn(&format!("error writing ir file: {}", err));
238     }
239 }
240
241 pub(crate) fn write_clif_file<'tcx>(
242     tcx: TyCtxt<'tcx>,
243     postfix: &str,
244     isa: Option<&dyn cranelift_codegen::isa::TargetIsa>,
245     instance: Instance<'tcx>,
246     context: &cranelift_codegen::Context,
247     mut clif_comments: &CommentWriter,
248 ) {
249     write_ir_file(
250         tcx,
251         &format!("{}.{}.clif", tcx.symbol_name(instance).name, postfix),
252         |file| {
253             let value_ranges = isa.map(|isa| {
254                 context
255                     .build_value_labels_ranges(isa)
256                     .expect("value location ranges")
257             });
258
259             let mut clif = String::new();
260             cranelift_codegen::write::decorate_function(
261                 &mut clif_comments,
262                 &mut clif,
263                 &context.func,
264                 &DisplayFunctionAnnotations {
265                     isa: Some(&*crate::build_isa(tcx.sess)),
266                     value_ranges: value_ranges.as_ref(),
267                 },
268             )
269             .unwrap();
270
271             writeln!(file, "test compile")?;
272             writeln!(file, "set is_pic")?;
273             writeln!(file, "set enable_simd")?;
274             writeln!(file, "target {} haswell", crate::target_triple(tcx.sess))?;
275             writeln!(file)?;
276             file.write_all(clif.as_bytes())?;
277             Ok(())
278         },
279     );
280 }
281
282 impl<M: Module> fmt::Debug for FunctionCx<'_, '_, M> {
283     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
284         writeln!(f, "{:?}", self.instance.substs)?;
285         writeln!(f, "{:?}", self.local_map)?;
286
287         let mut clif = String::new();
288         ::cranelift_codegen::write::decorate_function(
289             &mut &self.clif_comments,
290             &mut clif,
291             &self.bcx.func,
292             &DisplayFunctionAnnotations::default(),
293         )
294         .unwrap();
295         writeln!(f, "\n{}", clif)
296     }
297 }