2 use std::collections::HashMap;
5 use cranelift::codegen::{
10 function::DisplayFunctionAnnotations,
12 write::{FuncWriter, PlainWriter},
16 use crate::prelude::*;
18 /// This module provides the [CommentWriter] which makes it possible
19 /// to add comments to the written cranelift ir.
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)
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]
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] }
45 /// ebb0(v0: i64, v1: i64, v2: i64):
46 /// v3 = stack_addr.i64 ss0
47 /// v4 = stack_addr.i64 ss1
49 /// v5 = stack_addr.i64 ss2
59 /// ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
61 /// call fn0(v0, v3, v7)
73 pub struct CommentWriter {
74 global_comments: Vec<String>,
75 entity_comments: HashMap<AnyEntity, String>,
76 inst_comments: HashMap<Inst, String>,
80 pub fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
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))),
88 entity_comments: HashMap::new(),
89 inst_comments: HashMap::new(),
94 impl FuncWriter for &'_ CommentWriter {
97 w: &mut dyn fmt::Write,
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)?;
108 if !self.global_comments.is_empty() {
112 self.super_preamble(w, func, reg_info)
115 fn write_entity_definition(
117 w: &mut dyn fmt::Write,
120 value: &dyn fmt::Display,
122 write!(w, " {} = {}", entity, value)?;
124 if let Some(comment) = self.entity_comments.get(&entity) {
125 writeln!(w, " ; {}", comment.replace('\n', "\n; "))
133 w: &mut dyn fmt::Write,
135 isa: Option<&dyn isa::TargetIsa>,
139 PlainWriter.write_ebb_header(w, func, isa, ebb, indent)
142 fn write_instruction(
144 w: &mut dyn fmt::Write,
146 aliases: &SecondaryMap<Value, Vec<Value>>,
147 isa: Option<&dyn isa::TargetIsa>,
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; "))?;
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());
165 pub fn add_entity_comment<'s, S: Into<Cow<'s, str>>, E: Into<AnyEntity>>(
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());
176 Entry::Vacant(vac) => {
177 vac.insert(comment.into().into_owned());
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());
189 Entry::Vacant(vac) => {
190 vac.insert(comment.into().into_owned());
196 pub fn write_clif_file<'tcx>(
199 instance: Instance<'tcx>,
201 mut clif_comments: &CommentWriter,
202 value_ranges: Option<&ValueLabelsRanges>,
206 let symbol_name = tcx.symbol_name(instance).as_str();
207 let clif_file_name = format!(
209 concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
210 tcx.crate_name(LOCAL_CRATE),
215 let mut clif = String::new();
216 cranelift::codegen::write::decorate_function(
220 &DisplayFunctionAnnotations {
221 isa: Some(&*crate::build_isa(tcx.sess)),
227 match ::std::fs::File::create(clif_file_name) {
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();
237 tcx.sess.warn(&format!("err opening clif file: {:?}", e));
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)?;
247 let mut clif = String::new();
248 ::cranelift::codegen::write::decorate_function(
249 &mut &self.clif_comments,
252 // FIXME use DisplayFunctionAnnotations::default() instead
253 &DisplayFunctionAnnotations {
259 writeln!(f, "\n{}", clif)