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