1 //! Intermediate representation of a function.
2 //!
3 //! The `Function` struct defined in this module owns all of its basic blocks and
4 //! instructions.
5 
6 use crate::entity::{PrimaryMap, SecondaryMap};
7 use crate::ir;
8 use crate::ir::JumpTables;
9 use crate::ir::{
10     instructions::BranchInfo, Block, DynamicStackSlot, DynamicStackSlotData, DynamicType,
11     ExtFuncData, FuncRef, GlobalValue, GlobalValueData, Heap, HeapData, Inst, InstructionData,
12     JumpTable, JumpTableData, Opcode, SigRef, StackSlot, StackSlotData, Table, TableData, Type,
13 };
14 use crate::ir::{DataFlowGraph, ExternalName, Layout, Signature};
15 use crate::ir::{DynamicStackSlots, SourceLocs, StackSlots};
16 use crate::isa::CallConv;
17 use crate::value_label::ValueLabelsRanges;
18 use crate::write::write_function;
19 #[cfg(feature = "enable-serde")]
20 use alloc::string::String;
21 use core::fmt;
22 
23 #[cfg(feature = "enable-serde")]
24 use serde::de::{Deserializer, Error};
25 #[cfg(feature = "enable-serde")]
26 use serde::ser::Serializer;
27 #[cfg(feature = "enable-serde")]
28 use serde::{Deserialize, Serialize};
29 
30 /// A version marker used to ensure that serialized clif ir is never deserialized with a
31 /// different version of Cranelift.
32 #[derive(Copy, Clone, Debug)]
33 pub struct VersionMarker;
34 
35 #[cfg(feature = "enable-serde")]
36 impl Serialize for VersionMarker {
37     fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
38     where
39         S: Serializer,
40     {
41         crate::VERSION.serialize(serializer)
42     }
43 }
44 
45 #[cfg(feature = "enable-serde")]
46 impl<'de> Deserialize<'de> for VersionMarker {
47     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
48     where
49         D: Deserializer<'de>,
50     {
51         let version = String::deserialize(deserializer)?;
52         if version != crate::VERSION {
53             return Err(D::Error::custom(&format!(
54                 "Expected a clif ir function for version {}, found one for version {}",
55                 crate::VERSION,
56                 version,
57             )));
58         }
59         Ok(VersionMarker)
60     }
61 }
62 
63 ///
64 /// Functions can be cloned, but it is not a very fast operation.
65 /// The clone will have all the same entity numbers as the original.
66 #[derive(Clone)]
67 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
68 pub struct Function {
69     /// A version marker used to ensure that serialized clif ir is never deserialized with a
70     /// different version of Cranelift.
71     // Note: This must be the first field to ensure that Serde will deserialize it before
72     // attempting to deserialize other fields that are potentially changed between versions.
73     pub version_marker: VersionMarker,
74 
75     /// Name of this function. Mostly used by `.clif` files.
76     pub name: ExternalName,
77 
78     /// Signature of this function.
79     pub signature: Signature,
80 
81     /// Sized stack slots allocated in this function.
82     pub sized_stack_slots: StackSlots,
83 
84     /// Dynamic stack slots allocated in this function.
85     pub dynamic_stack_slots: DynamicStackSlots,
86 
87     /// Global values referenced.
88     pub global_values: PrimaryMap<ir::GlobalValue, ir::GlobalValueData>,
89 
90     /// Heaps referenced.
91     pub heaps: PrimaryMap<ir::Heap, ir::HeapData>,
92 
93     /// Tables referenced.
94     pub tables: PrimaryMap<ir::Table, ir::TableData>,
95 
96     /// Jump tables used in this function.
97     pub jump_tables: JumpTables,
98 
99     /// Data flow graph containing the primary definition of all instructions, blocks and values.
100     pub dfg: DataFlowGraph,
101 
102     /// Layout of blocks and instructions in the function body.
103     pub layout: Layout,
104 
105     /// Source locations.
106     ///
107     /// Track the original source location for each instruction. The source locations are not
108     /// interpreted by Cranelift, only preserved.
109     pub srclocs: SourceLocs,
110 
111     /// An optional global value which represents an expression evaluating to
112     /// the stack limit for this function. This `GlobalValue` will be
113     /// interpreted in the prologue, if necessary, to insert a stack check to
114     /// ensure that a trap happens if the stack pointer goes below the
115     /// threshold specified here.
116     pub stack_limit: Option<ir::GlobalValue>,
117 }
118 
119 impl Function {
120     /// Create a function with the given name and signature.
121     pub fn with_name_signature(name: ExternalName, sig: Signature) -> Self {
122         Self {
123             version_marker: VersionMarker,
124             name,
125             signature: sig,
126             sized_stack_slots: StackSlots::new(),
127             dynamic_stack_slots: DynamicStackSlots::new(),
128             global_values: PrimaryMap::new(),
129             heaps: PrimaryMap::new(),
130             tables: PrimaryMap::new(),
131             jump_tables: PrimaryMap::new(),
132             dfg: DataFlowGraph::new(),
133             layout: Layout::new(),
134             srclocs: SecondaryMap::new(),
135             stack_limit: None,
136         }
137     }
138 
139     /// Clear all data structures in this function.
140     pub fn clear(&mut self) {
141         self.signature.clear(CallConv::Fast);
142         self.sized_stack_slots.clear();
143         self.dynamic_stack_slots.clear();
144         self.global_values.clear();
145         self.heaps.clear();
146         self.tables.clear();
147         self.jump_tables.clear();
148         self.dfg.clear();
149         self.layout.clear();
150         self.srclocs.clear();
151         self.stack_limit = None;
152     }
153 
154     /// Create a new empty, anonymous function with a Fast calling convention.
155     pub fn new() -> Self {
156         Self::with_name_signature(ExternalName::default(), Signature::new(CallConv::Fast))
157     }
158 
159     /// Creates a jump table in the function, to be used by `br_table` instructions.
160     pub fn create_jump_table(&mut self, data: JumpTableData) -> JumpTable {
161         self.jump_tables.push(data)
162     }
163 
164     /// Creates a sized stack slot in the function, to be used by `stack_load`, `stack_store`
165     /// and `stack_addr` instructions.
166     pub fn create_sized_stack_slot(&mut self, data: StackSlotData) -> StackSlot {
167         self.sized_stack_slots.push(data)
168     }
169 
170     /// Creates a dynamic stack slot in the function, to be used by `dynamic_stack_load`,
171     /// `dynamic_stack_store` and `dynamic_stack_addr` instructions.
172     pub fn create_dynamic_stack_slot(&mut self, data: DynamicStackSlotData) -> DynamicStackSlot {
173         self.dynamic_stack_slots.push(data)
174     }
175 
176     /// Adds a signature which can later be used to declare an external function import.
177     pub fn import_signature(&mut self, signature: Signature) -> SigRef {
178         self.dfg.signatures.push(signature)
179     }
180 
181     /// Declare an external function import.
182     pub fn import_function(&mut self, data: ExtFuncData) -> FuncRef {
183         self.dfg.ext_funcs.push(data)
184     }
185 
186     /// Declares a global value accessible to the function.
187     pub fn create_global_value(&mut self, data: GlobalValueData) -> GlobalValue {
188         self.global_values.push(data)
189     }
190 
191     /// Find the global dyn_scale value associated with given DynamicType
192     pub fn get_dyn_scale(&self, ty: DynamicType) -> GlobalValue {
193         self.dfg.dynamic_types.get(ty).unwrap().dynamic_scale
194     }
195 
196     /// Find the global dyn_scale for the given stack slot.
197     pub fn get_dynamic_slot_scale(&self, dss: DynamicStackSlot) -> GlobalValue {
198         let dyn_ty = self.dynamic_stack_slots.get(dss).unwrap().dyn_ty;
199         self.get_dyn_scale(dyn_ty)
200     }
201 
202     /// Get a concrete `Type` from a user defined `DynamicType`.
203     pub fn get_concrete_dynamic_ty(&self, ty: DynamicType) -> Option<Type> {
204         self.dfg
205             .dynamic_types
206             .get(ty)
207             .unwrap_or_else(|| panic!("Undeclared dynamic vector type: {}", ty))
208             .concrete()
209     }
210 
211     /// Declares a heap accessible to the function.
212     pub fn create_heap(&mut self, data: HeapData) -> Heap {
213         self.heaps.push(data)
214     }
215 
216     /// Declares a table accessible to the function.
217     pub fn create_table(&mut self, data: TableData) -> Table {
218         self.tables.push(data)
219     }
220 
221     /// Return an object that can display this function with correct ISA-specific annotations.
222     pub fn display(&self) -> DisplayFunction<'_> {
223         DisplayFunction(self, Default::default())
224     }
225 
226     /// Return an object that can display this function with correct ISA-specific annotations.
227     pub fn display_with<'a>(
228         &'a self,
229         annotations: DisplayFunctionAnnotations<'a>,
230     ) -> DisplayFunction<'a> {
231         DisplayFunction(self, annotations)
232     }
233 
234     /// Find a presumed unique special-purpose function parameter value.
235     ///
236     /// Returns the value of the last `purpose` parameter, or `None` if no such parameter exists.
237     pub fn special_param(&self, purpose: ir::ArgumentPurpose) -> Option<ir::Value> {
238         let entry = self.layout.entry_block().expect("Function is empty");
239         self.signature
240             .special_param_index(purpose)
241             .map(|i| self.dfg.block_params(entry)[i])
242     }
243 
244     /// Starts collection of debug information.
245     pub fn collect_debug_info(&mut self) {
246         self.dfg.collect_debug_info();
247     }
248 
249     /// Changes the destination of a jump or branch instruction.
250     /// Does nothing if called with a non-jump or non-branch instruction.
251     ///
252     /// Note that this method ignores multi-destination branches like `br_table`.
253     pub fn change_branch_destination(&mut self, inst: Inst, new_dest: Block) {
254         match self.dfg[inst].branch_destination_mut() {
255             None => (),
256             Some(inst_dest) => *inst_dest = new_dest,
257         }
258     }
259 
260     /// Rewrite the branch destination to `new_dest` if the destination matches `old_dest`.
261     /// Does nothing if called with a non-jump or non-branch instruction.
262     ///
263     /// Unlike [change_branch_destination](Function::change_branch_destination), this method rewrite the destinations of
264     /// multi-destination branches like `br_table`.
265     pub fn rewrite_branch_destination(&mut self, inst: Inst, old_dest: Block, new_dest: Block) {
266         match self.dfg.analyze_branch(inst) {
267             BranchInfo::SingleDest(dest, ..) => {
268                 if dest == old_dest {
269                     self.change_branch_destination(inst, new_dest);
270                 }
271             }
272 
273             BranchInfo::Table(table, default_dest) => {
274                 self.jump_tables[table].iter_mut().for_each(|entry| {
275                     if *entry == old_dest {
276                         *entry = new_dest;
277                     }
278                 });
279 
280                 if default_dest == Some(old_dest) {
281                     match &mut self.dfg[inst] {
282                         InstructionData::BranchTable { destination, .. } => {
283                             *destination = new_dest;
284                         }
285                         _ => panic!(
286                             "Unexpected instruction {} having default destination",
287                             self.dfg.display_inst(inst)
288                         ),
289                     }
290                 }
291             }
292 
293             BranchInfo::NotABranch => {}
294         }
295     }
296 
297     /// Checks that the specified block can be encoded as a basic block.
298     ///
299     /// On error, returns the first invalid instruction and an error message.
300     pub fn is_block_basic(&self, block: Block) -> Result<(), (Inst, &'static str)> {
301         let dfg = &self.dfg;
302         let inst_iter = self.layout.block_insts(block);
303 
304         // Ignore all instructions prior to the first branch.
305         let mut inst_iter = inst_iter.skip_while(|&inst| !dfg[inst].opcode().is_branch());
306 
307         // A conditional branch is permitted in a basic block only when followed
308         // by a terminal jump instruction.
309         if let Some(_branch) = inst_iter.next() {
310             if let Some(next) = inst_iter.next() {
311                 match dfg[next].opcode() {
312                     Opcode::Jump => (),
313                     _ => return Err((next, "post-branch instruction not jump")),
314                 }
315             }
316         }
317 
318         Ok(())
319     }
320 
321     /// Returns true if the function is function that doesn't call any other functions. This is not
322     /// to be confused with a "leaf function" in Windows terminology.
323     pub fn is_leaf(&self) -> bool {
324         // Conservative result: if there's at least one function signature referenced in this
325         // function, assume it is not a leaf.
326         self.dfg.signatures.is_empty()
327     }
328 
329     /// Replace the `dst` instruction's data with the `src` instruction's data
330     /// and then remove `src`.
331     ///
332     /// `src` and its result values should not be used at all, as any uses would
333     /// be left dangling after calling this method.
334     ///
335     /// `src` and `dst` must have the same number of resulting values, and
336     /// `src`'s i^th value must have the same type as `dst`'s i^th value.
337     pub fn transplant_inst(&mut self, dst: Inst, src: Inst) {
338         debug_assert_eq!(
339             self.dfg.inst_results(dst).len(),
340             self.dfg.inst_results(src).len()
341         );
342         debug_assert!(self
343             .dfg
344             .inst_results(dst)
345             .iter()
346             .zip(self.dfg.inst_results(src))
347             .all(|(a, b)| self.dfg.value_type(*a) == self.dfg.value_type(*b)));
348 
349         self.dfg[dst] = self.dfg[src].clone();
350         self.layout.remove_inst(src);
351     }
352 
353     /// Size occupied by all stack slots associated with this function.
354     ///
355     /// Does not include any padding necessary due to offsets
356     pub fn fixed_stack_size(&self) -> u32 {
357         self.sized_stack_slots.values().map(|ss| ss.size).sum()
358     }
359 }
360 
361 /// Additional annotations for function display.
362 #[derive(Default)]
363 pub struct DisplayFunctionAnnotations<'a> {
364     /// Enable value labels annotations.
365     pub value_ranges: Option<&'a ValueLabelsRanges>,
366 }
367 
368 /// Wrapper type capable of displaying a `Function` with correct ISA annotations.
369 pub struct DisplayFunction<'a>(&'a Function, DisplayFunctionAnnotations<'a>);
370 
371 impl<'a> fmt::Display for DisplayFunction<'a> {
372     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
373         write_function(fmt, self.0)
374     }
375 }
376 
377 impl fmt::Display for Function {
378     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
379         write_function(fmt, self)
380     }
381 }
382 
383 impl fmt::Debug for Function {
384     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
385         write_function(fmt, self)
386     }
387 }
388