1 //! This implements the VCode container: a CFG of Insts that have been lowered. 2 //! 3 //! VCode is virtual-register code. An instruction in VCode is almost a machine 4 //! instruction; however, its register slots can refer to virtual registers in 5 //! addition to real machine registers. 6 //! 7 //! VCode is structured with traditional basic blocks, and 8 //! each block must be terminated by an unconditional branch (one target), a 9 //! conditional branch (two targets), or a return (no targets). Note that this 10 //! slightly differs from the machine code of most ISAs: in most ISAs, a 11 //! conditional branch has one target (and the not-taken case falls through). 12 //! However, we expect that machine backends will elide branches to the following 13 //! block (i.e., zero-offset jumps), and will be able to codegen a branch-cond / 14 //! branch-uncond pair if *both* targets are not fallthrough. This allows us to 15 //! play with layout prior to final binary emission, as well, if we want. 16 //! 17 //! See the main module comment in `mod.rs` for more details on the VCode-based 18 //! backend pipeline. 19 20 use crate::ir::pcc::*; 21 use crate::ir::{self, types, Constant, ConstantData, ValueLabel}; 22 use crate::machinst::*; 23 use crate::ranges::Ranges; 24 use crate::timing; 25 use crate::trace; 26 use crate::CodegenError; 27 use crate::{LabelValueLoc, ValueLocRange}; 28 use regalloc2::{ 29 Edit, Function as RegallocFunction, InstOrEdit, InstRange, MachineEnv, Operand, 30 OperandConstraint, OperandKind, PRegSet, RegClass, 31 }; 32 use rustc_hash::FxHashMap; 33 34 use core::mem::take; 35 use cranelift_entity::{entity_impl, Keys}; 36 use std::collections::hash_map::Entry; 37 use std::collections::HashMap; 38 use std::fmt; 39 40 /// Index referring to an instruction in VCode. 41 pub type InsnIndex = regalloc2::Inst; 42 43 /// Extension trait for `InsnIndex` to allow conversion to a 44 /// `BackwardsInsnIndex`. 45 trait ToBackwardsInsnIndex { 46 fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex; 47 } 48 49 impl ToBackwardsInsnIndex for InsnIndex { 50 fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex { 51 BackwardsInsnIndex::new(num_insts - self.index() - 1) 52 } 53 } 54 55 /// An index referring to an instruction in the VCode when it is backwards, 56 /// during VCode construction. 57 #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 58 #[cfg_attr( 59 feature = "enable-serde", 60 derive(::serde::Serialize, ::serde::Deserialize) 61 )] 62 pub struct BackwardsInsnIndex(InsnIndex); 63 64 impl BackwardsInsnIndex { 65 pub fn new(i: usize) -> Self { 66 BackwardsInsnIndex(InsnIndex::new(i)) 67 } 68 } 69 70 /// Index referring to a basic block in VCode. 71 pub type BlockIndex = regalloc2::Block; 72 73 /// VCodeInst wraps all requirements for a MachInst to be in VCode: it must be 74 /// a `MachInst` and it must be able to emit itself at least to a `SizeCodeSink`. 75 pub trait VCodeInst: MachInst + MachInstEmit {} 76 impl<I: MachInst + MachInstEmit> VCodeInst for I {} 77 78 /// A function in "VCode" (virtualized-register code) form, after 79 /// lowering. This is essentially a standard CFG of basic blocks, 80 /// where each basic block consists of lowered instructions produced 81 /// by the machine-specific backend. 82 /// 83 /// Note that the VCode is immutable once produced, and is not 84 /// modified by register allocation in particular. Rather, register 85 /// allocation on the `VCode` produces a separate `regalloc2::Output` 86 /// struct, and this can be passed to `emit`. `emit` in turn does not 87 /// modify the vcode, but produces an `EmitResult`, which contains the 88 /// machine code itself, and the associated disassembly and/or 89 /// metadata as requested. 90 pub struct VCode<I: VCodeInst> { 91 /// VReg IR-level types. 92 vreg_types: Vec<Type>, 93 94 /// Lowered machine instructions in order corresponding to the original IR. 95 insts: Vec<I>, 96 97 /// A map from backwards instruction index to the user stack map for that 98 /// instruction. 99 /// 100 /// This is a sparse side table that only has entries for instructions that 101 /// are safepoints, and only for a subset of those that have an associated 102 /// user stack map. 103 user_stack_maps: FxHashMap<BackwardsInsnIndex, ir::UserStackMap>, 104 105 /// Operands: pre-regalloc references to virtual registers with 106 /// constraints, in one flattened array. This allows the regalloc 107 /// to efficiently access all operands without requiring expensive 108 /// matches or method invocations on insts. 109 operands: Vec<Operand>, 110 111 /// Operand index ranges: for each instruction in `insts`, there 112 /// is a tuple here providing the range in `operands` for that 113 /// instruction's operands. 114 operand_ranges: Ranges, 115 116 /// Clobbers: a sparse map from instruction indices to clobber masks. 117 clobbers: FxHashMap<InsnIndex, PRegSet>, 118 119 /// Source locations for each instruction. (`SourceLoc` is a `u32`, so it is 120 /// reasonable to keep one of these per instruction.) 121 srclocs: Vec<RelSourceLoc>, 122 123 /// Entry block. 124 entry: BlockIndex, 125 126 /// Block instruction indices. 127 block_ranges: Ranges, 128 129 /// Block successors: index range in the `block_succs` list. 130 block_succ_range: Ranges, 131 132 /// Block successor lists, concatenated into one vec. The 133 /// `block_succ_range` list of tuples above gives (start, end) 134 /// ranges within this list that correspond to each basic block's 135 /// successors. 136 block_succs: Vec<regalloc2::Block>, 137 138 /// Block predecessors: index range in the `block_preds` list. 139 block_pred_range: Ranges, 140 141 /// Block predecessor lists, concatenated into one vec. The 142 /// `block_pred_range` list of tuples above gives (start, end) 143 /// ranges within this list that correspond to each basic block's 144 /// predecessors. 145 block_preds: Vec<regalloc2::Block>, 146 147 /// Block parameters: index range in `block_params` below. 148 block_params_range: Ranges, 149 150 /// Block parameter lists, concatenated into one vec. The 151 /// `block_params_range` list of tuples above gives (start, end) 152 /// ranges within this list that correspond to each basic block's 153 /// blockparam vregs. 154 block_params: Vec<regalloc2::VReg>, 155 156 /// Outgoing block arguments on branch instructions, concatenated 157 /// into one list. 158 /// 159 /// Note that this is conceptually a 3D array: we have a VReg list 160 /// per block, per successor. We flatten those three dimensions 161 /// into this 1D vec, then store index ranges in two levels of 162 /// indirection. 163 /// 164 /// Indexed by the indices in `branch_block_arg_succ_range`. 165 branch_block_args: Vec<regalloc2::VReg>, 166 167 /// Array of sequences of (start, end) tuples in 168 /// `branch_block_args`, one for each successor; these sequences 169 /// for each block are concatenated. 170 /// 171 /// Indexed by the indices in `branch_block_arg_succ_range`. 172 branch_block_arg_range: Ranges, 173 174 /// For a given block, indices in `branch_block_arg_range` 175 /// corresponding to all of its successors. 176 branch_block_arg_succ_range: Ranges, 177 178 /// Block-order information. 179 block_order: BlockLoweringOrder, 180 181 /// ABI object. 182 pub(crate) abi: Callee<I::ABIMachineSpec>, 183 184 /// Constant information used during code emission. This should be 185 /// immutable across function compilations within the same module. 186 emit_info: I::Info, 187 188 /// Reference-typed `regalloc2::VReg`s. The regalloc requires 189 /// these in a dense slice (as opposed to querying the 190 /// reftype-status of each vreg) for efficient iteration. 191 reftyped_vregs: Vec<VReg>, 192 193 /// Constants. 194 pub(crate) constants: VCodeConstants, 195 196 /// Value labels for debuginfo attached to vregs. 197 debug_value_labels: Vec<(VReg, InsnIndex, InsnIndex, u32)>, 198 199 pub(crate) sigs: SigSet, 200 201 /// Facts on VRegs, for proof-carrying code verification. 202 facts: Vec<Option<Fact>>, 203 } 204 205 /// The result of `VCode::emit`. Contains all information computed 206 /// during emission: actual machine code, optionally a disassembly, 207 /// and optionally metadata about the code layout. 208 pub struct EmitResult { 209 /// The MachBuffer containing the machine code. 210 pub buffer: MachBufferFinalized<Stencil>, 211 212 /// Offset of each basic block, recorded during emission. Computed 213 /// only if `debug_value_labels` is non-empty. 214 pub bb_offsets: Vec<CodeOffset>, 215 216 /// Final basic-block edges, in terms of code offsets of 217 /// bb-starts. Computed only if `debug_value_labels` is non-empty. 218 pub bb_edges: Vec<(CodeOffset, CodeOffset)>, 219 220 /// Final length of function body. 221 pub func_body_len: CodeOffset, 222 223 /// The pretty-printed disassembly, if any. This uses the same 224 /// pretty-printing for MachInsts as the pre-regalloc VCode Debug 225 /// implementation, but additionally includes the prologue and 226 /// epilogue(s), and makes use of the regalloc results. 227 pub disasm: Option<String>, 228 229 /// Offsets of sized stackslots. 230 pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>, 231 232 /// Offsets of dynamic stackslots. 233 pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>, 234 235 /// Value-labels information (debug metadata). 236 pub value_labels_ranges: ValueLabelsRanges, 237 238 /// Stack frame size. 239 pub frame_size: u32, 240 } 241 242 /// A builder for a VCode function body. 243 /// 244 /// This builder has the ability to accept instructions in either 245 /// forward or reverse order, depending on the pass direction that 246 /// produces the VCode. The lowering from CLIF to VCode<MachInst> 247 /// ordinarily occurs in reverse order (in order to allow instructions 248 /// to be lowered only if used, and not merged) so a reversal will 249 /// occur at the end of lowering to ensure the VCode is in machine 250 /// order. 251 /// 252 /// If built in reverse, block and instruction indices used once the 253 /// VCode is built are relative to the final (reversed) order, not the 254 /// order of construction. Note that this means we do not know the 255 /// final block or instruction indices when building, so we do not 256 /// hand them out. (The user is assumed to know them when appending 257 /// terminator instructions with successor blocks.) 258 pub struct VCodeBuilder<I: VCodeInst> { 259 /// In-progress VCode. 260 pub(crate) vcode: VCode<I>, 261 262 /// In what direction is the build occurring? 263 direction: VCodeBuildDirection, 264 265 /// Debug-value label in-progress map, keyed by label. For each 266 /// label, we keep disjoint ranges mapping to vregs. We'll flatten 267 /// this into (vreg, range, label) tuples when done. 268 debug_info: FxHashMap<ValueLabel, Vec<(InsnIndex, InsnIndex, VReg)>>, 269 } 270 271 /// Direction in which a VCodeBuilder builds VCode. 272 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 273 pub enum VCodeBuildDirection { 274 // TODO: add `Forward` once we need it and can test it adequately. 275 /// Backward-build pass: we expect the producer to call `emit()` 276 /// with instructions in reverse program order within each block. 277 Backward, 278 } 279 280 impl<I: VCodeInst> VCodeBuilder<I> { 281 /// Create a new VCodeBuilder. 282 pub fn new( 283 sigs: SigSet, 284 abi: Callee<I::ABIMachineSpec>, 285 emit_info: I::Info, 286 block_order: BlockLoweringOrder, 287 constants: VCodeConstants, 288 direction: VCodeBuildDirection, 289 ) -> Self { 290 let vcode = VCode::new(sigs, abi, emit_info, block_order, constants); 291 292 VCodeBuilder { 293 vcode, 294 direction, 295 debug_info: FxHashMap::default(), 296 } 297 } 298 299 pub fn init_retval_area(&mut self, vregs: &mut VRegAllocator<I>) -> CodegenResult<()> { 300 self.vcode.abi.init_retval_area(&self.vcode.sigs, vregs) 301 } 302 303 /// Access the ABI object. 304 pub fn abi(&self) -> &Callee<I::ABIMachineSpec> { 305 &self.vcode.abi 306 } 307 308 /// Access the ABI object. 309 pub fn abi_mut(&mut self) -> &mut Callee<I::ABIMachineSpec> { 310 &mut self.vcode.abi 311 } 312 313 pub fn sigs(&self) -> &SigSet { 314 &self.vcode.sigs 315 } 316 317 pub fn sigs_mut(&mut self) -> &mut SigSet { 318 &mut self.vcode.sigs 319 } 320 321 /// Access to the BlockLoweringOrder object. 322 pub fn block_order(&self) -> &BlockLoweringOrder { 323 &self.vcode.block_order 324 } 325 326 /// Set the current block as the entry block. 327 pub fn set_entry(&mut self, block: BlockIndex) { 328 self.vcode.entry = block; 329 } 330 331 /// End the current basic block. Must be called after emitting vcode insts 332 /// for IR insts and prior to ending the function (building the VCode). 333 pub fn end_bb(&mut self) { 334 let end_idx = self.vcode.insts.len(); 335 // Add the instruction index range to the list of blocks. 336 self.vcode.block_ranges.push_end(end_idx); 337 // End the successors list. 338 let succ_end = self.vcode.block_succs.len(); 339 self.vcode.block_succ_range.push_end(succ_end); 340 // End the blockparams list. 341 let block_params_end = self.vcode.block_params.len(); 342 self.vcode.block_params_range.push_end(block_params_end); 343 // End the branch blockparam args list. 344 let branch_block_arg_succ_end = self.vcode.branch_block_arg_range.len(); 345 self.vcode 346 .branch_block_arg_succ_range 347 .push_end(branch_block_arg_succ_end); 348 } 349 350 pub fn add_block_param(&mut self, param: VirtualReg) { 351 self.vcode.block_params.push(param.into()); 352 } 353 354 fn add_branch_args_for_succ(&mut self, args: &[Reg]) { 355 self.vcode 356 .branch_block_args 357 .extend(args.iter().map(|&arg| VReg::from(arg))); 358 let end = self.vcode.branch_block_args.len(); 359 self.vcode.branch_block_arg_range.push_end(end); 360 } 361 362 /// Push an instruction for the current BB and current IR inst 363 /// within the BB. 364 pub fn push(&mut self, insn: I, loc: RelSourceLoc) { 365 self.vcode.insts.push(insn); 366 self.vcode.srclocs.push(loc); 367 } 368 369 /// Add a successor block with branch args. 370 pub fn add_succ(&mut self, block: BlockIndex, args: &[Reg]) { 371 self.vcode.block_succs.push(block); 372 self.add_branch_args_for_succ(args); 373 } 374 375 /// Add a debug value label to a register. 376 pub fn add_value_label(&mut self, reg: Reg, label: ValueLabel) { 377 // We'll fix up labels in reverse(). Because we're generating 378 // code bottom-to-top, the liverange of the label goes *from* 379 // the last index at which was defined (or 0, which is the end 380 // of the eventual function) *to* just this instruction, and 381 // no further. 382 let inst = InsnIndex::new(self.vcode.insts.len()); 383 let labels = self.debug_info.entry(label).or_insert_with(|| vec![]); 384 let last = labels 385 .last() 386 .map(|(_start, end, _vreg)| *end) 387 .unwrap_or(InsnIndex::new(0)); 388 labels.push((last, inst, reg.into())); 389 } 390 391 /// Access the constants. 392 pub fn constants(&mut self) -> &mut VCodeConstants { 393 &mut self.vcode.constants 394 } 395 396 fn compute_preds_from_succs(&mut self) { 397 // Do a linear-time counting sort: first determine how many 398 // times each block appears as a successor. 399 let mut starts = vec![0u32; self.vcode.num_blocks()]; 400 for succ in &self.vcode.block_succs { 401 starts[succ.index()] += 1; 402 } 403 404 // Determine for each block the starting index where that 405 // block's predecessors should go. This is equivalent to the 406 // ranges we need to store in block_pred_range. 407 self.vcode.block_pred_range.reserve(starts.len()); 408 let mut end = 0; 409 for count in starts.iter_mut() { 410 let start = end; 411 end += *count; 412 *count = start; 413 self.vcode.block_pred_range.push_end(end as usize); 414 } 415 let end = end as usize; 416 debug_assert_eq!(end, self.vcode.block_succs.len()); 417 418 // Walk over the successors again, this time grouped by 419 // predecessor, and push the predecessor at the current 420 // starting position of each of its successors. We build 421 // each group of predecessors in whatever order Ranges::iter 422 // returns them; regalloc2 doesn't care. 423 self.vcode.block_preds.resize(end, BlockIndex::invalid()); 424 for (pred, range) in self.vcode.block_succ_range.iter() { 425 let pred = BlockIndex::new(pred); 426 for succ in &self.vcode.block_succs[range] { 427 let pos = &mut starts[succ.index()]; 428 self.vcode.block_preds[*pos as usize] = pred; 429 *pos += 1; 430 } 431 } 432 debug_assert!(self.vcode.block_preds.iter().all(|pred| pred.is_valid())); 433 } 434 435 /// Called once, when a build in Backward order is complete, to 436 /// perform the overall reversal (into final forward order) and 437 /// finalize metadata accordingly. 438 fn reverse_and_finalize(&mut self, vregs: &VRegAllocator<I>) { 439 let n_insts = self.vcode.insts.len(); 440 if n_insts == 0 { 441 return; 442 } 443 444 // Reverse the per-block and per-inst sequences. 445 self.vcode.block_ranges.reverse_index(); 446 self.vcode.block_ranges.reverse_target(n_insts); 447 // block_params_range is indexed by block (and blocks were 448 // traversed in reverse) so we reverse it; but block-param 449 // sequences in the concatenated vec can remain in reverse 450 // order (it is effectively an arena of arbitrarily-placed 451 // referenced sequences). 452 self.vcode.block_params_range.reverse_index(); 453 // Likewise, we reverse block_succ_range, but the block_succ 454 // concatenated array can remain as-is. 455 self.vcode.block_succ_range.reverse_index(); 456 self.vcode.insts.reverse(); 457 self.vcode.srclocs.reverse(); 458 // Likewise, branch_block_arg_succ_range is indexed by block 459 // so must be reversed. 460 self.vcode.branch_block_arg_succ_range.reverse_index(); 461 462 // To translate an instruction index *endpoint* in reversed 463 // order to forward order, compute `n_insts - i`. 464 // 465 // Why not `n_insts - 1 - i`? That would be correct to 466 // translate an individual instruction index (for ten insts 0 467 // to 9 inclusive, inst 0 becomes 9, and inst 9 becomes 468 // 0). But for the usual inclusive-start, exclusive-end range 469 // idiom, inclusive starts become exclusive ends and 470 // vice-versa, so e.g. an (inclusive) start of 0 becomes an 471 // (exclusive) end of 10. 472 let translate = |inst: InsnIndex| InsnIndex::new(n_insts - inst.index()); 473 474 // Generate debug-value labels based on per-label maps. 475 for (label, tuples) in &self.debug_info { 476 for &(start, end, vreg) in tuples { 477 let vreg = vregs.resolve_vreg_alias(vreg); 478 let fwd_start = translate(end); 479 let fwd_end = translate(start); 480 self.vcode 481 .debug_value_labels 482 .push((vreg, fwd_start, fwd_end, label.as_u32())); 483 } 484 } 485 486 // Now sort debug value labels by VReg, as required 487 // by regalloc2. 488 self.vcode 489 .debug_value_labels 490 .sort_unstable_by_key(|(vreg, _, _, _)| *vreg); 491 } 492 493 fn collect_operands(&mut self, vregs: &VRegAllocator<I>) { 494 let allocatable = PRegSet::from(self.vcode.machine_env()); 495 for (i, insn) in self.vcode.insts.iter_mut().enumerate() { 496 // Push operands from the instruction onto the operand list. 497 // 498 // We rename through the vreg alias table as we collect 499 // the operands. This is better than a separate post-pass 500 // over operands, because it has more cache locality: 501 // operands only need to pass through L1 once. This is 502 // also better than renaming instructions' 503 // operands/registers while lowering, because here we only 504 // need to do the `match` over the instruction to visit 505 // its register fields (which is slow, branchy code) once. 506 507 let mut op_collector = 508 OperandCollector::new(&mut self.vcode.operands, allocatable, |vreg| { 509 vregs.resolve_vreg_alias(vreg) 510 }); 511 insn.get_operands(&mut op_collector); 512 let (ops, clobbers) = op_collector.finish(); 513 self.vcode.operand_ranges.push_end(ops); 514 515 if clobbers != PRegSet::default() { 516 self.vcode.clobbers.insert(InsnIndex::new(i), clobbers); 517 } 518 519 if let Some((dst, src)) = insn.is_move() { 520 // We should never see non-virtual registers present in move 521 // instructions. 522 assert!( 523 src.is_virtual(), 524 "the real register {src:?} was used as the source of a move instruction" 525 ); 526 assert!( 527 dst.to_reg().is_virtual(), 528 "the real register {:?} was used as the destination of a move instruction", 529 dst.to_reg() 530 ); 531 } 532 } 533 534 // Translate blockparam args via the vreg aliases table as well. 535 for arg in &mut self.vcode.branch_block_args { 536 let new_arg = vregs.resolve_vreg_alias(*arg); 537 trace!("operandcollector: block arg {:?} -> {:?}", arg, new_arg); 538 *arg = new_arg; 539 } 540 } 541 542 /// Build the final VCode. 543 pub fn build(mut self, mut vregs: VRegAllocator<I>) -> VCode<I> { 544 self.vcode.vreg_types = take(&mut vregs.vreg_types); 545 self.vcode.facts = take(&mut vregs.facts); 546 self.vcode.reftyped_vregs = take(&mut vregs.reftyped_vregs); 547 548 if self.direction == VCodeBuildDirection::Backward { 549 self.reverse_and_finalize(&vregs); 550 } 551 self.collect_operands(&vregs); 552 553 // Apply register aliases to the `reftyped_vregs` list since this list 554 // will be returned directly to `regalloc2` eventually and all 555 // operands/results of instructions will use the alias-resolved vregs 556 // from `regalloc2`'s perspective. 557 // 558 // Also note that `reftyped_vregs` can't have duplicates, so after the 559 // aliases are applied duplicates are removed. 560 for reg in self.vcode.reftyped_vregs.iter_mut() { 561 *reg = vregs.resolve_vreg_alias(*reg); 562 } 563 self.vcode.reftyped_vregs.sort(); 564 self.vcode.reftyped_vregs.dedup(); 565 566 self.compute_preds_from_succs(); 567 self.vcode.debug_value_labels.sort_unstable(); 568 569 // At this point, nothing in the vcode should mention any 570 // VReg which has been aliased. All the appropriate rewriting 571 // should have happened above. Just to be sure, let's 572 // double-check each field which has vregs. 573 // Note: can't easily check vcode.insts, resolved in collect_operands. 574 // Operands are resolved in collect_operands. 575 vregs.debug_assert_no_vreg_aliases(self.vcode.operands.iter().map(|op| op.vreg())); 576 // Currently block params are never aliased to another vreg. 577 vregs.debug_assert_no_vreg_aliases(self.vcode.block_params.iter().copied()); 578 // Branch block args are resolved in collect_operands. 579 vregs.debug_assert_no_vreg_aliases(self.vcode.branch_block_args.iter().copied()); 580 // Reftyped vregs are resolved above in this function. 581 vregs.debug_assert_no_vreg_aliases(self.vcode.reftyped_vregs.iter().copied()); 582 // Debug value labels are resolved in reverse_and_finalize. 583 vregs.debug_assert_no_vreg_aliases( 584 self.vcode.debug_value_labels.iter().map(|&(vreg, ..)| vreg), 585 ); 586 // Facts are resolved eagerly during set_vreg_alias. 587 vregs.debug_assert_no_vreg_aliases( 588 self.vcode 589 .facts 590 .iter() 591 .zip(&vregs.vreg_types) 592 .enumerate() 593 .filter(|(_, (fact, _))| fact.is_some()) 594 .map(|(vreg, (_, &ty))| { 595 let (regclasses, _) = I::rc_for_type(ty).unwrap(); 596 VReg::new(vreg, regclasses[0]) 597 }), 598 ); 599 600 self.vcode 601 } 602 603 /// Add a user stack map for the associated instruction. 604 pub fn add_user_stack_map( 605 &mut self, 606 inst: BackwardsInsnIndex, 607 entries: &[ir::UserStackMapEntry], 608 ) { 609 let stack_map = ir::UserStackMap::new(entries, self.vcode.abi.sized_stackslot_offsets()); 610 let old_entry = self.vcode.user_stack_maps.insert(inst, stack_map); 611 debug_assert!(old_entry.is_none()); 612 } 613 } 614 615 /// Is this type a reference type? 616 fn is_reftype(ty: Type) -> bool { 617 ty == types::R64 || ty == types::R32 618 } 619 620 const NO_INST_OFFSET: CodeOffset = u32::MAX; 621 622 impl<I: VCodeInst> VCode<I> { 623 /// New empty VCode. 624 fn new( 625 sigs: SigSet, 626 abi: Callee<I::ABIMachineSpec>, 627 emit_info: I::Info, 628 block_order: BlockLoweringOrder, 629 constants: VCodeConstants, 630 ) -> Self { 631 let n_blocks = block_order.lowered_order().len(); 632 VCode { 633 sigs, 634 vreg_types: vec![], 635 insts: Vec::with_capacity(10 * n_blocks), 636 user_stack_maps: FxHashMap::default(), 637 operands: Vec::with_capacity(30 * n_blocks), 638 operand_ranges: Ranges::with_capacity(10 * n_blocks), 639 clobbers: FxHashMap::default(), 640 srclocs: Vec::with_capacity(10 * n_blocks), 641 entry: BlockIndex::new(0), 642 block_ranges: Ranges::with_capacity(n_blocks), 643 block_succ_range: Ranges::with_capacity(n_blocks), 644 block_succs: Vec::with_capacity(n_blocks), 645 block_pred_range: Ranges::default(), 646 block_preds: Vec::new(), 647 block_params_range: Ranges::with_capacity(n_blocks), 648 block_params: Vec::with_capacity(5 * n_blocks), 649 branch_block_args: Vec::with_capacity(10 * n_blocks), 650 branch_block_arg_range: Ranges::with_capacity(2 * n_blocks), 651 branch_block_arg_succ_range: Ranges::with_capacity(n_blocks), 652 block_order, 653 abi, 654 emit_info, 655 reftyped_vregs: vec![], 656 constants, 657 debug_value_labels: vec![], 658 facts: vec![], 659 } 660 } 661 662 /// Get the ABI-dependent MachineEnv for managing register allocation. 663 pub fn machine_env(&self) -> &MachineEnv { 664 self.abi.machine_env(&self.sigs) 665 } 666 667 /// Get the number of blocks. Block indices will be in the range `0 .. 668 /// (self.num_blocks() - 1)`. 669 pub fn num_blocks(&self) -> usize { 670 self.block_ranges.len() 671 } 672 673 /// The number of lowered instructions. 674 pub fn num_insts(&self) -> usize { 675 self.insts.len() 676 } 677 678 fn compute_clobbers(&self, regalloc: ®alloc2::Output) -> Vec<Writable<RealReg>> { 679 let mut clobbered = PRegSet::default(); 680 681 // All moves are included in clobbers. 682 for (_, Edit::Move { to, .. }) in ®alloc.edits { 683 if let Some(preg) = to.as_reg() { 684 clobbered.add(preg); 685 } 686 } 687 688 for (i, range) in self.operand_ranges.iter() { 689 // Skip this instruction if not "included in clobbers" as 690 // per the MachInst. (Some backends use this to implement 691 // ABI specifics; e.g., excluding calls of the same ABI as 692 // the current function from clobbers, because by 693 // definition everything clobbered by the call can be 694 // clobbered by this function without saving as well.) 695 if !self.insts[i].is_included_in_clobbers() { 696 continue; 697 } 698 699 let operands = &self.operands[range.clone()]; 700 let allocs = ®alloc.allocs[range]; 701 for (operand, alloc) in operands.iter().zip(allocs.iter()) { 702 if operand.kind() == OperandKind::Def { 703 if let Some(preg) = alloc.as_reg() { 704 clobbered.add(preg); 705 } 706 } 707 } 708 709 // Also add explicitly-clobbered registers. 710 if let Some(&inst_clobbered) = self.clobbers.get(&InsnIndex::new(i)) { 711 clobbered.union_from(inst_clobbered); 712 } 713 } 714 715 clobbered 716 .into_iter() 717 .map(|preg| Writable::from_reg(RealReg::from(preg))) 718 .collect() 719 } 720 721 /// Emit the instructions to a `MachBuffer`, containing fixed-up 722 /// code and external reloc/trap/etc. records ready for use. Takes 723 /// the regalloc results as well. 724 /// 725 /// Returns the machine code itself, and optionally metadata 726 /// and/or a disassembly, as an `EmitResult`. The `VCode` itself 727 /// is consumed by the emission process. 728 pub fn emit( 729 mut self, 730 regalloc: ®alloc2::Output, 731 want_disasm: bool, 732 flags: &settings::Flags, 733 ctrl_plane: &mut ControlPlane, 734 ) -> EmitResult 735 where 736 I: VCodeInst, 737 { 738 // To write into disasm string. 739 use core::fmt::Write; 740 741 let _tt = timing::vcode_emit(); 742 let mut buffer = MachBuffer::new(); 743 let mut bb_starts: Vec<Option<CodeOffset>> = vec![]; 744 745 // The first M MachLabels are reserved for block indices. 746 buffer.reserve_labels_for_blocks(self.num_blocks()); 747 748 // Register all allocated constants with the `MachBuffer` to ensure that 749 // any references to the constants during instructions can be handled 750 // correctly. 751 buffer.register_constants(&self.constants); 752 753 // Construct the final order we emit code in: cold blocks at the end. 754 let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![]; 755 let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![]; 756 for block in 0..self.num_blocks() { 757 let block = BlockIndex::new(block); 758 if self.block_order.is_cold(block) { 759 cold_blocks.push(block); 760 } else { 761 final_order.push(block); 762 } 763 } 764 final_order.extend(cold_blocks.clone()); 765 766 // Compute/save info we need for the prologue: clobbers and 767 // number of spillslots. 768 // 769 // We clone `abi` here because we will mutate it as we 770 // generate the prologue and set other info, but we can't 771 // mutate `VCode`. The info it usually carries prior to 772 // setting clobbers is fairly minimal so this should be 773 // relatively cheap. 774 let clobbers = self.compute_clobbers(regalloc); 775 self.abi 776 .compute_frame_layout(&self.sigs, regalloc.num_spillslots, clobbers); 777 778 // Emit blocks. 779 let mut cur_srcloc = None; 780 let mut last_offset = None; 781 let mut inst_offsets = vec![]; 782 let mut state = I::State::new(&self.abi, std::mem::take(ctrl_plane)); 783 784 let mut disasm = String::new(); 785 786 if !self.debug_value_labels.is_empty() { 787 inst_offsets.resize(self.insts.len(), NO_INST_OFFSET); 788 } 789 790 // Count edits per block ahead of time; this is needed for 791 // lookahead island emission. (We could derive it per-block 792 // with binary search in the edit list, but it's more 793 // efficient to do it in one pass here.) 794 let mut ra_edits_per_block: SmallVec<[u32; 64]> = smallvec![]; 795 let mut edit_idx = 0; 796 for block in 0..self.num_blocks() { 797 let end_inst = InsnIndex::new(self.block_ranges.get(block).end); 798 let start_edit_idx = edit_idx; 799 while edit_idx < regalloc.edits.len() && regalloc.edits[edit_idx].0.inst() < end_inst { 800 edit_idx += 1; 801 } 802 let end_edit_idx = edit_idx; 803 ra_edits_per_block.push((end_edit_idx - start_edit_idx) as u32); 804 } 805 806 let is_forward_edge_cfi_enabled = self.abi.is_forward_edge_cfi_enabled(); 807 let mut bb_padding = match flags.bb_padding_log2_minus_one() { 808 0 => Vec::new(), 809 n => vec![0; 1 << (n - 1)], 810 }; 811 let mut total_bb_padding = 0; 812 813 for (block_order_idx, &block) in final_order.iter().enumerate() { 814 trace!("emitting block {:?}", block); 815 816 // Call the new block hook for state 817 state.on_new_block(); 818 819 // Emit NOPs to align the block. 820 let new_offset = I::align_basic_block(buffer.cur_offset()); 821 while new_offset > buffer.cur_offset() { 822 // Pad with NOPs up to the aligned block offset. 823 let nop = I::gen_nop((new_offset - buffer.cur_offset()) as usize); 824 nop.emit(&mut buffer, &self.emit_info, &mut Default::default()); 825 } 826 assert_eq!(buffer.cur_offset(), new_offset); 827 828 let do_emit = |inst: &I, 829 disasm: &mut String, 830 buffer: &mut MachBuffer<I>, 831 state: &mut I::State| { 832 if want_disasm && !inst.is_args() { 833 let mut s = state.clone(); 834 writeln!(disasm, " {}", inst.pretty_print_inst(&mut s)).unwrap(); 835 } 836 inst.emit(buffer, &self.emit_info, state); 837 }; 838 839 // Is this the first block? Emit the prologue directly if so. 840 if block == self.entry { 841 trace!(" -> entry block"); 842 buffer.start_srcloc(Default::default()); 843 for inst in &self.abi.gen_prologue() { 844 do_emit(&inst, &mut disasm, &mut buffer, &mut state); 845 } 846 buffer.end_srcloc(); 847 } 848 849 // Now emit the regular block body. 850 851 buffer.bind_label(MachLabel::from_block(block), state.ctrl_plane_mut()); 852 853 if want_disasm { 854 writeln!(&mut disasm, "block{}:", block.index()).unwrap(); 855 } 856 857 if flags.machine_code_cfg_info() { 858 // Track BB starts. If we have backed up due to MachBuffer 859 // branch opts, note that the removed blocks were removed. 860 let cur_offset = buffer.cur_offset(); 861 if last_offset.is_some() && cur_offset <= last_offset.unwrap() { 862 for i in (0..bb_starts.len()).rev() { 863 if bb_starts[i].is_some() && cur_offset > bb_starts[i].unwrap() { 864 break; 865 } 866 bb_starts[i] = None; 867 } 868 } 869 bb_starts.push(Some(cur_offset)); 870 last_offset = Some(cur_offset); 871 } 872 873 if let Some(block_start) = I::gen_block_start( 874 self.block_order.is_indirect_branch_target(block), 875 is_forward_edge_cfi_enabled, 876 ) { 877 do_emit(&block_start, &mut disasm, &mut buffer, &mut state); 878 } 879 880 for inst_or_edit in regalloc.block_insts_and_edits(&self, block) { 881 match inst_or_edit { 882 InstOrEdit::Inst(iix) => { 883 if !self.debug_value_labels.is_empty() { 884 // If we need to produce debug info, 885 // record the offset of each instruction 886 // so that we can translate value-label 887 // ranges to machine-code offsets. 888 889 // Cold blocks violate monotonicity 890 // assumptions elsewhere (that 891 // instructions in inst-index order are in 892 // order in machine code), so we omit 893 // their offsets here. Value-label range 894 // generation below will skip empty ranges 895 // and ranges with to-offsets of zero. 896 if !self.block_order.is_cold(block) { 897 inst_offsets[iix.index()] = buffer.cur_offset(); 898 } 899 } 900 901 // Update the srcloc at this point in the buffer. 902 let srcloc = self.srclocs[iix.index()]; 903 if cur_srcloc != Some(srcloc) { 904 if cur_srcloc.is_some() { 905 buffer.end_srcloc(); 906 } 907 buffer.start_srcloc(srcloc); 908 cur_srcloc = Some(srcloc); 909 } 910 911 // If this is a safepoint, compute a stack map 912 // and pass it to the emit state. 913 let stack_map_disasm = if self.insts[iix.index()].is_safepoint() { 914 let mut safepoint_slots: SmallVec<[SpillSlot; 8]> = smallvec![]; 915 // Find the contiguous range of 916 // (progpoint, allocation) safepoint slot 917 // records in `regalloc.safepoint_slots` 918 // for this instruction index. 919 let safepoint_slots_start = regalloc 920 .safepoint_slots 921 .binary_search_by(|(progpoint, _alloc)| { 922 if progpoint.inst() >= iix { 923 std::cmp::Ordering::Greater 924 } else { 925 std::cmp::Ordering::Less 926 } 927 }) 928 .unwrap_err(); 929 930 for (_, alloc) in regalloc.safepoint_slots[safepoint_slots_start..] 931 .iter() 932 .take_while(|(progpoint, _)| progpoint.inst() == iix) 933 { 934 let slot = alloc.as_stack().unwrap(); 935 safepoint_slots.push(slot); 936 } 937 938 let (user_stack_map, user_stack_map_disasm) = { 939 // The `user_stack_maps` is keyed by reverse 940 // instruction index, so we must flip the 941 // index. We can't put this into a helper method 942 // due to borrowck issues because parts of 943 // `self` are borrowed mutably elsewhere in this 944 // function. 945 let index = iix.to_backwards_insn_index(self.num_insts()); 946 let user_stack_map = self.user_stack_maps.remove(&index); 947 let user_stack_map_disasm = 948 user_stack_map.as_ref().map(|m| format!(" ; {m:?}")); 949 (user_stack_map, user_stack_map_disasm) 950 }; 951 952 state.pre_safepoint(user_stack_map); 953 954 user_stack_map_disasm 955 } else { 956 None 957 }; 958 959 // If the instruction we are about to emit is 960 // a return, place an epilogue at this point 961 // (and don't emit the return; the actual 962 // epilogue will contain it). 963 if self.insts[iix.index()].is_term() == MachTerminator::Ret { 964 for inst in self.abi.gen_epilogue() { 965 do_emit(&inst, &mut disasm, &mut buffer, &mut state); 966 } 967 } else { 968 // Update the operands for this inst using the 969 // allocations from the regalloc result. 970 let mut allocs = regalloc.inst_allocs(iix).iter(); 971 self.insts[iix.index()].get_operands( 972 &mut |reg: &mut Reg, constraint, _kind, _pos| { 973 let alloc = allocs 974 .next() 975 .expect("enough allocations for all operands") 976 .as_reg() 977 .expect("only register allocations, not stack allocations") 978 .into(); 979 980 if let OperandConstraint::FixedReg(rreg) = constraint { 981 debug_assert_eq!(Reg::from(rreg), alloc); 982 } 983 *reg = alloc; 984 }, 985 ); 986 debug_assert!(allocs.next().is_none()); 987 988 // Emit the instruction! 989 do_emit( 990 &self.insts[iix.index()], 991 &mut disasm, 992 &mut buffer, 993 &mut state, 994 ); 995 if let Some(stack_map_disasm) = stack_map_disasm { 996 disasm.push_str(&stack_map_disasm); 997 disasm.push('\n'); 998 } 999 } 1000 } 1001 1002 InstOrEdit::Edit(Edit::Move { from, to }) => { 1003 // Create a move/spill/reload instruction and 1004 // immediately emit it. 1005 match (from.as_reg(), to.as_reg()) { 1006 (Some(from), Some(to)) => { 1007 // Reg-to-reg move. 1008 let from_rreg = Reg::from(from); 1009 let to_rreg = Writable::from_reg(Reg::from(to)); 1010 debug_assert_eq!(from.class(), to.class()); 1011 let ty = I::canonical_type_for_rc(from.class()); 1012 let mv = I::gen_move(to_rreg, from_rreg, ty); 1013 do_emit(&mv, &mut disasm, &mut buffer, &mut state); 1014 } 1015 (Some(from), None) => { 1016 // Spill from register to spillslot. 1017 let to = to.as_stack().unwrap(); 1018 let from_rreg = RealReg::from(from); 1019 let spill = self.abi.gen_spill(to, from_rreg); 1020 do_emit(&spill, &mut disasm, &mut buffer, &mut state); 1021 } 1022 (None, Some(to)) => { 1023 // Load from spillslot to register. 1024 let from = from.as_stack().unwrap(); 1025 let to_rreg = Writable::from_reg(RealReg::from(to)); 1026 let reload = self.abi.gen_reload(to_rreg, from); 1027 do_emit(&reload, &mut disasm, &mut buffer, &mut state); 1028 } 1029 (None, None) => { 1030 panic!("regalloc2 should have eliminated stack-to-stack moves!"); 1031 } 1032 } 1033 } 1034 } 1035 } 1036 1037 if cur_srcloc.is_some() { 1038 buffer.end_srcloc(); 1039 cur_srcloc = None; 1040 } 1041 1042 // Do we need an island? Get the worst-case size of the next BB, add 1043 // it to the optional padding behind the block, and pass this to the 1044 // `MachBuffer` to determine if an island is necessary. 1045 let worst_case_next_bb = if block_order_idx < final_order.len() - 1 { 1046 let next_block = final_order[block_order_idx + 1]; 1047 let next_block_range = self.block_ranges.get(next_block.index()); 1048 let next_block_size = next_block_range.len() as u32; 1049 let next_block_ra_insertions = ra_edits_per_block[next_block.index()]; 1050 I::worst_case_size() * (next_block_size + next_block_ra_insertions) 1051 } else { 1052 0 1053 }; 1054 let padding = if bb_padding.is_empty() { 1055 0 1056 } else { 1057 bb_padding.len() as u32 + I::LabelUse::ALIGN - 1 1058 }; 1059 if buffer.island_needed(padding + worst_case_next_bb) { 1060 buffer.emit_island(padding + worst_case_next_bb, ctrl_plane); 1061 } 1062 1063 // Insert padding, if configured, to stress the `MachBuffer`'s 1064 // relocation and island calculations. 1065 // 1066 // Padding can get quite large during fuzzing though so place a 1067 // total cap on it where when a per-function threshold is exceeded 1068 // the padding is turned back down to zero. This avoids a small-ish 1069 // test case generating a GB+ memory footprint in Cranelift for 1070 // example. 1071 if !bb_padding.is_empty() { 1072 buffer.put_data(&bb_padding); 1073 buffer.align_to(I::LabelUse::ALIGN); 1074 total_bb_padding += bb_padding.len(); 1075 if total_bb_padding > (150 << 20) { 1076 bb_padding = Vec::new(); 1077 } 1078 } 1079 } 1080 1081 debug_assert!( 1082 self.user_stack_maps.is_empty(), 1083 "any stack maps should have been consumed by instruction emission, still have: {:#?}", 1084 self.user_stack_maps, 1085 ); 1086 1087 // Do any optimizations on branches at tail of buffer, as if we had 1088 // bound one last label. 1089 buffer.optimize_branches(ctrl_plane); 1090 1091 // emission state is not needed anymore, move control plane back out 1092 *ctrl_plane = state.take_ctrl_plane(); 1093 1094 let func_body_len = buffer.cur_offset(); 1095 1096 // Create `bb_edges` and final (filtered) `bb_starts`. 1097 let mut bb_edges = vec![]; 1098 let mut bb_offsets = vec![]; 1099 if flags.machine_code_cfg_info() { 1100 for block in 0..self.num_blocks() { 1101 if bb_starts[block].is_none() { 1102 // Block was deleted by MachBuffer; skip. 1103 continue; 1104 } 1105 let from = bb_starts[block].unwrap(); 1106 1107 bb_offsets.push(from); 1108 // Resolve each `succ` label and add edges. 1109 let succs = self.block_succs(BlockIndex::new(block)); 1110 for &succ in succs.iter() { 1111 let to = buffer.resolve_label_offset(MachLabel::from_block(succ)); 1112 bb_edges.push((from, to)); 1113 } 1114 } 1115 } 1116 1117 self.monotonize_inst_offsets(&mut inst_offsets[..], func_body_len); 1118 let value_labels_ranges = 1119 self.compute_value_labels_ranges(regalloc, &inst_offsets[..], func_body_len); 1120 let frame_size = self.abi.frame_size(); 1121 1122 EmitResult { 1123 buffer: buffer.finish(&self.constants, ctrl_plane), 1124 bb_offsets, 1125 bb_edges, 1126 func_body_len, 1127 disasm: if want_disasm { Some(disasm) } else { None }, 1128 sized_stackslot_offsets: self.abi.sized_stackslot_offsets().clone(), 1129 dynamic_stackslot_offsets: self.abi.dynamic_stackslot_offsets().clone(), 1130 value_labels_ranges, 1131 frame_size, 1132 } 1133 } 1134 1135 fn monotonize_inst_offsets(&self, inst_offsets: &mut [CodeOffset], func_body_len: u32) { 1136 if self.debug_value_labels.is_empty() { 1137 return; 1138 } 1139 1140 // During emission, branch removal can make offsets of instructions incorrect. 1141 // Consider the following sequence: [insi][jmp0][jmp1][jmp2][insj] 1142 // It will be recorded as (say): [30] [34] [38] [42] [<would be 46>] 1143 // When the jumps get removed we are left with (in "inst_offsets"): 1144 // [insi][jmp0][jmp1][jmp2][insj][...] 1145 // [30] [34] [38] [42] [34] 1146 // Which violates the monotonicity invariant. This method sets offsets of these 1147 // removed instructions such as to make them appear zero-sized: 1148 // [insi][jmp0][jmp1][jmp2][insj][...] 1149 // [30] [34] [34] [34] [34] 1150 // 1151 let mut next_offset = func_body_len; 1152 for inst_index in (0..(inst_offsets.len() - 1)).rev() { 1153 let inst_offset = inst_offsets[inst_index]; 1154 1155 // Not all instructions get their offsets recorded. 1156 if inst_offset == NO_INST_OFFSET { 1157 continue; 1158 } 1159 1160 if inst_offset > next_offset { 1161 trace!( 1162 "Fixing code offset of the removed Inst {}: {} -> {}", 1163 inst_index, 1164 inst_offset, 1165 next_offset 1166 ); 1167 inst_offsets[inst_index] = next_offset; 1168 continue; 1169 } 1170 1171 next_offset = inst_offset; 1172 } 1173 } 1174 1175 fn compute_value_labels_ranges( 1176 &self, 1177 regalloc: ®alloc2::Output, 1178 inst_offsets: &[CodeOffset], 1179 func_body_len: u32, 1180 ) -> ValueLabelsRanges { 1181 if self.debug_value_labels.is_empty() { 1182 return ValueLabelsRanges::default(); 1183 } 1184 1185 let mut value_labels_ranges: ValueLabelsRanges = HashMap::new(); 1186 for &(label, from, to, alloc) in ®alloc.debug_locations { 1187 let ranges = value_labels_ranges 1188 .entry(ValueLabel::from_u32(label)) 1189 .or_insert_with(|| vec![]); 1190 let from_offset = inst_offsets[from.inst().index()]; 1191 let to_offset = if to.inst().index() == inst_offsets.len() { 1192 func_body_len 1193 } else { 1194 inst_offsets[to.inst().index()] 1195 }; 1196 1197 // Empty ranges or unavailable offsets can happen 1198 // due to cold blocks and branch removal (see above). 1199 if from_offset == NO_INST_OFFSET 1200 || to_offset == NO_INST_OFFSET 1201 || from_offset == to_offset 1202 { 1203 continue; 1204 } 1205 1206 let loc = if let Some(preg) = alloc.as_reg() { 1207 LabelValueLoc::Reg(Reg::from(preg)) 1208 } else { 1209 let slot = alloc.as_stack().unwrap(); 1210 let slot_offset = self.abi.get_spillslot_offset(slot); 1211 let slot_base_to_caller_sp_offset = self.abi.slot_base_to_caller_sp_offset(); 1212 let caller_sp_to_cfa_offset = 1213 crate::isa::unwind::systemv::caller_sp_to_cfa_offset(); 1214 // NOTE: this is a negative offset because it's relative to the caller's SP 1215 let cfa_to_sp_offset = 1216 -((slot_base_to_caller_sp_offset + caller_sp_to_cfa_offset) as i64); 1217 LabelValueLoc::CFAOffset(cfa_to_sp_offset + slot_offset) 1218 }; 1219 1220 // ValueLocRanges are recorded by *instruction-end 1221 // offset*. `from_offset` is the *start* of the 1222 // instruction; that is the same as the end of another 1223 // instruction, so we only want to begin coverage once 1224 // we are past the previous instruction's end. 1225 let start = from_offset + 1; 1226 1227 // Likewise, `end` is exclusive, but we want to 1228 // *include* the end of the last 1229 // instruction. `to_offset` is the start of the 1230 // `to`-instruction, which is the exclusive end, i.e., 1231 // the first instruction not covered. That 1232 // instruction's start is the same as the end of the 1233 // last instruction that is included, so we go one 1234 // byte further to be sure to include it. 1235 let end = to_offset + 1; 1236 1237 // Coalesce adjacent ranges that for the same location 1238 // to minimize output size here and for the consumers. 1239 if let Some(last_loc_range) = ranges.last_mut() { 1240 if last_loc_range.loc == loc && last_loc_range.end == start { 1241 trace!( 1242 "Extending debug range for VL{} in {:?} to {}", 1243 label, 1244 loc, 1245 end 1246 ); 1247 last_loc_range.end = end; 1248 continue; 1249 } 1250 } 1251 1252 trace!( 1253 "Recording debug range for VL{} in {:?}: [Inst {}..Inst {}) [{}..{})", 1254 label, 1255 loc, 1256 from.inst().index(), 1257 to.inst().index(), 1258 start, 1259 end 1260 ); 1261 1262 ranges.push(ValueLocRange { loc, start, end }); 1263 } 1264 1265 value_labels_ranges 1266 } 1267 1268 /// Get the IR block for a BlockIndex, if one exists. 1269 pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> { 1270 self.block_order.lowered_order()[block.index()].orig_block() 1271 } 1272 1273 /// Get the type of a VReg. 1274 pub fn vreg_type(&self, vreg: VReg) -> Type { 1275 self.vreg_types[vreg.vreg()] 1276 } 1277 1278 /// Get the fact, if any, for a given VReg. 1279 pub fn vreg_fact(&self, vreg: VReg) -> Option<&Fact> { 1280 self.facts[vreg.vreg()].as_ref() 1281 } 1282 1283 /// Set the fact for a given VReg. 1284 pub fn set_vreg_fact(&mut self, vreg: VReg, fact: Fact) { 1285 trace!("set fact on {}: {:?}", vreg, fact); 1286 self.facts[vreg.vreg()] = Some(fact); 1287 } 1288 1289 /// Does a given instruction define any facts? 1290 pub fn inst_defines_facts(&self, inst: InsnIndex) -> bool { 1291 self.inst_operands(inst) 1292 .iter() 1293 .filter(|o| o.kind() == OperandKind::Def) 1294 .map(|o| o.vreg()) 1295 .any(|vreg| self.facts[vreg.vreg()].is_some()) 1296 } 1297 1298 /// Get the user stack map associated with the given forward instruction index. 1299 pub fn get_user_stack_map(&self, inst: InsnIndex) -> Option<&ir::UserStackMap> { 1300 let index = inst.to_backwards_insn_index(self.num_insts()); 1301 self.user_stack_maps.get(&index) 1302 } 1303 } 1304 1305 impl<I: VCodeInst> std::ops::Index<InsnIndex> for VCode<I> { 1306 type Output = I; 1307 fn index(&self, idx: InsnIndex) -> &Self::Output { 1308 &self.insts[idx.index()] 1309 } 1310 } 1311 1312 impl<I: VCodeInst> RegallocFunction for VCode<I> { 1313 fn num_insts(&self) -> usize { 1314 self.insts.len() 1315 } 1316 1317 fn num_blocks(&self) -> usize { 1318 self.block_ranges.len() 1319 } 1320 1321 fn entry_block(&self) -> BlockIndex { 1322 self.entry 1323 } 1324 1325 fn block_insns(&self, block: BlockIndex) -> InstRange { 1326 let range = self.block_ranges.get(block.index()); 1327 InstRange::forward(InsnIndex::new(range.start), InsnIndex::new(range.end)) 1328 } 1329 1330 fn block_succs(&self, block: BlockIndex) -> &[BlockIndex] { 1331 let range = self.block_succ_range.get(block.index()); 1332 &self.block_succs[range] 1333 } 1334 1335 fn block_preds(&self, block: BlockIndex) -> &[BlockIndex] { 1336 let range = self.block_pred_range.get(block.index()); 1337 &self.block_preds[range] 1338 } 1339 1340 fn block_params(&self, block: BlockIndex) -> &[VReg] { 1341 // As a special case we don't return block params for the entry block, as all the arguments 1342 // will be defined by the `Inst::Args` instruction. 1343 if block == self.entry { 1344 return &[]; 1345 } 1346 1347 let range = self.block_params_range.get(block.index()); 1348 &self.block_params[range] 1349 } 1350 1351 fn branch_blockparams(&self, block: BlockIndex, _insn: InsnIndex, succ_idx: usize) -> &[VReg] { 1352 let succ_range = self.branch_block_arg_succ_range.get(block.index()); 1353 debug_assert!(succ_idx < succ_range.len()); 1354 let branch_block_args = self.branch_block_arg_range.get(succ_range.start + succ_idx); 1355 &self.branch_block_args[branch_block_args] 1356 } 1357 1358 fn is_ret(&self, insn: InsnIndex) -> bool { 1359 match self.insts[insn.index()].is_term() { 1360 // We treat blocks terminated by an unconditional trap like a return for regalloc. 1361 MachTerminator::None => self.insts[insn.index()].is_trap(), 1362 MachTerminator::Ret | MachTerminator::RetCall => true, 1363 MachTerminator::Uncond | MachTerminator::Cond | MachTerminator::Indirect => false, 1364 } 1365 } 1366 1367 fn is_branch(&self, insn: InsnIndex) -> bool { 1368 match self.insts[insn.index()].is_term() { 1369 MachTerminator::Cond | MachTerminator::Uncond | MachTerminator::Indirect => true, 1370 _ => false, 1371 } 1372 } 1373 1374 fn requires_refs_on_stack(&self, insn: InsnIndex) -> bool { 1375 self.insts[insn.index()].is_safepoint() 1376 } 1377 1378 fn inst_operands(&self, insn: InsnIndex) -> &[Operand] { 1379 let range = self.operand_ranges.get(insn.index()); 1380 &self.operands[range] 1381 } 1382 1383 fn inst_clobbers(&self, insn: InsnIndex) -> PRegSet { 1384 self.clobbers.get(&insn).cloned().unwrap_or_default() 1385 } 1386 1387 fn num_vregs(&self) -> usize { 1388 self.vreg_types.len() 1389 } 1390 1391 fn reftype_vregs(&self) -> &[VReg] { 1392 &self.reftyped_vregs 1393 } 1394 1395 fn debug_value_labels(&self) -> &[(VReg, InsnIndex, InsnIndex, u32)] { 1396 &self.debug_value_labels 1397 } 1398 1399 fn spillslot_size(&self, regclass: RegClass) -> usize { 1400 self.abi.get_spillslot_size(regclass) as usize 1401 } 1402 1403 fn allow_multiple_vreg_defs(&self) -> bool { 1404 // At least the s390x backend requires this, because the 1405 // `Loop` pseudo-instruction aggregates all Operands so pinned 1406 // vregs (RealRegs) may occur more than once. 1407 true 1408 } 1409 } 1410 1411 impl<I: VCodeInst> Debug for VRegAllocator<I> { 1412 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1413 writeln!(f, "VRegAllocator {{")?; 1414 1415 let mut alias_keys = self.vreg_aliases.keys().cloned().collect::<Vec<_>>(); 1416 alias_keys.sort_unstable(); 1417 for key in alias_keys { 1418 let dest = self.vreg_aliases.get(&key).unwrap(); 1419 writeln!(f, " {:?} := {:?}", Reg::from(key), Reg::from(*dest))?; 1420 } 1421 1422 for (vreg, fact) in self.facts.iter().enumerate() { 1423 if let Some(fact) = fact { 1424 writeln!(f, " v{vreg} ! {fact}")?; 1425 } 1426 } 1427 1428 writeln!(f, "}}") 1429 } 1430 } 1431 1432 impl<I: VCodeInst> fmt::Debug for VCode<I> { 1433 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1434 writeln!(f, "VCode {{")?; 1435 writeln!(f, " Entry block: {}", self.entry.index())?; 1436 1437 let mut state = Default::default(); 1438 1439 for block in 0..self.num_blocks() { 1440 let block = BlockIndex::new(block); 1441 writeln!( 1442 f, 1443 "Block {}({:?}):", 1444 block.index(), 1445 self.block_params(block) 1446 )?; 1447 if let Some(bb) = self.bindex_to_bb(block) { 1448 writeln!(f, " (original IR block: {bb})")?; 1449 } 1450 for (succ_idx, succ) in self.block_succs(block).iter().enumerate() { 1451 writeln!( 1452 f, 1453 " (successor: Block {}({:?}))", 1454 succ.index(), 1455 self.branch_blockparams(block, InsnIndex::new(0) /* dummy */, succ_idx) 1456 )?; 1457 } 1458 for inst in self.block_ranges.get(block.index()) { 1459 writeln!( 1460 f, 1461 " Inst {}: {}", 1462 inst, 1463 self.insts[inst].pretty_print_inst(&mut state) 1464 )?; 1465 if !self.operands.is_empty() { 1466 for operand in self.inst_operands(InsnIndex::new(inst)) { 1467 if operand.kind() == OperandKind::Def { 1468 if let Some(fact) = &self.facts[operand.vreg().vreg()] { 1469 writeln!(f, " v{} ! {}", operand.vreg().vreg(), fact)?; 1470 } 1471 } 1472 } 1473 } 1474 if let Some(user_stack_map) = self.get_user_stack_map(InsnIndex::new(inst)) { 1475 writeln!(f, " {user_stack_map:?}")?; 1476 } 1477 } 1478 } 1479 1480 writeln!(f, "}}")?; 1481 Ok(()) 1482 } 1483 } 1484 1485 /// This structure manages VReg allocation during the lifetime of the VCodeBuilder. 1486 pub struct VRegAllocator<I> { 1487 /// VReg IR-level types. 1488 vreg_types: Vec<Type>, 1489 1490 /// Reference-typed `regalloc2::VReg`s. The regalloc requires 1491 /// these in a dense slice (as opposed to querying the 1492 /// reftype-status of each vreg) for efficient iteration. 1493 reftyped_vregs: Vec<VReg>, 1494 1495 /// VReg aliases. When the final VCode is built we rewrite all 1496 /// uses of the keys in this table to their replacement values. 1497 /// 1498 /// We use these aliases to rename an instruction's expected 1499 /// result vregs to the returned vregs from lowering, which are 1500 /// usually freshly-allocated temps. 1501 vreg_aliases: FxHashMap<regalloc2::VReg, regalloc2::VReg>, 1502 1503 /// A deferred error, to be bubbled up to the top level of the 1504 /// lowering algorithm. We take this approach because we cannot 1505 /// currently propagate a `Result` upward through ISLE code (the 1506 /// lowering rules) or some ABI code. 1507 deferred_error: Option<CodegenError>, 1508 1509 /// Facts on VRegs, for proof-carrying code. 1510 facts: Vec<Option<Fact>>, 1511 1512 /// The type of instruction that this allocator makes registers for. 1513 _inst: core::marker::PhantomData<I>, 1514 } 1515 1516 impl<I: VCodeInst> VRegAllocator<I> { 1517 /// Make a new VRegAllocator. 1518 pub fn with_capacity(capacity: usize) -> Self { 1519 let capacity = first_user_vreg_index() + capacity; 1520 let mut vreg_types = Vec::with_capacity(capacity); 1521 vreg_types.resize(first_user_vreg_index(), types::INVALID); 1522 Self { 1523 vreg_types, 1524 reftyped_vregs: vec![], 1525 vreg_aliases: FxHashMap::with_capacity_and_hasher(capacity, Default::default()), 1526 deferred_error: None, 1527 facts: Vec::with_capacity(capacity), 1528 _inst: core::marker::PhantomData::default(), 1529 } 1530 } 1531 1532 /// Allocate a fresh ValueRegs. 1533 pub fn alloc(&mut self, ty: Type) -> CodegenResult<ValueRegs<Reg>> { 1534 if self.deferred_error.is_some() { 1535 return Err(CodegenError::CodeTooLarge); 1536 } 1537 let v = self.vreg_types.len(); 1538 let (regclasses, tys) = I::rc_for_type(ty)?; 1539 if v + regclasses.len() >= VReg::MAX { 1540 return Err(CodegenError::CodeTooLarge); 1541 } 1542 1543 let regs: ValueRegs<Reg> = match regclasses { 1544 &[rc0] => ValueRegs::one(VReg::new(v, rc0).into()), 1545 &[rc0, rc1] => ValueRegs::two(VReg::new(v, rc0).into(), VReg::new(v + 1, rc1).into()), 1546 // We can extend this if/when we support 32-bit targets; e.g., 1547 // an i128 on a 32-bit machine will need up to four machine regs 1548 // for a `Value`. 1549 _ => panic!("Value must reside in 1 or 2 registers"), 1550 }; 1551 for (®_ty, ®) in tys.iter().zip(regs.regs().iter()) { 1552 let vreg = reg.to_virtual_reg().unwrap(); 1553 debug_assert_eq!(self.vreg_types.len(), vreg.index()); 1554 self.vreg_types.push(reg_ty); 1555 if is_reftype(reg_ty) { 1556 self.reftyped_vregs.push(vreg.into()); 1557 } 1558 } 1559 1560 // Create empty facts for each allocated vreg. 1561 self.facts.resize(self.vreg_types.len(), None); 1562 1563 Ok(regs) 1564 } 1565 1566 /// Allocate a fresh ValueRegs, deferring any out-of-vregs 1567 /// errors. This is useful in places where we cannot bubble a 1568 /// `CodegenResult` upward easily, and which are known to be 1569 /// invoked from within the lowering loop that checks the deferred 1570 /// error status below. 1571 pub fn alloc_with_deferred_error(&mut self, ty: Type) -> ValueRegs<Reg> { 1572 match self.alloc(ty) { 1573 Ok(x) => x, 1574 Err(e) => { 1575 self.deferred_error = Some(e); 1576 self.bogus_for_deferred_error(ty) 1577 } 1578 } 1579 } 1580 1581 /// Take any deferred error that was accumulated by `alloc_with_deferred_error`. 1582 pub fn take_deferred_error(&mut self) -> Option<CodegenError> { 1583 self.deferred_error.take() 1584 } 1585 1586 /// Produce an bogus VReg placeholder with the proper number of 1587 /// registers for the given type. This is meant to be used with 1588 /// deferred allocation errors (see `Lower::alloc_tmp()`). 1589 fn bogus_for_deferred_error(&self, ty: Type) -> ValueRegs<Reg> { 1590 let (regclasses, _tys) = I::rc_for_type(ty).expect("must have valid type"); 1591 match regclasses { 1592 &[rc0] => ValueRegs::one(VReg::new(0, rc0).into()), 1593 &[rc0, rc1] => ValueRegs::two(VReg::new(0, rc0).into(), VReg::new(1, rc1).into()), 1594 _ => panic!("Value must reside in 1 or 2 registers"), 1595 } 1596 } 1597 1598 /// Rewrite any mention of `from` into `to`. 1599 pub fn set_vreg_alias(&mut self, from: Reg, to: Reg) { 1600 let from = from.into(); 1601 let resolved_to = self.resolve_vreg_alias(to.into()); 1602 // Disallow cycles (see below). 1603 assert_ne!(resolved_to, from); 1604 1605 // Maintain the invariant that PCC facts only exist on vregs 1606 // which aren't aliases. We want to preserve whatever was 1607 // stated about the vreg before its producer was lowered. 1608 if let Some(fact) = self.facts[from.vreg()].take() { 1609 self.set_fact(resolved_to, fact); 1610 } 1611 1612 let old_alias = self.vreg_aliases.insert(from, resolved_to); 1613 debug_assert_eq!(old_alias, None); 1614 } 1615 1616 fn resolve_vreg_alias(&self, mut vreg: regalloc2::VReg) -> regalloc2::VReg { 1617 // We prevent cycles from existing by resolving targets of 1618 // aliases eagerly before setting them. If the target resolves 1619 // to the origin of the alias, then a cycle would be created 1620 // and the alias is disallowed. Because of the structure of 1621 // SSA code (one instruction can refer to another's defs but 1622 // not vice-versa, except indirectly through 1623 // phis/blockparams), cycles should not occur as we use 1624 // aliases to redirect vregs to the temps that actually define 1625 // them. 1626 while let Some(to) = self.vreg_aliases.get(&vreg) { 1627 vreg = *to; 1628 } 1629 vreg 1630 } 1631 1632 #[inline] 1633 fn debug_assert_no_vreg_aliases(&self, mut list: impl Iterator<Item = VReg>) { 1634 debug_assert!(list.all(|vreg| !self.vreg_aliases.contains_key(&vreg))); 1635 } 1636 1637 /// Set the proof-carrying code fact on a given virtual register. 1638 /// 1639 /// Returns the old fact, if any (only one fact can be stored). 1640 fn set_fact(&mut self, vreg: regalloc2::VReg, fact: Fact) -> Option<Fact> { 1641 trace!("vreg {:?} has fact: {:?}", vreg, fact); 1642 debug_assert!(!self.vreg_aliases.contains_key(&vreg)); 1643 self.facts[vreg.vreg()].replace(fact) 1644 } 1645 1646 /// Set a fact only if one doesn't already exist. 1647 pub fn set_fact_if_missing(&mut self, vreg: VirtualReg, fact: Fact) { 1648 let vreg = self.resolve_vreg_alias(vreg.into()); 1649 if self.facts[vreg.vreg()].is_none() { 1650 self.set_fact(vreg, fact); 1651 } 1652 } 1653 1654 /// Allocate a fresh ValueRegs, with a given fact to apply if 1655 /// the value fits in one VReg. 1656 pub fn alloc_with_maybe_fact( 1657 &mut self, 1658 ty: Type, 1659 fact: Option<Fact>, 1660 ) -> CodegenResult<ValueRegs<Reg>> { 1661 let result = self.alloc(ty)?; 1662 1663 // Ensure that we don't lose a fact on a value that splits 1664 // into multiple VRegs. 1665 assert!(result.len() == 1 || fact.is_none()); 1666 if let Some(fact) = fact { 1667 self.set_fact(result.regs()[0].into(), fact); 1668 } 1669 1670 Ok(result) 1671 } 1672 } 1673 1674 /// This structure tracks the large constants used in VCode that will be emitted separately by the 1675 /// [MachBuffer]. 1676 /// 1677 /// First, during the lowering phase, constants are inserted using 1678 /// [VCodeConstants.insert]; an intermediate handle, `VCodeConstant`, tracks what constants are 1679 /// used in this phase. Some deduplication is performed, when possible, as constant 1680 /// values are inserted. 1681 /// 1682 /// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the 1683 /// constants so that instructions can refer to the value's memory location. The [MachBuffer] 1684 /// then writes the constant values to the buffer. 1685 #[derive(Default)] 1686 pub struct VCodeConstants { 1687 constants: PrimaryMap<VCodeConstant, VCodeConstantData>, 1688 pool_uses: HashMap<Constant, VCodeConstant>, 1689 well_known_uses: HashMap<*const [u8], VCodeConstant>, 1690 u64s: HashMap<[u8; 8], VCodeConstant>, 1691 } 1692 impl VCodeConstants { 1693 /// Initialize the structure with the expected number of constants. 1694 pub fn with_capacity(expected_num_constants: usize) -> Self { 1695 Self { 1696 constants: PrimaryMap::with_capacity(expected_num_constants), 1697 pool_uses: HashMap::with_capacity(expected_num_constants), 1698 well_known_uses: HashMap::new(), 1699 u64s: HashMap::new(), 1700 } 1701 } 1702 1703 /// Insert a constant; using this method indicates that a constant value will be used and thus 1704 /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants 1705 /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not 1706 /// [VCodeConstantData::Generated]. 1707 pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant { 1708 match data { 1709 VCodeConstantData::Generated(_) => self.constants.push(data), 1710 VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) { 1711 None => { 1712 let vcode_constant = self.constants.push(data); 1713 self.pool_uses.insert(constant, vcode_constant); 1714 vcode_constant 1715 } 1716 Some(&vcode_constant) => vcode_constant, 1717 }, 1718 VCodeConstantData::WellKnown(data_ref) => { 1719 match self.well_known_uses.entry(data_ref as *const [u8]) { 1720 Entry::Vacant(v) => { 1721 let vcode_constant = self.constants.push(data); 1722 v.insert(vcode_constant); 1723 vcode_constant 1724 } 1725 Entry::Occupied(o) => *o.get(), 1726 } 1727 } 1728 VCodeConstantData::U64(value) => match self.u64s.entry(value) { 1729 Entry::Vacant(v) => { 1730 let vcode_constant = self.constants.push(data); 1731 v.insert(vcode_constant); 1732 vcode_constant 1733 } 1734 Entry::Occupied(o) => *o.get(), 1735 }, 1736 } 1737 } 1738 1739 /// Return the number of constants inserted. 1740 pub fn len(&self) -> usize { 1741 self.constants.len() 1742 } 1743 1744 /// Iterate over the `VCodeConstant` keys inserted in this structure. 1745 pub fn keys(&self) -> Keys<VCodeConstant> { 1746 self.constants.keys() 1747 } 1748 1749 /// Iterate over the `VCodeConstant` keys and the data (as a byte slice) inserted in this 1750 /// structure. 1751 pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> { 1752 self.constants.iter() 1753 } 1754 1755 /// Returns the data associated with the specified constant. 1756 pub fn get(&self, c: VCodeConstant) -> &VCodeConstantData { 1757 &self.constants[c] 1758 } 1759 1760 /// Checks if the given [VCodeConstantData] is registered as 1761 /// used by the pool. 1762 pub fn pool_uses(&self, constant: &VCodeConstantData) -> bool { 1763 match constant { 1764 VCodeConstantData::Pool(c, _) => self.pool_uses.contains_key(c), 1765 _ => false, 1766 } 1767 } 1768 } 1769 1770 /// A use of a constant by one or more VCode instructions; see [VCodeConstants]. 1771 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 1772 pub struct VCodeConstant(u32); 1773 entity_impl!(VCodeConstant); 1774 1775 /// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking 1776 /// these separately instead of as raw byte buffers allows us to avoid some duplication. 1777 pub enum VCodeConstantData { 1778 /// A constant already present in the Cranelift IR 1779 /// [ConstantPool](crate::ir::constant::ConstantPool). 1780 Pool(Constant, ConstantData), 1781 /// A reference to a well-known constant value that is statically encoded within the compiler. 1782 WellKnown(&'static [u8]), 1783 /// A constant value generated during lowering; the value may depend on the instruction context 1784 /// which makes it difficult to de-duplicate--if possible, use other variants. 1785 Generated(ConstantData), 1786 /// A constant of at most 64 bits. These are deduplicated as 1787 /// well. Stored as a fixed-size array of `u8` so that we do not 1788 /// encounter endianness problems when cross-compiling. 1789 U64([u8; 8]), 1790 } 1791 impl VCodeConstantData { 1792 /// Retrieve the constant data as a byte slice. 1793 pub fn as_slice(&self) -> &[u8] { 1794 match self { 1795 VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(), 1796 VCodeConstantData::WellKnown(d) => d, 1797 VCodeConstantData::U64(value) => &value[..], 1798 } 1799 } 1800 1801 /// Calculate the alignment of the constant data. 1802 pub fn alignment(&self) -> u32 { 1803 if self.as_slice().len() <= 8 { 1804 8 1805 } else { 1806 16 1807 } 1808 } 1809 } 1810 1811 #[cfg(test)] 1812 mod test { 1813 use super::*; 1814 use std::mem::size_of; 1815 1816 #[test] 1817 fn size_of_constant_structs() { 1818 assert_eq!(size_of::<Constant>(), 4); 1819 assert_eq!(size_of::<VCodeConstant>(), 4); 1820 assert_eq!(size_of::<ConstantData>(), 24); 1821 assert_eq!(size_of::<VCodeConstantData>(), 32); 1822 assert_eq!( 1823 size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(), 1824 24 1825 ); 1826 // TODO The VCodeConstants structure's memory size could be further optimized. 1827 // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at 1828 // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes. 1829 } 1830 } 1831