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