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