Skip to main content

cranelift_codegen/ir/
entities.rs

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