Skip to main content

cranelift_codegen/machinst/
buffers.rs

1//! When configured to emit constants into a separate section, we use a `MachBuffer` for each
2//! section in the output (the equivalent of `.text` and `.rodata`). `MachBuffers` contains borrows
3//! to two `MachBuffer`s, one for each section, and abstracts the relocations that let `.text`
4//! refer to `.rodata`. Instruction emission takes a `MachBuffers` so it can emit both
5//! machine code and data as needed.
6
7use crate::binemit::{Addend, CodeOffset, Reloc};
8use crate::machinst::{
9    MachBuffer, MachBufferFinalized, MachInstLabelUse, MachLabel, VCodeConstant, VCodeInst,
10};
11use alloc::vec::Vec;
12use core::ops::{Deref, DerefMut};
13use cranelift_control::ControlPlane;
14use cranelift_entity::SecondaryMap;
15
16/// A reference from the code to a constant.
17///
18/// The embedder resolves it as a relocation whose target is the constant. The result is added to
19/// the value already at `offset`.
20#[derive(Clone, Copy, Debug, PartialEq, Eq)]
21#[cfg_attr(
22    feature = "enable-serde",
23    derive(serde_derive::Serialize, serde_derive::Deserialize)
24)]
25pub struct MachConstantRef {
26    /// The offset of the reference in the code.
27    pub offset: CodeOffset,
28    /// The kind of relocation.
29    pub kind: Reloc,
30    /// The addend of the relocation.
31    pub addend: Addend,
32    /// The constant, as an index into `MachConstantsFinalized::offsets`.
33    pub constant: usize,
34}
35
36/// The constants of a function and the references to them from its code.
37#[derive(PartialEq, Debug, Clone)]
38#[cfg_attr(
39    feature = "enable-serde",
40    derive(serde_derive::Serialize, serde_derive::Deserialize)
41)]
42pub struct MachConstantsFinalized {
43    /// The buffer that holds the constants. Its `min_alignment` is at least the alignment of each
44    /// constant.
45    pub buffer: MachBufferFinalized,
46    /// The start of each constant in `buffer`, in increasing order.
47    pub offsets: Vec<CodeOffset>,
48    /// The references to the constants, in the order they were emitted.
49    pub refs: Vec<MachConstantRef>,
50}
51
52/// The `MachBuffer`s that a function is emitted into.
53///
54/// The `rodata` buffer is present only if the `separate_constant_pool` setting is on.
55pub struct MachBuffers<'a, I: VCodeInst> {
56    text: &'a mut MachBuffer<I>,
57    rodata: Option<&'a mut MachBuffer<I>>,
58    /// The index in `labels` of each constant used so far.
59    indices: SecondaryMap<VCodeConstant, Option<usize>>,
60    /// The label in `rodata` of each constant used so far, in order of first use.
61    labels: Vec<MachLabel>,
62    /// The references to constants emitted so far.
63    refs: Vec<MachConstantRef>,
64}
65
66impl<'a, I: VCodeInst> MachBuffers<'a, I> {
67    /// Wraps a buffer for the code and an optional buffer for the constants.
68    ///
69    /// The constants must be registered with `rodata` if it is present, and with `text` otherwise.
70    pub(crate) fn new(text: &'a mut MachBuffer<I>, rodata: Option<&'a mut MachBuffer<I>>) -> Self {
71        MachBuffers {
72            text,
73            rodata,
74            indices: SecondaryMap::new(),
75            labels: Vec::new(),
76            refs: Vec::new(),
77        }
78    }
79
80    /// Wraps a buffer for the code. Constants are emitted into the same buffer.
81    pub fn text_only(text: &'a mut MachBuffer<I>) -> Self {
82        Self::new(text, None)
83    }
84
85    /// Makes the code at `text_offset` refer to `constant` with a relocation of `kind` and `addend`.
86    ///
87    /// If there is no `rodata` buffer, this is the equivalent label use in `text`.
88    pub fn use_constant(
89        &mut self,
90        text_offset: CodeOffset,
91        constant: VCodeConstant,
92        kind: Reloc,
93        addend: Addend,
94    ) {
95        match self.rodata.as_deref_mut() {
96            None => {
97                let label_use = I::LabelUse::from_reloc(kind, addend)
98                    .unwrap_or_else(|| panic!("no label use for a constant reference {kind:?}"));
99                let label = self.text.get_label_for_constant(constant);
100                self.text.use_label_at_offset(text_offset, label, label_use);
101            }
102            Some(rodata) => {
103                let index = *self.indices[constant].get_or_insert_with(|| {
104                    self.labels.push(rodata.get_label_for_constant(constant));
105                    self.labels.len() - 1
106                });
107                self.refs.push(MachConstantRef {
108                    offset: text_offset,
109                    kind,
110                    addend,
111                    constant: index,
112                });
113            }
114        }
115    }
116
117    /// Emits the constants into the `rodata` buffer, if it is present.
118    ///
119    /// Returns the start of each constant and the references to the constants.
120    pub(crate) fn finish(
121        self,
122        ctrl_plane: &mut ControlPlane,
123    ) -> (Vec<CodeOffset>, Vec<MachConstantRef>) {
124        let Some(rodata) = self.rodata else {
125            return (Vec::new(), Vec::new());
126        };
127        // The `rodata` buffer only holds constants, so this island emits all of them.
128        rodata.emit_island(0, ctrl_plane);
129        let offsets = self
130            .labels
131            .iter()
132            .map(|&label| rodata.resolve_label_offset(label))
133            .collect();
134        (offsets, self.refs)
135    }
136}
137
138impl<I: VCodeInst> Deref for MachBuffers<'_, I> {
139    type Target = MachBuffer<I>;
140
141    fn deref(&self) -> &Self::Target {
142        self.text
143    }
144}
145
146impl<I: VCodeInst> DerefMut for MachBuffers<'_, I> {
147    fn deref_mut(&mut self) -> &mut Self::Target {
148        self.text
149    }
150}
151
152/// Pulley's encoders are generic over `Extend<u8>`, and trait bounds do not see through `Deref`.
153impl<I: VCodeInst> Extend<u8> for MachBuffers<'_, I> {
154    fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
155        self.text.extend(iter);
156    }
157}