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