3 use cranelift_codegen::{
5 ir::{entities::AnyEntity, function::DisplayFunctionAnnotations},
6 write::{FuncWriter, PlainWriter},
9 use rustc_session::config::OutputType;
11 use crate::prelude::*;
13 /// This module provides the [CommentWriter] which makes it possible
14 /// to add comments to the written cranelift ir.
22 /// function u0:0(i64, i64, i64) system_v {
23 /// ; 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
24 /// ; instance Instance { def: Item(DefId(0/0:29 ~ example[8787]::{{impl}}[0]::call_once[0])), substs: [ReErased, ReErased] }
25 /// ; sig ([IsNotEmpty, (&&[u16],)]; c_variadic: false)->(u8, u8)
27 /// ; ssa {_2: NOT_SSA, _4: NOT_SSA, _0: NOT_SSA, _3: (empty), _1: NOT_SSA}
28 /// ; msg loc.idx param pass mode ssa flags ty
29 /// ; ret _0 = v0 ByRef NOT_SSA (u8, u8)
30 /// ; arg _1 = v1 ByRef NOT_SSA IsNotEmpty
31 /// ; arg _2.0 = v2 ByVal(types::I64) NOT_SSA &&[u16]
33 /// ss0 = explicit_slot 0 ; _1: IsNotEmpty size=0 align=1,8
34 /// ss1 = explicit_slot 8 ; _2: (&&[u16],) size=8 align=8,8
35 /// ss2 = explicit_slot 8 ; _4: (&&[u16],) size=8 align=8,8
36 /// sig0 = (i64, i64, i64) system_v
37 /// sig1 = (i64, i64, i64) system_v
38 /// fn0 = colocated u0:6 sig1 ; Instance { def: Item(DefId(0/0:31 ~ example[8787]::{{impl}}[1]::call_mut[0])), substs: [ReErased, ReErased] }
40 /// block0(v0: i64, v1: i64, v2: i64):
41 /// v3 = stack_addr.i64 ss0
42 /// v4 = stack_addr.i64 ss1
44 /// v5 = stack_addr.i64 ss2
54 /// ; _0 = const mini_core::FnMut::call_mut(move _3, move _4)
56 /// call fn0(v0, v3, v7)
68 pub(crate) struct CommentWriter {
69 global_comments: Vec<String>,
70 entity_comments: FxHashMap<AnyEntity, String>,
74 pub(crate) fn new<'tcx>(tcx: TyCtxt<'tcx>, instance: Instance<'tcx>) -> Self {
75 let global_comments = if cfg!(debug_assertions) {
77 format!("symbol {}", tcx.symbol_name(instance).name),
78 format!("instance {:?}", instance),
81 tcx.normalize_erasing_late_bound_regions(
82 ParamEnv::reveal_all(),
83 &crate::abi::fn_sig_for_fn_abi(tcx, instance)
94 entity_comments: FxHashMap::default(),
99 #[cfg(debug_assertions)]
101 pub(crate) fn add_global_comment<S: Into<String>>(&mut self, comment: S) {
102 self.global_comments.push(comment.into());
105 pub(crate) fn add_comment<S: Into<String> + AsRef<str>, E: Into<AnyEntity>>(
110 use std::collections::hash_map::Entry;
111 match self.entity_comments.entry(entity.into()) {
112 Entry::Occupied(mut occ) => {
113 occ.get_mut().push('\n');
114 occ.get_mut().push_str(comment.as_ref());
116 Entry::Vacant(vac) => {
117 vac.insert(comment.into());
123 impl FuncWriter for &'_ CommentWriter {
126 w: &mut dyn fmt::Write,
128 reg_info: Option<&isa::RegInfo>,
129 ) -> Result<bool, fmt::Error> {
130 for comment in &self.global_comments {
131 if !comment.is_empty() {
132 writeln!(w, "; {}", comment)?;
137 if !self.global_comments.is_empty() {
141 self.super_preamble(w, func, reg_info)
144 fn write_entity_definition(
146 w: &mut dyn fmt::Write,
149 value: &dyn fmt::Display,
151 write!(w, " {} = {}", entity, value)?;
153 if let Some(comment) = self.entity_comments.get(&entity) {
154 writeln!(w, " ; {}", comment.replace('\n', "\n; "))
160 fn write_block_header(
162 w: &mut dyn fmt::Write,
164 isa: Option<&dyn isa::TargetIsa>,
168 PlainWriter.write_block_header(w, func, isa, block, indent)
171 fn write_instruction(
173 w: &mut dyn fmt::Write,
175 aliases: &SecondaryMap<Value, Vec<Value>>,
176 isa: Option<&dyn isa::TargetIsa>,
180 PlainWriter.write_instruction(w, func, aliases, isa, inst, indent)?;
181 if let Some(comment) = self.entity_comments.get(&inst.into()) {
182 writeln!(w, "; {}", comment.replace('\n', "\n; "))?;
188 #[cfg(debug_assertions)]
189 impl<B: Backend + 'static> FunctionCx<'_, '_, B> {
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 write_clif_file<'tcx>(
206 isa: Option<&dyn cranelift_codegen::isa::TargetIsa>,
207 instance: Instance<'tcx>,
208 context: &cranelift_codegen::Context,
209 mut clif_comments: &CommentWriter,
213 if !cfg!(debug_assertions) && !tcx.sess.opts.output_types.contains_key(&OutputType::LlvmAssembly) {
217 let value_ranges = isa.map(|isa| {
219 .build_value_labels_ranges(isa)
220 .expect("value location ranges")
223 let symbol_name = tcx.symbol_name(instance).name;
224 let clif_file_name = format!(
226 concat!(env!("CARGO_MANIFEST_DIR"), "/target/out/clif"),
227 tcx.crate_name(LOCAL_CRATE),
232 let mut clif = String::new();
233 cranelift_codegen::write::decorate_function(
237 &DisplayFunctionAnnotations {
238 isa: Some(&*crate::build_isa(
239 tcx.sess, true, /* PIC doesn't matter here */
241 value_ranges: value_ranges.as_ref(),
246 let res: std::io::Result<()> = try {
247 let mut file = std::fs::File::create(clif_file_name)?;
248 let target_triple = crate::target_triple(tcx.sess);
249 writeln!(file, "test compile")?;
250 writeln!(file, "set is_pic")?;
251 writeln!(file, "set enable_simd")?;
252 writeln!(file, "target {} haswell", target_triple)?;
254 file.write(clif.as_bytes())?;
256 if let Err(err) = res {
257 tcx.sess.warn(&format!("err writing clif file: {}", err));
261 impl<B: Backend + 'static> fmt::Debug for FunctionCx<'_, '_, B> {
262 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263 writeln!(f, "{:?}", self.instance.substs)?;
264 writeln!(f, "{:?}", self.local_map)?;
266 let mut clif = String::new();
267 ::cranelift_codegen::write::decorate_function(
268 &mut &self.clif_comments,
271 &DisplayFunctionAnnotations::default(),
274 writeln!(f, "\n{}", clif)