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