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 stack_map = if safepoint_slots.is_empty() { 939 None 940 } else { 941 Some( 942 self.abi 943 .spillslots_to_stack_map(&safepoint_slots[..], &state), 944 ) 945 }; 946 947 let (user_stack_map, user_stack_map_disasm) = { 948 // The `user_stack_maps` is keyed by reverse 949 // instruction index, so we must flip the 950 // index. We can't put this into a helper method 951 // due to borrowck issues because parts of 952 // `self` are borrowed mutably elsewhere in this 953 // function. 954 let index = iix.to_backwards_insn_index(self.num_insts()); 955 let user_stack_map = self.user_stack_maps.remove(&index); 956 let user_stack_map_disasm = 957 user_stack_map.as_ref().map(|m| format!(" ; {m:?}")); 958 (user_stack_map, user_stack_map_disasm) 959 }; 960 961 state.pre_safepoint(stack_map, user_stack_map); 962 963 user_stack_map_disasm 964 } else { 965 None 966 }; 967 968 // If the instruction we are about to emit is 969 // a return, place an epilogue at this point 970 // (and don't emit the return; the actual 971 // epilogue will contain it). 972 if self.insts[iix.index()].is_term() == MachTerminator::Ret { 973 for inst in self.abi.gen_epilogue() { 974 do_emit(&inst, &mut disasm, &mut buffer, &mut state); 975 } 976 } else { 977 // Update the operands for this inst using the 978 // allocations from the regalloc result. 979 let mut allocs = regalloc.inst_allocs(iix).iter(); 980 self.insts[iix.index()].get_operands( 981 &mut |reg: &mut Reg, constraint, _kind, _pos| { 982 let alloc = allocs 983 .next() 984 .expect("enough allocations for all operands") 985 .as_reg() 986 .expect("only register allocations, not stack allocations") 987 .into(); 988 989 if let OperandConstraint::FixedReg(rreg) = constraint { 990 debug_assert_eq!(Reg::from(rreg), alloc); 991 } 992 *reg = alloc; 993 }, 994 ); 995 debug_assert!(allocs.next().is_none()); 996 997 // Emit the instruction! 998 do_emit( 999 &self.insts[iix.index()], 1000 &mut disasm, 1001 &mut buffer, 1002 &mut state, 1003 ); 1004 if let Some(stack_map_disasm) = stack_map_disasm { 1005 disasm.push_str(&stack_map_disasm); 1006 disasm.push('\n'); 1007 } 1008 } 1009 } 1010 1011 InstOrEdit::Edit(Edit::Move { from, to }) => { 1012 // Create a move/spill/reload instruction and 1013 // immediately emit it. 1014 match (from.as_reg(), to.as_reg()) { 1015 (Some(from), Some(to)) => { 1016 // Reg-to-reg move. 1017 let from_rreg = Reg::from(from); 1018 let to_rreg = Writable::from_reg(Reg::from(to)); 1019 debug_assert_eq!(from.class(), to.class()); 1020 let ty = I::canonical_type_for_rc(from.class()); 1021 let mv = I::gen_move(to_rreg, from_rreg, ty); 1022 do_emit(&mv, &mut disasm, &mut buffer, &mut state); 1023 } 1024 (Some(from), None) => { 1025 // Spill from register to spillslot. 1026 let to = to.as_stack().unwrap(); 1027 let from_rreg = RealReg::from(from); 1028 let spill = self.abi.gen_spill(to, from_rreg); 1029 do_emit(&spill, &mut disasm, &mut buffer, &mut state); 1030 } 1031 (None, Some(to)) => { 1032 // Load from spillslot to register. 1033 let from = from.as_stack().unwrap(); 1034 let to_rreg = Writable::from_reg(RealReg::from(to)); 1035 let reload = self.abi.gen_reload(to_rreg, from); 1036 do_emit(&reload, &mut disasm, &mut buffer, &mut state); 1037 } 1038 (None, None) => { 1039 panic!("regalloc2 should have eliminated stack-to-stack moves!"); 1040 } 1041 } 1042 } 1043 } 1044 } 1045 1046 if cur_srcloc.is_some() { 1047 buffer.end_srcloc(); 1048 cur_srcloc = None; 1049 } 1050 1051 // Do we need an island? Get the worst-case size of the next BB, add 1052 // it to the optional padding behind the block, and pass this to the 1053 // `MachBuffer` to determine if an island is necessary. 1054 let worst_case_next_bb = if block_order_idx < final_order.len() - 1 { 1055 let next_block = final_order[block_order_idx + 1]; 1056 let next_block_range = self.block_ranges.get(next_block.index()); 1057 let next_block_size = next_block_range.len() as u32; 1058 let next_block_ra_insertions = ra_edits_per_block[next_block.index()]; 1059 I::worst_case_size() * (next_block_size + next_block_ra_insertions) 1060 } else { 1061 0 1062 }; 1063 let padding = if bb_padding.is_empty() { 1064 0 1065 } else { 1066 bb_padding.len() as u32 + I::LabelUse::ALIGN - 1 1067 }; 1068 if buffer.island_needed(padding + worst_case_next_bb) { 1069 buffer.emit_island(padding + worst_case_next_bb, ctrl_plane); 1070 } 1071 1072 // Insert padding, if configured, to stress the `MachBuffer`'s 1073 // relocation and island calculations. 1074 // 1075 // Padding can get quite large during fuzzing though so place a 1076 // total cap on it where when a per-function threshold is exceeded 1077 // the padding is turned back down to zero. This avoids a small-ish 1078 // test case generating a GB+ memory footprint in Cranelift for 1079 // example. 1080 if !bb_padding.is_empty() { 1081 buffer.put_data(&bb_padding); 1082 buffer.align_to(I::LabelUse::ALIGN); 1083 total_bb_padding += bb_padding.len(); 1084 if total_bb_padding > (150 << 20) { 1085 bb_padding = Vec::new(); 1086 } 1087 } 1088 } 1089 1090 debug_assert!( 1091 self.user_stack_maps.is_empty(), 1092 "any stack maps should have been consumed by instruction emission, still have: {:#?}", 1093 self.user_stack_maps, 1094 ); 1095 1096 // Do any optimizations on branches at tail of buffer, as if we had 1097 // bound one last label. 1098 buffer.optimize_branches(ctrl_plane); 1099 1100 // emission state is not needed anymore, move control plane back out 1101 *ctrl_plane = state.take_ctrl_plane(); 1102 1103 let func_body_len = buffer.cur_offset(); 1104 1105 // Create `bb_edges` and final (filtered) `bb_starts`. 1106 let mut bb_edges = vec![]; 1107 let mut bb_offsets = vec![]; 1108 if flags.machine_code_cfg_info() { 1109 for block in 0..self.num_blocks() { 1110 if bb_starts[block].is_none() { 1111 // Block was deleted by MachBuffer; skip. 1112 continue; 1113 } 1114 let from = bb_starts[block].unwrap(); 1115 1116 bb_offsets.push(from); 1117 // Resolve each `succ` label and add edges. 1118 let succs = self.block_succs(BlockIndex::new(block)); 1119 for &succ in succs.iter() { 1120 let to = buffer.resolve_label_offset(MachLabel::from_block(succ)); 1121 bb_edges.push((from, to)); 1122 } 1123 } 1124 } 1125 1126 self.monotonize_inst_offsets(&mut inst_offsets[..], func_body_len); 1127 let value_labels_ranges = 1128 self.compute_value_labels_ranges(regalloc, &inst_offsets[..], func_body_len); 1129 let frame_size = self.abi.frame_size(); 1130 1131 EmitResult { 1132 buffer: buffer.finish(&self.constants, ctrl_plane), 1133 bb_offsets, 1134 bb_edges, 1135 func_body_len, 1136 disasm: if want_disasm { Some(disasm) } else { None }, 1137 sized_stackslot_offsets: self.abi.sized_stackslot_offsets().clone(), 1138 dynamic_stackslot_offsets: self.abi.dynamic_stackslot_offsets().clone(), 1139 value_labels_ranges, 1140 frame_size, 1141 } 1142 } 1143 1144 fn monotonize_inst_offsets(&self, inst_offsets: &mut [CodeOffset], func_body_len: u32) { 1145 if self.debug_value_labels.is_empty() { 1146 return; 1147 } 1148 1149 // During emission, branch removal can make offsets of instructions incorrect. 1150 // Consider the following sequence: [insi][jmp0][jmp1][jmp2][insj] 1151 // It will be recorded as (say): [30] [34] [38] [42] [<would be 46>] 1152 // When the jumps get removed we are left with (in "inst_offsets"): 1153 // [insi][jmp0][jmp1][jmp2][insj][...] 1154 // [30] [34] [38] [42] [34] 1155 // Which violates the monotonicity invariant. This method sets offsets of these 1156 // removed instructions such as to make them appear zero-sized: 1157 // [insi][jmp0][jmp1][jmp2][insj][...] 1158 // [30] [34] [34] [34] [34] 1159 // 1160 let mut next_offset = func_body_len; 1161 for inst_index in (0..(inst_offsets.len() - 1)).rev() { 1162 let inst_offset = inst_offsets[inst_index]; 1163 1164 // Not all instructions get their offsets recorded. 1165 if inst_offset == NO_INST_OFFSET { 1166 continue; 1167 } 1168 1169 if inst_offset > next_offset { 1170 trace!( 1171 "Fixing code offset of the removed Inst {}: {} -> {}", 1172 inst_index, 1173 inst_offset, 1174 next_offset 1175 ); 1176 inst_offsets[inst_index] = next_offset; 1177 continue; 1178 } 1179 1180 next_offset = inst_offset; 1181 } 1182 } 1183 1184 fn compute_value_labels_ranges( 1185 &self, 1186 regalloc: ®alloc2::Output, 1187 inst_offsets: &[CodeOffset], 1188 func_body_len: u32, 1189 ) -> ValueLabelsRanges { 1190 if self.debug_value_labels.is_empty() { 1191 return ValueLabelsRanges::default(); 1192 } 1193 1194 let mut value_labels_ranges: ValueLabelsRanges = HashMap::new(); 1195 for &(label, from, to, alloc) in ®alloc.debug_locations { 1196 let ranges = value_labels_ranges 1197 .entry(ValueLabel::from_u32(label)) 1198 .or_insert_with(|| vec![]); 1199 let from_offset = inst_offsets[from.inst().index()]; 1200 let to_offset = if to.inst().index() == inst_offsets.len() { 1201 func_body_len 1202 } else { 1203 inst_offsets[to.inst().index()] 1204 }; 1205 1206 // Empty ranges or unavailable offsets can happen 1207 // due to cold blocks and branch removal (see above). 1208 if from_offset == NO_INST_OFFSET 1209 || to_offset == NO_INST_OFFSET 1210 || from_offset == to_offset 1211 { 1212 continue; 1213 } 1214 1215 let loc = if let Some(preg) = alloc.as_reg() { 1216 LabelValueLoc::Reg(Reg::from(preg)) 1217 } else { 1218 let slot = alloc.as_stack().unwrap(); 1219 let slot_offset = self.abi.get_spillslot_offset(slot); 1220 let slot_base_to_caller_sp_offset = self.abi.slot_base_to_caller_sp_offset(); 1221 let caller_sp_to_cfa_offset = 1222 crate::isa::unwind::systemv::caller_sp_to_cfa_offset(); 1223 // NOTE: this is a negative offset because it's relative to the caller's SP 1224 let cfa_to_sp_offset = 1225 -((slot_base_to_caller_sp_offset + caller_sp_to_cfa_offset) as i64); 1226 LabelValueLoc::CFAOffset(cfa_to_sp_offset + slot_offset) 1227 }; 1228 1229 // ValueLocRanges are recorded by *instruction-end 1230 // offset*. `from_offset` is the *start* of the 1231 // instruction; that is the same as the end of another 1232 // instruction, so we only want to begin coverage once 1233 // we are past the previous instruction's end. 1234 let start = from_offset + 1; 1235 1236 // Likewise, `end` is exclusive, but we want to 1237 // *include* the end of the last 1238 // instruction. `to_offset` is the start of the 1239 // `to`-instruction, which is the exclusive end, i.e., 1240 // the first instruction not covered. That 1241 // instruction's start is the same as the end of the 1242 // last instruction that is included, so we go one 1243 // byte further to be sure to include it. 1244 let end = to_offset + 1; 1245 1246 // Coalesce adjacent ranges that for the same location 1247 // to minimize output size here and for the consumers. 1248 if let Some(last_loc_range) = ranges.last_mut() { 1249 if last_loc_range.loc == loc && last_loc_range.end == start { 1250 trace!( 1251 "Extending debug range for VL{} in {:?} to {}", 1252 label, 1253 loc, 1254 end 1255 ); 1256 last_loc_range.end = end; 1257 continue; 1258 } 1259 } 1260 1261 trace!( 1262 "Recording debug range for VL{} in {:?}: [Inst {}..Inst {}) [{}..{})", 1263 label, 1264 loc, 1265 from.inst().index(), 1266 to.inst().index(), 1267 start, 1268 end 1269 ); 1270 1271 ranges.push(ValueLocRange { loc, start, end }); 1272 } 1273 1274 value_labels_ranges 1275 } 1276 1277 /// Get the IR block for a BlockIndex, if one exists. 1278 pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> { 1279 self.block_order.lowered_order()[block.index()].orig_block() 1280 } 1281 1282 /// Get the type of a VReg. 1283 pub fn vreg_type(&self, vreg: VReg) -> Type { 1284 self.vreg_types[vreg.vreg()] 1285 } 1286 1287 /// Get the fact, if any, for a given VReg. 1288 pub fn vreg_fact(&self, vreg: VReg) -> Option<&Fact> { 1289 self.facts[vreg.vreg()].as_ref() 1290 } 1291 1292 /// Set the fact for a given VReg. 1293 pub fn set_vreg_fact(&mut self, vreg: VReg, fact: Fact) { 1294 trace!("set fact on {}: {:?}", vreg, fact); 1295 self.facts[vreg.vreg()] = Some(fact); 1296 } 1297 1298 /// Does a given instruction define any facts? 1299 pub fn inst_defines_facts(&self, inst: InsnIndex) -> bool { 1300 self.inst_operands(inst) 1301 .iter() 1302 .filter(|o| o.kind() == OperandKind::Def) 1303 .map(|o| o.vreg()) 1304 .any(|vreg| self.facts[vreg.vreg()].is_some()) 1305 } 1306 1307 /// Get the user stack map associated with the given forward instruction index. 1308 pub fn get_user_stack_map(&self, inst: InsnIndex) -> Option<&ir::UserStackMap> { 1309 let index = inst.to_backwards_insn_index(self.num_insts()); 1310 self.user_stack_maps.get(&index) 1311 } 1312 } 1313 1314 impl<I: VCodeInst> std::ops::Index<InsnIndex> for VCode<I> { 1315 type Output = I; 1316 fn index(&self, idx: InsnIndex) -> &Self::Output { 1317 &self.insts[idx.index()] 1318 } 1319 } 1320 1321 impl<I: VCodeInst> RegallocFunction for VCode<I> { 1322 fn num_insts(&self) -> usize { 1323 self.insts.len() 1324 } 1325 1326 fn num_blocks(&self) -> usize { 1327 self.block_ranges.len() 1328 } 1329 1330 fn entry_block(&self) -> BlockIndex { 1331 self.entry 1332 } 1333 1334 fn block_insns(&self, block: BlockIndex) -> InstRange { 1335 let range = self.block_ranges.get(block.index()); 1336 InstRange::forward(InsnIndex::new(range.start), InsnIndex::new(range.end)) 1337 } 1338 1339 fn block_succs(&self, block: BlockIndex) -> &[BlockIndex] { 1340 let range = self.block_succ_range.get(block.index()); 1341 &self.block_succs[range] 1342 } 1343 1344 fn block_preds(&self, block: BlockIndex) -> &[BlockIndex] { 1345 let range = self.block_pred_range.get(block.index()); 1346 &self.block_preds[range] 1347 } 1348 1349 fn block_params(&self, block: BlockIndex) -> &[VReg] { 1350 // As a special case we don't return block params for the entry block, as all the arguments 1351 // will be defined by the `Inst::Args` instruction. 1352 if block == self.entry { 1353 return &[]; 1354 } 1355 1356 let range = self.block_params_range.get(block.index()); 1357 &self.block_params[range] 1358 } 1359 1360 fn branch_blockparams(&self, block: BlockIndex, _insn: InsnIndex, succ_idx: usize) -> &[VReg] { 1361 let succ_range = self.branch_block_arg_succ_range.get(block.index()); 1362 debug_assert!(succ_idx < succ_range.len()); 1363 let branch_block_args = self.branch_block_arg_range.get(succ_range.start + succ_idx); 1364 &self.branch_block_args[branch_block_args] 1365 } 1366 1367 fn is_ret(&self, insn: InsnIndex) -> bool { 1368 match self.insts[insn.index()].is_term() { 1369 // We treat blocks terminated by an unconditional trap like a return for regalloc. 1370 MachTerminator::None => self.insts[insn.index()].is_trap(), 1371 MachTerminator::Ret | MachTerminator::RetCall => true, 1372 MachTerminator::Uncond | MachTerminator::Cond | MachTerminator::Indirect => false, 1373 } 1374 } 1375 1376 fn is_branch(&self, insn: InsnIndex) -> bool { 1377 match self.insts[insn.index()].is_term() { 1378 MachTerminator::Cond | MachTerminator::Uncond | MachTerminator::Indirect => true, 1379 _ => false, 1380 } 1381 } 1382 1383 fn requires_refs_on_stack(&self, insn: InsnIndex) -> bool { 1384 self.insts[insn.index()].is_safepoint() 1385 } 1386 1387 fn inst_operands(&self, insn: InsnIndex) -> &[Operand] { 1388 let range = self.operand_ranges.get(insn.index()); 1389 &self.operands[range] 1390 } 1391 1392 fn inst_clobbers(&self, insn: InsnIndex) -> PRegSet { 1393 self.clobbers.get(&insn).cloned().unwrap_or_default() 1394 } 1395 1396 fn num_vregs(&self) -> usize { 1397 self.vreg_types.len() 1398 } 1399 1400 fn reftype_vregs(&self) -> &[VReg] { 1401 &self.reftyped_vregs 1402 } 1403 1404 fn debug_value_labels(&self) -> &[(VReg, InsnIndex, InsnIndex, u32)] { 1405 &self.debug_value_labels 1406 } 1407 1408 fn spillslot_size(&self, regclass: RegClass) -> usize { 1409 self.abi.get_spillslot_size(regclass) as usize 1410 } 1411 1412 fn allow_multiple_vreg_defs(&self) -> bool { 1413 // At least the s390x backend requires this, because the 1414 // `Loop` pseudo-instruction aggregates all Operands so pinned 1415 // vregs (RealRegs) may occur more than once. 1416 true 1417 } 1418 } 1419 1420 impl<I: VCodeInst> Debug for VRegAllocator<I> { 1421 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1422 writeln!(f, "VRegAllocator {{")?; 1423 1424 let mut alias_keys = self.vreg_aliases.keys().cloned().collect::<Vec<_>>(); 1425 alias_keys.sort_unstable(); 1426 for key in alias_keys { 1427 let dest = self.vreg_aliases.get(&key).unwrap(); 1428 writeln!(f, " {:?} := {:?}", Reg::from(key), Reg::from(*dest))?; 1429 } 1430 1431 for (vreg, fact) in self.facts.iter().enumerate() { 1432 if let Some(fact) = fact { 1433 writeln!(f, " v{vreg} ! {fact}")?; 1434 } 1435 } 1436 1437 writeln!(f, "}}") 1438 } 1439 } 1440 1441 impl<I: VCodeInst> fmt::Debug for VCode<I> { 1442 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1443 writeln!(f, "VCode {{")?; 1444 writeln!(f, " Entry block: {}", self.entry.index())?; 1445 1446 let mut state = Default::default(); 1447 1448 for block in 0..self.num_blocks() { 1449 let block = BlockIndex::new(block); 1450 writeln!( 1451 f, 1452 "Block {}({:?}):", 1453 block.index(), 1454 self.block_params(block) 1455 )?; 1456 if let Some(bb) = self.bindex_to_bb(block) { 1457 writeln!(f, " (original IR block: {bb})")?; 1458 } 1459 for (succ_idx, succ) in self.block_succs(block).iter().enumerate() { 1460 writeln!( 1461 f, 1462 " (successor: Block {}({:?}))", 1463 succ.index(), 1464 self.branch_blockparams(block, InsnIndex::new(0) /* dummy */, succ_idx) 1465 )?; 1466 } 1467 for inst in self.block_ranges.get(block.index()) { 1468 writeln!( 1469 f, 1470 " Inst {}: {}", 1471 inst, 1472 self.insts[inst].pretty_print_inst(&mut state) 1473 )?; 1474 if !self.operands.is_empty() { 1475 for operand in self.inst_operands(InsnIndex::new(inst)) { 1476 if operand.kind() == OperandKind::Def { 1477 if let Some(fact) = &self.facts[operand.vreg().vreg()] { 1478 writeln!(f, " v{} ! {}", operand.vreg().vreg(), fact)?; 1479 } 1480 } 1481 } 1482 } 1483 if let Some(user_stack_map) = self.get_user_stack_map(InsnIndex::new(inst)) { 1484 writeln!(f, " {user_stack_map:?}")?; 1485 } 1486 } 1487 } 1488 1489 writeln!(f, "}}")?; 1490 Ok(()) 1491 } 1492 } 1493 1494 /// This structure manages VReg allocation during the lifetime of the VCodeBuilder. 1495 pub struct VRegAllocator<I> { 1496 /// VReg IR-level types. 1497 vreg_types: Vec<Type>, 1498 1499 /// Reference-typed `regalloc2::VReg`s. The regalloc requires 1500 /// these in a dense slice (as opposed to querying the 1501 /// reftype-status of each vreg) for efficient iteration. 1502 reftyped_vregs: Vec<VReg>, 1503 1504 /// VReg aliases. When the final VCode is built we rewrite all 1505 /// uses of the keys in this table to their replacement values. 1506 /// 1507 /// We use these aliases to rename an instruction's expected 1508 /// result vregs to the returned vregs from lowering, which are 1509 /// usually freshly-allocated temps. 1510 vreg_aliases: FxHashMap<regalloc2::VReg, regalloc2::VReg>, 1511 1512 /// A deferred error, to be bubbled up to the top level of the 1513 /// lowering algorithm. We take this approach because we cannot 1514 /// currently propagate a `Result` upward through ISLE code (the 1515 /// lowering rules) or some ABI code. 1516 deferred_error: Option<CodegenError>, 1517 1518 /// Facts on VRegs, for proof-carrying code. 1519 facts: Vec<Option<Fact>>, 1520 1521 /// The type of instruction that this allocator makes registers for. 1522 _inst: core::marker::PhantomData<I>, 1523 } 1524 1525 impl<I: VCodeInst> VRegAllocator<I> { 1526 /// Make a new VRegAllocator. 1527 pub fn with_capacity(capacity: usize) -> Self { 1528 let capacity = first_user_vreg_index() + capacity; 1529 let mut vreg_types = Vec::with_capacity(capacity); 1530 vreg_types.resize(first_user_vreg_index(), types::INVALID); 1531 Self { 1532 vreg_types, 1533 reftyped_vregs: vec![], 1534 vreg_aliases: FxHashMap::with_capacity_and_hasher(capacity, Default::default()), 1535 deferred_error: None, 1536 facts: Vec::with_capacity(capacity), 1537 _inst: core::marker::PhantomData::default(), 1538 } 1539 } 1540 1541 /// Allocate a fresh ValueRegs. 1542 pub fn alloc(&mut self, ty: Type) -> CodegenResult<ValueRegs<Reg>> { 1543 if self.deferred_error.is_some() { 1544 return Err(CodegenError::CodeTooLarge); 1545 } 1546 let v = self.vreg_types.len(); 1547 let (regclasses, tys) = I::rc_for_type(ty)?; 1548 if v + regclasses.len() >= VReg::MAX { 1549 return Err(CodegenError::CodeTooLarge); 1550 } 1551 1552 let regs: ValueRegs<Reg> = match regclasses { 1553 &[rc0] => ValueRegs::one(VReg::new(v, rc0).into()), 1554 &[rc0, rc1] => ValueRegs::two(VReg::new(v, rc0).into(), VReg::new(v + 1, rc1).into()), 1555 // We can extend this if/when we support 32-bit targets; e.g., 1556 // an i128 on a 32-bit machine will need up to four machine regs 1557 // for a `Value`. 1558 _ => panic!("Value must reside in 1 or 2 registers"), 1559 }; 1560 for (®_ty, ®) in tys.iter().zip(regs.regs().iter()) { 1561 let vreg = reg.to_virtual_reg().unwrap(); 1562 debug_assert_eq!(self.vreg_types.len(), vreg.index()); 1563 self.vreg_types.push(reg_ty); 1564 if is_reftype(reg_ty) { 1565 self.reftyped_vregs.push(vreg.into()); 1566 } 1567 } 1568 1569 // Create empty facts for each allocated vreg. 1570 self.facts.resize(self.vreg_types.len(), None); 1571 1572 Ok(regs) 1573 } 1574 1575 /// Allocate a fresh ValueRegs, deferring any out-of-vregs 1576 /// errors. This is useful in places where we cannot bubble a 1577 /// `CodegenResult` upward easily, and which are known to be 1578 /// invoked from within the lowering loop that checks the deferred 1579 /// error status below. 1580 pub fn alloc_with_deferred_error(&mut self, ty: Type) -> ValueRegs<Reg> { 1581 match self.alloc(ty) { 1582 Ok(x) => x, 1583 Err(e) => { 1584 self.deferred_error = Some(e); 1585 self.bogus_for_deferred_error(ty) 1586 } 1587 } 1588 } 1589 1590 /// Take any deferred error that was accumulated by `alloc_with_deferred_error`. 1591 pub fn take_deferred_error(&mut self) -> Option<CodegenError> { 1592 self.deferred_error.take() 1593 } 1594 1595 /// Produce an bogus VReg placeholder with the proper number of 1596 /// registers for the given type. This is meant to be used with 1597 /// deferred allocation errors (see `Lower::alloc_tmp()`). 1598 fn bogus_for_deferred_error(&self, ty: Type) -> ValueRegs<Reg> { 1599 let (regclasses, _tys) = I::rc_for_type(ty).expect("must have valid type"); 1600 match regclasses { 1601 &[rc0] => ValueRegs::one(VReg::new(0, rc0).into()), 1602 &[rc0, rc1] => ValueRegs::two(VReg::new(0, rc0).into(), VReg::new(1, rc1).into()), 1603 _ => panic!("Value must reside in 1 or 2 registers"), 1604 } 1605 } 1606 1607 /// Rewrite any mention of `from` into `to`. 1608 pub fn set_vreg_alias(&mut self, from: Reg, to: Reg) { 1609 let from = from.into(); 1610 let resolved_to = self.resolve_vreg_alias(to.into()); 1611 // Disallow cycles (see below). 1612 assert_ne!(resolved_to, from); 1613 1614 // Maintain the invariant that PCC facts only exist on vregs 1615 // which aren't aliases. We want to preserve whatever was 1616 // stated about the vreg before its producer was lowered. 1617 if let Some(fact) = self.facts[from.vreg()].take() { 1618 self.set_fact(resolved_to, fact); 1619 } 1620 1621 let old_alias = self.vreg_aliases.insert(from, resolved_to); 1622 debug_assert_eq!(old_alias, None); 1623 } 1624 1625 fn resolve_vreg_alias(&self, mut vreg: regalloc2::VReg) -> regalloc2::VReg { 1626 // We prevent cycles from existing by resolving targets of 1627 // aliases eagerly before setting them. If the target resolves 1628 // to the origin of the alias, then a cycle would be created 1629 // and the alias is disallowed. Because of the structure of 1630 // SSA code (one instruction can refer to another's defs but 1631 // not vice-versa, except indirectly through 1632 // phis/blockparams), cycles should not occur as we use 1633 // aliases to redirect vregs to the temps that actually define 1634 // them. 1635 while let Some(to) = self.vreg_aliases.get(&vreg) { 1636 vreg = *to; 1637 } 1638 vreg 1639 } 1640 1641 #[inline] 1642 fn debug_assert_no_vreg_aliases(&self, mut list: impl Iterator<Item = VReg>) { 1643 debug_assert!(list.all(|vreg| !self.vreg_aliases.contains_key(&vreg))); 1644 } 1645 1646 /// Set the proof-carrying code fact on a given virtual register. 1647 /// 1648 /// Returns the old fact, if any (only one fact can be stored). 1649 fn set_fact(&mut self, vreg: regalloc2::VReg, fact: Fact) -> Option<Fact> { 1650 trace!("vreg {:?} has fact: {:?}", vreg, fact); 1651 debug_assert!(!self.vreg_aliases.contains_key(&vreg)); 1652 self.facts[vreg.vreg()].replace(fact) 1653 } 1654 1655 /// Set a fact only if one doesn't already exist. 1656 pub fn set_fact_if_missing(&mut self, vreg: VirtualReg, fact: Fact) { 1657 let vreg = self.resolve_vreg_alias(vreg.into()); 1658 if self.facts[vreg.vreg()].is_none() { 1659 self.set_fact(vreg, fact); 1660 } 1661 } 1662 1663 /// Allocate a fresh ValueRegs, with a given fact to apply if 1664 /// the value fits in one VReg. 1665 pub fn alloc_with_maybe_fact( 1666 &mut self, 1667 ty: Type, 1668 fact: Option<Fact>, 1669 ) -> CodegenResult<ValueRegs<Reg>> { 1670 let result = self.alloc(ty)?; 1671 1672 // Ensure that we don't lose a fact on a value that splits 1673 // into multiple VRegs. 1674 assert!(result.len() == 1 || fact.is_none()); 1675 if let Some(fact) = fact { 1676 self.set_fact(result.regs()[0].into(), fact); 1677 } 1678 1679 Ok(result) 1680 } 1681 } 1682 1683 /// This structure tracks the large constants used in VCode that will be emitted separately by the 1684 /// [MachBuffer]. 1685 /// 1686 /// First, during the lowering phase, constants are inserted using 1687 /// [VCodeConstants.insert]; an intermediate handle, `VCodeConstant`, tracks what constants are 1688 /// used in this phase. Some deduplication is performed, when possible, as constant 1689 /// values are inserted. 1690 /// 1691 /// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the 1692 /// constants so that instructions can refer to the value's memory location. The [MachBuffer] 1693 /// then writes the constant values to the buffer. 1694 #[derive(Default)] 1695 pub struct VCodeConstants { 1696 constants: PrimaryMap<VCodeConstant, VCodeConstantData>, 1697 pool_uses: HashMap<Constant, VCodeConstant>, 1698 well_known_uses: HashMap<*const [u8], VCodeConstant>, 1699 u64s: HashMap<[u8; 8], VCodeConstant>, 1700 } 1701 impl VCodeConstants { 1702 /// Initialize the structure with the expected number of constants. 1703 pub fn with_capacity(expected_num_constants: usize) -> Self { 1704 Self { 1705 constants: PrimaryMap::with_capacity(expected_num_constants), 1706 pool_uses: HashMap::with_capacity(expected_num_constants), 1707 well_known_uses: HashMap::new(), 1708 u64s: HashMap::new(), 1709 } 1710 } 1711 1712 /// Insert a constant; using this method indicates that a constant value will be used and thus 1713 /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants 1714 /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not 1715 /// [VCodeConstantData::Generated]. 1716 pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant { 1717 match data { 1718 VCodeConstantData::Generated(_) => self.constants.push(data), 1719 VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) { 1720 None => { 1721 let vcode_constant = self.constants.push(data); 1722 self.pool_uses.insert(constant, vcode_constant); 1723 vcode_constant 1724 } 1725 Some(&vcode_constant) => vcode_constant, 1726 }, 1727 VCodeConstantData::WellKnown(data_ref) => { 1728 match self.well_known_uses.entry(data_ref as *const [u8]) { 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 VCodeConstantData::U64(value) => match self.u64s.entry(value) { 1738 Entry::Vacant(v) => { 1739 let vcode_constant = self.constants.push(data); 1740 v.insert(vcode_constant); 1741 vcode_constant 1742 } 1743 Entry::Occupied(o) => *o.get(), 1744 }, 1745 } 1746 } 1747 1748 /// Return the number of constants inserted. 1749 pub fn len(&self) -> usize { 1750 self.constants.len() 1751 } 1752 1753 /// Iterate over the `VCodeConstant` keys inserted in this structure. 1754 pub fn keys(&self) -> Keys<VCodeConstant> { 1755 self.constants.keys() 1756 } 1757 1758 /// Iterate over the `VCodeConstant` keys and the data (as a byte slice) inserted in this 1759 /// structure. 1760 pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> { 1761 self.constants.iter() 1762 } 1763 1764 /// Returns the data associated with the specified constant. 1765 pub fn get(&self, c: VCodeConstant) -> &VCodeConstantData { 1766 &self.constants[c] 1767 } 1768 1769 /// Checks if the given [VCodeConstantData] is registered as 1770 /// used by the pool. 1771 pub fn pool_uses(&self, constant: &VCodeConstantData) -> bool { 1772 match constant { 1773 VCodeConstantData::Pool(c, _) => self.pool_uses.contains_key(c), 1774 _ => false, 1775 } 1776 } 1777 } 1778 1779 /// A use of a constant by one or more VCode instructions; see [VCodeConstants]. 1780 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 1781 pub struct VCodeConstant(u32); 1782 entity_impl!(VCodeConstant); 1783 1784 /// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking 1785 /// these separately instead of as raw byte buffers allows us to avoid some duplication. 1786 pub enum VCodeConstantData { 1787 /// A constant already present in the Cranelift IR 1788 /// [ConstantPool](crate::ir::constant::ConstantPool). 1789 Pool(Constant, ConstantData), 1790 /// A reference to a well-known constant value that is statically encoded within the compiler. 1791 WellKnown(&'static [u8]), 1792 /// A constant value generated during lowering; the value may depend on the instruction context 1793 /// which makes it difficult to de-duplicate--if possible, use other variants. 1794 Generated(ConstantData), 1795 /// A constant of at most 64 bits. These are deduplicated as 1796 /// well. Stored as a fixed-size array of `u8` so that we do not 1797 /// encounter endianness problems when cross-compiling. 1798 U64([u8; 8]), 1799 } 1800 impl VCodeConstantData { 1801 /// Retrieve the constant data as a byte slice. 1802 pub fn as_slice(&self) -> &[u8] { 1803 match self { 1804 VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(), 1805 VCodeConstantData::WellKnown(d) => d, 1806 VCodeConstantData::U64(value) => &value[..], 1807 } 1808 } 1809 1810 /// Calculate the alignment of the constant data. 1811 pub fn alignment(&self) -> u32 { 1812 if self.as_slice().len() <= 8 { 1813 8 1814 } else { 1815 16 1816 } 1817 } 1818 } 1819 1820 #[cfg(test)] 1821 mod test { 1822 use super::*; 1823 use std::mem::size_of; 1824 1825 #[test] 1826 fn size_of_constant_structs() { 1827 assert_eq!(size_of::<Constant>(), 4); 1828 assert_eq!(size_of::<VCodeConstant>(), 4); 1829 assert_eq!(size_of::<ConstantData>(), 24); 1830 assert_eq!(size_of::<VCodeConstantData>(), 32); 1831 assert_eq!( 1832 size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(), 1833 24 1834 ); 1835 // TODO The VCodeConstants structure's memory size could be further optimized. 1836 // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at 1837 // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes. 1838 } 1839 } 1840