1 //! Cranelift IR entity references.
2 //!
3 //! Instructions in Cranelift IR need to reference other entities in the function. This can be other
4 //! parts of the function like basic blocks or stack slots, or it can be external entities
5 //! that are declared in the function preamble in the text format.
6 //!
7 //! These entity references in instruction operands are not implemented as Rust references both
8 //! because Rust's ownership and mutability rules make it difficult, and because 64-bit pointers
9 //! take up a lot of space, and we want a compact in-memory representation. Instead, entity
10 //! references are structs wrapping a `u32` index into a table in the `Function` main data
11 //! structure. There is a separate index type for each entity type, so we don't lose type safety.
12 //!
13 //! The `entities` module defines public types for the entity references along with constants
14 //! representing an invalid reference. We prefer to use `Option<EntityRef>` whenever possible, but
15 //! unfortunately that type is twice as large as the 32-bit index type on its own. Thus, compact
16 //! data structures use the `PackedOption<EntityRef>` representation, while function arguments and
17 //! return values prefer the more Rust-like `Option<EntityRef>` variant.
18 //!
19 //! The entity references all implement the `Display` trait in a way that matches the textual IR
20 //! format.
21 
22 use crate::entity::entity_impl;
23 use core::fmt;
24 use core::u32;
25 #[cfg(feature = "enable-serde")]
26 use serde_derive::{Deserialize, Serialize};
27 
28 /// An opaque reference to a [basic block](https://en.wikipedia.org/wiki/Basic_block) in a
29 /// [`Function`](super::function::Function).
30 ///
31 /// You can get a `Block` using
32 /// [`FunctionBuilder::create_block`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_block)
33 ///
34 /// While the order is stable, it is arbitrary and does not necessarily resemble the layout order.
35 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
36 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
37 pub struct Block(u32);
38 entity_impl!(Block, "block");
39 
40 impl Block {
41     /// Create a new block reference from its number. This corresponds to the `blockNN` representation.
42     ///
43     /// This method is for use by the parser.
44     pub fn with_number(n: u32) -> Option<Self> {
45         if n < u32::MAX {
46             Some(Self(n))
47         } else {
48             None
49         }
50     }
51 }
52 
53 /// An opaque reference to an SSA value.
54 ///
55 /// You can get a constant `Value` from the following
56 /// [`InstBuilder`](super::InstBuilder) instructions:
57 ///
58 /// - [`iconst`](super::InstBuilder::iconst) for integer constants
59 /// - [`f16const`](super::InstBuilder::f16const) for 16-bit float constants
60 /// - [`f32const`](super::InstBuilder::f32const) for 32-bit float constants
61 /// - [`f64const`](super::InstBuilder::f64const) for 64-bit float constants
62 /// - [`f128const`](super::InstBuilder::f128const) for 128-bit float constants
63 /// - [`vconst`](super::InstBuilder::vconst) for vector constants
64 /// - [`null`](super::InstBuilder::null) for null reference constants
65 ///
66 /// Any `InstBuilder` instruction that has an output will also return a `Value`.
67 ///
68 /// While the order is stable, it is arbitrary.
69 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
70 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
71 pub struct Value(u32);
72 entity_impl!(Value, "v");
73 
74 impl Value {
75     /// Create a value from its number representation.
76     /// This is the number in the `vNN` notation.
77     ///
78     /// This method is for use by the parser.
79     pub fn with_number(n: u32) -> Option<Self> {
80         if n < u32::MAX / 2 {
81             Some(Self(n))
82         } else {
83             None
84         }
85     }
86 }
87 
88 /// An opaque reference to an instruction in a [`Function`](super::Function).
89 ///
90 /// Most usage of `Inst` is internal. `Inst`ructions are returned by
91 /// [`InstBuilder`](super::InstBuilder) instructions that do not return a
92 /// [`Value`], such as control flow and trap instructions, as well as instructions that return a
93 /// variable (potentially zero!) number of values, like call or call-indirect instructions. To get
94 /// the `Value` of such instructions, use [`inst_results`](super::DataFlowGraph::inst_results) or
95 /// its analogue in `cranelift_frontend::FuncBuilder`.
96 ///
97 /// [inst_comment]: https://github.com/bjorn3/rustc_codegen_cranelift/blob/0f8814fd6da3d436a90549d4bb19b94034f2b19c/src/pretty_clif.rs
98 ///
99 /// While the order is stable, it is arbitrary and does not necessarily resemble the layout order.
100 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
101 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
102 pub struct Inst(u32);
103 entity_impl!(Inst, "inst");
104 
105 /// An opaque reference to a stack slot.
106 ///
107 /// Stack slots represent an address on the
108 /// [call stack](https://en.wikipedia.org/wiki/Call_stack).
109 ///
110 /// `StackSlot`s can be created with
111 /// [`FunctionBuilder::create_sized_stack_slot`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_sized_stack_slot)
112 /// or
113 /// [`FunctionBuilder::create_dynamic_stack_slot`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_dynamic_stack_slot).
114 ///
115 /// `StackSlot`s are most often used with
116 /// [`stack_addr`](super::InstBuilder::stack_addr),
117 /// [`stack_load`](super::InstBuilder::stack_load), and
118 /// [`stack_store`](super::InstBuilder::stack_store).
119 ///
120 /// While the order is stable, it is arbitrary and does not necessarily resemble the stack order.
121 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
122 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
123 pub struct StackSlot(u32);
124 entity_impl!(StackSlot, "ss");
125 
126 impl StackSlot {
127     /// Create a new stack slot reference from its number.
128     ///
129     /// This method is for use by the parser.
130     pub fn with_number(n: u32) -> Option<Self> {
131         if n < u32::MAX {
132             Some(Self(n))
133         } else {
134             None
135         }
136     }
137 }
138 
139 /// An opaque reference to a dynamic stack slot.
140 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
141 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
142 pub struct DynamicStackSlot(u32);
143 entity_impl!(DynamicStackSlot, "dss");
144 
145 impl DynamicStackSlot {
146     /// Create a new stack slot reference from its number.
147     ///
148     /// This method is for use by the parser.
149     pub fn with_number(n: u32) -> Option<Self> {
150         if n < u32::MAX {
151             Some(Self(n))
152         } else {
153             None
154         }
155     }
156 }
157 
158 /// An opaque reference to a dynamic type.
159 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
160 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
161 pub struct DynamicType(u32);
162 entity_impl!(DynamicType, "dt");
163 
164 impl DynamicType {
165     /// Create a new dynamic type reference from its number.
166     ///
167     /// This method is for use by the parser.
168     pub fn with_number(n: u32) -> Option<Self> {
169         if n < u32::MAX {
170             Some(Self(n))
171         } else {
172             None
173         }
174     }
175 }
176 
177 /// An opaque reference to a global value.
178 ///
179 /// A `GlobalValue` is a [`Value`] that will be live across the entire
180 /// function lifetime. It can be preloaded from other global values.
181 ///
182 /// You can create a `GlobalValue` in the following ways:
183 ///
184 /// - When compiling to WASM, you can use it to load values from a
185 /// [`VmContext`](super::GlobalValueData::VMContext) using
186 /// [`FuncEnvironment::make_global`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_global).
187 /// - When compiling to native code, you can use it for objects in static memory with
188 /// [`Module::declare_data_in_func`](https://docs.rs/cranelift-module/*/cranelift_module/trait.Module.html#method.declare_data_in_func).
189 /// - For any compilation target, it can be registered with
190 /// [`FunctionBuilder::create_global_value`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_global_value).
191 ///
192 /// `GlobalValue`s can be retrieved with
193 /// [`InstBuilder:global_value`](super::InstBuilder::global_value).
194 ///
195 /// While the order is stable, it is arbitrary.
196 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
197 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
198 pub struct GlobalValue(u32);
199 entity_impl!(GlobalValue, "gv");
200 
201 impl GlobalValue {
202     /// Create a new global value reference from its number.
203     ///
204     /// This method is for use by the parser.
205     pub fn with_number(n: u32) -> Option<Self> {
206         if n < u32::MAX {
207             Some(Self(n))
208         } else {
209             None
210         }
211     }
212 }
213 
214 /// An opaque reference to a memory type.
215 ///
216 /// A `MemoryType` is a descriptor of a struct layout in memory, with
217 /// types and proof-carrying-code facts optionally attached to the
218 /// fields.
219 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
220 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
221 pub struct MemoryType(u32);
222 entity_impl!(MemoryType, "mt");
223 
224 impl MemoryType {
225     /// Create a new memory type reference from its number.
226     ///
227     /// This method is for use by the parser.
228     pub fn with_number(n: u32) -> Option<Self> {
229         if n < u32::MAX {
230             Some(Self(n))
231         } else {
232             None
233         }
234     }
235 }
236 
237 /// An opaque reference to a constant.
238 ///
239 /// You can store [`ConstantData`](super::ConstantData) in a
240 /// [`ConstantPool`](super::ConstantPool) for efficient storage and retrieval.
241 /// See [`ConstantPool::insert`](super::ConstantPool::insert).
242 ///
243 /// While the order is stable, it is arbitrary and does not necessarily resemble the order in which
244 /// the constants are written in the constant pool.
245 #[derive(Copy, Clone, PartialEq, Eq, Hash, Ord, PartialOrd)]
246 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
247 pub struct Constant(u32);
248 entity_impl!(Constant, "const");
249 
250 impl Constant {
251     /// Create a const reference from its number.
252     ///
253     /// This method is for use by the parser.
254     pub fn with_number(n: u32) -> Option<Self> {
255         if n < u32::MAX {
256             Some(Self(n))
257         } else {
258             None
259         }
260     }
261 }
262 
263 /// An opaque reference to an immediate.
264 ///
265 /// Some immediates (e.g. SIMD shuffle masks) are too large to store in the
266 /// [`InstructionData`](super::instructions::InstructionData) struct and therefore must be
267 /// tracked separately in [`DataFlowGraph::immediates`](super::dfg::DataFlowGraph). `Immediate`
268 /// provides a way to reference values stored there.
269 ///
270 /// While the order is stable, it is arbitrary.
271 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
272 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
273 pub struct Immediate(u32);
274 entity_impl!(Immediate, "imm");
275 
276 impl Immediate {
277     /// Create an immediate reference from its number.
278     ///
279     /// This method is for use by the parser.
280     pub fn with_number(n: u32) -> Option<Self> {
281         if n < u32::MAX {
282             Some(Self(n))
283         } else {
284             None
285         }
286     }
287 }
288 
289 /// An opaque reference to a [jump table](https://en.wikipedia.org/wiki/Branch_table).
290 ///
291 /// `JumpTable`s are used for indirect branching and are specialized for dense,
292 /// 0-based jump offsets. If you want a jump table which doesn't start at 0,
293 /// or is not contiguous, consider using a [`Switch`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.Switch.html) instead.
294 ///
295 /// `JumpTable` are used with [`br_table`](super::InstBuilder::br_table).
296 ///
297 /// `JumpTable`s can be created with
298 /// [`create_jump_table`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.create_jump_table).
299 ///
300 /// While the order is stable, it is arbitrary.
301 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
302 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
303 pub struct JumpTable(u32);
304 entity_impl!(JumpTable, "jt");
305 
306 impl JumpTable {
307     /// Create a new jump table reference from its number.
308     ///
309     /// This method is for use by the parser.
310     pub fn with_number(n: u32) -> Option<Self> {
311         if n < u32::MAX {
312             Some(Self(n))
313         } else {
314             None
315         }
316     }
317 }
318 
319 /// An opaque reference to another [`Function`](super::Function).
320 ///
321 /// `FuncRef`s are used for [direct](super::InstBuilder::call) function calls
322 /// and by [`func_addr`](super::InstBuilder::func_addr) for use in
323 /// [indirect](super::InstBuilder::call_indirect) function calls.
324 ///
325 /// `FuncRef`s can be created with
326 ///
327 /// - [`FunctionBuilder::import_function`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.import_function)
328 /// for external functions
329 /// - [`Module::declare_func_in_func`](https://docs.rs/cranelift-module/*/cranelift_module/trait.Module.html#method.declare_func_in_func)
330 /// for functions declared elsewhere in the same native
331 /// [`Module`](https://docs.rs/cranelift-module/*/cranelift_module/trait.Module.html)
332 /// - [`FuncEnvironment::make_direct_func`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_direct_func)
333 /// for functions declared in the same WebAssembly
334 /// [`FuncEnvironment`](https://docs.rs/cranelift-wasm/*/cranelift_wasm/trait.FuncEnvironment.html#tymethod.make_direct_func)
335 ///
336 /// While the order is stable, it is arbitrary.
337 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
338 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
339 pub struct FuncRef(u32);
340 entity_impl!(FuncRef, "fn");
341 
342 impl FuncRef {
343     /// Create a new external function reference from its number.
344     ///
345     /// This method is for use by the parser.
346     pub fn with_number(n: u32) -> Option<Self> {
347         if n < u32::MAX {
348             Some(Self(n))
349         } else {
350             None
351         }
352     }
353 }
354 
355 /// A reference to an `UserExternalName`, declared with `Function::declare_imported_user_function`.
356 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Default)]
357 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
358 pub struct UserExternalNameRef(u32);
359 entity_impl!(UserExternalNameRef, "userextname");
360 
361 /// An opaque reference to a function [`Signature`](super::Signature).
362 ///
363 /// `SigRef`s are used to declare a function with
364 /// [`FunctionBuilder::import_function`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.import_function)
365 /// as well as to make an [indirect function call](super::InstBuilder::call_indirect).
366 ///
367 /// `SigRef`s can be created with
368 /// [`FunctionBuilder::import_signature`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.import_signature).
369 ///
370 /// You can retrieve the [`Signature`](super::Signature) that was used to create a `SigRef` with
371 /// [`FunctionBuilder::signature`](https://docs.rs/cranelift-frontend/*/cranelift_frontend/struct.FunctionBuilder.html#method.signature) or
372 /// [`func.dfg.signatures`](super::dfg::DataFlowGraph::signatures).
373 ///
374 /// While the order is stable, it is arbitrary.
375 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
376 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
377 pub struct SigRef(u32);
378 entity_impl!(SigRef, "sig");
379 
380 impl SigRef {
381     /// Create a new function signature reference from its number.
382     ///
383     /// This method is for use by the parser.
384     pub fn with_number(n: u32) -> Option<Self> {
385         if n < u32::MAX {
386             Some(Self(n))
387         } else {
388             None
389         }
390     }
391 }
392 
393 /// An opaque reference to any of the entities defined in this module that can appear in CLIF IR.
394 #[derive(Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
395 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
396 pub enum AnyEntity {
397     /// The whole function.
398     Function,
399     /// a basic block.
400     Block(Block),
401     /// An instruction.
402     Inst(Inst),
403     /// An SSA value.
404     Value(Value),
405     /// A stack slot.
406     StackSlot(StackSlot),
407     /// A dynamic stack slot.
408     DynamicStackSlot(DynamicStackSlot),
409     /// A dynamic type
410     DynamicType(DynamicType),
411     /// A Global value.
412     GlobalValue(GlobalValue),
413     /// A memory type.
414     MemoryType(MemoryType),
415     /// A jump table.
416     JumpTable(JumpTable),
417     /// A constant.
418     Constant(Constant),
419     /// An external function.
420     FuncRef(FuncRef),
421     /// A function call signature.
422     SigRef(SigRef),
423     /// A function's stack limit
424     StackLimit,
425 }
426 
427 impl fmt::Display for AnyEntity {
428     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
429         match *self {
430             Self::Function => write!(f, "function"),
431             Self::Block(r) => r.fmt(f),
432             Self::Inst(r) => r.fmt(f),
433             Self::Value(r) => r.fmt(f),
434             Self::StackSlot(r) => r.fmt(f),
435             Self::DynamicStackSlot(r) => r.fmt(f),
436             Self::DynamicType(r) => r.fmt(f),
437             Self::GlobalValue(r) => r.fmt(f),
438             Self::MemoryType(r) => r.fmt(f),
439             Self::JumpTable(r) => r.fmt(f),
440             Self::Constant(r) => r.fmt(f),
441             Self::FuncRef(r) => r.fmt(f),
442             Self::SigRef(r) => r.fmt(f),
443             Self::StackLimit => write!(f, "stack_limit"),
444         }
445     }
446 }
447 
448 impl fmt::Debug for AnyEntity {
449     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
450         (self as &dyn fmt::Display).fmt(f)
451     }
452 }
453 
454 impl From<Block> for AnyEntity {
455     fn from(r: Block) -> Self {
456         Self::Block(r)
457     }
458 }
459 
460 impl From<Inst> for AnyEntity {
461     fn from(r: Inst) -> Self {
462         Self::Inst(r)
463     }
464 }
465 
466 impl From<Value> for AnyEntity {
467     fn from(r: Value) -> Self {
468         Self::Value(r)
469     }
470 }
471 
472 impl From<StackSlot> for AnyEntity {
473     fn from(r: StackSlot) -> Self {
474         Self::StackSlot(r)
475     }
476 }
477 
478 impl From<DynamicStackSlot> for AnyEntity {
479     fn from(r: DynamicStackSlot) -> Self {
480         Self::DynamicStackSlot(r)
481     }
482 }
483 
484 impl From<DynamicType> for AnyEntity {
485     fn from(r: DynamicType) -> Self {
486         Self::DynamicType(r)
487     }
488 }
489 
490 impl From<GlobalValue> for AnyEntity {
491     fn from(r: GlobalValue) -> Self {
492         Self::GlobalValue(r)
493     }
494 }
495 
496 impl From<MemoryType> for AnyEntity {
497     fn from(r: MemoryType) -> Self {
498         Self::MemoryType(r)
499     }
500 }
501 
502 impl From<JumpTable> for AnyEntity {
503     fn from(r: JumpTable) -> Self {
504         Self::JumpTable(r)
505     }
506 }
507 
508 impl From<Constant> for AnyEntity {
509     fn from(r: Constant) -> Self {
510         Self::Constant(r)
511     }
512 }
513 
514 impl From<FuncRef> for AnyEntity {
515     fn from(r: FuncRef) -> Self {
516         Self::FuncRef(r)
517     }
518 }
519 
520 impl From<SigRef> for AnyEntity {
521     fn from(r: SigRef) -> Self {
522         Self::SigRef(r)
523     }
524 }
525 
526 #[cfg(test)]
527 mod tests {
528     use super::*;
529     use alloc::string::ToString;
530 
531     #[test]
532     fn value_with_number() {
533         assert_eq!(Value::with_number(0).unwrap().to_string(), "v0");
534         assert_eq!(Value::with_number(1).unwrap().to_string(), "v1");
535 
536         assert_eq!(Value::with_number(u32::MAX / 2), None);
537         assert!(Value::with_number(u32::MAX / 2 - 1).is_some());
538     }
539 
540     #[test]
541     fn memory() {
542         use crate::packed_option::PackedOption;
543         use core::mem;
544         // This is the whole point of `PackedOption`.
545         assert_eq!(
546             mem::size_of::<Value>(),
547             mem::size_of::<PackedOption<Value>>()
548         );
549     }
550 
551     #[test]
552     fn memory_option() {
553         use core::mem;
554         // PackedOption is used because Option<EntityRef> is twice as large
555         // as EntityRef. If this ever fails to be the case, this test will fail.
556         assert_eq!(mem::size_of::<Value>() * 2, mem::size_of::<Option<Value>>());
557     }
558 
559     #[test]
560     fn constant_with_number() {
561         assert_eq!(Constant::with_number(0).unwrap().to_string(), "const0");
562         assert_eq!(Constant::with_number(1).unwrap().to_string(), "const1");
563     }
564 }
565