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