1 //! This module provides the [CommentWriter] which makes it possible
2 //! to add comments to the written cranelift ir.
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)
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]
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] }
28 //! block0(v0: i64, v1: i64, v2: i64):
29 //! v3 = stack_addr.i64 ss0
30 //! v4 = stack_addr.i64 ss1
32 //! v5 = stack_addr.i64 ss2
42 //! ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
44 //! call fn0(v0, v3, v7)
58 use cranelift_codegen::{
60 ir::entities::AnyEntity,
61 write::{FuncWriter, PlainWriter},
64 use rustc_middle::ty::layout::FnAbiOf;
65 use rustc_session::config::{OutputFilenames, OutputType};
67 use crate::prelude::*;
69 #[derive(Clone, Debug)]
70 pub(crate) struct CommentWriter {
72 global_comments: Vec<String>,
73 entity_comments: FxHashMap<AnyEntity, String>,
77 pub(crate) fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
78 let enabled = should_write_ir(tcx);
79 let global_comments = if enabled {
81 format!("symbol {}", tcx.symbol_name(instance).name),
82 format!("instance {:?}", instance),
85 RevealAllLayoutCx(tcx).fn_abi_of_instance(instance, ty::List::empty())
93 CommentWriter { enabled, global_comments, entity_comments: FxHashMap::default() }
98 pub(crate) fn enabled(&self) -> bool {
102 pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
103 debug_assert!(self.enabled);
104 self.global_comments.push(comment.into());
107 pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
112 debug_assert!(self.enabled);
114 use std::collections::hash_map::Entry;
115 match self.entity_comments.entry(entity.into()) {
116 Entry::Occupied(mut occ) => {
117 occ.get_mut().push('\n');
118 occ.get_mut().push_str(comment.as_ref());
120 Entry::Vacant(vac) => {
121 vac.insert(comment.into());
127 impl FuncWriter for &'_ CommentWriter {
130 w: &mut dyn fmt::Write,
132 ) -> Result<bool, fmt::Error> {
133 for comment in &self.global_comments {
134 if !comment.is_empty() {
135 writeln!(w, "; {}", comment)?;
140 if !self.global_comments.is_empty() {
144 self.super_preamble(w, func)
147 fn write_entity_definition(
149 w: &mut dyn fmt::Write,
152 value: &dyn fmt::Display,
154 write!(w, " {} = {}", entity, value)?;
156 if let Some(comment) = self.entity_comments.get(&entity) {
157 writeln!(w, " ; {}", comment.replace('\n', "\n; "))
163 fn write_block_header(
165 w: &mut dyn fmt::Write,
170 PlainWriter.write_block_header(w, func, block, indent)
173 fn write_instruction(
175 w: &mut dyn fmt::Write,
177 aliases: &SecondaryMap<Value, Vec<Value>>,
181 PlainWriter.write_instruction(w, func, aliases, inst, indent)?;
182 if let Some(comment) = self.entity_comments.get(&inst.into()) {
183 writeln!(w, "; {}", comment.replace('\n', "\n; "))?;
189 impl FunctionCx<'_, '_, '_> {
190 pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
191 self.clif_comments.add_global_comment(comment);
194 pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
199 self.clif_comments.add_comment(entity, comment);
203 pub(crate) fn should_write_ir(tcx: TyCtxt<'_>) -> bool {
204 tcx.sess.opts.output_types.contains_key(&OutputType::LlvmAssembly)
207 pub(crate) fn write_ir_file(
208 output_filenames: &OutputFilenames,
210 write: impl FnOnce(&mut dyn Write) -> std::io::Result<()>,
212 let clif_output_dir = output_filenames.with_extension("clif");
214 match std::fs::create_dir(&clif_output_dir) {
216 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => {}
217 res @ Err(_) => res.unwrap(),
220 let clif_file_name = clif_output_dir.join(name);
222 let res = std::fs::File::create(clif_file_name).and_then(|mut file| write(&mut file));
223 if let Err(err) = res {
224 // Using early_warn as no Session is available here
225 rustc_session::early_warn(
226 rustc_session::config::ErrorOutputType::default(),
227 &format!("error writing ir file: {}", err),
232 pub(crate) fn write_clif_file(
233 output_filenames: &OutputFilenames,
236 isa: &dyn cranelift_codegen::isa::TargetIsa,
237 func: &cranelift_codegen::ir::Function,
238 mut clif_comments: &CommentWriter,
240 // FIXME work around filename too long errors
241 write_ir_file(output_filenames, &format!("{}.{}.clif", symbol_name, postfix), |file| {
242 let mut clif = String::new();
243 cranelift_codegen::write::decorate_function(&mut clif_comments, &mut clif, func).unwrap();
245 for flag in isa.flags().iter() {
246 writeln!(file, "set {}", flag)?;
248 write!(file, "target {}", isa.triple().architecture.to_string())?;
249 for isa_flag in isa.isa_flags().iter() {
250 write!(file, " {}", isa_flag)?;
252 writeln!(file, "\n")?;
254 file.write_all(clif.as_bytes())?;
259 impl fmt::Debug for FunctionCx<'_, '_, '_> {
260 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
261 writeln!(f, "{:?}", self.instance.substs)?;
262 writeln!(f, "{:?}", self.local_map)?;
264 let mut clif = String::new();
265 ::cranelift_codegen::write::decorate_function(
266 &mut &self.clif_comments,
271 writeln!(f, "\n{}", clif)