1 //! In-memory representation of compiled machine code, with labels and fixups to
2 //! refer to those labels. Handles constant-pool island insertion and also
3 //! veneer insertion for out-of-range jumps.
4 //!
5 //! This code exists to solve three problems:
6 //!
7 //! - Branch targets for forward branches are not known until later, when we
8 //!   emit code in a single pass through the instruction structs.
9 //!
10 //! - On many architectures, address references or offsets have limited range.
11 //!   For example, on AArch64, conditional branches can only target code +/- 1MB
12 //!   from the branch itself.
13 //!
14 //! - The lowering of control flow from the CFG-with-edges produced by
15 //!   [BlockLoweringOrder](super::BlockLoweringOrder), combined with many empty
16 //!   edge blocks when the register allocator does not need to insert any
17 //!   spills/reloads/moves in edge blocks, results in many suboptimal branch
18 //!   patterns. The lowering also pays no attention to block order, and so
19 //!   two-target conditional forms (cond-br followed by uncond-br) can often by
20 //!   avoided because one of the targets is the fallthrough. There are several
21 //!   cases here where we can simplify to use fewer branches.
22 //!
23 //! This "buffer" implements a single-pass code emission strategy (with a later
24 //! "fixup" pass, but only through recorded fixups, not all instructions). The
25 //! basic idea is:
26 //!
27 //! - Emit branches as they are, including two-target (cond/uncond) compound
28 //!   forms, but with zero offsets and optimistically assuming the target will be
29 //!   in range. Record the "fixup" for later. Targets are denoted instead by
30 //!   symbolic "labels" that are then bound to certain offsets in the buffer as
31 //!   we emit code. (Nominally, there is a label at the start of every basic
32 //!   block.)
33 //!
34 //! - As we do this, track the offset in the buffer at which the first label
35 //!   reference "goes out of range". We call this the "deadline". If we reach the
36 //!   deadline and we still have not bound the label to which an unresolved branch
37 //!   refers, we have a problem!
38 //!
39 //! - To solve this problem, we emit "islands" full of "veneers". An island is
40 //!   simply a chunk of code inserted in the middle of the code actually produced
41 //!   by the emitter (e.g., vcode iterating over instruction structs). The emitter
42 //!   has some awareness of this: it either asks for an island between blocks, so
43 //!   it is not accidentally executed, or else it emits a branch around the island
44 //!   when all other options fail (see `Inst::EmitIsland` meta-instruction).
45 //!
46 //! - A "veneer" is an instruction (or sequence of instructions) in an "island"
47 //!   that implements a longer-range reference to a label. The idea is that, for
48 //!   example, a branch with a limited range can branch to a "veneer" instead,
49 //!   which is simply a branch in a form that can use a longer-range reference. On
50 //!   AArch64, for example, conditionals have a +/- 1 MB range, but a conditional
51 //!   can branch to an unconditional branch which has a +/- 128 MB range. Hence, a
52 //!   conditional branch's label reference can be fixed up with a "veneer" to
53 //!   achieve a longer range.
54 //!
55 //! - To implement all of this, we require the backend to provide a `LabelUse`
56 //!   type that implements a trait. This is nominally an enum that records one of
57 //!   several kinds of references to an offset in code -- basically, a relocation
58 //!   type -- and will usually correspond to different instruction formats. The
59 //!   `LabelUse` implementation specifies the maximum range, how to patch in the
60 //!   actual label location when known, and how to generate a veneer to extend the
61 //!   range.
62 //!
63 //! That satisfies label references, but we still may have suboptimal branch
64 //! patterns. To clean up the branches, we do a simple "peephole"-style
65 //! optimization on the fly. To do so, the emitter (e.g., `Inst::emit()`)
66 //! informs the buffer of branches in the code and, in the case of conditionals,
67 //! the code that would have been emitted to invert this branch's condition. We
68 //! track the "latest branches": these are branches that are contiguous up to
69 //! the current offset. (If any code is emitted after a branch, that branch or
70 //! run of contiguous branches is no longer "latest".) The latest branches are
71 //! those that we can edit by simply truncating the buffer and doing something
72 //! else instead.
73 //!
74 //! To optimize branches, we implement several simple rules, and try to apply
75 //! them to the "latest branches" when possible:
76 //!
77 //! - A branch with a label target, when that label is bound to the ending
78 //!   offset of the branch (the fallthrough location), can be removed altogether,
79 //!   because the branch would have no effect).
80 //!
81 //! - An unconditional branch that starts at a label location, and branches to
82 //!   another label, results in a "label alias": all references to the label bound
83 //!   *to* this branch instruction are instead resolved to the *target* of the
84 //!   branch instruction. This effectively removes empty blocks that just
85 //!   unconditionally branch to the next block. We call this "branch threading".
86 //!
87 //! - A conditional followed by an unconditional, when the conditional branches
88 //!   to the unconditional's fallthrough, results in (i) the truncation of the
89 //!   unconditional, (ii) the inversion of the condition's condition, and (iii)
90 //!   replacement of the conditional's target (using the original target of the
91 //!   unconditional). This is a fancy way of saying "we can flip a two-target
92 //!   conditional branch's taken/not-taken targets if it works better with our
93 //!   fallthrough". To make this work, the emitter actually gives the buffer
94 //!   *both* forms of every conditional branch: the true form is emitted into the
95 //!   buffer, and the "inverted" machine-code bytes are provided as part of the
96 //!   branch-fixup metadata.
97 //!
98 //! - An unconditional B preceded by another unconditional P, when B's label(s) have
99 //!   been redirected to target(B), can be removed entirely. This is an extension
100 //!   of the branch-threading optimization, and is valid because if we know there
101 //!   will be no fallthrough into this branch instruction (the prior instruction
102 //!   is an unconditional jump), and if we know we have successfully redirected
103 //!   all labels, then this branch instruction is unreachable. Note that this
104 //!   works because the redirection happens before the label is ever resolved
105 //!   (fixups happen at island emission time, at which point latest-branches are
106 //!   cleared, or at the end of emission), so we are sure to catch and redirect
107 //!   all possible paths to this instruction.
108 //!
109 //! # Branch-optimization Correctness
110 //!
111 //! The branch-optimization mechanism depends on a few data structures with
112 //! invariants, which are always held outside the scope of top-level public
113 //! methods:
114 //!
115 //! - The latest-branches list. Each entry describes a span of the buffer
116 //!   (start/end offsets), the label target, the corresponding fixup-list entry
117 //!   index, and the bytes (must be the same length) for the inverted form, if
118 //!   conditional. The list of labels that are bound to the start-offset of this
119 //!   branch is *complete* (if any label has a resolved offset equal to `start`
120 //!   and is not an alias, it must appear in this list) and *precise* (no label
121 //!   in this list can be bound to another offset). No label in this list should
122 //!   be an alias.  No two branch ranges can overlap, and branches are in
123 //!   ascending-offset order.
124 //!
125 //! - The labels-at-tail list. This contains all MachLabels that have been bound
126 //!   to (whose resolved offsets are equal to) the tail offset of the buffer.
127 //!   No label in this list should be an alias.
128 //!
129 //! - The label_offsets array, containing the bound offset of a label or
130 //!   UNKNOWN. No label can be bound at an offset greater than the current
131 //!   buffer tail.
132 //!
133 //! - The label_aliases array, containing another label to which a label is
134 //!   bound or UNKNOWN. A label's resolved offset is the resolved offset
135 //!   of the label it is aliased to, if this is set.
136 //!
137 //! We argue below, at each method, how the invariants in these data structures
138 //! are maintained (grep for "Post-invariant").
139 //!
140 //! Given these invariants, we argue why each optimization preserves execution
141 //! semantics below (grep for "Preserves execution semantics").
142 //!
143 //! # Avoiding Quadratic Behavior
144 //!
145 //! There are two cases where we've had to take some care to avoid
146 //! quadratic worst-case behavior:
147 //!
148 //! - The "labels at this branch" list can grow unboundedly if the
149 //!   code generator binds many labels at one location. If the count
150 //!   gets too high (defined by the `LABEL_LIST_THRESHOLD` constant), we
151 //!   simply abort an optimization early in a way that is always correct
152 //!   but is conservative.
153 //!
154 //! - The fixup list can interact with island emission to create
155 //!   "quadratic island behavior". In a little more detail, one can hit
156 //!   this behavior by having some pending fixups (forward label
157 //!   references) with long-range label-use kinds, and some others
158 //!   with shorter-range references that nonetheless still are pending
159 //!   long enough to trigger island generation. In such a case, we
160 //!   process the fixup list, generate veneers to extend some forward
161 //!   references' ranges, but leave the other (longer-range) ones
162 //!   alone. The way this was implemented put them back on a list and
163 //!   resulted in quadratic behavior.
164 //!
165 //!   To avoid this fixups are split into two lists: one "pending" list and one
166 //!   final list. The pending list is kept around for handling fixups related to
167 //!   branches so it can be edited/truncated. When an island is reached, which
168 //!   starts processing fixups, all pending fixups are flushed into the final
169 //!   list. The final list is a `BinaryHeap` which enables fixup processing to
170 //!   only process those which are required during island emission, deferring
171 //!   all longer-range fixups to later.
172 
173 use crate::binemit::{Addend, CodeOffset, Reloc};
174 use crate::ir::function::FunctionParameters;
175 use crate::ir::{ExternalName, RelSourceLoc, SourceLoc, TrapCode};
176 use crate::isa::unwind::UnwindInst;
177 use crate::machinst::{
178     BlockIndex, MachInstLabelUse, TextSectionBuilder, VCodeConstant, VCodeConstants, VCodeInst,
179 };
180 use crate::trace;
181 use crate::{ir, MachInstEmitState};
182 use crate::{timing, VCodeConstantData};
183 use cranelift_control::ControlPlane;
184 use cranelift_entity::{entity_impl, PrimaryMap};
185 use smallvec::SmallVec;
186 use std::cmp::Ordering;
187 use std::collections::BinaryHeap;
188 use std::mem;
189 use std::string::String;
190 use std::vec::Vec;
191 
192 #[cfg(feature = "enable-serde")]
193 use serde::{Deserialize, Serialize};
194 
195 #[cfg(feature = "enable-serde")]
196 pub trait CompilePhase {
197     type MachSrcLocType: for<'a> Deserialize<'a> + Serialize + core::fmt::Debug + PartialEq + Clone;
198     type SourceLocType: for<'a> Deserialize<'a> + Serialize + core::fmt::Debug + PartialEq + Clone;
199 }
200 
201 #[cfg(not(feature = "enable-serde"))]
202 pub trait CompilePhase {
203     type MachSrcLocType: core::fmt::Debug + PartialEq + Clone;
204     type SourceLocType: core::fmt::Debug + PartialEq + Clone;
205 }
206 
207 /// Status of a compiled artifact that needs patching before being used.
208 #[derive(Clone, Debug, PartialEq)]
209 #[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
210 pub struct Stencil;
211 
212 /// Status of a compiled artifact ready to use.
213 #[derive(Clone, Debug, PartialEq)]
214 pub struct Final;
215 
216 impl CompilePhase for Stencil {
217     type MachSrcLocType = MachSrcLoc<Stencil>;
218     type SourceLocType = RelSourceLoc;
219 }
220 
221 impl CompilePhase for Final {
222     type MachSrcLocType = MachSrcLoc<Final>;
223     type SourceLocType = SourceLoc;
224 }
225 
226 #[derive(Clone, Copy, Debug, PartialEq, Eq)]
227 enum ForceVeneers {
228     Yes,
229     No,
230 }
231 
232 /// A buffer of output to be produced, fixed up, and then emitted to a CodeSink
233 /// in bulk.
234 ///
235 /// This struct uses `SmallVec`s to support small-ish function bodies without
236 /// any heap allocation. As such, it will be several kilobytes large. This is
237 /// likely fine as long as it is stack-allocated for function emission then
238 /// thrown away; but beware if many buffer objects are retained persistently.
239 pub struct MachBuffer<I: VCodeInst> {
240     /// The buffer contents, as raw bytes.
241     data: SmallVec<[u8; 1024]>,
242     /// The required alignment of this buffer.
243     min_alignment: u32,
244     /// Any relocations referring to this code. Note that only *external*
245     /// relocations are tracked here; references to labels within the buffer are
246     /// resolved before emission.
247     relocs: SmallVec<[MachReloc; 16]>,
248     /// Any trap records referring to this code.
249     traps: SmallVec<[MachTrap; 16]>,
250     /// Any call site records referring to this code.
251     call_sites: SmallVec<[MachCallSite; 16]>,
252     /// Any source location mappings referring to this code.
253     srclocs: SmallVec<[MachSrcLoc<Stencil>; 64]>,
254     /// Any user stack maps for this code.
255     ///
256     /// Each entry is an `(offset, span, stack_map)` triple. Entries are sorted
257     /// by code offset, and each stack map covers `span` bytes on the stack.
258     user_stack_maps: SmallVec<[(CodeOffset, u32, ir::UserStackMap); 8]>,
259     /// Any unwind info at a given location.
260     unwind_info: SmallVec<[(CodeOffset, UnwindInst); 8]>,
261     /// The current source location in progress (after `start_srcloc()` and
262     /// before `end_srcloc()`).  This is a (start_offset, src_loc) tuple.
263     cur_srcloc: Option<(CodeOffset, RelSourceLoc)>,
264     /// Known label offsets; `UNKNOWN_LABEL_OFFSET` if unknown.
265     label_offsets: SmallVec<[CodeOffset; 16]>,
266     /// Label aliases: when one label points to an unconditional jump, and that
267     /// jump points to another label, we can redirect references to the first
268     /// label immediately to the second.
269     ///
270     /// Invariant: we don't have label-alias cycles. We ensure this by,
271     /// before setting label A to alias label B, resolving B's alias
272     /// target (iteratively until a non-aliased label); if B is already
273     /// aliased to A, then we cannot alias A back to B.
274     label_aliases: SmallVec<[MachLabel; 16]>,
275     /// Constants that must be emitted at some point.
276     pending_constants: SmallVec<[VCodeConstant; 16]>,
277     /// Byte size of all constants in `pending_constants`.
278     pending_constants_size: CodeOffset,
279     /// Traps that must be emitted at some point.
280     pending_traps: SmallVec<[MachLabelTrap; 16]>,
281     /// Fixups that haven't yet been flushed into `fixup_records` below and may
282     /// be related to branches that are chomped. These all get added to
283     /// `fixup_records` during island emission.
284     pending_fixup_records: SmallVec<[MachLabelFixup<I>; 16]>,
285     /// The nearest upcoming deadline for entries in `pending_fixup_records`.
286     pending_fixup_deadline: CodeOffset,
287     /// Fixups that must be performed after all code is emitted.
288     fixup_records: BinaryHeap<MachLabelFixup<I>>,
289     /// Latest branches, to facilitate in-place editing for better fallthrough
290     /// behavior and empty-block removal.
291     latest_branches: SmallVec<[MachBranch; 4]>,
292     /// All labels at the current offset (emission tail). This is lazily
293     /// cleared: it is actually accurate as long as the current offset is
294     /// `labels_at_tail_off`, but if `cur_offset()` has grown larger, it should
295     /// be considered as empty.
296     ///
297     /// For correctness, this *must* be complete (i.e., the vector must contain
298     /// all labels whose offsets are resolved to the current tail), because we
299     /// rely on it to update labels when we truncate branches.
300     labels_at_tail: SmallVec<[MachLabel; 4]>,
301     /// The last offset at which `labels_at_tail` is valid. It is conceptually
302     /// always describing the tail of the buffer, but we do not clear
303     /// `labels_at_tail` eagerly when the tail grows, rather we lazily clear it
304     /// when the offset has grown past this (`labels_at_tail_off`) point.
305     /// Always <= `cur_offset()`.
306     labels_at_tail_off: CodeOffset,
307     /// Metadata about all constants that this function has access to.
308     ///
309     /// This records the size/alignment of all constants (not the actual data)
310     /// along with the last available label generated for the constant. This map
311     /// is consulted when constants are referred to and the label assigned to a
312     /// constant may change over time as well.
313     constants: PrimaryMap<VCodeConstant, MachBufferConstant>,
314     /// All recorded usages of constants as pairs of the constant and where the
315     /// constant needs to be placed within `self.data`. Note that the same
316     /// constant may appear in this array multiple times if it was emitted
317     /// multiple times.
318     used_constants: SmallVec<[(VCodeConstant, CodeOffset); 4]>,
319     /// Indicates when a patchable region is currently open, to guard that it's
320     /// not possible to nest patchable regions.
321     open_patchable: bool,
322 }
323 
324 impl MachBufferFinalized<Stencil> {
325     /// Get a finalized machine buffer by applying the function's base source location.
326     pub fn apply_base_srcloc(self, base_srcloc: SourceLoc) -> MachBufferFinalized<Final> {
327         MachBufferFinalized {
328             data: self.data,
329             relocs: self.relocs,
330             traps: self.traps,
331             call_sites: self.call_sites,
332             srclocs: self
333                 .srclocs
334                 .into_iter()
335                 .map(|srcloc| srcloc.apply_base_srcloc(base_srcloc))
336                 .collect(),
337             user_stack_maps: self.user_stack_maps,
338             unwind_info: self.unwind_info,
339             alignment: self.alignment,
340         }
341     }
342 }
343 
344 /// A `MachBuffer` once emission is completed: holds generated code and records,
345 /// without fixups. This allows the type to be independent of the backend.
346 #[derive(PartialEq, Debug, Clone)]
347 #[cfg_attr(
348     feature = "enable-serde",
349     derive(serde_derive::Serialize, serde_derive::Deserialize)
350 )]
351 pub struct MachBufferFinalized<T: CompilePhase> {
352     /// The buffer contents, as raw bytes.
353     pub(crate) data: SmallVec<[u8; 1024]>,
354     /// Any relocations referring to this code. Note that only *external*
355     /// relocations are tracked here; references to labels within the buffer are
356     /// resolved before emission.
357     pub(crate) relocs: SmallVec<[FinalizedMachReloc; 16]>,
358     /// Any trap records referring to this code.
359     pub(crate) traps: SmallVec<[MachTrap; 16]>,
360     /// Any call site records referring to this code.
361     pub(crate) call_sites: SmallVec<[MachCallSite; 16]>,
362     /// Any source location mappings referring to this code.
363     pub(crate) srclocs: SmallVec<[T::MachSrcLocType; 64]>,
364     /// Any user stack maps for this code.
365     ///
366     /// Each entry is an `(offset, span, stack_map)` triple. Entries are sorted
367     /// by code offset, and each stack map covers `span` bytes on the stack.
368     pub(crate) user_stack_maps: SmallVec<[(CodeOffset, u32, ir::UserStackMap); 8]>,
369     /// Any unwind info at a given location.
370     pub unwind_info: SmallVec<[(CodeOffset, UnwindInst); 8]>,
371     /// The required alignment of this buffer.
372     pub alignment: u32,
373 }
374 
375 const UNKNOWN_LABEL_OFFSET: CodeOffset = 0xffff_ffff;
376 const UNKNOWN_LABEL: MachLabel = MachLabel(0xffff_ffff);
377 
378 /// Threshold on max length of `labels_at_this_branch` list to avoid
379 /// unbounded quadratic behavior (see comment below at use-site).
380 const LABEL_LIST_THRESHOLD: usize = 100;
381 
382 /// A label refers to some offset in a `MachBuffer`. It may not be resolved at
383 /// the point at which it is used by emitted code; the buffer records "fixups"
384 /// for references to the label, and will come back and patch the code
385 /// appropriately when the label's location is eventually known.
386 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
387 pub struct MachLabel(u32);
388 entity_impl!(MachLabel);
389 
390 impl MachLabel {
391     /// Get a label for a block. (The first N MachLabels are always reserved for
392     /// the N blocks in the vcode.)
393     pub fn from_block(bindex: BlockIndex) -> MachLabel {
394         MachLabel(bindex.index() as u32)
395     }
396 
397     /// Creates a string representing this label, for convenience.
398     pub fn to_string(&self) -> String {
399         format!("label{}", self.0)
400     }
401 }
402 
403 impl Default for MachLabel {
404     fn default() -> Self {
405         UNKNOWN_LABEL
406     }
407 }
408 
409 /// Represents the beginning of an editable region in the [`MachBuffer`], while code emission is
410 /// still occurring. An [`OpenPatchRegion`] is closed by [`MachBuffer::end_patchable`], consuming
411 /// the [`OpenPatchRegion`] token in the process.
412 pub struct OpenPatchRegion(usize);
413 
414 /// A region in the [`MachBuffer`] code buffer that can be edited prior to finalization. An example
415 /// of where you might want to use this is for patching instructions that mention constants that
416 /// won't be known until later: [`MachBuffer::start_patchable`] can be used to begin the patchable
417 /// region, instructions can be emitted with placeholder constants, and the [`PatchRegion`] token
418 /// can be produced by [`MachBuffer::end_patchable`]. Once the values of those constants are known,
419 /// the [`PatchRegion::patch`] function can be used to get a mutable buffer to the instruction
420 /// bytes, and the constants uses can be updated directly.
421 pub struct PatchRegion {
422     range: std::ops::Range<usize>,
423 }
424 
425 impl PatchRegion {
426     /// Consume the patch region to yield a mutable slice of the [`MachBuffer`] data buffer.
427     pub fn patch<I: VCodeInst>(self, buffer: &mut MachBuffer<I>) -> &mut [u8] {
428         &mut buffer.data[self.range]
429     }
430 }
431 
432 impl<I: VCodeInst> MachBuffer<I> {
433     /// Create a new section, known to start at `start_offset` and with a size limited to
434     /// `length_limit`.
435     pub fn new() -> MachBuffer<I> {
436         MachBuffer {
437             data: SmallVec::new(),
438             min_alignment: I::function_alignment().minimum,
439             relocs: SmallVec::new(),
440             traps: SmallVec::new(),
441             call_sites: SmallVec::new(),
442             srclocs: SmallVec::new(),
443             user_stack_maps: SmallVec::new(),
444             unwind_info: SmallVec::new(),
445             cur_srcloc: None,
446             label_offsets: SmallVec::new(),
447             label_aliases: SmallVec::new(),
448             pending_constants: SmallVec::new(),
449             pending_constants_size: 0,
450             pending_traps: SmallVec::new(),
451             pending_fixup_records: SmallVec::new(),
452             pending_fixup_deadline: u32::MAX,
453             fixup_records: Default::default(),
454             latest_branches: SmallVec::new(),
455             labels_at_tail: SmallVec::new(),
456             labels_at_tail_off: 0,
457             constants: Default::default(),
458             used_constants: Default::default(),
459             open_patchable: false,
460         }
461     }
462 
463     /// Current offset from start of buffer.
464     pub fn cur_offset(&self) -> CodeOffset {
465         self.data.len() as CodeOffset
466     }
467 
468     /// Add a byte.
469     pub fn put1(&mut self, value: u8) {
470         self.data.push(value);
471 
472         // Post-invariant: conceptual-labels_at_tail contains a complete and
473         // precise list of labels bound at `cur_offset()`. We have advanced
474         // `cur_offset()`, hence if it had been equal to `labels_at_tail_off`
475         // before, it is not anymore (and it cannot become equal, because
476         // `labels_at_tail_off` is always <= `cur_offset()`). Thus the list is
477         // conceptually empty (even though it is only lazily cleared). No labels
478         // can be bound at this new offset (by invariant on `label_offsets`).
479         // Hence the invariant holds.
480     }
481 
482     /// Add 2 bytes.
483     pub fn put2(&mut self, value: u16) {
484         let bytes = value.to_le_bytes();
485         self.data.extend_from_slice(&bytes[..]);
486 
487         // Post-invariant: as for `put1()`.
488     }
489 
490     /// Add 4 bytes.
491     pub fn put4(&mut self, value: u32) {
492         let bytes = value.to_le_bytes();
493         self.data.extend_from_slice(&bytes[..]);
494 
495         // Post-invariant: as for `put1()`.
496     }
497 
498     /// Add 8 bytes.
499     pub fn put8(&mut self, value: u64) {
500         let bytes = value.to_le_bytes();
501         self.data.extend_from_slice(&bytes[..]);
502 
503         // Post-invariant: as for `put1()`.
504     }
505 
506     /// Add a slice of bytes.
507     pub fn put_data(&mut self, data: &[u8]) {
508         self.data.extend_from_slice(data);
509 
510         // Post-invariant: as for `put1()`.
511     }
512 
513     /// Reserve appended space and return a mutable slice referring to it.
514     pub fn get_appended_space(&mut self, len: usize) -> &mut [u8] {
515         let off = self.data.len();
516         let new_len = self.data.len() + len;
517         self.data.resize(new_len, 0);
518         &mut self.data[off..]
519 
520         // Post-invariant: as for `put1()`.
521     }
522 
523     /// Align up to the given alignment.
524     pub fn align_to(&mut self, align_to: CodeOffset) {
525         trace!("MachBuffer: align to {}", align_to);
526         assert!(
527             align_to.is_power_of_two(),
528             "{align_to} is not a power of two"
529         );
530         while self.cur_offset() & (align_to - 1) != 0 {
531             self.put1(0);
532         }
533 
534         // Post-invariant: as for `put1()`.
535     }
536 
537     /// Begin a region of patchable code. There is one requirement for the
538     /// code that is emitted: It must not introduce any instructions that
539     /// could be chomped (branches are an example of this). In other words,
540     /// you must not call [`MachBuffer::add_cond_branch`] or
541     /// [`MachBuffer::add_uncond_branch`] between calls to this method and
542     /// [`MachBuffer::end_patchable`].
543     pub fn start_patchable(&mut self) -> OpenPatchRegion {
544         assert!(!self.open_patchable, "Patchable regions may not be nested");
545         self.open_patchable = true;
546         OpenPatchRegion(usize::try_from(self.cur_offset()).unwrap())
547     }
548 
549     /// End a region of patchable code, yielding a [`PatchRegion`] value that
550     /// can be consumed later to produce a one-off mutable slice to the
551     /// associated region of the data buffer.
552     pub fn end_patchable(&mut self, open: OpenPatchRegion) -> PatchRegion {
553         // No need to assert the state of `open_patchable` here, as we take
554         // ownership of the only `OpenPatchable` value.
555         self.open_patchable = false;
556         let end = usize::try_from(self.cur_offset()).unwrap();
557         PatchRegion { range: open.0..end }
558     }
559 
560     /// Allocate a `Label` to refer to some offset. May not be bound to a fixed
561     /// offset yet.
562     pub fn get_label(&mut self) -> MachLabel {
563         let l = self.label_offsets.len() as u32;
564         self.label_offsets.push(UNKNOWN_LABEL_OFFSET);
565         self.label_aliases.push(UNKNOWN_LABEL);
566         trace!("MachBuffer: new label -> {:?}", MachLabel(l));
567         MachLabel(l)
568 
569         // Post-invariant: the only mutation is to add a new label; it has no
570         // bound offset yet, so it trivially satisfies all invariants.
571     }
572 
573     /// Reserve the first N MachLabels for blocks.
574     pub fn reserve_labels_for_blocks(&mut self, blocks: usize) {
575         trace!("MachBuffer: first {} labels are for blocks", blocks);
576         debug_assert!(self.label_offsets.is_empty());
577         self.label_offsets.resize(blocks, UNKNOWN_LABEL_OFFSET);
578         self.label_aliases.resize(blocks, UNKNOWN_LABEL);
579 
580         // Post-invariant: as for `get_label()`.
581     }
582 
583     /// Registers metadata in this `MachBuffer` about the `constants` provided.
584     ///
585     /// This will record the size/alignment of all constants which will prepare
586     /// them for emission later on.
587     pub fn register_constants(&mut self, constants: &VCodeConstants) {
588         for (c, val) in constants.iter() {
589             self.register_constant(&c, val);
590         }
591     }
592 
593     /// Similar to [`MachBuffer::register_constants`] but registers a
594     /// single constant metadata. This function is useful in
595     /// situations where not all constants are known at the time of
596     /// emission.
597     pub fn register_constant(&mut self, constant: &VCodeConstant, data: &VCodeConstantData) {
598         let c2 = self.constants.push(MachBufferConstant {
599             upcoming_label: None,
600             align: data.alignment(),
601             size: data.as_slice().len(),
602         });
603         assert_eq!(*constant, c2);
604     }
605 
606     /// Completes constant emission by iterating over `self.used_constants` and
607     /// filling in the "holes" with the constant values provided by `constants`.
608     ///
609     /// Returns the alignment required for this entire buffer. Alignment starts
610     /// at the ISA's minimum function alignment and can be increased due to
611     /// constant requirements.
612     fn finish_constants(&mut self, constants: &VCodeConstants) -> u32 {
613         let mut alignment = self.min_alignment;
614         for (constant, offset) in mem::take(&mut self.used_constants) {
615             let constant = constants.get(constant);
616             let data = constant.as_slice();
617             self.data[offset as usize..][..data.len()].copy_from_slice(data);
618             alignment = constant.alignment().max(alignment);
619         }
620         alignment
621     }
622 
623     /// Returns a label that can be used to refer to the `constant` provided.
624     ///
625     /// This will automatically defer a new constant to be emitted for
626     /// `constant` if it has not been previously emitted. Note that this
627     /// function may return a different label for the same constant at
628     /// different points in time. The label is valid to use only from the
629     /// current location; the MachBuffer takes care to emit the same constant
630     /// multiple times if needed so the constant is always in range.
631     pub fn get_label_for_constant(&mut self, constant: VCodeConstant) -> MachLabel {
632         let MachBufferConstant {
633             align,
634             size,
635             upcoming_label,
636         } = self.constants[constant];
637         if let Some(label) = upcoming_label {
638             return label;
639         }
640 
641         let label = self.get_label();
642         trace!(
643             "defer constant: eventually emit {size} bytes aligned \
644              to {align} at label {label:?}",
645         );
646         self.pending_constants.push(constant);
647         self.pending_constants_size += size as u32;
648         self.constants[constant].upcoming_label = Some(label);
649         label
650     }
651 
652     /// Bind a label to the current offset. A label can only be bound once.
653     pub fn bind_label(&mut self, label: MachLabel, ctrl_plane: &mut ControlPlane) {
654         trace!(
655             "MachBuffer: bind label {:?} at offset {}",
656             label,
657             self.cur_offset()
658         );
659         debug_assert_eq!(self.label_offsets[label.0 as usize], UNKNOWN_LABEL_OFFSET);
660         debug_assert_eq!(self.label_aliases[label.0 as usize], UNKNOWN_LABEL);
661         let offset = self.cur_offset();
662         self.label_offsets[label.0 as usize] = offset;
663         self.lazily_clear_labels_at_tail();
664         self.labels_at_tail.push(label);
665 
666         // Invariants hold: bound offset of label is <= cur_offset (in fact it
667         // is equal). If the `labels_at_tail` list was complete and precise
668         // before, it is still, because we have bound this label to the current
669         // offset and added it to the list (which contains all labels at the
670         // current offset).
671 
672         self.optimize_branches(ctrl_plane);
673 
674         // Post-invariant: by `optimize_branches()` (see argument there).
675     }
676 
677     /// Lazily clear `labels_at_tail` if the tail offset has moved beyond the
678     /// offset that it applies to.
679     fn lazily_clear_labels_at_tail(&mut self) {
680         let offset = self.cur_offset();
681         if offset > self.labels_at_tail_off {
682             self.labels_at_tail_off = offset;
683             self.labels_at_tail.clear();
684         }
685 
686         // Post-invariant: either labels_at_tail_off was at cur_offset, and
687         // state is untouched, or was less than cur_offset, in which case the
688         // labels_at_tail list was conceptually empty, and is now actually
689         // empty.
690     }
691 
692     /// Resolve a label to an offset, if known. May return `UNKNOWN_LABEL_OFFSET`.
693     pub(crate) fn resolve_label_offset(&self, mut label: MachLabel) -> CodeOffset {
694         let mut iters = 0;
695         while self.label_aliases[label.0 as usize] != UNKNOWN_LABEL {
696             label = self.label_aliases[label.0 as usize];
697             // To protect against an infinite loop (despite our assurances to
698             // ourselves that the invariants make this impossible), assert out
699             // after 1M iterations. The number of basic blocks is limited
700             // in most contexts anyway so this should be impossible to hit with
701             // a legitimate input.
702             iters += 1;
703             assert!(iters < 1_000_000, "Unexpected cycle in label aliases");
704         }
705         self.label_offsets[label.0 as usize]
706 
707         // Post-invariant: no mutations.
708     }
709 
710     /// Emit a reference to the given label with the given reference type (i.e.,
711     /// branch-instruction format) at the current offset.  This is like a
712     /// relocation, but handled internally.
713     ///
714     /// This can be called before the branch is actually emitted; fixups will
715     /// not happen until an island is emitted or the buffer is finished.
716     pub fn use_label_at_offset(&mut self, offset: CodeOffset, label: MachLabel, kind: I::LabelUse) {
717         trace!(
718             "MachBuffer: use_label_at_offset: offset {} label {:?} kind {:?}",
719             offset,
720             label,
721             kind
722         );
723 
724         // Add the fixup, and update the worst-case island size based on a
725         // veneer for this label use.
726         let fixup = MachLabelFixup {
727             label,
728             offset,
729             kind,
730         };
731         self.pending_fixup_deadline = self.pending_fixup_deadline.min(fixup.deadline());
732         self.pending_fixup_records.push(fixup);
733 
734         // Post-invariant: no mutations to branches/labels data structures.
735     }
736 
737     /// Inform the buffer of an unconditional branch at the given offset,
738     /// targeting the given label. May be used to optimize branches.
739     /// The last added label-use must correspond to this branch.
740     /// This must be called when the current offset is equal to `start`; i.e.,
741     /// before actually emitting the branch. This implies that for a branch that
742     /// uses a label and is eligible for optimizations by the MachBuffer, the
743     /// proper sequence is:
744     ///
745     /// - Call `use_label_at_offset()` to emit the fixup record.
746     /// - Call `add_uncond_branch()` to make note of the branch.
747     /// - Emit the bytes for the branch's machine code.
748     ///
749     /// Additional requirement: no labels may be bound between `start` and `end`
750     /// (exclusive on both ends).
751     pub fn add_uncond_branch(&mut self, start: CodeOffset, end: CodeOffset, target: MachLabel) {
752         debug_assert!(
753             !self.open_patchable,
754             "Branch instruction inserted within a patchable region"
755         );
756         assert!(self.cur_offset() == start);
757         debug_assert!(end > start);
758         assert!(!self.pending_fixup_records.is_empty());
759         let fixup = self.pending_fixup_records.len() - 1;
760         self.lazily_clear_labels_at_tail();
761         self.latest_branches.push(MachBranch {
762             start,
763             end,
764             target,
765             fixup,
766             inverted: None,
767             labels_at_this_branch: self.labels_at_tail.clone(),
768         });
769 
770         // Post-invariant: we asserted branch start is current tail; the list of
771         // labels at branch is cloned from list of labels at current tail.
772     }
773 
774     /// Inform the buffer of a conditional branch at the given offset,
775     /// targeting the given label. May be used to optimize branches.
776     /// The last added label-use must correspond to this branch.
777     ///
778     /// Additional requirement: no labels may be bound between `start` and `end`
779     /// (exclusive on both ends).
780     pub fn add_cond_branch(
781         &mut self,
782         start: CodeOffset,
783         end: CodeOffset,
784         target: MachLabel,
785         inverted: &[u8],
786     ) {
787         debug_assert!(
788             !self.open_patchable,
789             "Branch instruction inserted within a patchable region"
790         );
791         assert!(self.cur_offset() == start);
792         debug_assert!(end > start);
793         assert!(!self.pending_fixup_records.is_empty());
794         debug_assert!(
795             inverted.len() == (end - start) as usize,
796             "branch length = {}, but inverted length = {}",
797             end - start,
798             inverted.len()
799         );
800         let fixup = self.pending_fixup_records.len() - 1;
801         let inverted = Some(SmallVec::from(inverted));
802         self.lazily_clear_labels_at_tail();
803         self.latest_branches.push(MachBranch {
804             start,
805             end,
806             target,
807             fixup,
808             inverted,
809             labels_at_this_branch: self.labels_at_tail.clone(),
810         });
811 
812         // Post-invariant: we asserted branch start is current tail; labels at
813         // branch list is cloned from list of labels at current tail.
814     }
815 
816     fn truncate_last_branch(&mut self) {
817         debug_assert!(
818             !self.open_patchable,
819             "Branch instruction truncated within a patchable region"
820         );
821 
822         self.lazily_clear_labels_at_tail();
823         // Invariants hold at this point.
824 
825         let b = self.latest_branches.pop().unwrap();
826         assert!(b.end == self.cur_offset());
827 
828         // State:
829         //    [PRE CODE]
830         //  Offset b.start, b.labels_at_this_branch:
831         //    [BRANCH CODE]
832         //  cur_off, self.labels_at_tail -->
833         //    (end of buffer)
834         self.data.truncate(b.start as usize);
835         self.pending_fixup_records.truncate(b.fixup);
836         while let Some(last_srcloc) = self.srclocs.last_mut() {
837             if last_srcloc.end <= b.start {
838                 break;
839             }
840             if last_srcloc.start < b.start {
841                 last_srcloc.end = b.start;
842                 break;
843             }
844             self.srclocs.pop();
845         }
846         // State:
847         //    [PRE CODE]
848         //  cur_off, Offset b.start, b.labels_at_this_branch:
849         //    (end of buffer)
850         //
851         //  self.labels_at_tail -->  (past end of buffer)
852         let cur_off = self.cur_offset();
853         self.labels_at_tail_off = cur_off;
854         // State:
855         //    [PRE CODE]
856         //  cur_off, Offset b.start, b.labels_at_this_branch,
857         //  self.labels_at_tail:
858         //    (end of buffer)
859         //
860         // resolve_label_offset(l) for l in labels_at_tail:
861         //    (past end of buffer)
862 
863         trace!(
864             "truncate_last_branch: truncated {:?}; off now {}",
865             b,
866             cur_off
867         );
868 
869         // Fix up resolved label offsets for labels at tail.
870         for &l in &self.labels_at_tail {
871             self.label_offsets[l.0 as usize] = cur_off;
872         }
873         // Old labels_at_this_branch are now at cur_off.
874         self.labels_at_tail
875             .extend(b.labels_at_this_branch.into_iter());
876 
877         // Post-invariant: this operation is defined to truncate the buffer,
878         // which moves cur_off backward, and to move labels at the end of the
879         // buffer back to the start-of-branch offset.
880         //
881         // latest_branches satisfies all invariants:
882         // - it has no branches past the end of the buffer (branches are in
883         //   order, we removed the last one, and we truncated the buffer to just
884         //   before the start of that branch)
885         // - no labels were moved to lower offsets than the (new) cur_off, so
886         //   the labels_at_this_branch list for any other branch need not change.
887         //
888         // labels_at_tail satisfies all invariants:
889         // - all labels that were at the tail after the truncated branch are
890         //   moved backward to just before the branch, which becomes the new tail;
891         //   thus every element in the list should remain (ensured by `.extend()`
892         //   above).
893         // - all labels that refer to the new tail, which is the start-offset of
894         //   the truncated branch, must be present. The `labels_at_this_branch`
895         //   list in the truncated branch's record is a complete and precise list
896         //   of exactly these labels; we append these to labels_at_tail.
897         // - labels_at_tail_off is at cur_off after truncation occurs, so the
898         //   list is valid (not to be lazily cleared).
899         //
900         // The stated operation was performed:
901         // - For each label at the end of the buffer prior to this method, it
902         //   now resolves to the new (truncated) end of the buffer: it must have
903         //   been in `labels_at_tail` (this list is precise and complete, and
904         //   the tail was at the end of the truncated branch on entry), and we
905         //   iterate over this list and set `label_offsets` to the new tail.
906         //   None of these labels could have been an alias (by invariant), so
907         //   `label_offsets` is authoritative for each.
908         // - No other labels will be past the end of the buffer, because of the
909         //   requirement that no labels be bound to the middle of branch ranges
910         //   (see comments to `add_{cond,uncond}_branch()`).
911         // - The buffer is truncated to just before the last branch, and the
912         //   fixup record referring to that last branch is removed.
913     }
914 
915     /// Performs various optimizations on branches pointing at the current label.
916     pub fn optimize_branches(&mut self, ctrl_plane: &mut ControlPlane) {
917         if ctrl_plane.get_decision() {
918             return;
919         }
920 
921         self.lazily_clear_labels_at_tail();
922         // Invariants valid at this point.
923 
924         trace!(
925             "enter optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}",
926             self.latest_branches,
927             self.labels_at_tail,
928             self.pending_fixup_records
929         );
930 
931         // We continue to munch on branches at the tail of the buffer until no
932         // more rules apply. Note that the loop only continues if a branch is
933         // actually truncated (or if labels are redirected away from a branch),
934         // so this always makes progress.
935         while let Some(b) = self.latest_branches.last() {
936             let cur_off = self.cur_offset();
937             trace!("optimize_branches: last branch {:?} at off {}", b, cur_off);
938             // If there has been any code emission since the end of the last branch or
939             // label definition, then there's nothing we can edit (because we
940             // don't move code once placed, only back up and overwrite), so
941             // clear the records and finish.
942             if b.end < cur_off {
943                 break;
944             }
945 
946             // If the "labels at this branch" list on this branch is
947             // longer than a threshold, don't do any simplification,
948             // and let the branch remain to separate those labels from
949             // the current tail. This avoids quadratic behavior (see
950             // #3468): otherwise, if a long string of "goto next;
951             // next:" patterns are emitted, all of the labels will
952             // coalesce into a long list of aliases for the current
953             // buffer tail. We must track all aliases of the current
954             // tail for correctness, but we are also allowed to skip
955             // optimization (removal) of any branch, so we take the
956             // escape hatch here and let it stand. In effect this
957             // "spreads" the many thousands of labels in the
958             // pathological case among an actual (harmless but
959             // suboptimal) instruction once per N labels.
960             if b.labels_at_this_branch.len() > LABEL_LIST_THRESHOLD {
961                 break;
962             }
963 
964             // Invariant: we are looking at a branch that ends at the tail of
965             // the buffer.
966 
967             // For any branch, conditional or unconditional:
968             // - If the target is a label at the current offset, then remove
969             //   the conditional branch, and reset all labels that targeted
970             //   the current offset (end of branch) to the truncated
971             //   end-of-code.
972             //
973             // Preserves execution semantics: a branch to its own fallthrough
974             // address is equivalent to a no-op; in both cases, nextPC is the
975             // fallthrough.
976             if self.resolve_label_offset(b.target) == cur_off {
977                 trace!("branch with target == cur off; truncating");
978                 self.truncate_last_branch();
979                 continue;
980             }
981 
982             // If latest is an unconditional branch:
983             //
984             // - If the branch's target is not its own start address, then for
985             //   each label at the start of branch, make the label an alias of the
986             //   branch target, and remove the label from the "labels at this
987             //   branch" list.
988             //
989             //   - Preserves execution semantics: an unconditional branch's
990             //     only effect is to set PC to a new PC; this change simply
991             //     collapses one step in the step-semantics.
992             //
993             //   - Post-invariant: the labels that were bound to the start of
994             //     this branch become aliases, so they must not be present in any
995             //     labels-at-this-branch list or the labels-at-tail list. The
996             //     labels are removed form the latest-branch record's
997             //     labels-at-this-branch list, and are never placed in the
998             //     labels-at-tail list. Furthermore, it is correct that they are
999             //     not in either list, because they are now aliases, and labels
1000             //     that are aliases remain aliases forever.
1001             //
1002             // - If there is a prior unconditional branch that ends just before
1003             //   this one begins, and this branch has no labels bound to its
1004             //   start, then we can truncate this branch, because it is entirely
1005             //   unreachable (we have redirected all labels that make it
1006             //   reachable otherwise). Do so and continue around the loop.
1007             //
1008             //   - Preserves execution semantics: the branch is unreachable,
1009             //     because execution can only flow into an instruction from the
1010             //     prior instruction's fallthrough or from a branch bound to that
1011             //     instruction's start offset. Unconditional branches have no
1012             //     fallthrough, so if the prior instruction is an unconditional
1013             //     branch, no fallthrough entry can happen. The
1014             //     labels-at-this-branch list is complete (by invariant), so if it
1015             //     is empty, then the instruction is entirely unreachable. Thus,
1016             //     it can be removed.
1017             //
1018             //   - Post-invariant: ensured by truncate_last_branch().
1019             //
1020             // - If there is a prior conditional branch whose target label
1021             //   resolves to the current offset (branches around the
1022             //   unconditional branch), then remove the unconditional branch,
1023             //   and make the target of the unconditional the target of the
1024             //   conditional instead.
1025             //
1026             //   - Preserves execution semantics: previously we had:
1027             //
1028             //         L1:
1029             //            cond_br L2
1030             //            br L3
1031             //         L2:
1032             //            (end of buffer)
1033             //
1034             //     by removing the last branch, we have:
1035             //
1036             //         L1:
1037             //            cond_br L2
1038             //         L2:
1039             //            (end of buffer)
1040             //
1041             //     we then fix up the records for the conditional branch to
1042             //     have:
1043             //
1044             //         L1:
1045             //           cond_br.inverted L3
1046             //         L2:
1047             //
1048             //     In the original code, control flow reaches L2 when the
1049             //     conditional branch's predicate is true, and L3 otherwise. In
1050             //     the optimized code, the same is true.
1051             //
1052             //   - Post-invariant: all edits to latest_branches and
1053             //     labels_at_tail are performed by `truncate_last_branch()`,
1054             //     which maintains the invariants at each step.
1055 
1056             if b.is_uncond() {
1057                 // Set any label equal to current branch's start as an alias of
1058                 // the branch's target, if the target is not the branch itself
1059                 // (i.e., an infinite loop).
1060                 //
1061                 // We cannot perform this aliasing if the target of this branch
1062                 // ultimately aliases back here; if so, we need to keep this
1063                 // branch, so break out of this loop entirely (and clear the
1064                 // latest-branches list below).
1065                 //
1066                 // Note that this check is what prevents cycles from forming in
1067                 // `self.label_aliases`. To see why, consider an arbitrary start
1068                 // state:
1069                 //
1070                 // label_aliases[L1] = L2, label_aliases[L2] = L3, ..., up to
1071                 // Ln, which is not aliased.
1072                 //
1073                 // We would create a cycle if we assigned label_aliases[Ln]
1074                 // = L1.  Note that the below assignment is the only write
1075                 // to label_aliases.
1076                 //
1077                 // By our other invariants, we have that Ln (`l` below)
1078                 // resolves to the offset `b.start`, because it is in the
1079                 // set `b.labels_at_this_branch`.
1080                 //
1081                 // If L1 were already aliased, through some arbitrarily deep
1082                 // chain, to Ln, then it must also resolve to this offset
1083                 // `b.start`.
1084                 //
1085                 // By checking the resolution of `L1` against this offset,
1086                 // and aborting this branch-simplification if they are
1087                 // equal, we prevent the below assignment from ever creating
1088                 // a cycle.
1089                 if self.resolve_label_offset(b.target) != b.start {
1090                     let redirected = b.labels_at_this_branch.len();
1091                     for &l in &b.labels_at_this_branch {
1092                         trace!(
1093                             " -> label at start of branch {:?} redirected to target {:?}",
1094                             l,
1095                             b.target
1096                         );
1097                         self.label_aliases[l.0 as usize] = b.target;
1098                         // NOTE: we continue to ensure the invariant that labels
1099                         // pointing to tail of buffer are in `labels_at_tail`
1100                         // because we already ensured above that the last branch
1101                         // cannot have a target of `cur_off`; so we never have
1102                         // to put the label into `labels_at_tail` when moving it
1103                         // here.
1104                     }
1105                     // Maintain invariant: all branches have been redirected
1106                     // and are no longer pointing at the start of this branch.
1107                     let mut_b = self.latest_branches.last_mut().unwrap();
1108                     mut_b.labels_at_this_branch.clear();
1109 
1110                     if redirected > 0 {
1111                         trace!(" -> after label redirects, restarting loop");
1112                         continue;
1113                     }
1114                 } else {
1115                     break;
1116                 }
1117 
1118                 let b = self.latest_branches.last().unwrap();
1119 
1120                 // Examine any immediately preceding branch.
1121                 if self.latest_branches.len() > 1 {
1122                     let prev_b = &self.latest_branches[self.latest_branches.len() - 2];
1123                     trace!(" -> more than one branch; prev_b = {:?}", prev_b);
1124                     // This uncond is immediately after another uncond; we
1125                     // should have already redirected labels to this uncond away
1126                     // (but check to be sure); so we can truncate this uncond.
1127                     if prev_b.is_uncond()
1128                         && prev_b.end == b.start
1129                         && b.labels_at_this_branch.is_empty()
1130                     {
1131                         trace!(" -> uncond follows another uncond; truncating");
1132                         self.truncate_last_branch();
1133                         continue;
1134                     }
1135 
1136                     // This uncond is immediately after a conditional, and the
1137                     // conditional's target is the end of this uncond, and we've
1138                     // already redirected labels to this uncond away; so we can
1139                     // truncate this uncond, flip the sense of the conditional, and
1140                     // set the conditional's target (in `latest_branches` and in
1141                     // `fixup_records`) to the uncond's target.
1142                     if prev_b.is_cond()
1143                         && prev_b.end == b.start
1144                         && self.resolve_label_offset(prev_b.target) == cur_off
1145                     {
1146                         trace!(" -> uncond follows a conditional, and conditional's target resolves to current offset");
1147                         // Save the target of the uncond (this becomes the
1148                         // target of the cond), and truncate the uncond.
1149                         let target = b.target;
1150                         let data = prev_b.inverted.clone().unwrap();
1151                         self.truncate_last_branch();
1152 
1153                         // Mutate the code and cond branch.
1154                         let off_before_edit = self.cur_offset();
1155                         let prev_b = self.latest_branches.last_mut().unwrap();
1156                         let not_inverted = SmallVec::from(
1157                             &self.data[(prev_b.start as usize)..(prev_b.end as usize)],
1158                         );
1159 
1160                         // Low-level edit: replaces bytes of branch with
1161                         // inverted form. cur_off remains the same afterward, so
1162                         // we do not need to modify label data structures.
1163                         self.data.truncate(prev_b.start as usize);
1164                         self.data.extend_from_slice(&data[..]);
1165 
1166                         // Save the original code as the inversion of the
1167                         // inverted branch, in case we later edit this branch
1168                         // again.
1169                         prev_b.inverted = Some(not_inverted);
1170                         self.pending_fixup_records[prev_b.fixup].label = target;
1171                         trace!(" -> reassigning target of condbr to {:?}", target);
1172                         prev_b.target = target;
1173                         debug_assert_eq!(off_before_edit, self.cur_offset());
1174                         continue;
1175                     }
1176                 }
1177             }
1178 
1179             // If we couldn't do anything with the last branch, then break.
1180             break;
1181         }
1182 
1183         self.purge_latest_branches();
1184 
1185         trace!(
1186             "leave optimize_branches:\n b = {:?}\n l = {:?}\n f = {:?}",
1187             self.latest_branches,
1188             self.labels_at_tail,
1189             self.pending_fixup_records
1190         );
1191     }
1192 
1193     fn purge_latest_branches(&mut self) {
1194         // All of our branch simplification rules work only if a branch ends at
1195         // the tail of the buffer, with no following code; and branches are in
1196         // order in latest_branches; so if the last entry ends prior to
1197         // cur_offset, then clear all entries.
1198         let cur_off = self.cur_offset();
1199         if let Some(l) = self.latest_branches.last() {
1200             if l.end < cur_off {
1201                 trace!("purge_latest_branches: removing branch {:?}", l);
1202                 self.latest_branches.clear();
1203             }
1204         }
1205 
1206         // Post-invariant: no invariant requires any branch to appear in
1207         // `latest_branches`; it is always optional. The list-clear above thus
1208         // preserves all semantics.
1209     }
1210 
1211     /// Emit a trap at some point in the future with the specified code and
1212     /// stack map.
1213     ///
1214     /// This function returns a [`MachLabel`] which will be the future address
1215     /// of the trap. Jumps should refer to this label, likely by using the
1216     /// [`MachBuffer::use_label_at_offset`] method, to get a relocation
1217     /// patched in once the address of the trap is known.
1218     ///
1219     /// This will batch all traps into the end of the function.
1220     pub fn defer_trap(&mut self, code: TrapCode) -> MachLabel {
1221         let label = self.get_label();
1222         self.pending_traps.push(MachLabelTrap {
1223             label,
1224             code,
1225             loc: self.cur_srcloc.map(|(_start, loc)| loc),
1226         });
1227         label
1228     }
1229 
1230     /// Is an island needed within the next N bytes?
1231     pub fn island_needed(&self, distance: CodeOffset) -> bool {
1232         let deadline = match self.fixup_records.peek() {
1233             Some(fixup) => fixup.deadline().min(self.pending_fixup_deadline),
1234             None => self.pending_fixup_deadline,
1235         };
1236         deadline < u32::MAX && self.worst_case_end_of_island(distance) > deadline
1237     }
1238 
1239     /// Returns the maximal offset that islands can reach if `distance` more
1240     /// bytes are appended.
1241     ///
1242     /// This is used to determine if veneers need insertions since jumps that
1243     /// can't reach past this point must get a veneer of some form.
1244     fn worst_case_end_of_island(&self, distance: CodeOffset) -> CodeOffset {
1245         // Assume that all fixups will require veneers and that the veneers are
1246         // the worst-case size for each platform. This is an over-generalization
1247         // to avoid iterating over the `fixup_records` list or maintaining
1248         // information about it as we go along.
1249         let island_worst_case_size = ((self.fixup_records.len() + self.pending_fixup_records.len())
1250             as u32)
1251             * (I::LabelUse::worst_case_veneer_size())
1252             + self.pending_constants_size
1253             + (self.pending_traps.len() * I::TRAP_OPCODE.len()) as u32;
1254         self.cur_offset()
1255             .saturating_add(distance)
1256             .saturating_add(island_worst_case_size)
1257     }
1258 
1259     /// Emit all pending constants and required pending veneers.
1260     ///
1261     /// Should only be called if `island_needed()` returns true, i.e., if we
1262     /// actually reach a deadline. It's not necessarily a problem to do so
1263     /// otherwise but it may result in unnecessary work during emission.
1264     pub fn emit_island(&mut self, distance: CodeOffset, ctrl_plane: &mut ControlPlane) {
1265         self.emit_island_maybe_forced(ForceVeneers::No, distance, ctrl_plane);
1266     }
1267 
1268     /// Same as `emit_island`, but an internal API with a `force_veneers`
1269     /// argument to force all veneers to always get emitted for debugging.
1270     fn emit_island_maybe_forced(
1271         &mut self,
1272         force_veneers: ForceVeneers,
1273         distance: CodeOffset,
1274         ctrl_plane: &mut ControlPlane,
1275     ) {
1276         // We're going to purge fixups, so no latest-branch editing can happen
1277         // anymore.
1278         self.latest_branches.clear();
1279 
1280         // End the current location tracking since anything emitted during this
1281         // function shouldn't be attributed to whatever the current source
1282         // location is.
1283         //
1284         // Note that the current source location, if it's set right now, will be
1285         // restored at the end of this island emission.
1286         let cur_loc = self.cur_srcloc.map(|(_, loc)| loc);
1287         if cur_loc.is_some() {
1288             self.end_srcloc();
1289         }
1290 
1291         let forced_threshold = self.worst_case_end_of_island(distance);
1292 
1293         // First flush out all traps/constants so we have more labels in case
1294         // fixups are applied against these labels.
1295         //
1296         // Note that traps are placed first since this typically happens at the
1297         // end of the function and for disassemblers we try to keep all the code
1298         // contiguously together.
1299         for MachLabelTrap { label, code, loc } in mem::take(&mut self.pending_traps) {
1300             // If this trap has source information associated with it then
1301             // emit this information for the trap instruction going out now too.
1302             if let Some(loc) = loc {
1303                 self.start_srcloc(loc);
1304             }
1305             self.align_to(I::LabelUse::ALIGN);
1306             self.bind_label(label, ctrl_plane);
1307             self.add_trap(code);
1308             self.put_data(I::TRAP_OPCODE);
1309             if loc.is_some() {
1310                 self.end_srcloc();
1311             }
1312         }
1313 
1314         for constant in mem::take(&mut self.pending_constants) {
1315             let MachBufferConstant { align, size, .. } = self.constants[constant];
1316             let label = self.constants[constant].upcoming_label.take().unwrap();
1317             self.align_to(align);
1318             self.bind_label(label, ctrl_plane);
1319             self.used_constants.push((constant, self.cur_offset()));
1320             self.get_appended_space(size);
1321         }
1322 
1323         // Either handle all pending fixups because they're ready or move them
1324         // onto the `BinaryHeap` tracking all pending fixups if they aren't
1325         // ready.
1326         assert!(self.latest_branches.is_empty());
1327         for fixup in mem::take(&mut self.pending_fixup_records) {
1328             if self.should_apply_fixup(&fixup, forced_threshold) {
1329                 self.handle_fixup(fixup, force_veneers, forced_threshold);
1330             } else {
1331                 self.fixup_records.push(fixup);
1332             }
1333         }
1334         self.pending_fixup_deadline = u32::MAX;
1335         while let Some(fixup) = self.fixup_records.peek() {
1336             trace!("emit_island: fixup {:?}", fixup);
1337 
1338             // If this fixup shouldn't be applied, that means its label isn't
1339             // defined yet and there'll be remaining space to apply a veneer if
1340             // necessary in the future after this island. In that situation
1341             // because `fixup_records` is sorted by deadline this loop can
1342             // exit.
1343             if !self.should_apply_fixup(fixup, forced_threshold) {
1344                 break;
1345             }
1346 
1347             let fixup = self.fixup_records.pop().unwrap();
1348             self.handle_fixup(fixup, force_veneers, forced_threshold);
1349         }
1350 
1351         if let Some(loc) = cur_loc {
1352             self.start_srcloc(loc);
1353         }
1354     }
1355 
1356     fn should_apply_fixup(&self, fixup: &MachLabelFixup<I>, forced_threshold: CodeOffset) -> bool {
1357         let label_offset = self.resolve_label_offset(fixup.label);
1358         label_offset != UNKNOWN_LABEL_OFFSET || fixup.deadline() < forced_threshold
1359     }
1360 
1361     fn handle_fixup(
1362         &mut self,
1363         fixup: MachLabelFixup<I>,
1364         force_veneers: ForceVeneers,
1365         forced_threshold: CodeOffset,
1366     ) {
1367         let MachLabelFixup {
1368             label,
1369             offset,
1370             kind,
1371         } = fixup;
1372         let start = offset as usize;
1373         let end = (offset + kind.patch_size()) as usize;
1374         let label_offset = self.resolve_label_offset(label);
1375 
1376         if label_offset != UNKNOWN_LABEL_OFFSET {
1377             // If the offset of the label for this fixup is known then
1378             // we're going to do something here-and-now. We're either going
1379             // to patch the original offset because it's an in-bounds jump,
1380             // or we're going to generate a veneer, patch the fixup to jump
1381             // to the veneer, and then keep going.
1382             //
1383             // If the label comes after the original fixup, then we should
1384             // be guaranteed that the jump is in-bounds. Otherwise there's
1385             // a bug somewhere because this method wasn't called soon
1386             // enough. All forward-jumps are tracked and should get veneers
1387             // before their deadline comes and they're unable to jump
1388             // further.
1389             //
1390             // Otherwise if the label is before the fixup, then that's a
1391             // backwards jump. If it's past the maximum negative range
1392             // then we'll emit a veneer that to jump forward to which can
1393             // then jump backwards.
1394             let veneer_required = if label_offset >= offset {
1395                 assert!((label_offset - offset) <= kind.max_pos_range());
1396                 false
1397             } else {
1398                 (offset - label_offset) > kind.max_neg_range()
1399             };
1400             trace!(
1401                 " -> label_offset = {}, known, required = {} (pos {} neg {})",
1402                 label_offset,
1403                 veneer_required,
1404                 kind.max_pos_range(),
1405                 kind.max_neg_range()
1406             );
1407 
1408             if (force_veneers == ForceVeneers::Yes && kind.supports_veneer()) || veneer_required {
1409                 self.emit_veneer(label, offset, kind);
1410             } else {
1411                 let slice = &mut self.data[start..end];
1412                 trace!("patching in-range! slice = {slice:?}; offset = {offset:#x}; label_offset = {label_offset:#x}");
1413                 kind.patch(slice, offset, label_offset);
1414             }
1415         } else {
1416             // If the offset of this label is not known at this time then
1417             // that means that a veneer is required because after this
1418             // island the target can't be in range of the original target.
1419             assert!(forced_threshold - offset > kind.max_pos_range());
1420             self.emit_veneer(label, offset, kind);
1421         }
1422     }
1423 
1424     /// Emits a "veneer" the `kind` code at `offset` to jump to `label`.
1425     ///
1426     /// This will generate extra machine code, using `kind`, to get a
1427     /// larger-jump-kind than `kind` allows. The code at `offset` is then
1428     /// patched to jump to our new code, and then the new code is enqueued for
1429     /// a fixup to get processed at some later time.
1430     fn emit_veneer(&mut self, label: MachLabel, offset: CodeOffset, kind: I::LabelUse) {
1431         // If this `kind` doesn't support a veneer then that's a bug in the
1432         // backend because we need to implement support for such a veneer.
1433         assert!(
1434             kind.supports_veneer(),
1435             "jump beyond the range of {kind:?} but a veneer isn't supported",
1436         );
1437 
1438         // Allocate space for a veneer in the island.
1439         self.align_to(I::LabelUse::ALIGN);
1440         let veneer_offset = self.cur_offset();
1441         trace!("making a veneer at {}", veneer_offset);
1442         let start = offset as usize;
1443         let end = (offset + kind.patch_size()) as usize;
1444         let slice = &mut self.data[start..end];
1445         // Patch the original label use to refer to the veneer.
1446         trace!(
1447             "patching original at offset {} to veneer offset {}",
1448             offset,
1449             veneer_offset
1450         );
1451         kind.patch(slice, offset, veneer_offset);
1452         // Generate the veneer.
1453         let veneer_slice = self.get_appended_space(kind.veneer_size() as usize);
1454         let (veneer_fixup_off, veneer_label_use) =
1455             kind.generate_veneer(veneer_slice, veneer_offset);
1456         trace!(
1457             "generated veneer; fixup offset {}, label_use {:?}",
1458             veneer_fixup_off,
1459             veneer_label_use
1460         );
1461         // Register a new use of `label` with our new veneer fixup and
1462         // offset. This'll recalculate deadlines accordingly and
1463         // enqueue this fixup to get processed at some later
1464         // time.
1465         self.use_label_at_offset(veneer_fixup_off, label, veneer_label_use);
1466     }
1467 
1468     fn finish_emission_maybe_forcing_veneers(
1469         &mut self,
1470         force_veneers: ForceVeneers,
1471         ctrl_plane: &mut ControlPlane,
1472     ) {
1473         while !self.pending_constants.is_empty()
1474             || !self.pending_traps.is_empty()
1475             || !self.fixup_records.is_empty()
1476             || !self.pending_fixup_records.is_empty()
1477         {
1478             // `emit_island()` will emit any pending veneers and constants, and
1479             // as a side-effect, will also take care of any fixups with resolved
1480             // labels eagerly.
1481             self.emit_island_maybe_forced(force_veneers, u32::MAX, ctrl_plane);
1482         }
1483 
1484         // Ensure that all labels have been fixed up after the last island is emitted. This is a
1485         // full (release-mode) assert because an unresolved label means the emitted code is
1486         // incorrect.
1487         assert!(self.fixup_records.is_empty());
1488         assert!(self.pending_fixup_records.is_empty());
1489     }
1490 
1491     /// Finish any deferred emissions and/or fixups.
1492     pub fn finish(
1493         mut self,
1494         constants: &VCodeConstants,
1495         ctrl_plane: &mut ControlPlane,
1496     ) -> MachBufferFinalized<Stencil> {
1497         let _tt = timing::vcode_emit_finish();
1498 
1499         self.finish_emission_maybe_forcing_veneers(ForceVeneers::No, ctrl_plane);
1500 
1501         let alignment = self.finish_constants(constants);
1502 
1503         // Resolve all labels to their offsets.
1504         let finalized_relocs = self
1505             .relocs
1506             .iter()
1507             .map(|reloc| FinalizedMachReloc {
1508                 offset: reloc.offset,
1509                 kind: reloc.kind,
1510                 addend: reloc.addend,
1511                 target: match &reloc.target {
1512                     RelocTarget::ExternalName(name) => {
1513                         FinalizedRelocTarget::ExternalName(name.clone())
1514                     }
1515                     RelocTarget::Label(label) => {
1516                         FinalizedRelocTarget::Func(self.resolve_label_offset(*label))
1517                     }
1518                 },
1519             })
1520             .collect();
1521 
1522         let mut srclocs = self.srclocs;
1523         srclocs.sort_by_key(|entry| entry.start);
1524 
1525         MachBufferFinalized {
1526             data: self.data,
1527             relocs: finalized_relocs,
1528             traps: self.traps,
1529             call_sites: self.call_sites,
1530             srclocs,
1531             user_stack_maps: self.user_stack_maps,
1532             unwind_info: self.unwind_info,
1533             alignment,
1534         }
1535     }
1536 
1537     /// Add an external relocation at the given offset.
1538     pub fn add_reloc_at_offset<T: Into<RelocTarget> + Clone>(
1539         &mut self,
1540         offset: CodeOffset,
1541         kind: Reloc,
1542         target: &T,
1543         addend: Addend,
1544     ) {
1545         let target: RelocTarget = target.clone().into();
1546         // FIXME(#3277): This should use `I::LabelUse::from_reloc` to optionally
1547         // generate a label-use statement to track whether an island is possibly
1548         // needed to escape this function to actually get to the external name.
1549         // This is most likely to come up on AArch64 where calls between
1550         // functions use a 26-bit signed offset which gives +/- 64MB. This means
1551         // that if a function is 128MB in size and there's a call in the middle
1552         // it's impossible to reach the actual target. Also, while it's
1553         // technically possible to jump to the start of a function and then jump
1554         // further, island insertion below always inserts islands after
1555         // previously appended code so for Cranelift's own implementation this
1556         // is also a problem for 64MB functions on AArch64 which start with a
1557         // call instruction, those won't be able to escape.
1558         //
1559         // Ideally what needs to happen here is that a `LabelUse` is
1560         // transparently generated (or call-sites of this function are audited
1561         // to generate a `LabelUse` instead) and tracked internally. The actual
1562         // relocation would then change over time if and when a veneer is
1563         // inserted, where the relocation here would be patched by this
1564         // `MachBuffer` to jump to the veneer. The problem, though, is that all
1565         // this still needs to end up, in the case of a singular function,
1566         // generating a final relocation pointing either to this particular
1567         // relocation or to the veneer inserted. Additionally
1568         // `MachBuffer` needs the concept of a label which will never be
1569         // resolved, so `emit_island` doesn't trip over not actually ever
1570         // knowning what some labels are. Currently the loop in
1571         // `finish_emission_maybe_forcing_veneers` would otherwise infinitely
1572         // loop.
1573         //
1574         // For now this means that because relocs aren't tracked at all that
1575         // AArch64 functions have a rough size limits of 64MB. For now that's
1576         // somewhat reasonable and the failure mode is a panic in `MachBuffer`
1577         // when a relocation can't otherwise be resolved later, so it shouldn't
1578         // actually result in any memory unsafety or anything like that.
1579         self.relocs.push(MachReloc {
1580             offset,
1581             kind,
1582             target,
1583             addend,
1584         });
1585     }
1586 
1587     /// Add an external relocation at the current offset.
1588     pub fn add_reloc<T: Into<RelocTarget> + Clone>(
1589         &mut self,
1590         kind: Reloc,
1591         target: &T,
1592         addend: Addend,
1593     ) {
1594         self.add_reloc_at_offset(self.data.len() as CodeOffset, kind, target, addend);
1595     }
1596 
1597     /// Add a trap record at the current offset.
1598     pub fn add_trap(&mut self, code: TrapCode) {
1599         self.traps.push(MachTrap {
1600             offset: self.data.len() as CodeOffset,
1601             code,
1602         });
1603     }
1604 
1605     /// Add a call-site record at the current offset.
1606     pub fn add_call_site(&mut self) {
1607         self.call_sites.push(MachCallSite {
1608             ret_addr: self.data.len() as CodeOffset,
1609         });
1610     }
1611 
1612     /// Add an unwind record at the current offset.
1613     pub fn add_unwind(&mut self, unwind: UnwindInst) {
1614         self.unwind_info.push((self.cur_offset(), unwind));
1615     }
1616 
1617     /// Set the `SourceLoc` for code from this offset until the offset at the
1618     /// next call to `end_srcloc()`.
1619     /// Returns the current [CodeOffset] and [RelSourceLoc].
1620     pub fn start_srcloc(&mut self, loc: RelSourceLoc) -> (CodeOffset, RelSourceLoc) {
1621         let cur = (self.cur_offset(), loc);
1622         self.cur_srcloc = Some(cur);
1623         cur
1624     }
1625 
1626     /// Mark the end of the `SourceLoc` segment started at the last
1627     /// `start_srcloc()` call.
1628     pub fn end_srcloc(&mut self) {
1629         let (start, loc) = self
1630             .cur_srcloc
1631             .take()
1632             .expect("end_srcloc() called without start_srcloc()");
1633         let end = self.cur_offset();
1634         // Skip zero-length extends.
1635         debug_assert!(end >= start);
1636         if end > start {
1637             self.srclocs.push(MachSrcLoc { start, end, loc });
1638         }
1639     }
1640 
1641     /// Push a user stack map onto this buffer.
1642     ///
1643     /// The stack map is associated with the given `return_addr` code
1644     /// offset. This must be the PC for the instruction just *after* this stack
1645     /// map's associated instruction. For example in the sequence `call $foo;
1646     /// add r8, rax`, the `return_addr` must be the offset of the start of the
1647     /// `add` instruction.
1648     ///
1649     /// Stack maps must be pushed in sorted `return_addr` order.
1650     pub fn push_user_stack_map(
1651         &mut self,
1652         emit_state: &I::State,
1653         return_addr: CodeOffset,
1654         mut stack_map: ir::UserStackMap,
1655     ) {
1656         let span = emit_state.frame_layout().active_size();
1657         trace!("Adding user stack map @ {return_addr:#x} spanning {span} bytes: {stack_map:?}");
1658 
1659         debug_assert!(
1660             self.user_stack_maps
1661                 .last()
1662                 .map_or(true, |(prev_addr, _, _)| *prev_addr < return_addr),
1663             "pushed stack maps out of order: {} is not less than {}",
1664             self.user_stack_maps.last().unwrap().0,
1665             return_addr,
1666         );
1667 
1668         stack_map.finalize(emit_state.frame_layout().sp_to_sized_stack_slots());
1669         self.user_stack_maps.push((return_addr, span, stack_map));
1670     }
1671 
1672     /// Increase the alignment of the buffer to the given alignment if bigger
1673     /// than the current alignment.
1674     pub fn set_log2_min_function_alignment(&mut self, align_to: u8) {
1675         self.min_alignment = self.min_alignment.max(
1676             1u32.checked_shl(u32::from(align_to))
1677                 .expect("log2_min_function_alignment too large"),
1678         );
1679     }
1680 }
1681 
1682 impl<I: VCodeInst> Extend<u8> for MachBuffer<I> {
1683     fn extend<T: IntoIterator<Item = u8>>(&mut self, iter: T) {
1684         for b in iter {
1685             self.put1(b);
1686         }
1687     }
1688 }
1689 
1690 impl<T: CompilePhase> MachBufferFinalized<T> {
1691     /// Get a list of source location mapping tuples in sorted-by-start-offset order.
1692     pub fn get_srclocs_sorted(&self) -> &[T::MachSrcLocType] {
1693         &self.srclocs[..]
1694     }
1695 
1696     /// Get the total required size for the code.
1697     pub fn total_size(&self) -> CodeOffset {
1698         self.data.len() as CodeOffset
1699     }
1700 
1701     /// Return the code in this mach buffer as a hex string for testing purposes.
1702     pub fn stringify_code_bytes(&self) -> String {
1703         // This is pretty lame, but whatever ..
1704         use std::fmt::Write;
1705         let mut s = String::with_capacity(self.data.len() * 2);
1706         for b in &self.data {
1707             write!(&mut s, "{b:02X}").unwrap();
1708         }
1709         s
1710     }
1711 
1712     /// Get the code bytes.
1713     pub fn data(&self) -> &[u8] {
1714         // N.B.: we emit every section into the .text section as far as
1715         // the `CodeSink` is concerned; we do not bother to segregate
1716         // the contents into the actual program text, the jumptable and the
1717         // rodata (constant pool). This allows us to generate code assuming
1718         // that these will not be relocated relative to each other, and avoids
1719         // having to designate each section as belonging in one of the three
1720         // fixed categories defined by `CodeSink`. If this becomes a problem
1721         // later (e.g. because of memory permissions or similar), we can
1722         // add this designation and segregate the output; take care, however,
1723         // to add the appropriate relocations in this case.
1724 
1725         &self.data[..]
1726     }
1727 
1728     /// Get the list of external relocations for this code.
1729     pub fn relocs(&self) -> &[FinalizedMachReloc] {
1730         &self.relocs[..]
1731     }
1732 
1733     /// Get the list of trap records for this code.
1734     pub fn traps(&self) -> &[MachTrap] {
1735         &self.traps[..]
1736     }
1737 
1738     /// Get the user stack map metadata for this code.
1739     pub fn user_stack_maps(&self) -> &[(CodeOffset, u32, ir::UserStackMap)] {
1740         &self.user_stack_maps
1741     }
1742 
1743     /// Take this buffer's user strack map metadata.
1744     pub fn take_user_stack_maps(&mut self) -> SmallVec<[(CodeOffset, u32, ir::UserStackMap); 8]> {
1745         mem::take(&mut self.user_stack_maps)
1746     }
1747 
1748     /// Get the list of call sites for this code.
1749     pub fn call_sites(&self) -> &[MachCallSite] {
1750         &self.call_sites[..]
1751     }
1752 }
1753 
1754 /// Metadata about a constant.
1755 struct MachBufferConstant {
1756     /// A label which has not yet been bound which can be used for this
1757     /// constant.
1758     ///
1759     /// This is lazily created when a label is requested for a constant and is
1760     /// cleared when a constant is emitted.
1761     upcoming_label: Option<MachLabel>,
1762     /// Required alignment.
1763     align: CodeOffset,
1764     /// The byte size of this constant.
1765     size: usize,
1766 }
1767 
1768 /// A trap that is deferred to the next time an island is emitted for either
1769 /// traps, constants, or fixups.
1770 struct MachLabelTrap {
1771     /// This label will refer to the trap's offset.
1772     label: MachLabel,
1773     /// The code associated with this trap.
1774     code: TrapCode,
1775     /// An optional source location to assign for this trap.
1776     loc: Option<RelSourceLoc>,
1777 }
1778 
1779 /// A fixup to perform on the buffer once code is emitted. Fixups always refer
1780 /// to labels and patch the code based on label offsets. Hence, they are like
1781 /// relocations, but internal to one buffer.
1782 #[derive(Debug)]
1783 struct MachLabelFixup<I: VCodeInst> {
1784     /// The label whose offset controls this fixup.
1785     label: MachLabel,
1786     /// The offset to fix up / patch to refer to this label.
1787     offset: CodeOffset,
1788     /// The kind of fixup. This is architecture-specific; each architecture may have,
1789     /// e.g., several types of branch instructions, each with differently-sized
1790     /// offset fields and different places within the instruction to place the
1791     /// bits.
1792     kind: I::LabelUse,
1793 }
1794 
1795 impl<I: VCodeInst> MachLabelFixup<I> {
1796     fn deadline(&self) -> CodeOffset {
1797         self.offset.saturating_add(self.kind.max_pos_range())
1798     }
1799 }
1800 
1801 impl<I: VCodeInst> PartialEq for MachLabelFixup<I> {
1802     fn eq(&self, other: &Self) -> bool {
1803         self.deadline() == other.deadline()
1804     }
1805 }
1806 
1807 impl<I: VCodeInst> Eq for MachLabelFixup<I> {}
1808 
1809 impl<I: VCodeInst> PartialOrd for MachLabelFixup<I> {
1810     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
1811         Some(self.cmp(other))
1812     }
1813 }
1814 
1815 impl<I: VCodeInst> Ord for MachLabelFixup<I> {
1816     fn cmp(&self, other: &Self) -> Ordering {
1817         other.deadline().cmp(&self.deadline())
1818     }
1819 }
1820 
1821 /// A relocation resulting from a compilation.
1822 #[derive(Clone, Debug, PartialEq)]
1823 #[cfg_attr(
1824     feature = "enable-serde",
1825     derive(serde_derive::Serialize, serde_derive::Deserialize)
1826 )]
1827 pub struct MachRelocBase<T> {
1828     /// The offset at which the relocation applies, *relative to the
1829     /// containing section*.
1830     pub offset: CodeOffset,
1831     /// The kind of relocation.
1832     pub kind: Reloc,
1833     /// The external symbol / name to which this relocation refers.
1834     pub target: T,
1835     /// The addend to add to the symbol value.
1836     pub addend: i64,
1837 }
1838 
1839 type MachReloc = MachRelocBase<RelocTarget>;
1840 
1841 /// A relocation resulting from a compilation.
1842 pub type FinalizedMachReloc = MachRelocBase<FinalizedRelocTarget>;
1843 
1844 /// A Relocation target
1845 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1846 pub enum RelocTarget {
1847     /// Points to an [ExternalName] outside the current function.
1848     ExternalName(ExternalName),
1849     /// Points to a [MachLabel] inside this function.
1850     /// This is different from [MachLabelFixup] in that both the relocation and the
1851     /// label will be emitted and are only resolved at link time.
1852     ///
1853     /// There is no reason to prefer this over [MachLabelFixup] unless the ABI requires it.
1854     Label(MachLabel),
1855 }
1856 
1857 impl From<ExternalName> for RelocTarget {
1858     fn from(name: ExternalName) -> Self {
1859         Self::ExternalName(name)
1860     }
1861 }
1862 
1863 impl From<MachLabel> for RelocTarget {
1864     fn from(label: MachLabel) -> Self {
1865         Self::Label(label)
1866     }
1867 }
1868 
1869 /// A Relocation target
1870 #[derive(Debug, Clone, PartialEq, Eq, Hash)]
1871 #[cfg_attr(
1872     feature = "enable-serde",
1873     derive(serde_derive::Serialize, serde_derive::Deserialize)
1874 )]
1875 pub enum FinalizedRelocTarget {
1876     /// Points to an [ExternalName] outside the current function.
1877     ExternalName(ExternalName),
1878     /// Points to a [CodeOffset] from the start of the current function.
1879     Func(CodeOffset),
1880 }
1881 
1882 impl FinalizedRelocTarget {
1883     /// Returns a display for the current [FinalizedRelocTarget], with extra context to prettify the
1884     /// output.
1885     pub fn display<'a>(&'a self, params: Option<&'a FunctionParameters>) -> String {
1886         match self {
1887             FinalizedRelocTarget::ExternalName(name) => format!("{}", name.display(params)),
1888             FinalizedRelocTarget::Func(offset) => format!("func+{offset}"),
1889         }
1890     }
1891 }
1892 
1893 /// A trap record resulting from a compilation.
1894 #[derive(Clone, Debug, PartialEq)]
1895 #[cfg_attr(
1896     feature = "enable-serde",
1897     derive(serde_derive::Serialize, serde_derive::Deserialize)
1898 )]
1899 pub struct MachTrap {
1900     /// The offset at which the trap instruction occurs, *relative to the
1901     /// containing section*.
1902     pub offset: CodeOffset,
1903     /// The trap code.
1904     pub code: TrapCode,
1905 }
1906 
1907 /// A call site record resulting from a compilation.
1908 #[derive(Clone, Debug, PartialEq)]
1909 #[cfg_attr(
1910     feature = "enable-serde",
1911     derive(serde_derive::Serialize, serde_derive::Deserialize)
1912 )]
1913 pub struct MachCallSite {
1914     /// The offset of the call's return address, *relative to the containing section*.
1915     pub ret_addr: CodeOffset,
1916 }
1917 
1918 /// A source-location mapping resulting from a compilation.
1919 #[derive(PartialEq, Debug, Clone)]
1920 #[cfg_attr(
1921     feature = "enable-serde",
1922     derive(serde_derive::Serialize, serde_derive::Deserialize)
1923 )]
1924 pub struct MachSrcLoc<T: CompilePhase> {
1925     /// The start of the region of code corresponding to a source location.
1926     /// This is relative to the start of the function, not to the start of the
1927     /// section.
1928     pub start: CodeOffset,
1929     /// The end of the region of code corresponding to a source location.
1930     /// This is relative to the start of the section, not to the start of the
1931     /// section.
1932     pub end: CodeOffset,
1933     /// The source location.
1934     pub loc: T::SourceLocType,
1935 }
1936 
1937 impl MachSrcLoc<Stencil> {
1938     fn apply_base_srcloc(self, base_srcloc: SourceLoc) -> MachSrcLoc<Final> {
1939         MachSrcLoc {
1940             start: self.start,
1941             end: self.end,
1942             loc: self.loc.expand(base_srcloc),
1943         }
1944     }
1945 }
1946 
1947 /// Record of branch instruction in the buffer, to facilitate editing.
1948 #[derive(Clone, Debug)]
1949 struct MachBranch {
1950     start: CodeOffset,
1951     end: CodeOffset,
1952     target: MachLabel,
1953     fixup: usize,
1954     inverted: Option<SmallVec<[u8; 8]>>,
1955     /// All labels pointing to the start of this branch. For correctness, this
1956     /// *must* be complete (i.e., must contain all labels whose resolved offsets
1957     /// are at the start of this branch): we rely on being able to redirect all
1958     /// labels that could jump to this branch before removing it, if it is
1959     /// otherwise unreachable.
1960     labels_at_this_branch: SmallVec<[MachLabel; 4]>,
1961 }
1962 
1963 impl MachBranch {
1964     fn is_cond(&self) -> bool {
1965         self.inverted.is_some()
1966     }
1967     fn is_uncond(&self) -> bool {
1968         self.inverted.is_none()
1969     }
1970 }
1971 
1972 /// Implementation of the `TextSectionBuilder` trait backed by `MachBuffer`.
1973 ///
1974 /// Note that `MachBuffer` was primarily written for intra-function references
1975 /// of jumps between basic blocks, but it's also quite usable for entire text
1976 /// sections and resolving references between functions themselves. This
1977 /// builder interprets "blocks" as labeled functions for the purposes of
1978 /// resolving labels internally in the buffer.
1979 pub struct MachTextSectionBuilder<I: VCodeInst> {
1980     buf: MachBuffer<I>,
1981     next_func: usize,
1982     force_veneers: ForceVeneers,
1983 }
1984 
1985 impl<I: VCodeInst> MachTextSectionBuilder<I> {
1986     /// Creates a new text section builder which will have `num_funcs` functions
1987     /// pushed into it.
1988     pub fn new(num_funcs: usize) -> MachTextSectionBuilder<I> {
1989         let mut buf = MachBuffer::new();
1990         buf.reserve_labels_for_blocks(num_funcs);
1991         MachTextSectionBuilder {
1992             buf,
1993             next_func: 0,
1994             force_veneers: ForceVeneers::No,
1995         }
1996     }
1997 }
1998 
1999 impl<I: VCodeInst> TextSectionBuilder for MachTextSectionBuilder<I> {
2000     fn append(
2001         &mut self,
2002         labeled: bool,
2003         func: &[u8],
2004         align: u32,
2005         ctrl_plane: &mut ControlPlane,
2006     ) -> u64 {
2007         // Conditionally emit an island if it's necessary to resolve jumps
2008         // between functions which are too far away.
2009         let size = func.len() as u32;
2010         if self.force_veneers == ForceVeneers::Yes || self.buf.island_needed(size) {
2011             self.buf
2012                 .emit_island_maybe_forced(self.force_veneers, size, ctrl_plane);
2013         }
2014 
2015         self.buf.align_to(align);
2016         let pos = self.buf.cur_offset();
2017         if labeled {
2018             self.buf.bind_label(
2019                 MachLabel::from_block(BlockIndex::new(self.next_func)),
2020                 ctrl_plane,
2021             );
2022             self.next_func += 1;
2023         }
2024         self.buf.put_data(func);
2025         u64::from(pos)
2026     }
2027 
2028     fn resolve_reloc(&mut self, offset: u64, reloc: Reloc, addend: Addend, target: usize) -> bool {
2029         crate::trace!(
2030             "Resolving relocation @ {offset:#x} + {addend:#x} to target {target} of kind {reloc:?}"
2031         );
2032         let label = MachLabel::from_block(BlockIndex::new(target));
2033         let offset = u32::try_from(offset).unwrap();
2034         match I::LabelUse::from_reloc(reloc, addend) {
2035             Some(label_use) => {
2036                 self.buf.use_label_at_offset(offset, label, label_use);
2037                 true
2038             }
2039             None => false,
2040         }
2041     }
2042 
2043     fn force_veneers(&mut self) {
2044         self.force_veneers = ForceVeneers::Yes;
2045     }
2046 
2047     fn write(&mut self, offset: u64, data: &[u8]) {
2048         self.buf.data[offset.try_into().unwrap()..][..data.len()].copy_from_slice(data);
2049     }
2050 
2051     fn finish(&mut self, ctrl_plane: &mut ControlPlane) -> Vec<u8> {
2052         // Double-check all functions were pushed.
2053         assert_eq!(self.next_func, self.buf.label_offsets.len());
2054 
2055         // Finish up any veneers, if necessary.
2056         self.buf
2057             .finish_emission_maybe_forcing_veneers(self.force_veneers, ctrl_plane);
2058 
2059         // We don't need the data any more, so return it to the caller.
2060         mem::take(&mut self.buf.data).into_vec()
2061     }
2062 }
2063 
2064 // We use an actual instruction definition to do tests, so we depend on the `arm64` feature here.
2065 #[cfg(all(test, feature = "arm64"))]
2066 mod test {
2067     use cranelift_entity::EntityRef as _;
2068 
2069     use super::*;
2070     use crate::ir::UserExternalNameRef;
2071     use crate::isa::aarch64::inst::{xreg, OperandSize};
2072     use crate::isa::aarch64::inst::{BranchTarget, CondBrKind, EmitInfo, Inst};
2073     use crate::machinst::{MachInstEmit, MachInstEmitState};
2074     use crate::settings;
2075 
2076     fn label(n: u32) -> MachLabel {
2077         MachLabel::from_block(BlockIndex::new(n as usize))
2078     }
2079     fn target(n: u32) -> BranchTarget {
2080         BranchTarget::Label(label(n))
2081     }
2082 
2083     #[test]
2084     fn test_elide_jump_to_next() {
2085         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2086         let mut buf = MachBuffer::new();
2087         let mut state = <Inst as MachInstEmit>::State::default();
2088         let constants = Default::default();
2089 
2090         buf.reserve_labels_for_blocks(2);
2091         buf.bind_label(label(0), state.ctrl_plane_mut());
2092         let inst = Inst::Jump { dest: target(1) };
2093         inst.emit(&mut buf, &info, &mut state);
2094         buf.bind_label(label(1), state.ctrl_plane_mut());
2095         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2096         assert_eq!(0, buf.total_size());
2097     }
2098 
2099     #[test]
2100     fn test_elide_trivial_jump_blocks() {
2101         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2102         let mut buf = MachBuffer::new();
2103         let mut state = <Inst as MachInstEmit>::State::default();
2104         let constants = Default::default();
2105 
2106         buf.reserve_labels_for_blocks(4);
2107 
2108         buf.bind_label(label(0), state.ctrl_plane_mut());
2109         let inst = Inst::CondBr {
2110             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2111             taken: target(1),
2112             not_taken: target(2),
2113         };
2114         inst.emit(&mut buf, &info, &mut state);
2115 
2116         buf.bind_label(label(1), state.ctrl_plane_mut());
2117         let inst = Inst::Jump { dest: target(3) };
2118         inst.emit(&mut buf, &info, &mut state);
2119 
2120         buf.bind_label(label(2), state.ctrl_plane_mut());
2121         let inst = Inst::Jump { dest: target(3) };
2122         inst.emit(&mut buf, &info, &mut state);
2123 
2124         buf.bind_label(label(3), state.ctrl_plane_mut());
2125 
2126         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2127         assert_eq!(0, buf.total_size());
2128     }
2129 
2130     #[test]
2131     fn test_flip_cond() {
2132         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2133         let mut buf = MachBuffer::new();
2134         let mut state = <Inst as MachInstEmit>::State::default();
2135         let constants = Default::default();
2136 
2137         buf.reserve_labels_for_blocks(4);
2138 
2139         buf.bind_label(label(0), state.ctrl_plane_mut());
2140         let inst = Inst::CondBr {
2141             kind: CondBrKind::Zero(xreg(0), OperandSize::Size64),
2142             taken: target(1),
2143             not_taken: target(2),
2144         };
2145         inst.emit(&mut buf, &info, &mut state);
2146 
2147         buf.bind_label(label(1), state.ctrl_plane_mut());
2148         let inst = Inst::Nop4;
2149         inst.emit(&mut buf, &info, &mut state);
2150 
2151         buf.bind_label(label(2), state.ctrl_plane_mut());
2152         let inst = Inst::Udf {
2153             trap_code: TrapCode::STACK_OVERFLOW,
2154         };
2155         inst.emit(&mut buf, &info, &mut state);
2156 
2157         buf.bind_label(label(3), state.ctrl_plane_mut());
2158 
2159         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2160 
2161         let mut buf2 = MachBuffer::new();
2162         let mut state = Default::default();
2163         let inst = Inst::TrapIf {
2164             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2165             trap_code: TrapCode::STACK_OVERFLOW,
2166         };
2167         inst.emit(&mut buf2, &info, &mut state);
2168         let inst = Inst::Nop4;
2169         inst.emit(&mut buf2, &info, &mut state);
2170 
2171         let buf2 = buf2.finish(&constants, state.ctrl_plane_mut());
2172 
2173         assert_eq!(buf.data, buf2.data);
2174     }
2175 
2176     #[test]
2177     fn test_island() {
2178         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2179         let mut buf = MachBuffer::new();
2180         let mut state = <Inst as MachInstEmit>::State::default();
2181         let constants = Default::default();
2182 
2183         buf.reserve_labels_for_blocks(4);
2184 
2185         buf.bind_label(label(0), state.ctrl_plane_mut());
2186         let inst = Inst::CondBr {
2187             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2188             taken: target(2),
2189             not_taken: target(3),
2190         };
2191         inst.emit(&mut buf, &info, &mut state);
2192 
2193         buf.bind_label(label(1), state.ctrl_plane_mut());
2194         while buf.cur_offset() < 2000000 {
2195             if buf.island_needed(0) {
2196                 buf.emit_island(0, state.ctrl_plane_mut());
2197             }
2198             let inst = Inst::Nop4;
2199             inst.emit(&mut buf, &info, &mut state);
2200         }
2201 
2202         buf.bind_label(label(2), state.ctrl_plane_mut());
2203         let inst = Inst::Nop4;
2204         inst.emit(&mut buf, &info, &mut state);
2205 
2206         buf.bind_label(label(3), state.ctrl_plane_mut());
2207         let inst = Inst::Nop4;
2208         inst.emit(&mut buf, &info, &mut state);
2209 
2210         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2211 
2212         assert_eq!(2000000 + 8, buf.total_size());
2213 
2214         let mut buf2 = MachBuffer::new();
2215         let mut state = Default::default();
2216         let inst = Inst::CondBr {
2217             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2218 
2219             // This conditionally taken branch has a 19-bit constant, shifted
2220             // to the left by two, giving us a 21-bit range in total. Half of
2221             // this range positive so the we should be around 1 << 20 bytes
2222             // away for our jump target.
2223             //
2224             // There are two pending fixups by the time we reach this point,
2225             // one for this 19-bit jump and one for the unconditional 26-bit
2226             // jump below. A 19-bit veneer is 4 bytes large and the 26-bit
2227             // veneer is 20 bytes large, which means that pessimistically
2228             // assuming we'll need two veneers. Currently each veneer is
2229             // pessimistically assumed to be the maximal size which means we
2230             // need 40 bytes of extra space, meaning that the actual island
2231             // should come 40-bytes before the deadline.
2232             taken: BranchTarget::ResolvedOffset((1 << 20) - 20 - 20),
2233 
2234             // This branch is in-range so no veneers should be needed, it should
2235             // go directly to the target.
2236             not_taken: BranchTarget::ResolvedOffset(2000000 + 4 - 4),
2237         };
2238         inst.emit(&mut buf2, &info, &mut state);
2239 
2240         let buf2 = buf2.finish(&constants, state.ctrl_plane_mut());
2241 
2242         assert_eq!(&buf.data[0..8], &buf2.data[..]);
2243     }
2244 
2245     #[test]
2246     fn test_island_backward() {
2247         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2248         let mut buf = MachBuffer::new();
2249         let mut state = <Inst as MachInstEmit>::State::default();
2250         let constants = Default::default();
2251 
2252         buf.reserve_labels_for_blocks(4);
2253 
2254         buf.bind_label(label(0), state.ctrl_plane_mut());
2255         let inst = Inst::Nop4;
2256         inst.emit(&mut buf, &info, &mut state);
2257 
2258         buf.bind_label(label(1), state.ctrl_plane_mut());
2259         let inst = Inst::Nop4;
2260         inst.emit(&mut buf, &info, &mut state);
2261 
2262         buf.bind_label(label(2), state.ctrl_plane_mut());
2263         while buf.cur_offset() < 2000000 {
2264             let inst = Inst::Nop4;
2265             inst.emit(&mut buf, &info, &mut state);
2266         }
2267 
2268         buf.bind_label(label(3), state.ctrl_plane_mut());
2269         let inst = Inst::CondBr {
2270             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2271             taken: target(0),
2272             not_taken: target(1),
2273         };
2274         inst.emit(&mut buf, &info, &mut state);
2275 
2276         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2277 
2278         assert_eq!(2000000 + 12, buf.total_size());
2279 
2280         let mut buf2 = MachBuffer::new();
2281         let mut state = Default::default();
2282         let inst = Inst::CondBr {
2283             kind: CondBrKind::NotZero(xreg(0), OperandSize::Size64),
2284             taken: BranchTarget::ResolvedOffset(8),
2285             not_taken: BranchTarget::ResolvedOffset(4 - (2000000 + 4)),
2286         };
2287         inst.emit(&mut buf2, &info, &mut state);
2288         let inst = Inst::Jump {
2289             dest: BranchTarget::ResolvedOffset(-(2000000 + 8)),
2290         };
2291         inst.emit(&mut buf2, &info, &mut state);
2292 
2293         let buf2 = buf2.finish(&constants, state.ctrl_plane_mut());
2294 
2295         assert_eq!(&buf.data[2000000..], &buf2.data[..]);
2296     }
2297 
2298     #[test]
2299     fn test_multiple_redirect() {
2300         // label0:
2301         //   cbz x0, label1
2302         //   b label2
2303         // label1:
2304         //   b label3
2305         // label2:
2306         //   nop
2307         //   nop
2308         //   b label0
2309         // label3:
2310         //   b label4
2311         // label4:
2312         //   b label5
2313         // label5:
2314         //   b label7
2315         // label6:
2316         //   nop
2317         // label7:
2318         //   ret
2319         //
2320         // -- should become:
2321         //
2322         // label0:
2323         //   cbz x0, label7
2324         // label2:
2325         //   nop
2326         //   nop
2327         //   b label0
2328         // label6:
2329         //   nop
2330         // label7:
2331         //   ret
2332 
2333         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2334         let mut buf = MachBuffer::new();
2335         let mut state = <Inst as MachInstEmit>::State::default();
2336         let constants = Default::default();
2337 
2338         buf.reserve_labels_for_blocks(8);
2339 
2340         buf.bind_label(label(0), state.ctrl_plane_mut());
2341         let inst = Inst::CondBr {
2342             kind: CondBrKind::Zero(xreg(0), OperandSize::Size64),
2343             taken: target(1),
2344             not_taken: target(2),
2345         };
2346         inst.emit(&mut buf, &info, &mut state);
2347 
2348         buf.bind_label(label(1), state.ctrl_plane_mut());
2349         let inst = Inst::Jump { dest: target(3) };
2350         inst.emit(&mut buf, &info, &mut state);
2351 
2352         buf.bind_label(label(2), state.ctrl_plane_mut());
2353         let inst = Inst::Nop4;
2354         inst.emit(&mut buf, &info, &mut state);
2355         inst.emit(&mut buf, &info, &mut state);
2356         let inst = Inst::Jump { dest: target(0) };
2357         inst.emit(&mut buf, &info, &mut state);
2358 
2359         buf.bind_label(label(3), state.ctrl_plane_mut());
2360         let inst = Inst::Jump { dest: target(4) };
2361         inst.emit(&mut buf, &info, &mut state);
2362 
2363         buf.bind_label(label(4), state.ctrl_plane_mut());
2364         let inst = Inst::Jump { dest: target(5) };
2365         inst.emit(&mut buf, &info, &mut state);
2366 
2367         buf.bind_label(label(5), state.ctrl_plane_mut());
2368         let inst = Inst::Jump { dest: target(7) };
2369         inst.emit(&mut buf, &info, &mut state);
2370 
2371         buf.bind_label(label(6), state.ctrl_plane_mut());
2372         let inst = Inst::Nop4;
2373         inst.emit(&mut buf, &info, &mut state);
2374 
2375         buf.bind_label(label(7), state.ctrl_plane_mut());
2376         let inst = Inst::Ret {};
2377         inst.emit(&mut buf, &info, &mut state);
2378 
2379         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2380 
2381         let golden_data = vec![
2382             0xa0, 0x00, 0x00, 0xb4, // cbz x0, 0x14
2383             0x1f, 0x20, 0x03, 0xd5, // nop
2384             0x1f, 0x20, 0x03, 0xd5, // nop
2385             0xfd, 0xff, 0xff, 0x17, // b 0
2386             0x1f, 0x20, 0x03, 0xd5, // nop
2387             0xc0, 0x03, 0x5f, 0xd6, // ret
2388         ];
2389 
2390         assert_eq!(&golden_data[..], &buf.data[..]);
2391     }
2392 
2393     #[test]
2394     fn test_handle_branch_cycle() {
2395         // label0:
2396         //   b label1
2397         // label1:
2398         //   b label2
2399         // label2:
2400         //   b label3
2401         // label3:
2402         //   b label4
2403         // label4:
2404         //   b label1  // note: not label0 (to make it interesting).
2405         //
2406         // -- should become:
2407         //
2408         // label0, label1, ..., label4:
2409         //   b label0
2410         let info = EmitInfo::new(settings::Flags::new(settings::builder()));
2411         let mut buf = MachBuffer::new();
2412         let mut state = <Inst as MachInstEmit>::State::default();
2413         let constants = Default::default();
2414 
2415         buf.reserve_labels_for_blocks(5);
2416 
2417         buf.bind_label(label(0), state.ctrl_plane_mut());
2418         let inst = Inst::Jump { dest: target(1) };
2419         inst.emit(&mut buf, &info, &mut state);
2420 
2421         buf.bind_label(label(1), state.ctrl_plane_mut());
2422         let inst = Inst::Jump { dest: target(2) };
2423         inst.emit(&mut buf, &info, &mut state);
2424 
2425         buf.bind_label(label(2), state.ctrl_plane_mut());
2426         let inst = Inst::Jump { dest: target(3) };
2427         inst.emit(&mut buf, &info, &mut state);
2428 
2429         buf.bind_label(label(3), state.ctrl_plane_mut());
2430         let inst = Inst::Jump { dest: target(4) };
2431         inst.emit(&mut buf, &info, &mut state);
2432 
2433         buf.bind_label(label(4), state.ctrl_plane_mut());
2434         let inst = Inst::Jump { dest: target(1) };
2435         inst.emit(&mut buf, &info, &mut state);
2436 
2437         let buf = buf.finish(&constants, state.ctrl_plane_mut());
2438 
2439         let golden_data = vec![
2440             0x00, 0x00, 0x00, 0x14, // b 0
2441         ];
2442 
2443         assert_eq!(&golden_data[..], &buf.data[..]);
2444     }
2445 
2446     #[test]
2447     fn metadata_records() {
2448         let mut buf = MachBuffer::<Inst>::new();
2449         let ctrl_plane = &mut Default::default();
2450         let constants = Default::default();
2451 
2452         buf.reserve_labels_for_blocks(1);
2453 
2454         buf.bind_label(label(0), ctrl_plane);
2455         buf.put1(1);
2456         buf.add_trap(TrapCode::HEAP_OUT_OF_BOUNDS);
2457         buf.put1(2);
2458         buf.add_trap(TrapCode::INTEGER_OVERFLOW);
2459         buf.add_trap(TrapCode::INTEGER_DIVISION_BY_ZERO);
2460         buf.add_call_site();
2461         buf.add_reloc(
2462             Reloc::Abs4,
2463             &ExternalName::User(UserExternalNameRef::new(0)),
2464             0,
2465         );
2466         buf.put1(3);
2467         buf.add_reloc(
2468             Reloc::Abs8,
2469             &ExternalName::User(UserExternalNameRef::new(1)),
2470             1,
2471         );
2472         buf.put1(4);
2473 
2474         let buf = buf.finish(&constants, ctrl_plane);
2475 
2476         assert_eq!(buf.data(), &[1, 2, 3, 4]);
2477         assert_eq!(
2478             buf.traps()
2479                 .iter()
2480                 .map(|trap| (trap.offset, trap.code))
2481                 .collect::<Vec<_>>(),
2482             vec![
2483                 (1, TrapCode::HEAP_OUT_OF_BOUNDS),
2484                 (2, TrapCode::INTEGER_OVERFLOW),
2485                 (2, TrapCode::INTEGER_DIVISION_BY_ZERO)
2486             ]
2487         );
2488         assert_eq!(
2489             buf.call_sites()
2490                 .iter()
2491                 .map(|call_site| call_site.ret_addr)
2492                 .collect::<Vec<_>>(),
2493             vec![2]
2494         );
2495         assert_eq!(
2496             buf.relocs()
2497                 .iter()
2498                 .map(|reloc| (reloc.offset, reloc.kind))
2499                 .collect::<Vec<_>>(),
2500             vec![(2, Reloc::Abs4), (3, Reloc::Abs8)]
2501         );
2502     }
2503 }
2504