1 //! Cranelift compilation context and main entry point.
2 //!
3 //! When compiling many small functions, it is important to avoid repeatedly allocating and
4 //! deallocating the data structures needed for compilation. The `Context` struct is used to hold
5 //! on to memory allocations between function compilations.
6 //!
7 //! The context does not hold a `TargetIsa` instance which has to be provided as an argument
8 //! instead. This is because an ISA instance is immutable and can be used by multiple compilation
9 //! contexts concurrently. Typically, you would have one context per compilation thread and only a
10 //! single ISA instance.
11 
12 use crate::alias_analysis::AliasAnalysis;
13 use crate::dominator_tree::DominatorTree;
14 use crate::egraph::EgraphPass;
15 use crate::flowgraph::ControlFlowGraph;
16 use crate::ir::Function;
17 use crate::isa::TargetIsa;
18 use crate::legalizer::simple_legalize;
19 use crate::loop_analysis::LoopAnalysis;
20 use crate::machinst::{CompiledCode, CompiledCodeStencil};
21 use crate::nan_canonicalization::do_nan_canonicalization;
22 use crate::remove_constant_phis::do_remove_constant_phis;
23 use crate::result::{CodegenResult, CompileResult};
24 use crate::settings::{FlagsOrIsa, OptLevel};
25 use crate::trace;
26 use crate::unreachable_code::eliminate_unreachable_code;
27 use crate::verifier::{verify_context, VerifierErrors, VerifierResult};
28 use crate::{timing, CompileError};
29 #[cfg(feature = "souper-harvest")]
30 use alloc::string::String;
31 use alloc::vec::Vec;
32 use cranelift_control::ControlPlane;
33 use target_lexicon::Architecture;
34 
35 #[cfg(feature = "souper-harvest")]
36 use crate::souper_harvest::do_souper_harvest;
37 
38 /// Persistent data structures and compilation pipeline.
39 pub struct Context {
40     /// The function we're compiling.
41     pub func: Function,
42 
43     /// The control flow graph of `func`.
44     pub cfg: ControlFlowGraph,
45 
46     /// Dominator tree for `func`.
47     pub domtree: DominatorTree,
48 
49     /// Loop analysis of `func`.
50     pub loop_analysis: LoopAnalysis,
51 
52     /// Result of MachBackend compilation, if computed.
53     pub(crate) compiled_code: Option<CompiledCode>,
54 
55     /// Flag: do we want a disassembly with the CompiledCode?
56     pub want_disasm: bool,
57 }
58 
59 impl Context {
60     /// Allocate a new compilation context.
61     ///
62     /// The returned instance should be reused for compiling multiple functions in order to avoid
63     /// needless allocator thrashing.
64     pub fn new() -> Self {
65         Self::for_function(Function::new())
66     }
67 
68     /// Allocate a new compilation context with an existing Function.
69     ///
70     /// The returned instance should be reused for compiling multiple functions in order to avoid
71     /// needless allocator thrashing.
72     pub fn for_function(func: Function) -> Self {
73         Self {
74             func,
75             cfg: ControlFlowGraph::new(),
76             domtree: DominatorTree::new(),
77             loop_analysis: LoopAnalysis::new(),
78             compiled_code: None,
79             want_disasm: false,
80         }
81     }
82 
83     /// Clear all data structures in this context.
84     pub fn clear(&mut self) {
85         self.func.clear();
86         self.cfg.clear();
87         self.domtree.clear();
88         self.loop_analysis.clear();
89         self.compiled_code = None;
90         self.want_disasm = false;
91     }
92 
93     /// Returns the compilation result for this function, available after any `compile` function
94     /// has been called.
95     pub fn compiled_code(&self) -> Option<&CompiledCode> {
96         self.compiled_code.as_ref()
97     }
98 
99     /// Set the flag to request a disassembly when compiling with a
100     /// `MachBackend` backend.
101     pub fn set_disasm(&mut self, val: bool) {
102         self.want_disasm = val;
103     }
104 
105     /// Compile the function, and emit machine code into a `Vec<u8>`.
106     ///
107     /// Run the function through all the passes necessary to generate
108     /// code for the target ISA represented by `isa`, as well as the
109     /// final step of emitting machine code into a `Vec<u8>`. The
110     /// machine code is not relocated. Instead, any relocations can be
111     /// obtained from `compiled_code()`.
112     ///
113     /// Performs any optimizations that are enabled, unless
114     /// `optimize()` was already invoked.
115     ///
116     /// This function calls `compile`, taking care to resize `mem` as
117     /// needed.
118     ///
119     /// Returns information about the function's code and read-only
120     /// data.
121     pub fn compile_and_emit(
122         &mut self,
123         isa: &dyn TargetIsa,
124         mem: &mut Vec<u8>,
125         ctrl_plane: &mut ControlPlane,
126     ) -> CompileResult<&CompiledCode> {
127         let compiled_code = self.compile(isa, ctrl_plane)?;
128         mem.extend_from_slice(compiled_code.code_buffer());
129         Ok(compiled_code)
130     }
131 
132     /// Internally compiles the function into a stencil.
133     ///
134     /// Public only for testing and fuzzing purposes.
135     pub fn compile_stencil(
136         &mut self,
137         isa: &dyn TargetIsa,
138         ctrl_plane: &mut ControlPlane,
139     ) -> CodegenResult<CompiledCodeStencil> {
140         let _tt = timing::compile();
141 
142         self.verify_if(isa)?;
143 
144         self.optimize(isa, ctrl_plane)?;
145 
146         isa.compile_function(&self.func, &self.domtree, self.want_disasm, ctrl_plane)
147     }
148 
149     /// Optimize the function, performing all compilation steps up to
150     /// but not including machine-code lowering and register
151     /// allocation.
152     ///
153     /// Public only for testing purposes.
154     pub fn optimize(
155         &mut self,
156         isa: &dyn TargetIsa,
157         ctrl_plane: &mut ControlPlane,
158     ) -> CodegenResult<()> {
159         log::debug!(
160             "Number of CLIF instructions to optimize: {}",
161             self.func.dfg.num_insts()
162         );
163         log::debug!(
164             "Number of CLIF blocks to optimize: {}",
165             self.func.dfg.num_blocks()
166         );
167 
168         let opt_level = isa.flags().opt_level();
169         crate::trace!(
170             "Optimizing (opt level {:?}):\n{}",
171             opt_level,
172             self.func.display()
173         );
174 
175         self.compute_cfg();
176         if isa.flags().enable_nan_canonicalization() {
177             self.canonicalize_nans(isa)?;
178         }
179 
180         self.legalize(isa)?;
181 
182         self.compute_domtree();
183         self.eliminate_unreachable_code(isa)?;
184         self.remove_constant_phis(isa)?;
185 
186         if opt_level != OptLevel::None {
187             self.egraph_pass(isa, ctrl_plane)?;
188         }
189 
190         Ok(())
191     }
192 
193     /// Compile the function.
194     ///
195     /// Run the function through all the passes necessary to generate code for the target ISA
196     /// represented by `isa`. This does not include the final step of emitting machine code into a
197     /// code sink.
198     ///
199     /// Returns information about the function's code and read-only data.
200     pub fn compile(
201         &mut self,
202         isa: &dyn TargetIsa,
203         ctrl_plane: &mut ControlPlane,
204     ) -> CompileResult<&CompiledCode> {
205         let stencil = self
206             .compile_stencil(isa, ctrl_plane)
207             .map_err(|error| CompileError {
208                 inner: error,
209                 func: &self.func,
210             })?;
211         Ok(self
212             .compiled_code
213             .insert(stencil.apply_params(&self.func.params)))
214     }
215 
216     /// If available, return information about the code layout in the
217     /// final machine code: the offsets (in bytes) of each basic-block
218     /// start, and all basic-block edges.
219     #[deprecated = "use CompiledCode::get_code_bb_layout"]
220     pub fn get_code_bb_layout(&self) -> Option<(Vec<usize>, Vec<(usize, usize)>)> {
221         self.compiled_code().map(CompiledCode::get_code_bb_layout)
222     }
223 
224     /// Creates unwind information for the function.
225     ///
226     /// Returns `None` if the function has no unwind information.
227     #[cfg(feature = "unwind")]
228     #[deprecated = "use CompiledCode::create_unwind_info"]
229     pub fn create_unwind_info(
230         &self,
231         isa: &dyn TargetIsa,
232     ) -> CodegenResult<Option<crate::isa::unwind::UnwindInfo>> {
233         self.compiled_code().unwrap().create_unwind_info(isa)
234     }
235 
236     /// Run the verifier on the function.
237     ///
238     /// Also check that the dominator tree and control flow graph are consistent with the function.
239     ///
240     /// TODO: rename to "CLIF validate" or similar.
241     pub fn verify<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> VerifierResult<()> {
242         let mut errors = VerifierErrors::default();
243         let _ = verify_context(&self.func, &self.cfg, &self.domtree, fisa, &mut errors);
244 
245         if errors.is_empty() {
246             Ok(())
247         } else {
248             Err(errors)
249         }
250     }
251 
252     /// Run the verifier only if the `enable_verifier` setting is true.
253     pub fn verify_if<'a, FOI: Into<FlagsOrIsa<'a>>>(&self, fisa: FOI) -> CodegenResult<()> {
254         let fisa = fisa.into();
255         if fisa.flags.enable_verifier() {
256             self.verify(fisa)?;
257         }
258         Ok(())
259     }
260 
261     /// Perform constant-phi removal on the function.
262     pub fn remove_constant_phis<'a, FOI: Into<FlagsOrIsa<'a>>>(
263         &mut self,
264         fisa: FOI,
265     ) -> CodegenResult<()> {
266         do_remove_constant_phis(&mut self.func, &mut self.domtree);
267         self.verify_if(fisa)?;
268         Ok(())
269     }
270 
271     /// Perform NaN canonicalizing rewrites on the function.
272     pub fn canonicalize_nans(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> {
273         // Currently only RiscV64 is the only arch that may not have vector support.
274         let has_vector_support = match isa.triple().architecture {
275             Architecture::Riscv64(_) => match isa.isa_flags().iter().find(|f| f.name == "has_v") {
276                 Some(value) => value.as_bool().unwrap_or(false),
277                 None => false,
278             },
279             _ => true,
280         };
281         do_nan_canonicalization(&mut self.func, has_vector_support);
282         self.verify_if(isa)
283     }
284 
285     /// Run the legalizer for `isa` on the function.
286     pub fn legalize(&mut self, isa: &dyn TargetIsa) -> CodegenResult<()> {
287         // Legalization invalidates the domtree and loop_analysis by mutating the CFG.
288         // TODO: Avoid doing this when legalization doesn't actually mutate the CFG.
289         self.domtree.clear();
290         self.loop_analysis.clear();
291 
292         // Run some specific legalizations only.
293         simple_legalize(&mut self.func, &mut self.cfg, isa);
294         self.verify_if(isa)
295     }
296 
297     /// Compute the control flow graph.
298     pub fn compute_cfg(&mut self) {
299         self.cfg.compute(&self.func)
300     }
301 
302     /// Compute dominator tree.
303     pub fn compute_domtree(&mut self) {
304         self.domtree.compute(&self.func, &self.cfg)
305     }
306 
307     /// Compute the loop analysis.
308     pub fn compute_loop_analysis(&mut self) {
309         self.loop_analysis
310             .compute(&self.func, &self.cfg, &self.domtree)
311     }
312 
313     /// Compute the control flow graph and dominator tree.
314     pub fn flowgraph(&mut self) {
315         self.compute_cfg();
316         self.compute_domtree()
317     }
318 
319     /// Perform unreachable code elimination.
320     pub fn eliminate_unreachable_code<'a, FOI>(&mut self, fisa: FOI) -> CodegenResult<()>
321     where
322         FOI: Into<FlagsOrIsa<'a>>,
323     {
324         eliminate_unreachable_code(&mut self.func, &mut self.cfg, &self.domtree);
325         self.verify_if(fisa)
326     }
327 
328     /// Replace all redundant loads with the known values in
329     /// memory. These are loads whose values were already loaded by
330     /// other loads earlier, as well as loads whose values were stored
331     /// by a store instruction to the same instruction (so-called
332     /// "store-to-load forwarding").
333     pub fn replace_redundant_loads(&mut self) -> CodegenResult<()> {
334         let mut analysis = AliasAnalysis::new(&self.func, &self.domtree);
335         analysis.compute_and_update_aliases(&mut self.func);
336         Ok(())
337     }
338 
339     /// Harvest candidate left-hand sides for superoptimization with Souper.
340     #[cfg(feature = "souper-harvest")]
341     pub fn souper_harvest(
342         &mut self,
343         out: &mut std::sync::mpsc::Sender<String>,
344     ) -> CodegenResult<()> {
345         do_souper_harvest(&self.func, out);
346         Ok(())
347     }
348 
349     /// Run optimizations via the egraph infrastructure.
350     pub fn egraph_pass<'a, FOI>(
351         &mut self,
352         fisa: FOI,
353         ctrl_plane: &mut ControlPlane,
354     ) -> CodegenResult<()>
355     where
356         FOI: Into<FlagsOrIsa<'a>>,
357     {
358         let _tt = timing::egraph();
359 
360         trace!(
361             "About to optimize with egraph phase:\n{}",
362             self.func.display()
363         );
364         let fisa = fisa.into();
365         self.compute_loop_analysis();
366         let mut alias_analysis = AliasAnalysis::new(&self.func, &self.domtree);
367         let mut pass = EgraphPass::new(
368             &mut self.func,
369             &self.domtree,
370             &self.loop_analysis,
371             &mut alias_analysis,
372             &fisa.flags,
373             ctrl_plane,
374         );
375         pass.run();
376         log::debug!("egraph stats: {:?}", pass.stats);
377         trace!("pinned_union_count: {}", pass.eclasses.pinned_union_count);
378         trace!("After egraph optimization:\n{}", self.func.display());
379 
380         self.verify_if(fisa)
381     }
382 }
383