1d8357426SChris Fallin //! This implements the VCode container: a CFG of Insts that have been lowered. 2d8357426SChris Fallin //! 3d8357426SChris Fallin //! VCode is virtual-register code. An instruction in VCode is almost a machine 4d8357426SChris Fallin //! instruction; however, its register slots can refer to virtual registers in 5d8357426SChris Fallin //! addition to real machine registers. 6d8357426SChris Fallin //! 7d8357426SChris Fallin //! VCode is structured with traditional basic blocks, and 8d8357426SChris Fallin //! each block must be terminated by an unconditional branch (one target), a 9d8357426SChris Fallin //! conditional branch (two targets), or a return (no targets). Note that this 10d8357426SChris Fallin //! slightly differs from the machine code of most ISAs: in most ISAs, a 11d8357426SChris Fallin //! conditional branch has one target (and the not-taken case falls through). 12d8357426SChris Fallin //! However, we expect that machine backends will elide branches to the following 13d8357426SChris Fallin //! block (i.e., zero-offset jumps), and will be able to codegen a branch-cond / 14d8357426SChris Fallin //! branch-uncond pair if *both* targets are not fallthrough. This allows us to 15d8357426SChris Fallin //! play with layout prior to final binary emission, as well, if we want. 16d8357426SChris Fallin //! 17d8357426SChris Fallin //! See the main module comment in `mod.rs` for more details on the VCode-based 18d8357426SChris Fallin //! backend pipeline. 19d8357426SChris Fallin 20f466aa26SChris Fallin use crate::ir::pcc::*; 219ce3ffe1SAlex Crichton use crate::ir::{self, types, Constant, ConstantData, ValueLabel}; 222c409535SJamey Sharp use crate::ranges::Ranges; 232b9fefe8SChris Fallin use crate::timing; 248d022434SBenjamin Bouvier use crate::trace; 25d94173eaSTrevor Elliott use crate::CodegenError; 263da7fc8eSSingleAccretion use crate::{machinst::*, trace_log_enabled}; 27729e2640Sbjorn3 use crate::{LabelValueLoc, ValueLocRange}; 28a0318f36SChris Fallin use regalloc2::{ 29*5ded0f4eSUlrich Weigand Edit, Function as RegallocFunction, InstOrEdit, InstPosition, InstRange, Operand, 305b63c874SSingleAccretion OperandConstraint, OperandKind, PRegSet, ProgPoint, RegClass, 31be6f060aSChris Fallin }; 32132ef1e4SKirpal Grewal use rustc_hash::FxHashMap; 33d8357426SChris Fallin 343da7fc8eSSingleAccretion use core::cmp::Ordering; 353da7fc8eSSingleAccretion use core::fmt::{self, Write}; 363aa32064SJamey Sharp use core::mem::take; 379ce3ffe1SAlex Crichton use cranelift_entity::{entity_impl, Keys}; 38eb435f30SChris Fallin use std::collections::hash_map::Entry; 3983f182b3SAndrew Brown use std::collections::HashMap; 40d8357426SChris Fallin 41d8357426SChris Fallin /// Index referring to an instruction in VCode. 42a0318f36SChris Fallin pub type InsnIndex = regalloc2::Inst; 43a0318f36SChris Fallin 44e20b4244SNick Fitzgerald /// Extension trait for `InsnIndex` to allow conversion to a 45e20b4244SNick Fitzgerald /// `BackwardsInsnIndex`. 46e20b4244SNick Fitzgerald trait ToBackwardsInsnIndex { 47e20b4244SNick Fitzgerald fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex; 48e20b4244SNick Fitzgerald } 49e20b4244SNick Fitzgerald 50e20b4244SNick Fitzgerald impl ToBackwardsInsnIndex for InsnIndex { 51e20b4244SNick Fitzgerald fn to_backwards_insn_index(&self, num_insts: usize) -> BackwardsInsnIndex { 52e20b4244SNick Fitzgerald BackwardsInsnIndex::new(num_insts - self.index() - 1) 53e20b4244SNick Fitzgerald } 54e20b4244SNick Fitzgerald } 55e20b4244SNick Fitzgerald 56e20b4244SNick Fitzgerald /// An index referring to an instruction in the VCode when it is backwards, 57e20b4244SNick Fitzgerald /// during VCode construction. 58e20b4244SNick Fitzgerald #[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)] 59e20b4244SNick Fitzgerald #[cfg_attr( 60e20b4244SNick Fitzgerald feature = "enable-serde", 61e20b4244SNick Fitzgerald derive(::serde::Serialize, ::serde::Deserialize) 62e20b4244SNick Fitzgerald )] 63e20b4244SNick Fitzgerald pub struct BackwardsInsnIndex(InsnIndex); 64e20b4244SNick Fitzgerald 65e20b4244SNick Fitzgerald impl BackwardsInsnIndex { 66e20b4244SNick Fitzgerald pub fn new(i: usize) -> Self { 67e20b4244SNick Fitzgerald BackwardsInsnIndex(InsnIndex::new(i)) 68e20b4244SNick Fitzgerald } 69e20b4244SNick Fitzgerald } 70e20b4244SNick Fitzgerald 71d8357426SChris Fallin /// Index referring to a basic block in VCode. 72a0318f36SChris Fallin pub type BlockIndex = regalloc2::Block; 73d8357426SChris Fallin 74d8357426SChris Fallin /// VCodeInst wraps all requirements for a MachInst to be in VCode: it must be 75d8357426SChris Fallin /// a `MachInst` and it must be able to emit itself at least to a `SizeCodeSink`. 7672e6be93SChris Fallin pub trait VCodeInst: MachInst + MachInstEmit {} 7772e6be93SChris Fallin impl<I: MachInst + MachInstEmit> VCodeInst for I {} 78d8357426SChris Fallin 79a0318f36SChris Fallin /// A function in "VCode" (virtualized-register code) form, after 80a0318f36SChris Fallin /// lowering. This is essentially a standard CFG of basic blocks, 81a0318f36SChris Fallin /// where each basic block consists of lowered instructions produced 82a0318f36SChris Fallin /// by the machine-specific backend. 83a0318f36SChris Fallin /// 84a0318f36SChris Fallin /// Note that the VCode is immutable once produced, and is not 85a0318f36SChris Fallin /// modified by register allocation in particular. Rather, register 86a0318f36SChris Fallin /// allocation on the `VCode` produces a separate `regalloc2::Output` 87a0318f36SChris Fallin /// struct, and this can be passed to `emit`. `emit` in turn does not 88a0318f36SChris Fallin /// modify the vcode, but produces an `EmitResult`, which contains the 89a0318f36SChris Fallin /// machine code itself, and the associated disassembly and/or 90a0318f36SChris Fallin /// metadata as requested. 91d8357426SChris Fallin pub struct VCode<I: VCodeInst> { 92d8357426SChris Fallin /// VReg IR-level types. 93d8357426SChris Fallin vreg_types: Vec<Type>, 94d8357426SChris Fallin 95d8357426SChris Fallin /// Lowered machine instructions in order corresponding to the original IR. 9648cf2c2fSChris Fallin insts: Vec<I>, 97d8357426SChris Fallin 98e20b4244SNick Fitzgerald /// A map from backwards instruction index to the user stack map for that 99e20b4244SNick Fitzgerald /// instruction. 100e20b4244SNick Fitzgerald /// 101e20b4244SNick Fitzgerald /// This is a sparse side table that only has entries for instructions that 102e20b4244SNick Fitzgerald /// are safepoints, and only for a subset of those that have an associated 103e20b4244SNick Fitzgerald /// user stack map. 104e20b4244SNick Fitzgerald user_stack_maps: FxHashMap<BackwardsInsnIndex, ir::UserStackMap>, 105e20b4244SNick Fitzgerald 106a0318f36SChris Fallin /// Operands: pre-regalloc references to virtual registers with 107a0318f36SChris Fallin /// constraints, in one flattened array. This allows the regalloc 108a0318f36SChris Fallin /// to efficiently access all operands without requiring expensive 109a0318f36SChris Fallin /// matches or method invocations on insts. 110a0318f36SChris Fallin operands: Vec<Operand>, 111a0318f36SChris Fallin 112a0318f36SChris Fallin /// Operand index ranges: for each instruction in `insts`, there 113a0318f36SChris Fallin /// is a tuple here providing the range in `operands` for that 114a0318f36SChris Fallin /// instruction's operands. 1152c409535SJamey Sharp operand_ranges: Ranges, 116a0318f36SChris Fallin 117b2e28b91SChris Fallin /// Clobbers: a sparse map from instruction indices to clobber masks. 118b2e28b91SChris Fallin clobbers: FxHashMap<InsnIndex, PRegSet>, 119a0318f36SChris Fallin 120b691770fSChris Fallin /// Source locations for each instruction. (`SourceLoc` is a `u32`, so it is 121b691770fSChris Fallin /// reasonable to keep one of these per instruction.) 1228a9b1a90SBenjamin Bouvier srclocs: Vec<RelSourceLoc>, 123b691770fSChris Fallin 124d8357426SChris Fallin /// Entry block. 125d8357426SChris Fallin entry: BlockIndex, 126d8357426SChris Fallin 127d8357426SChris Fallin /// Block instruction indices. 1282c409535SJamey Sharp block_ranges: Ranges, 129d8357426SChris Fallin 1300f4c0d4aSJamey Sharp /// Block successors: index range in the `block_succs` list. 1312c409535SJamey Sharp block_succ_range: Ranges, 132d8357426SChris Fallin 1330f4c0d4aSJamey Sharp /// Block successor lists, concatenated into one vec. The 1340f4c0d4aSJamey Sharp /// `block_succ_range` list of tuples above gives (start, end) 1350f4c0d4aSJamey Sharp /// ranges within this list that correspond to each basic block's 1360f4c0d4aSJamey Sharp /// successors. 1370f4c0d4aSJamey Sharp block_succs: Vec<regalloc2::Block>, 1380f4c0d4aSJamey Sharp 1390f4c0d4aSJamey Sharp /// Block predecessors: index range in the `block_preds` list. 1402c409535SJamey Sharp block_pred_range: Ranges, 141a0318f36SChris Fallin 1420f4c0d4aSJamey Sharp /// Block predecessor lists, concatenated into one vec. The 1430f4c0d4aSJamey Sharp /// `block_pred_range` list of tuples above gives (start, end) 1440f4c0d4aSJamey Sharp /// ranges within this list that correspond to each basic block's 1450f4c0d4aSJamey Sharp /// predecessors. 1460f4c0d4aSJamey Sharp block_preds: Vec<regalloc2::Block>, 147a0318f36SChris Fallin 148a0318f36SChris Fallin /// Block parameters: index range in `block_params` below. 1492c409535SJamey Sharp block_params_range: Ranges, 150a0318f36SChris Fallin 151a0318f36SChris Fallin /// Block parameter lists, concatenated into one vec. The 152a0318f36SChris Fallin /// `block_params_range` list of tuples above gives (start, end) 153a0318f36SChris Fallin /// ranges within this list that correspond to each basic block's 154a0318f36SChris Fallin /// blockparam vregs. 155a0318f36SChris Fallin block_params: Vec<regalloc2::VReg>, 156a0318f36SChris Fallin 157a0318f36SChris Fallin /// Outgoing block arguments on branch instructions, concatenated 158a0318f36SChris Fallin /// into one list. 159a0318f36SChris Fallin /// 160a0318f36SChris Fallin /// Note that this is conceptually a 3D array: we have a VReg list 161a0318f36SChris Fallin /// per block, per successor. We flatten those three dimensions 162a0318f36SChris Fallin /// into this 1D vec, then store index ranges in two levels of 163a0318f36SChris Fallin /// indirection. 164a0318f36SChris Fallin /// 165a0318f36SChris Fallin /// Indexed by the indices in `branch_block_arg_succ_range`. 166a0318f36SChris Fallin branch_block_args: Vec<regalloc2::VReg>, 167a0318f36SChris Fallin 168a0318f36SChris Fallin /// Array of sequences of (start, end) tuples in 169a0318f36SChris Fallin /// `branch_block_args`, one for each successor; these sequences 170a0318f36SChris Fallin /// for each block are concatenated. 171a0318f36SChris Fallin /// 172a0318f36SChris Fallin /// Indexed by the indices in `branch_block_arg_succ_range`. 1732c409535SJamey Sharp branch_block_arg_range: Ranges, 174a0318f36SChris Fallin 175a0318f36SChris Fallin /// For a given block, indices in `branch_block_arg_range` 176a0318f36SChris Fallin /// corresponding to all of its successors. 1772c409535SJamey Sharp branch_block_arg_succ_range: Ranges, 178a0318f36SChris Fallin 17972e6be93SChris Fallin /// Block-order information. 18072e6be93SChris Fallin block_order: BlockLoweringOrder, 181d8357426SChris Fallin 182d8357426SChris Fallin /// ABI object. 1832986f6b0SChris Fallin pub(crate) abi: Callee<I::ABIMachineSpec>, 18408353fccSChris Fallin 185c5bbc874SBenjamin Bouvier /// Constant information used during code emission. This should be 186c5bbc874SBenjamin Bouvier /// immutable across function compilations within the same module. 187c5bbc874SBenjamin Bouvier emit_info: I::Info, 188c5bbc874SBenjamin Bouvier 18983f182b3SAndrew Brown /// Constants. 1904513d9caSChris Fallin pub(crate) constants: VCodeConstants, 191997fab55SChris Fallin 192a0318f36SChris Fallin /// Value labels for debuginfo attached to vregs. 193a0318f36SChris Fallin debug_value_labels: Vec<(VReg, InsnIndex, InsnIndex, u32)>, 194f18a1f14SNick Fitzgerald 1952986f6b0SChris Fallin pub(crate) sigs: SigSet, 196f466aa26SChris Fallin 197f466aa26SChris Fallin /// Facts on VRegs, for proof-carrying code verification. 198f466aa26SChris Fallin facts: Vec<Option<Fact>>, 1992af0a1f7Sbjorn3 2002af0a1f7Sbjorn3 log2_min_function_alignment: u8, 201d8357426SChris Fallin } 202d8357426SChris Fallin 203a0318f36SChris Fallin /// The result of `VCode::emit`. Contains all information computed 204a0318f36SChris Fallin /// during emission: actual machine code, optionally a disassembly, 205a0318f36SChris Fallin /// and optionally metadata about the code layout. 20649dd8fd7SAlex Crichton pub struct EmitResult { 207a0318f36SChris Fallin /// The MachBuffer containing the machine code. 20849dd8fd7SAlex Crichton pub buffer: MachBufferFinalized<Stencil>, 209a0318f36SChris Fallin 210a0318f36SChris Fallin /// Offset of each basic block, recorded during emission. Computed 211a0318f36SChris Fallin /// only if `debug_value_labels` is non-empty. 212a0318f36SChris Fallin pub bb_offsets: Vec<CodeOffset>, 213a0318f36SChris Fallin 214a0318f36SChris Fallin /// Final basic-block edges, in terms of code offsets of 215a0318f36SChris Fallin /// bb-starts. Computed only if `debug_value_labels` is non-empty. 216a0318f36SChris Fallin pub bb_edges: Vec<(CodeOffset, CodeOffset)>, 217a0318f36SChris Fallin 218a0318f36SChris Fallin /// Final length of function body. 219a0318f36SChris Fallin pub func_body_len: CodeOffset, 220a0318f36SChris Fallin 221a0318f36SChris Fallin /// The pretty-printed disassembly, if any. This uses the same 222a0318f36SChris Fallin /// pretty-printing for MachInsts as the pre-regalloc VCode Debug 223a0318f36SChris Fallin /// implementation, but additionally includes the prologue and 224a0318f36SChris Fallin /// epilogue(s), and makes use of the regalloc results. 225a0318f36SChris Fallin pub disasm: Option<String>, 226a0318f36SChris Fallin 2279c43749dSSam Parker /// Offsets of sized stackslots. 2289c43749dSSam Parker pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>, 2299c43749dSSam Parker 2309c43749dSSam Parker /// Offsets of dynamic stackslots. 2319c43749dSSam Parker pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>, 232a0318f36SChris Fallin 233a0318f36SChris Fallin /// Value-labels information (debug metadata). 234a0318f36SChris Fallin pub value_labels_ranges: ValueLabelsRanges, 235a0318f36SChris Fallin 236a0318f36SChris Fallin /// Stack frame size. 237a0318f36SChris Fallin pub frame_size: u32, 238d9d64694SChris Fallin } 239d9d64694SChris Fallin 240a0318f36SChris Fallin /// A builder for a VCode function body. 241d8357426SChris Fallin /// 242a0318f36SChris Fallin /// This builder has the ability to accept instructions in either 243a0318f36SChris Fallin /// forward or reverse order, depending on the pass direction that 244a0318f36SChris Fallin /// produces the VCode. The lowering from CLIF to VCode<MachInst> 245a0318f36SChris Fallin /// ordinarily occurs in reverse order (in order to allow instructions 246a0318f36SChris Fallin /// to be lowered only if used, and not merged) so a reversal will 247a0318f36SChris Fallin /// occur at the end of lowering to ensure the VCode is in machine 248a0318f36SChris Fallin /// order. 249a0318f36SChris Fallin /// 250a0318f36SChris Fallin /// If built in reverse, block and instruction indices used once the 251a0318f36SChris Fallin /// VCode is built are relative to the final (reversed) order, not the 252a0318f36SChris Fallin /// order of construction. Note that this means we do not know the 253a0318f36SChris Fallin /// final block or instruction indices when building, so we do not 254a0318f36SChris Fallin /// hand them out. (The user is assumed to know them when appending 255a0318f36SChris Fallin /// terminator instructions with successor blocks.) 256d8357426SChris Fallin pub struct VCodeBuilder<I: VCodeInst> { 257d8357426SChris Fallin /// In-progress VCode. 2582986f6b0SChris Fallin pub(crate) vcode: VCode<I>, 259d8357426SChris Fallin 2600e9121daSFrankReh /// In what direction is the build occurring? 261a0318f36SChris Fallin direction: VCodeBuildDirection, 26208353fccSChris Fallin 263a0318f36SChris Fallin /// Debug-value label in-progress map, keyed by label. For each 264a0318f36SChris Fallin /// label, we keep disjoint ranges mapping to vregs. We'll flatten 265a0318f36SChris Fallin /// this into (vreg, range, label) tuples when done. 266a0318f36SChris Fallin debug_info: FxHashMap<ValueLabel, Vec<(InsnIndex, InsnIndex, VReg)>>, 267a0318f36SChris Fallin } 268a0318f36SChris Fallin 269a0318f36SChris Fallin /// Direction in which a VCodeBuilder builds VCode. 270a0318f36SChris Fallin #[derive(Clone, Copy, Debug, PartialEq, Eq)] 271a0318f36SChris Fallin pub enum VCodeBuildDirection { 272a0318f36SChris Fallin // TODO: add `Forward` once we need it and can test it adequately. 273a0318f36SChris Fallin /// Backward-build pass: we expect the producer to call `emit()` 274a0318f36SChris Fallin /// with instructions in reverse program order within each block. 275a0318f36SChris Fallin Backward, 276d8357426SChris Fallin } 277d8357426SChris Fallin 278d8357426SChris Fallin impl<I: VCodeInst> VCodeBuilder<I> { 279d8357426SChris Fallin /// Create a new VCodeBuilder. 280c5bbc874SBenjamin Bouvier pub fn new( 281f18a1f14SNick Fitzgerald sigs: SigSet, 282f0c60f46SNick Fitzgerald abi: Callee<I::ABIMachineSpec>, 283c5bbc874SBenjamin Bouvier emit_info: I::Info, 284c5bbc874SBenjamin Bouvier block_order: BlockLoweringOrder, 28583f182b3SAndrew Brown constants: VCodeConstants, 286a0318f36SChris Fallin direction: VCodeBuildDirection, 2872af0a1f7Sbjorn3 log2_min_function_alignment: u8, 288e20b4244SNick Fitzgerald ) -> Self { 2892af0a1f7Sbjorn3 let vcode = VCode::new( 2902af0a1f7Sbjorn3 sigs, 2912af0a1f7Sbjorn3 abi, 2922af0a1f7Sbjorn3 emit_info, 2932af0a1f7Sbjorn3 block_order, 2942af0a1f7Sbjorn3 constants, 2952af0a1f7Sbjorn3 log2_min_function_alignment, 2962af0a1f7Sbjorn3 ); 29708353fccSChris Fallin 298d8357426SChris Fallin VCodeBuilder { 299d8357426SChris Fallin vcode, 300a0318f36SChris Fallin direction, 301a0318f36SChris Fallin debug_info: FxHashMap::default(), 302d8357426SChris Fallin } 303d8357426SChris Fallin } 304d8357426SChris Fallin 305b6e7cc38SJamey Sharp pub fn init_retval_area(&mut self, vregs: &mut VRegAllocator<I>) -> CodegenResult<()> { 306b6e7cc38SJamey Sharp self.vcode.abi.init_retval_area(&self.vcode.sigs, vregs) 307f18a1f14SNick Fitzgerald } 308f18a1f14SNick Fitzgerald 309d8357426SChris Fallin /// Access the ABI object. 310f18a1f14SNick Fitzgerald pub fn abi(&self) -> &Callee<I::ABIMachineSpec> { 311f18a1f14SNick Fitzgerald &self.vcode.abi 312f18a1f14SNick Fitzgerald } 313f18a1f14SNick Fitzgerald 314f18a1f14SNick Fitzgerald /// Access the ABI object. 315f18a1f14SNick Fitzgerald pub fn abi_mut(&mut self) -> &mut Callee<I::ABIMachineSpec> { 316f0c60f46SNick Fitzgerald &mut self.vcode.abi 317d8357426SChris Fallin } 318d8357426SChris Fallin 319f18a1f14SNick Fitzgerald pub fn sigs(&self) -> &SigSet { 320f18a1f14SNick Fitzgerald &self.vcode.sigs 321f18a1f14SNick Fitzgerald } 322f18a1f14SNick Fitzgerald 323f18a1f14SNick Fitzgerald pub fn sigs_mut(&mut self) -> &mut SigSet { 324f18a1f14SNick Fitzgerald &mut self.vcode.sigs 325f18a1f14SNick Fitzgerald } 326f18a1f14SNick Fitzgerald 32772e6be93SChris Fallin /// Access to the BlockLoweringOrder object. 32872e6be93SChris Fallin pub fn block_order(&self) -> &BlockLoweringOrder { 32972e6be93SChris Fallin &self.vcode.block_order 3301d90751bSBenjamin Bouvier } 3311d90751bSBenjamin Bouvier 332d8357426SChris Fallin /// Set the current block as the entry block. 333d8357426SChris Fallin pub fn set_entry(&mut self, block: BlockIndex) { 334d8357426SChris Fallin self.vcode.entry = block; 335d8357426SChris Fallin } 336d8357426SChris Fallin 337d8357426SChris Fallin /// End the current basic block. Must be called after emitting vcode insts 338d8357426SChris Fallin /// for IR insts and prior to ending the function (building the VCode). 33972e6be93SChris Fallin pub fn end_bb(&mut self) { 340a0318f36SChris Fallin let end_idx = self.vcode.insts.len(); 341d8357426SChris Fallin // Add the instruction index range to the list of blocks. 3422c409535SJamey Sharp self.vcode.block_ranges.push_end(end_idx); 343d8357426SChris Fallin // End the successors list. 3440f4c0d4aSJamey Sharp let succ_end = self.vcode.block_succs.len(); 3452c409535SJamey Sharp self.vcode.block_succ_range.push_end(succ_end); 346a0318f36SChris Fallin // End the blockparams list. 347a0318f36SChris Fallin let block_params_end = self.vcode.block_params.len(); 3482c409535SJamey Sharp self.vcode.block_params_range.push_end(block_params_end); 349a0318f36SChris Fallin // End the branch blockparam args list. 350a0318f36SChris Fallin let branch_block_arg_succ_end = self.vcode.branch_block_arg_range.len(); 3512c409535SJamey Sharp self.vcode 3522c409535SJamey Sharp .branch_block_arg_succ_range 3532c409535SJamey Sharp .push_end(branch_block_arg_succ_end); 354d8357426SChris Fallin } 355d8357426SChris Fallin 356d94173eaSTrevor Elliott pub fn add_block_param(&mut self, param: VirtualReg) { 357a0318f36SChris Fallin self.vcode.block_params.push(param.into()); 358a0318f36SChris Fallin } 359a0318f36SChris Fallin 3605774e068SChris Fallin fn add_branch_args_for_succ(&mut self, args: &[Reg]) { 361a0318f36SChris Fallin self.vcode 362a0318f36SChris Fallin .branch_block_args 363a0318f36SChris Fallin .extend(args.iter().map(|&arg| VReg::from(arg))); 364a0318f36SChris Fallin let end = self.vcode.branch_block_args.len(); 3652c409535SJamey Sharp self.vcode.branch_block_arg_range.push_end(end); 366a0318f36SChris Fallin } 367a0318f36SChris Fallin 368a0318f36SChris Fallin /// Push an instruction for the current BB and current IR inst 369a0318f36SChris Fallin /// within the BB. 3703e878837SJamey Sharp pub fn push(&mut self, insn: I, loc: RelSourceLoc) { 371392c7a96SChris Fallin assert!(!insn.is_low_level_branch()); // These are not meant to be in VCode. 37272e6be93SChris Fallin self.vcode.insts.push(insn); 3733e878837SJamey Sharp self.vcode.srclocs.push(loc); 37472e6be93SChris Fallin } 37572e6be93SChris Fallin 3765774e068SChris Fallin /// Add a successor block with branch args. 3775774e068SChris Fallin pub fn add_succ(&mut self, block: BlockIndex, args: &[Reg]) { 3780f4c0d4aSJamey Sharp self.vcode.block_succs.push(block); 3795774e068SChris Fallin self.add_branch_args_for_succ(args); 3805774e068SChris Fallin } 3815774e068SChris Fallin 382a0318f36SChris Fallin /// Add a debug value label to a register. 383a0318f36SChris Fallin pub fn add_value_label(&mut self, reg: Reg, label: ValueLabel) { 3845b63c874SSingleAccretion // 1) In the reversed order, we consider the instructions 3855b63c874SSingleAccretion // that define ranges in the "debug_info" array to refer 3865b63c874SSingleAccretion // to the IP **after** them (when reversed): 3875b63c874SSingleAccretion // IP[2]__| Inst 3 | 3885b63c874SSingleAccretion // IP[1]__| Inst 2 | 3895b63c874SSingleAccretion // IP[0]__| Inst 1 | 3905b63c874SSingleAccretion // | Inst 0 | 3915b63c874SSingleAccretion // This is so that we can represent IP[<function start>], 3925b63c874SSingleAccretion // done at the cost of not being to represent IP[<function end>], 3935b63c874SSingleAccretion // which is OK since no values will be live at that point. 3945b63c874SSingleAccretion // 2) The live range for "reg" begins at the current IP 3955b63c874SSingleAccretion // and continues until the next, in execution order, 3965b63c874SSingleAccretion // VReg that defines "label". Since the ranges are open 3975b63c874SSingleAccretion // at the end, the subtraction of 1 cancels out: 3985b63c874SSingleAccretion // [last..current IP] <=> 3995b63c874SSingleAccretion // [last..last emitted inst index] <=> 4005b63c874SSingleAccretion // [last..next_inst_index - 1] <=> 4015b63c874SSingleAccretion // [last..next_inst_index) 4025b63c874SSingleAccretion // 4035b63c874SSingleAccretion let next_inst_index = self.vcode.insts.len(); 4045b63c874SSingleAccretion if next_inst_index == 0 { 4055b63c874SSingleAccretion // This would produce a defective [0..0) range. 4065b63c874SSingleAccretion return; 4075b63c874SSingleAccretion } 4085b63c874SSingleAccretion let next_inst = InsnIndex::new(next_inst_index); 409a0318f36SChris Fallin let labels = self.debug_info.entry(label).or_insert_with(|| vec![]); 410a0318f36SChris Fallin let last = labels 411a0318f36SChris Fallin .last() 412a0318f36SChris Fallin .map(|(_start, end, _vreg)| *end) 413a0318f36SChris Fallin .unwrap_or(InsnIndex::new(0)); 4145b63c874SSingleAccretion labels.push((last, next_inst, reg.into())); 415a0318f36SChris Fallin } 416a0318f36SChris Fallin 41783f182b3SAndrew Brown /// Access the constants. 41883f182b3SAndrew Brown pub fn constants(&mut self) -> &mut VCodeConstants { 41983f182b3SAndrew Brown &mut self.vcode.constants 42083f182b3SAndrew Brown } 42183f182b3SAndrew Brown 422a0318f36SChris Fallin fn compute_preds_from_succs(&mut self) { 4230f4c0d4aSJamey Sharp // Do a linear-time counting sort: first determine how many 4240f4c0d4aSJamey Sharp // times each block appears as a successor. 4250f4c0d4aSJamey Sharp let mut starts = vec![0u32; self.vcode.num_blocks()]; 4260f4c0d4aSJamey Sharp for succ in &self.vcode.block_succs { 4270f4c0d4aSJamey Sharp starts[succ.index()] += 1; 4280f4c0d4aSJamey Sharp } 4290f4c0d4aSJamey Sharp 4300f4c0d4aSJamey Sharp // Determine for each block the starting index where that 4310f4c0d4aSJamey Sharp // block's predecessors should go. This is equivalent to the 4320f4c0d4aSJamey Sharp // ranges we need to store in block_pred_range. 4330f4c0d4aSJamey Sharp self.vcode.block_pred_range.reserve(starts.len()); 4340f4c0d4aSJamey Sharp let mut end = 0; 4350f4c0d4aSJamey Sharp for count in starts.iter_mut() { 4360f4c0d4aSJamey Sharp let start = end; 4370f4c0d4aSJamey Sharp end += *count; 4380f4c0d4aSJamey Sharp *count = start; 4392c409535SJamey Sharp self.vcode.block_pred_range.push_end(end as usize); 4400f4c0d4aSJamey Sharp } 4410f4c0d4aSJamey Sharp let end = end as usize; 4420f4c0d4aSJamey Sharp debug_assert_eq!(end, self.vcode.block_succs.len()); 4430f4c0d4aSJamey Sharp 4440f4c0d4aSJamey Sharp // Walk over the successors again, this time grouped by 4450f4c0d4aSJamey Sharp // predecessor, and push the predecessor at the current 4462c409535SJamey Sharp // starting position of each of its successors. We build 4472c409535SJamey Sharp // each group of predecessors in whatever order Ranges::iter 4482c409535SJamey Sharp // returns them; regalloc2 doesn't care. 4490f4c0d4aSJamey Sharp self.vcode.block_preds.resize(end, BlockIndex::invalid()); 4502c409535SJamey Sharp for (pred, range) in self.vcode.block_succ_range.iter() { 451a0318f36SChris Fallin let pred = BlockIndex::new(pred); 4522c409535SJamey Sharp for succ in &self.vcode.block_succs[range] { 4530f4c0d4aSJamey Sharp let pos = &mut starts[succ.index()]; 4540f4c0d4aSJamey Sharp self.vcode.block_preds[*pos as usize] = pred; 4550f4c0d4aSJamey Sharp *pos += 1; 456a0318f36SChris Fallin } 457a0318f36SChris Fallin } 4580f4c0d4aSJamey Sharp debug_assert!(self.vcode.block_preds.iter().all(|pred| pred.is_valid())); 459d8357426SChris Fallin } 460d8357426SChris Fallin 461a0318f36SChris Fallin /// Called once, when a build in Backward order is complete, to 462a0318f36SChris Fallin /// perform the overall reversal (into final forward order) and 463a0318f36SChris Fallin /// finalize metadata accordingly. 4643aa32064SJamey Sharp fn reverse_and_finalize(&mut self, vregs: &VRegAllocator<I>) { 465a0318f36SChris Fallin let n_insts = self.vcode.insts.len(); 466a0318f36SChris Fallin if n_insts == 0 { 467a0318f36SChris Fallin return; 468a0318f36SChris Fallin } 469a0318f36SChris Fallin 470a0318f36SChris Fallin // Reverse the per-block and per-inst sequences. 4712c409535SJamey Sharp self.vcode.block_ranges.reverse_index(); 4722c409535SJamey Sharp self.vcode.block_ranges.reverse_target(n_insts); 473a0318f36SChris Fallin // block_params_range is indexed by block (and blocks were 474a0318f36SChris Fallin // traversed in reverse) so we reverse it; but block-param 475a0318f36SChris Fallin // sequences in the concatenated vec can remain in reverse 476a0318f36SChris Fallin // order (it is effectively an arena of arbitrarily-placed 477a0318f36SChris Fallin // referenced sequences). 4782c409535SJamey Sharp self.vcode.block_params_range.reverse_index(); 479a0318f36SChris Fallin // Likewise, we reverse block_succ_range, but the block_succ 480a0318f36SChris Fallin // concatenated array can remain as-is. 4812c409535SJamey Sharp self.vcode.block_succ_range.reverse_index(); 482a0318f36SChris Fallin self.vcode.insts.reverse(); 483a0318f36SChris Fallin self.vcode.srclocs.reverse(); 484a0318f36SChris Fallin // Likewise, branch_block_arg_succ_range is indexed by block 485a0318f36SChris Fallin // so must be reversed. 4862c409535SJamey Sharp self.vcode.branch_block_arg_succ_range.reverse_index(); 487a0318f36SChris Fallin 488a0318f36SChris Fallin // To translate an instruction index *endpoint* in reversed 489a0318f36SChris Fallin // order to forward order, compute `n_insts - i`. 490a0318f36SChris Fallin // 491a0318f36SChris Fallin // Why not `n_insts - 1 - i`? That would be correct to 492a0318f36SChris Fallin // translate an individual instruction index (for ten insts 0 493a0318f36SChris Fallin // to 9 inclusive, inst 0 becomes 9, and inst 9 becomes 494a0318f36SChris Fallin // 0). But for the usual inclusive-start, exclusive-end range 495a0318f36SChris Fallin // idiom, inclusive starts become exclusive ends and 496a0318f36SChris Fallin // vice-versa, so e.g. an (inclusive) start of 0 becomes an 497a0318f36SChris Fallin // (exclusive) end of 10. 498a0318f36SChris Fallin let translate = |inst: InsnIndex| InsnIndex::new(n_insts - inst.index()); 499a0318f36SChris Fallin 500a0318f36SChris Fallin // Generate debug-value labels based on per-label maps. 501a0318f36SChris Fallin for (label, tuples) in &self.debug_info { 502a0318f36SChris Fallin for &(start, end, vreg) in tuples { 5033aa32064SJamey Sharp let vreg = vregs.resolve_vreg_alias(vreg); 504a0318f36SChris Fallin let fwd_start = translate(end); 505a0318f36SChris Fallin let fwd_end = translate(start); 506a0318f36SChris Fallin self.vcode 507a0318f36SChris Fallin .debug_value_labels 508a0318f36SChris Fallin .push((vreg, fwd_start, fwd_end, label.as_u32())); 509a0318f36SChris Fallin } 510a0318f36SChris Fallin } 511a0318f36SChris Fallin 512a0318f36SChris Fallin // Now sort debug value labels by VReg, as required 513a0318f36SChris Fallin // by regalloc2. 514a0318f36SChris Fallin self.vcode 515a0318f36SChris Fallin .debug_value_labels 516a0318f36SChris Fallin .sort_unstable_by_key(|(vreg, _, _, _)| *vreg); 517a0318f36SChris Fallin } 518a0318f36SChris Fallin 5193aa32064SJamey Sharp fn collect_operands(&mut self, vregs: &VRegAllocator<I>) { 520*5ded0f4eSUlrich Weigand let allocatable = PRegSet::from(self.vcode.abi.machine_env()); 521d180b907SJamey Sharp for (i, insn) in self.vcode.insts.iter_mut().enumerate() { 522a0318f36SChris Fallin // Push operands from the instruction onto the operand list. 523a0318f36SChris Fallin // 524a0318f36SChris Fallin // We rename through the vreg alias table as we collect 525a0318f36SChris Fallin // the operands. This is better than a separate post-pass 526a0318f36SChris Fallin // over operands, because it has more cache locality: 527a0318f36SChris Fallin // operands only need to pass through L1 once. This is 528a0318f36SChris Fallin // also better than renaming instructions' 529a0318f36SChris Fallin // operands/registers while lowering, because here we only 530a0318f36SChris Fallin // need to do the `match` over the instruction to visit 531a0318f36SChris Fallin // its register fields (which is slow, branchy code) once. 532a0318f36SChris Fallin 533a007e02bSTrevor Elliott let mut op_collector = 534a007e02bSTrevor Elliott OperandCollector::new(&mut self.vcode.operands, allocatable, |vreg| { 5353aa32064SJamey Sharp vregs.resolve_vreg_alias(vreg) 536a0318f36SChris Fallin }); 537a0318f36SChris Fallin insn.get_operands(&mut op_collector); 538a0318f36SChris Fallin let (ops, clobbers) = op_collector.finish(); 5392c409535SJamey Sharp self.vcode.operand_ranges.push_end(ops); 540a0318f36SChris Fallin 541b2e28b91SChris Fallin if clobbers != PRegSet::default() { 542b2e28b91SChris Fallin self.vcode.clobbers.insert(InsnIndex::new(i), clobbers); 543a0318f36SChris Fallin } 544a0318f36SChris Fallin 545a0318f36SChris Fallin if let Some((dst, src)) = insn.is_move() { 546fac4a915STrevor Elliott // We should never see non-virtual registers present in move 547fac4a915STrevor Elliott // instructions. 548fac4a915STrevor Elliott assert!( 549fac4a915STrevor Elliott src.is_virtual(), 550a0442ea0SHamir Mahal "the real register {src:?} was used as the source of a move instruction" 551fac4a915STrevor Elliott ); 552fac4a915STrevor Elliott assert!( 553fac4a915STrevor Elliott dst.to_reg().is_virtual(), 554fac4a915STrevor Elliott "the real register {:?} was used as the destination of a move instruction", 555fac4a915STrevor Elliott dst.to_reg() 556fac4a915STrevor Elliott ); 557a0318f36SChris Fallin } 558a0318f36SChris Fallin } 559a0318f36SChris Fallin 560a0318f36SChris Fallin // Translate blockparam args via the vreg aliases table as well. 561a0318f36SChris Fallin for arg in &mut self.vcode.branch_block_args { 5623aa32064SJamey Sharp let new_arg = vregs.resolve_vreg_alias(*arg); 5638d022434SBenjamin Bouvier trace!("operandcollector: block arg {:?} -> {:?}", arg, new_arg); 564a0318f36SChris Fallin *arg = new_arg; 565a0318f36SChris Fallin } 566a0318f36SChris Fallin } 567a0318f36SChris Fallin 568a0318f36SChris Fallin /// Build the final VCode. 5693aa32064SJamey Sharp pub fn build(mut self, mut vregs: VRegAllocator<I>) -> VCode<I> { 5703aa32064SJamey Sharp self.vcode.vreg_types = take(&mut vregs.vreg_types); 5713aa32064SJamey Sharp self.vcode.facts = take(&mut vregs.facts); 572d94173eaSTrevor Elliott 573a0318f36SChris Fallin if self.direction == VCodeBuildDirection::Backward { 5743aa32064SJamey Sharp self.reverse_and_finalize(&vregs); 575a0318f36SChris Fallin } 5763aa32064SJamey Sharp self.collect_operands(&vregs); 5772154c63dSAlex Crichton 578a0318f36SChris Fallin self.compute_preds_from_succs(); 579a0318f36SChris Fallin self.vcode.debug_value_labels.sort_unstable(); 580d180b907SJamey Sharp 5813aa32064SJamey Sharp // At this point, nothing in the vcode should mention any 5823aa32064SJamey Sharp // VReg which has been aliased. All the appropriate rewriting 5833aa32064SJamey Sharp // should have happened above. Just to be sure, let's 5843aa32064SJamey Sharp // double-check each field which has vregs. 5853aa32064SJamey Sharp // Note: can't easily check vcode.insts, resolved in collect_operands. 5863aa32064SJamey Sharp // Operands are resolved in collect_operands. 5873aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases(self.vcode.operands.iter().map(|op| op.vreg())); 5883aa32064SJamey Sharp // Currently block params are never aliased to another vreg. 5893aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases(self.vcode.block_params.iter().copied()); 5903aa32064SJamey Sharp // Branch block args are resolved in collect_operands. 5913aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases(self.vcode.branch_block_args.iter().copied()); 5923aa32064SJamey Sharp // Debug value labels are resolved in reverse_and_finalize. 5933aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases( 5943aa32064SJamey Sharp self.vcode.debug_value_labels.iter().map(|&(vreg, ..)| vreg), 5953aa32064SJamey Sharp ); 5963aa32064SJamey Sharp // Facts are resolved eagerly during set_vreg_alias. 5973aa32064SJamey Sharp vregs.debug_assert_no_vreg_aliases( 5983aa32064SJamey Sharp self.vcode 5993aa32064SJamey Sharp .facts 6003aa32064SJamey Sharp .iter() 6013aa32064SJamey Sharp .zip(&vregs.vreg_types) 6023aa32064SJamey Sharp .enumerate() 6033aa32064SJamey Sharp .filter(|(_, (fact, _))| fact.is_some()) 6043aa32064SJamey Sharp .map(|(vreg, (_, &ty))| { 6053aa32064SJamey Sharp let (regclasses, _) = I::rc_for_type(ty).unwrap(); 6063aa32064SJamey Sharp VReg::new(vreg, regclasses[0]) 6073aa32064SJamey Sharp }), 6083aa32064SJamey Sharp ); 6093aa32064SJamey Sharp 610a0318f36SChris Fallin self.vcode 611d8357426SChris Fallin } 612e20b4244SNick Fitzgerald 613e20b4244SNick Fitzgerald /// Add a user stack map for the associated instruction. 614e20b4244SNick Fitzgerald pub fn add_user_stack_map( 615e20b4244SNick Fitzgerald &mut self, 616e20b4244SNick Fitzgerald inst: BackwardsInsnIndex, 617e20b4244SNick Fitzgerald entries: &[ir::UserStackMapEntry], 618e20b4244SNick Fitzgerald ) { 619e20b4244SNick Fitzgerald let stack_map = ir::UserStackMap::new(entries, self.vcode.abi.sized_stackslot_offsets()); 620e20b4244SNick Fitzgerald let old_entry = self.vcode.user_stack_maps.insert(inst, stack_map); 621e20b4244SNick Fitzgerald debug_assert!(old_entry.is_none()); 622e20b4244SNick Fitzgerald } 623d8357426SChris Fallin } 624d8357426SChris Fallin 625d4a4d4f9SSingleAccretion const NO_INST_OFFSET: CodeOffset = u32::MAX; 626d4a4d4f9SSingleAccretion 627d8357426SChris Fallin impl<I: VCodeInst> VCode<I> { 628d8357426SChris Fallin /// New empty VCode. 629c5bbc874SBenjamin Bouvier fn new( 630f18a1f14SNick Fitzgerald sigs: SigSet, 631f0c60f46SNick Fitzgerald abi: Callee<I::ABIMachineSpec>, 632c5bbc874SBenjamin Bouvier emit_info: I::Info, 633c5bbc874SBenjamin Bouvier block_order: BlockLoweringOrder, 63483f182b3SAndrew Brown constants: VCodeConstants, 6352af0a1f7Sbjorn3 log2_min_function_alignment: u8, 636e20b4244SNick Fitzgerald ) -> Self { 637a0318f36SChris Fallin let n_blocks = block_order.lowered_order().len(); 638d8357426SChris Fallin VCode { 639f18a1f14SNick Fitzgerald sigs, 640d8357426SChris Fallin vreg_types: vec![], 641a0318f36SChris Fallin insts: Vec::with_capacity(10 * n_blocks), 642e20b4244SNick Fitzgerald user_stack_maps: FxHashMap::default(), 643a0318f36SChris Fallin operands: Vec::with_capacity(30 * n_blocks), 6442c409535SJamey Sharp operand_ranges: Ranges::with_capacity(10 * n_blocks), 645b2e28b91SChris Fallin clobbers: FxHashMap::default(), 646a0318f36SChris Fallin srclocs: Vec::with_capacity(10 * n_blocks), 647a0318f36SChris Fallin entry: BlockIndex::new(0), 6482c409535SJamey Sharp block_ranges: Ranges::with_capacity(n_blocks), 6492c409535SJamey Sharp block_succ_range: Ranges::with_capacity(n_blocks), 6500f4c0d4aSJamey Sharp block_succs: Vec::with_capacity(n_blocks), 6512c409535SJamey Sharp block_pred_range: Ranges::default(), 6520f4c0d4aSJamey Sharp block_preds: Vec::new(), 6532c409535SJamey Sharp block_params_range: Ranges::with_capacity(n_blocks), 654a0318f36SChris Fallin block_params: Vec::with_capacity(5 * n_blocks), 655a0318f36SChris Fallin branch_block_args: Vec::with_capacity(10 * n_blocks), 6562c409535SJamey Sharp branch_block_arg_range: Ranges::with_capacity(2 * n_blocks), 6572c409535SJamey Sharp branch_block_arg_succ_range: Ranges::with_capacity(n_blocks), 65872e6be93SChris Fallin block_order, 659d8357426SChris Fallin abi, 660c5bbc874SBenjamin Bouvier emit_info, 66183f182b3SAndrew Brown constants, 662a0318f36SChris Fallin debug_value_labels: vec![], 663f466aa26SChris Fallin facts: vec![], 6642af0a1f7Sbjorn3 log2_min_function_alignment, 665d8357426SChris Fallin } 666d8357426SChris Fallin } 667d8357426SChris Fallin 668d8357426SChris Fallin /// Get the number of blocks. Block indices will be in the range `0 .. 669d8357426SChris Fallin /// (self.num_blocks() - 1)`. 670d8357426SChris Fallin pub fn num_blocks(&self) -> usize { 671d8357426SChris Fallin self.block_ranges.len() 672d8357426SChris Fallin } 673d8357426SChris Fallin 6746fe69d00SNick Fitzgerald /// The number of lowered instructions. 6756fe69d00SNick Fitzgerald pub fn num_insts(&self) -> usize { 6766fe69d00SNick Fitzgerald self.insts.len() 6776fe69d00SNick Fitzgerald } 6786fe69d00SNick Fitzgerald 679a0318f36SChris Fallin fn compute_clobbers(&self, regalloc: ®alloc2::Output) -> Vec<Writable<RealReg>> { 6801a17dfb5SJamey Sharp let mut clobbered = PRegSet::default(); 681d8357426SChris Fallin 682a0318f36SChris Fallin // All moves are included in clobbers. 6831a17dfb5SJamey Sharp for (_, Edit::Move { to, .. }) in ®alloc.edits { 684a0318f36SChris Fallin if let Some(preg) = to.as_reg() { 6851a17dfb5SJamey Sharp clobbered.add(preg); 686a0318f36SChris Fallin } 687d8357426SChris Fallin } 688d8357426SChris Fallin 6892c409535SJamey Sharp for (i, range) in self.operand_ranges.iter() { 6902c409535SJamey Sharp let operands = &self.operands[range.clone()]; 6912c409535SJamey Sharp let allocs = ®alloc.allocs[range]; 692a0318f36SChris Fallin for (operand, alloc) in operands.iter().zip(allocs.iter()) { 6931a17dfb5SJamey Sharp if operand.kind() == OperandKind::Def { 694a0318f36SChris Fallin if let Some(preg) = alloc.as_reg() { 6951a17dfb5SJamey Sharp clobbered.add(preg); 696a0318f36SChris Fallin } 69708353fccSChris Fallin } 698d8357426SChris Fallin } 699d8357426SChris Fallin 700a0318f36SChris Fallin // Also add explicitly-clobbered registers. 701a62b396fSChris Fallin // 702a62b396fSChris Fallin // Skip merging this instruction's clobber list if not 703a62b396fSChris Fallin // "included in clobbers" as per the MachInst. (Some 704a62b396fSChris Fallin // backends use this to implement ABI specifics; e.g., 705a62b396fSChris Fallin // excluding calls of the same ABI as the current function 706a62b396fSChris Fallin // from clobbers, because by definition everything 707a62b396fSChris Fallin // clobbered by the call can be clobbered by this function 708a62b396fSChris Fallin // without saving as well. 709a62b396fSChris Fallin // 710a62b396fSChris Fallin // This is important for a particular optimization: when 711a62b396fSChris Fallin // some registers are "half-clobbered", e.g. vector/float 712a62b396fSChris Fallin // registers on aarch64, we want them to be seen as 713a62b396fSChris Fallin // clobbered by regalloc so it avoids carrying values 714a62b396fSChris Fallin // across calls in these registers but not seen as 715a62b396fSChris Fallin // clobbered by prologue generation here (because the 716a62b396fSChris Fallin // actual half-clobber implied by the clobber list fits 717a62b396fSChris Fallin // within the clobbers that we allow without 718a62b396fSChris Fallin // clobber-saves). 719a62b396fSChris Fallin if self.insts[i].is_included_in_clobbers() { 7201a17dfb5SJamey Sharp if let Some(&inst_clobbered) = self.clobbers.get(&InsnIndex::new(i)) { 7211a17dfb5SJamey Sharp clobbered.union_from(inst_clobbered); 722a0318f36SChris Fallin } 723a0318f36SChris Fallin } 724a62b396fSChris Fallin } 725d8357426SChris Fallin 726a0318f36SChris Fallin clobbered 7271a17dfb5SJamey Sharp .into_iter() 7281a17dfb5SJamey Sharp .map(|preg| Writable::from_reg(RealReg::from(preg))) 7291a17dfb5SJamey Sharp .collect() 730d8357426SChris Fallin } 731d8357426SChris Fallin 732a0318f36SChris Fallin /// Emit the instructions to a `MachBuffer`, containing fixed-up 733a0318f36SChris Fallin /// code and external reloc/trap/etc. records ready for use. Takes 734a0318f36SChris Fallin /// the regalloc results as well. 735a0318f36SChris Fallin /// 736a0318f36SChris Fallin /// Returns the machine code itself, and optionally metadata 737a0318f36SChris Fallin /// and/or a disassembly, as an `EmitResult`. The `VCode` itself 738a0318f36SChris Fallin /// is consumed by the emission process. 73911a2ef01SChris Fallin pub fn emit( 740a0318f36SChris Fallin mut self, 741a0318f36SChris Fallin regalloc: ®alloc2::Output, 742a0318f36SChris Fallin want_disasm: bool, 74349dd8fd7SAlex Crichton flags: &settings::Flags, 7447eb89140SRemo Senekowitsch ctrl_plane: &mut ControlPlane, 74549dd8fd7SAlex Crichton ) -> EmitResult 746d8357426SChris Fallin where 747f18a1f14SNick Fitzgerald I: VCodeInst, 748d8357426SChris Fallin { 7492b9fefe8SChris Fallin let _tt = timing::vcode_emit(); 75072e6be93SChris Fallin let mut buffer = MachBuffer::new(); 7512af0a1f7Sbjorn3 buffer.set_log2_min_function_alignment(self.log2_min_function_alignment); 75211a2ef01SChris Fallin let mut bb_starts: Vec<Option<CodeOffset>> = vec![]; 753d8357426SChris Fallin 75449dd8fd7SAlex Crichton // The first M MachLabels are reserved for block indices. 755a0318f36SChris Fallin buffer.reserve_labels_for_blocks(self.num_blocks()); 75649dd8fd7SAlex Crichton 75749dd8fd7SAlex Crichton // Register all allocated constants with the `MachBuffer` to ensure that 75849dd8fd7SAlex Crichton // any references to the constants during instructions can be handled 75949dd8fd7SAlex Crichton // correctly. 76049dd8fd7SAlex Crichton buffer.register_constants(&self.constants); 761d8357426SChris Fallin 762ef1b2d2fSChris Fallin // Construct the final order we emit code in: cold blocks at the end. 763ef1b2d2fSChris Fallin let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![]; 764ef1b2d2fSChris Fallin let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![]; 765ef1b2d2fSChris Fallin for block in 0..self.num_blocks() { 766a0318f36SChris Fallin let block = BlockIndex::new(block); 767ef1b2d2fSChris Fallin if self.block_order.is_cold(block) { 768ef1b2d2fSChris Fallin cold_blocks.push(block); 769ef1b2d2fSChris Fallin } else { 770ef1b2d2fSChris Fallin final_order.push(block); 771ef1b2d2fSChris Fallin } 772ef1b2d2fSChris Fallin } 773d9d64694SChris Fallin final_order.extend(cold_blocks.clone()); 774ef1b2d2fSChris Fallin 775a0318f36SChris Fallin // Compute/save info we need for the prologue: clobbers and 776a0318f36SChris Fallin // number of spillslots. 777a0318f36SChris Fallin // 778a0318f36SChris Fallin // We clone `abi` here because we will mutate it as we 779a0318f36SChris Fallin // generate the prologue and set other info, but we can't 780a0318f36SChris Fallin // mutate `VCode`. The info it usually carries prior to 781a0318f36SChris Fallin // setting clobbers is fairly minimal so this should be 782a0318f36SChris Fallin // relatively cheap. 783a0318f36SChris Fallin let clobbers = self.compute_clobbers(regalloc); 7845d4e319cSJamey Sharp self.abi 7855d4e319cSJamey Sharp .compute_frame_layout(&self.sigs, regalloc.num_spillslots, clobbers); 786a0318f36SChris Fallin 787ef1b2d2fSChris Fallin // Emit blocks. 788964c6087SChris Fallin let mut cur_srcloc = None; 78911a2ef01SChris Fallin let mut last_offset = None; 790a0318f36SChris Fallin let mut inst_offsets = vec![]; 7917eb89140SRemo Senekowitsch let mut state = I::State::new(&self.abi, std::mem::take(ctrl_plane)); 792a0318f36SChris Fallin 793a0318f36SChris Fallin let mut disasm = String::new(); 794a0318f36SChris Fallin 795a0318f36SChris Fallin if !self.debug_value_labels.is_empty() { 796d4a4d4f9SSingleAccretion inst_offsets.resize(self.insts.len(), NO_INST_OFFSET); 797a0318f36SChris Fallin } 798a0318f36SChris Fallin 799863659e0SChris Fallin // Count edits per block ahead of time; this is needed for 800863659e0SChris Fallin // lookahead island emission. (We could derive it per-block 801863659e0SChris Fallin // with binary search in the edit list, but it's more 802863659e0SChris Fallin // efficient to do it in one pass here.) 803863659e0SChris Fallin let mut ra_edits_per_block: SmallVec<[u32; 64]> = smallvec![]; 804863659e0SChris Fallin let mut edit_idx = 0; 805863659e0SChris Fallin for block in 0..self.num_blocks() { 8062c409535SJamey Sharp let end_inst = InsnIndex::new(self.block_ranges.get(block).end); 807863659e0SChris Fallin let start_edit_idx = edit_idx; 808863659e0SChris Fallin while edit_idx < regalloc.edits.len() && regalloc.edits[edit_idx].0.inst() < end_inst { 809863659e0SChris Fallin edit_idx += 1; 810863659e0SChris Fallin } 811863659e0SChris Fallin let end_edit_idx = edit_idx; 812863659e0SChris Fallin ra_edits_per_block.push((end_edit_idx - start_edit_idx) as u32); 813863659e0SChris Fallin } 814863659e0SChris Fallin 815d8b29089SAnton Kirilov let is_forward_edge_cfi_enabled = self.abi.is_forward_edge_cfi_enabled(); 816475d1ba5SAlex Crichton let mut bb_padding = match flags.bb_padding_log2_minus_one() { 81749dd8fd7SAlex Crichton 0 => Vec::new(), 81849dd8fd7SAlex Crichton n => vec![0; 1 << (n - 1)], 81949dd8fd7SAlex Crichton }; 820475d1ba5SAlex Crichton let mut total_bb_padding = 0; 821d8b29089SAnton Kirilov 822863659e0SChris Fallin for (block_order_idx, &block) in final_order.iter().enumerate() { 8238d022434SBenjamin Bouvier trace!("emitting block {:?}", block); 82460e4a004SAfonso Bordado 82560e4a004SAfonso Bordado // Call the new block hook for state 82660e4a004SAfonso Bordado state.on_new_block(); 82760e4a004SAfonso Bordado 82860e4a004SAfonso Bordado // Emit NOPs to align the block. 82972e6be93SChris Fallin let new_offset = I::align_basic_block(buffer.cur_offset()); 83072e6be93SChris Fallin while new_offset > buffer.cur_offset() { 831d8357426SChris Fallin // Pad with NOPs up to the aligned block offset. 83272e6be93SChris Fallin let nop = I::gen_nop((new_offset - buffer.cur_offset()) as usize); 8337d703191SJamey Sharp nop.emit(&mut buffer, &self.emit_info, &mut Default::default()); 834d8357426SChris Fallin } 83572e6be93SChris Fallin assert_eq!(buffer.cur_offset(), new_offset); 836d8357426SChris Fallin 837a0318f36SChris Fallin let do_emit = |inst: &I, 838a0318f36SChris Fallin disasm: &mut String, 839a0318f36SChris Fallin buffer: &mut MachBuffer<I>, 840a0318f36SChris Fallin state: &mut I::State| { 8412986f6b0SChris Fallin if want_disasm && !inst.is_args() { 842a0318f36SChris Fallin let mut s = state.clone(); 8437d703191SJamey Sharp writeln!(disasm, " {}", inst.pretty_print_inst(&mut s)).unwrap(); 844a0318f36SChris Fallin } 8457d703191SJamey Sharp inst.emit(buffer, &self.emit_info, state); 846a0318f36SChris Fallin }; 847a0318f36SChris Fallin 848a0318f36SChris Fallin // Is this the first block? Emit the prologue directly if so. 849a0318f36SChris Fallin if block == self.entry { 8508d022434SBenjamin Bouvier trace!(" -> entry block"); 8518a9b1a90SBenjamin Bouvier buffer.start_srcloc(Default::default()); 85286652959SUlrich Weigand for inst in &self.abi.gen_prologue() { 8537d703191SJamey Sharp do_emit(&inst, &mut disasm, &mut buffer, &mut state); 854a0318f36SChris Fallin } 855a0318f36SChris Fallin buffer.end_srcloc(); 856d9d64694SChris Fallin } 857d9d64694SChris Fallin 858a0318f36SChris Fallin // Now emit the regular block body. 85911a2ef01SChris Fallin 8607eb89140SRemo Senekowitsch buffer.bind_label(MachLabel::from_block(block), state.ctrl_plane_mut()); 861a0318f36SChris Fallin 862a0318f36SChris Fallin if want_disasm { 863a0318f36SChris Fallin writeln!(&mut disasm, "block{}:", block.index()).unwrap(); 864a0318f36SChris Fallin } 865a0318f36SChris Fallin 86649dd8fd7SAlex Crichton if flags.machine_code_cfg_info() { 86711a2ef01SChris Fallin // Track BB starts. If we have backed up due to MachBuffer 86811a2ef01SChris Fallin // branch opts, note that the removed blocks were removed. 86911a2ef01SChris Fallin let cur_offset = buffer.cur_offset(); 87011a2ef01SChris Fallin if last_offset.is_some() && cur_offset <= last_offset.unwrap() { 87111a2ef01SChris Fallin for i in (0..bb_starts.len()).rev() { 87211a2ef01SChris Fallin if bb_starts[i].is_some() && cur_offset > bb_starts[i].unwrap() { 87311a2ef01SChris Fallin break; 87411a2ef01SChris Fallin } 87511a2ef01SChris Fallin bb_starts[i] = None; 87611a2ef01SChris Fallin } 87711a2ef01SChris Fallin } 87811a2ef01SChris Fallin bb_starts.push(Some(cur_offset)); 87911a2ef01SChris Fallin last_offset = Some(cur_offset); 880800cf25bSChris Fallin } 88111a2ef01SChris Fallin 882d8b29089SAnton Kirilov if let Some(block_start) = I::gen_block_start( 883d8b29089SAnton Kirilov self.block_order.is_indirect_branch_target(block), 884d8b29089SAnton Kirilov is_forward_edge_cfi_enabled, 885d8b29089SAnton Kirilov ) { 8867d703191SJamey Sharp do_emit(&block_start, &mut disasm, &mut buffer, &mut state); 887d8b29089SAnton Kirilov } 888d8b29089SAnton Kirilov 889a0318f36SChris Fallin for inst_or_edit in regalloc.block_insts_and_edits(&self, block) { 890a0318f36SChris Fallin match inst_or_edit { 891a0318f36SChris Fallin InstOrEdit::Inst(iix) => { 892a0318f36SChris Fallin if !self.debug_value_labels.is_empty() { 893a0318f36SChris Fallin // If we need to produce debug info, 894a0318f36SChris Fallin // record the offset of each instruction 895a0318f36SChris Fallin // so that we can translate value-label 896a0318f36SChris Fallin // ranges to machine-code offsets. 897a0318f36SChris Fallin 898a0318f36SChris Fallin // Cold blocks violate monotonicity 899a0318f36SChris Fallin // assumptions elsewhere (that 900a0318f36SChris Fallin // instructions in inst-index order are in 901a0318f36SChris Fallin // order in machine code), so we omit 902a0318f36SChris Fallin // their offsets here. Value-label range 903a0318f36SChris Fallin // generation below will skip empty ranges 904a0318f36SChris Fallin // and ranges with to-offsets of zero. 905a0318f36SChris Fallin if !self.block_order.is_cold(block) { 906a0318f36SChris Fallin inst_offsets[iix.index()] = buffer.cur_offset(); 907a0318f36SChris Fallin } 908a0318f36SChris Fallin } 909a0318f36SChris Fallin 910a0318f36SChris Fallin // Update the srcloc at this point in the buffer. 911a0318f36SChris Fallin let srcloc = self.srclocs[iix.index()]; 912964c6087SChris Fallin if cur_srcloc != Some(srcloc) { 913964c6087SChris Fallin if cur_srcloc.is_some() { 91472e6be93SChris Fallin buffer.end_srcloc(); 915b691770fSChris Fallin } 91672e6be93SChris Fallin buffer.start_srcloc(srcloc); 917964c6087SChris Fallin cur_srcloc = Some(srcloc); 918b691770fSChris Fallin } 919b691770fSChris Fallin 920a0318f36SChris Fallin // If this is a safepoint, compute a stack map 921a0318f36SChris Fallin // and pass it to the emit state. 922e20b4244SNick Fitzgerald let stack_map_disasm = if self.insts[iix.index()].is_safepoint() { 923e20b4244SNick Fitzgerald let (user_stack_map, user_stack_map_disasm) = { 924e20b4244SNick Fitzgerald // The `user_stack_maps` is keyed by reverse 925e20b4244SNick Fitzgerald // instruction index, so we must flip the 926e20b4244SNick Fitzgerald // index. We can't put this into a helper method 927e20b4244SNick Fitzgerald // due to borrowck issues because parts of 928e20b4244SNick Fitzgerald // `self` are borrowed mutably elsewhere in this 929e20b4244SNick Fitzgerald // function. 930e20b4244SNick Fitzgerald let index = iix.to_backwards_insn_index(self.num_insts()); 931e20b4244SNick Fitzgerald let user_stack_map = self.user_stack_maps.remove(&index); 932e20b4244SNick Fitzgerald let user_stack_map_disasm = 933e20b4244SNick Fitzgerald user_stack_map.as_ref().map(|m| format!(" ; {m:?}")); 934e20b4244SNick Fitzgerald (user_stack_map, user_stack_map_disasm) 935e20b4244SNick Fitzgerald }; 936e20b4244SNick Fitzgerald 937c0c3a68cSNick Fitzgerald state.pre_safepoint(user_stack_map); 938e20b4244SNick Fitzgerald 939e20b4244SNick Fitzgerald user_stack_map_disasm 940e20b4244SNick Fitzgerald } else { 941e20b4244SNick Fitzgerald None 942e20b4244SNick Fitzgerald }; 94308353fccSChris Fallin 944a0318f36SChris Fallin // If the instruction we are about to emit is 945a0318f36SChris Fallin // a return, place an epilogue at this point 946a0318f36SChris Fallin // (and don't emit the return; the actual 947a0318f36SChris Fallin // epilogue will contain it). 948a0318f36SChris Fallin if self.insts[iix.index()].is_term() == MachTerminator::Ret { 94986652959SUlrich Weigand for inst in self.abi.gen_epilogue() { 9507d703191SJamey Sharp do_emit(&inst, &mut disasm, &mut buffer, &mut state); 951a0318f36SChris Fallin } 952c84d6be6SChris Fallin } else { 953d48d6102SJamey Sharp // Update the operands for this inst using the 954d48d6102SJamey Sharp // allocations from the regalloc result. 955d48d6102SJamey Sharp let mut allocs = regalloc.inst_allocs(iix).iter(); 956d48d6102SJamey Sharp self.insts[iix.index()].get_operands( 957d48d6102SJamey Sharp &mut |reg: &mut Reg, constraint, _kind, _pos| { 958a62b396fSChris Fallin let alloc = 959a62b396fSChris Fallin allocs.next().expect("enough allocations for all operands"); 960d48d6102SJamey Sharp 961a62b396fSChris Fallin if let Some(alloc) = alloc.as_reg() { 962a62b396fSChris Fallin let alloc: Reg = alloc.into(); 963d48d6102SJamey Sharp if let OperandConstraint::FixedReg(rreg) = constraint { 964d48d6102SJamey Sharp debug_assert_eq!(Reg::from(rreg), alloc); 965d48d6102SJamey Sharp } 966d48d6102SJamey Sharp *reg = alloc; 967a62b396fSChris Fallin } else if let Some(alloc) = alloc.as_stack() { 968a62b396fSChris Fallin let alloc: Reg = alloc.into(); 969a62b396fSChris Fallin *reg = alloc; 970a62b396fSChris Fallin } 971d48d6102SJamey Sharp }, 972d48d6102SJamey Sharp ); 973d48d6102SJamey Sharp debug_assert!(allocs.next().is_none()); 974d48d6102SJamey Sharp 975a0318f36SChris Fallin // Emit the instruction! 976a0318f36SChris Fallin do_emit( 977a0318f36SChris Fallin &self.insts[iix.index()], 978a0318f36SChris Fallin &mut disasm, 979a0318f36SChris Fallin &mut buffer, 980a0318f36SChris Fallin &mut state, 981a0318f36SChris Fallin ); 982e20b4244SNick Fitzgerald if let Some(stack_map_disasm) = stack_map_disasm { 983e20b4244SNick Fitzgerald disasm.push_str(&stack_map_disasm); 984e20b4244SNick Fitzgerald disasm.push('\n'); 985e20b4244SNick Fitzgerald } 986c84d6be6SChris Fallin } 987c84d6be6SChris Fallin } 988a0318f36SChris Fallin 989a0318f36SChris Fallin InstOrEdit::Edit(Edit::Move { from, to }) => { 990a0318f36SChris Fallin // Create a move/spill/reload instruction and 991a0318f36SChris Fallin // immediately emit it. 992a0318f36SChris Fallin match (from.as_reg(), to.as_reg()) { 993a0318f36SChris Fallin (Some(from), Some(to)) => { 994a0318f36SChris Fallin // Reg-to-reg move. 995a0318f36SChris Fallin let from_rreg = Reg::from(from); 996a0318f36SChris Fallin let to_rreg = Writable::from_reg(Reg::from(to)); 997a0318f36SChris Fallin debug_assert_eq!(from.class(), to.class()); 998a0318f36SChris Fallin let ty = I::canonical_type_for_rc(from.class()); 999a0318f36SChris Fallin let mv = I::gen_move(to_rreg, from_rreg, ty); 10007d703191SJamey Sharp do_emit(&mv, &mut disasm, &mut buffer, &mut state); 1001a0318f36SChris Fallin } 1002a0318f36SChris Fallin (Some(from), None) => { 1003a0318f36SChris Fallin // Spill from register to spillslot. 1004a0318f36SChris Fallin let to = to.as_stack().unwrap(); 1005a0318f36SChris Fallin let from_rreg = RealReg::from(from); 1006a0318f36SChris Fallin let spill = self.abi.gen_spill(to, from_rreg); 10077d703191SJamey Sharp do_emit(&spill, &mut disasm, &mut buffer, &mut state); 1008a0318f36SChris Fallin } 1009a0318f36SChris Fallin (None, Some(to)) => { 1010a0318f36SChris Fallin // Load from spillslot to register. 1011a0318f36SChris Fallin let from = from.as_stack().unwrap(); 1012a0318f36SChris Fallin let to_rreg = Writable::from_reg(RealReg::from(to)); 1013a0318f36SChris Fallin let reload = self.abi.gen_reload(to_rreg, from); 10147d703191SJamey Sharp do_emit(&reload, &mut disasm, &mut buffer, &mut state); 1015a0318f36SChris Fallin } 1016a0318f36SChris Fallin (None, None) => { 1017a0318f36SChris Fallin panic!("regalloc2 should have eliminated stack-to-stack moves!"); 1018a0318f36SChris Fallin } 1019a0318f36SChris Fallin } 1020a0318f36SChris Fallin } 1021c84d6be6SChris Fallin } 1022d8357426SChris Fallin } 1023b691770fSChris Fallin 1024964c6087SChris Fallin if cur_srcloc.is_some() { 102572e6be93SChris Fallin buffer.end_srcloc(); 1026964c6087SChris Fallin cur_srcloc = None; 1027b691770fSChris Fallin } 102872e6be93SChris Fallin 102949dd8fd7SAlex Crichton // Do we need an island? Get the worst-case size of the next BB, add 103049dd8fd7SAlex Crichton // it to the optional padding behind the block, and pass this to the 103149dd8fd7SAlex Crichton // `MachBuffer` to determine if an island is necessary. 103249dd8fd7SAlex Crichton let worst_case_next_bb = if block_order_idx < final_order.len() - 1 { 1033863659e0SChris Fallin let next_block = final_order[block_order_idx + 1]; 10342c409535SJamey Sharp let next_block_range = self.block_ranges.get(next_block.index()); 10352c409535SJamey Sharp let next_block_size = next_block_range.len() as u32; 1036863659e0SChris Fallin let next_block_ra_insertions = ra_edits_per_block[next_block.index()]; 103749dd8fd7SAlex Crichton I::worst_case_size() * (next_block_size + next_block_ra_insertions) 103849dd8fd7SAlex Crichton } else { 103949dd8fd7SAlex Crichton 0 104049dd8fd7SAlex Crichton }; 104149dd8fd7SAlex Crichton let padding = if bb_padding.is_empty() { 104249dd8fd7SAlex Crichton 0 104349dd8fd7SAlex Crichton } else { 104449dd8fd7SAlex Crichton bb_padding.len() as u32 + I::LabelUse::ALIGN - 1 104549dd8fd7SAlex Crichton }; 104649dd8fd7SAlex Crichton if buffer.island_needed(padding + worst_case_next_bb) { 1047f8c03d5aSAlex Crichton buffer.emit_island(padding + worst_case_next_bb, ctrl_plane); 104872e6be93SChris Fallin } 104949dd8fd7SAlex Crichton 105049dd8fd7SAlex Crichton // Insert padding, if configured, to stress the `MachBuffer`'s 105149dd8fd7SAlex Crichton // relocation and island calculations. 1052475d1ba5SAlex Crichton // 1053475d1ba5SAlex Crichton // Padding can get quite large during fuzzing though so place a 1054475d1ba5SAlex Crichton // total cap on it where when a per-function threshold is exceeded 1055475d1ba5SAlex Crichton // the padding is turned back down to zero. This avoids a small-ish 1056475d1ba5SAlex Crichton // test case generating a GB+ memory footprint in Cranelift for 1057475d1ba5SAlex Crichton // example. 105849dd8fd7SAlex Crichton if !bb_padding.is_empty() { 105949dd8fd7SAlex Crichton buffer.put_data(&bb_padding); 106049dd8fd7SAlex Crichton buffer.align_to(I::LabelUse::ALIGN); 1061475d1ba5SAlex Crichton total_bb_padding += bb_padding.len(); 1062475d1ba5SAlex Crichton if total_bb_padding > (150 << 20) { 1063475d1ba5SAlex Crichton bb_padding = Vec::new(); 1064475d1ba5SAlex Crichton } 106572e6be93SChris Fallin } 1066d8357426SChris Fallin } 1067d8357426SChris Fallin 1068e20b4244SNick Fitzgerald debug_assert!( 1069e20b4244SNick Fitzgerald self.user_stack_maps.is_empty(), 1070e20b4244SNick Fitzgerald "any stack maps should have been consumed by instruction emission, still have: {:#?}", 1071e20b4244SNick Fitzgerald self.user_stack_maps, 1072e20b4244SNick Fitzgerald ); 1073e20b4244SNick Fitzgerald 1074d4a4d4f9SSingleAccretion // Do any optimizations on branches at tail of buffer, as if we had 1075d4a4d4f9SSingleAccretion // bound one last label. 1076d4a4d4f9SSingleAccretion buffer.optimize_branches(ctrl_plane); 1077d4a4d4f9SSingleAccretion 10787eb89140SRemo Senekowitsch // emission state is not needed anymore, move control plane back out 10797eb89140SRemo Senekowitsch *ctrl_plane = state.take_ctrl_plane(); 10807eb89140SRemo Senekowitsch 1081a0318f36SChris Fallin let func_body_len = buffer.cur_offset(); 1082de4af90aSYury Delendik 108311a2ef01SChris Fallin // Create `bb_edges` and final (filtered) `bb_starts`. 108411a2ef01SChris Fallin let mut bb_edges = vec![]; 1085a0318f36SChris Fallin let mut bb_offsets = vec![]; 108649dd8fd7SAlex Crichton if flags.machine_code_cfg_info() { 108711a2ef01SChris Fallin for block in 0..self.num_blocks() { 108811a2ef01SChris Fallin if bb_starts[block].is_none() { 108911a2ef01SChris Fallin // Block was deleted by MachBuffer; skip. 109011a2ef01SChris Fallin continue; 109111a2ef01SChris Fallin } 109211a2ef01SChris Fallin let from = bb_starts[block].unwrap(); 109311a2ef01SChris Fallin 1094a0318f36SChris Fallin bb_offsets.push(from); 109511a2ef01SChris Fallin // Resolve each `succ` label and add edges. 1096a0318f36SChris Fallin let succs = self.block_succs(BlockIndex::new(block)); 1097a0318f36SChris Fallin for &succ in succs.iter() { 1098a0318f36SChris Fallin let to = buffer.resolve_label_offset(MachLabel::from_block(succ)); 109911a2ef01SChris Fallin bb_edges.push((from, to)); 110011a2ef01SChris Fallin } 110111a2ef01SChris Fallin } 1102800cf25bSChris Fallin } 110311a2ef01SChris Fallin 1104d4a4d4f9SSingleAccretion self.monotonize_inst_offsets(&mut inst_offsets[..], func_body_len); 1105a0318f36SChris Fallin let value_labels_ranges = 1106a0318f36SChris Fallin self.compute_value_labels_ranges(regalloc, &inst_offsets[..], func_body_len); 1107a0318f36SChris Fallin let frame_size = self.abi.frame_size(); 1108a0318f36SChris Fallin 1109a0318f36SChris Fallin EmitResult { 111049dd8fd7SAlex Crichton buffer: buffer.finish(&self.constants, ctrl_plane), 1111a0318f36SChris Fallin bb_offsets, 1112a0318f36SChris Fallin bb_edges, 1113a0318f36SChris Fallin func_body_len, 1114a0318f36SChris Fallin disasm: if want_disasm { Some(disasm) } else { None }, 11159c43749dSSam Parker sized_stackslot_offsets: self.abi.sized_stackslot_offsets().clone(), 11169c43749dSSam Parker dynamic_stackslot_offsets: self.abi.dynamic_stackslot_offsets().clone(), 1117a0318f36SChris Fallin value_labels_ranges, 1118a0318f36SChris Fallin frame_size, 1119a0318f36SChris Fallin } 1120d8357426SChris Fallin } 1121d8357426SChris Fallin 1122d4a4d4f9SSingleAccretion fn monotonize_inst_offsets(&self, inst_offsets: &mut [CodeOffset], func_body_len: u32) { 1123d4a4d4f9SSingleAccretion if self.debug_value_labels.is_empty() { 1124d4a4d4f9SSingleAccretion return; 1125d4a4d4f9SSingleAccretion } 1126d4a4d4f9SSingleAccretion 1127d4a4d4f9SSingleAccretion // During emission, branch removal can make offsets of instructions incorrect. 1128d4a4d4f9SSingleAccretion // Consider the following sequence: [insi][jmp0][jmp1][jmp2][insj] 1129d4a4d4f9SSingleAccretion // It will be recorded as (say): [30] [34] [38] [42] [<would be 46>] 1130d4a4d4f9SSingleAccretion // When the jumps get removed we are left with (in "inst_offsets"): 1131d4a4d4f9SSingleAccretion // [insi][jmp0][jmp1][jmp2][insj][...] 1132d4a4d4f9SSingleAccretion // [30] [34] [38] [42] [34] 1133d4a4d4f9SSingleAccretion // Which violates the monotonicity invariant. This method sets offsets of these 1134d4a4d4f9SSingleAccretion // removed instructions such as to make them appear zero-sized: 1135d4a4d4f9SSingleAccretion // [insi][jmp0][jmp1][jmp2][insj][...] 1136d4a4d4f9SSingleAccretion // [30] [34] [34] [34] [34] 1137d4a4d4f9SSingleAccretion // 1138d4a4d4f9SSingleAccretion let mut next_offset = func_body_len; 1139d4a4d4f9SSingleAccretion for inst_index in (0..(inst_offsets.len() - 1)).rev() { 1140d4a4d4f9SSingleAccretion let inst_offset = inst_offsets[inst_index]; 1141d4a4d4f9SSingleAccretion 1142d4a4d4f9SSingleAccretion // Not all instructions get their offsets recorded. 1143d4a4d4f9SSingleAccretion if inst_offset == NO_INST_OFFSET { 1144d4a4d4f9SSingleAccretion continue; 1145d4a4d4f9SSingleAccretion } 1146d4a4d4f9SSingleAccretion 1147d4a4d4f9SSingleAccretion if inst_offset > next_offset { 1148d4a4d4f9SSingleAccretion trace!( 1149d4a4d4f9SSingleAccretion "Fixing code offset of the removed Inst {}: {} -> {}", 1150d4a4d4f9SSingleAccretion inst_index, 1151d4a4d4f9SSingleAccretion inst_offset, 1152d4a4d4f9SSingleAccretion next_offset 1153d4a4d4f9SSingleAccretion ); 1154d4a4d4f9SSingleAccretion inst_offsets[inst_index] = next_offset; 1155d4a4d4f9SSingleAccretion continue; 1156d4a4d4f9SSingleAccretion } 1157d4a4d4f9SSingleAccretion 1158d4a4d4f9SSingleAccretion next_offset = inst_offset; 1159d4a4d4f9SSingleAccretion } 1160d4a4d4f9SSingleAccretion } 1161d4a4d4f9SSingleAccretion 1162a0318f36SChris Fallin fn compute_value_labels_ranges( 1163a0318f36SChris Fallin &self, 1164a0318f36SChris Fallin regalloc: ®alloc2::Output, 1165a0318f36SChris Fallin inst_offsets: &[CodeOffset], 1166a0318f36SChris Fallin func_body_len: u32, 1167a0318f36SChris Fallin ) -> ValueLabelsRanges { 1168a0318f36SChris Fallin if self.debug_value_labels.is_empty() { 1169602006ffSbjorn3 return ValueLabelsRanges::default(); 1170997fab55SChris Fallin } 1171997fab55SChris Fallin 11723da7fc8eSSingleAccretion if trace_log_enabled!() { 11733da7fc8eSSingleAccretion self.log_value_labels_ranges(regalloc, inst_offsets); 11743da7fc8eSSingleAccretion } 11753da7fc8eSSingleAccretion 1176a0318f36SChris Fallin let mut value_labels_ranges: ValueLabelsRanges = HashMap::new(); 1177a0318f36SChris Fallin for &(label, from, to, alloc) in ®alloc.debug_locations { 11783da7fc8eSSingleAccretion let label = ValueLabel::from_u32(label); 11793da7fc8eSSingleAccretion let ranges = value_labels_ranges.entry(label).or_insert_with(|| vec![]); 11805b63c874SSingleAccretion let prog_point_to_inst = |prog_point: ProgPoint| { 11815b63c874SSingleAccretion let mut inst = prog_point.inst(); 11825b63c874SSingleAccretion if prog_point.pos() == InstPosition::After { 11835b63c874SSingleAccretion inst = inst.next(); 11845b63c874SSingleAccretion } 11855b63c874SSingleAccretion inst.index() 11865b63c874SSingleAccretion }; 11875b63c874SSingleAccretion let from_inst_index = prog_point_to_inst(from); 11885b63c874SSingleAccretion let to_inst_index = prog_point_to_inst(to); 11895b63c874SSingleAccretion let from_offset = inst_offsets[from_inst_index]; 11905b63c874SSingleAccretion let to_offset = if to_inst_index == inst_offsets.len() { 1191a0318f36SChris Fallin func_body_len 1192a0318f36SChris Fallin } else { 11935b63c874SSingleAccretion inst_offsets[to_inst_index] 1194a0318f36SChris Fallin }; 1195a0318f36SChris Fallin 1196d4a4d4f9SSingleAccretion // Empty ranges or unavailable offsets can happen 1197d4a4d4f9SSingleAccretion // due to cold blocks and branch removal (see above). 1198d4a4d4f9SSingleAccretion if from_offset == NO_INST_OFFSET 1199d4a4d4f9SSingleAccretion || to_offset == NO_INST_OFFSET 1200d4a4d4f9SSingleAccretion || from_offset == to_offset 1201d4a4d4f9SSingleAccretion { 1202a0318f36SChris Fallin continue; 120376d61504Sbjorn3 } 120476d61504Sbjorn3 1205a0318f36SChris Fallin let loc = if let Some(preg) = alloc.as_reg() { 1206a0318f36SChris Fallin LabelValueLoc::Reg(Reg::from(preg)) 1207a0318f36SChris Fallin } else { 12087b16eccdSSingleAccretion let slot = alloc.as_stack().unwrap(); 120961d0b319STrevor Elliott let slot_offset = self.abi.get_spillslot_offset(slot); 121061d0b319STrevor Elliott let slot_base_to_caller_sp_offset = self.abi.slot_base_to_caller_sp_offset(); 12117b16eccdSSingleAccretion let caller_sp_to_cfa_offset = 12127b16eccdSSingleAccretion crate::isa::unwind::systemv::caller_sp_to_cfa_offset(); 121361d0b319STrevor Elliott // NOTE: this is a negative offset because it's relative to the caller's SP 121461d0b319STrevor Elliott let cfa_to_sp_offset = 121561d0b319STrevor Elliott -((slot_base_to_caller_sp_offset + caller_sp_to_cfa_offset) as i64); 121661d0b319STrevor Elliott LabelValueLoc::CFAOffset(cfa_to_sp_offset + slot_offset) 1217a0318f36SChris Fallin }; 1218a0318f36SChris Fallin 12197b16eccdSSingleAccretion // Coalesce adjacent ranges that for the same location 12207b16eccdSSingleAccretion // to minimize output size here and for the consumers. 12217b16eccdSSingleAccretion if let Some(last_loc_range) = ranges.last_mut() { 12225b63c874SSingleAccretion if last_loc_range.loc == loc && last_loc_range.end == from_offset { 12237b16eccdSSingleAccretion trace!( 12245b63c874SSingleAccretion "Extending debug range for {:?} in {:?} to Inst {} ({})", 12257b16eccdSSingleAccretion label, 12267b16eccdSSingleAccretion loc, 12275b63c874SSingleAccretion to_inst_index, 12285b63c874SSingleAccretion to_offset 12297b16eccdSSingleAccretion ); 12305b63c874SSingleAccretion last_loc_range.end = to_offset; 12317b16eccdSSingleAccretion continue; 12327b16eccdSSingleAccretion } 12337b16eccdSSingleAccretion } 12347b16eccdSSingleAccretion 1235d4a4d4f9SSingleAccretion trace!( 12363da7fc8eSSingleAccretion "Recording debug range for {:?} in {:?}: [Inst {}..Inst {}) [{}..{})", 1237d4a4d4f9SSingleAccretion label, 1238d4a4d4f9SSingleAccretion loc, 12395b63c874SSingleAccretion from_inst_index, 12405b63c874SSingleAccretion to_inst_index, 12415b63c874SSingleAccretion from_offset, 12425b63c874SSingleAccretion to_offset 1243d4a4d4f9SSingleAccretion ); 1244d4a4d4f9SSingleAccretion 12455b63c874SSingleAccretion ranges.push(ValueLocRange { 12465b63c874SSingleAccretion loc, 12475b63c874SSingleAccretion start: from_offset, 12485b63c874SSingleAccretion end: to_offset, 12495b63c874SSingleAccretion }); 1250a0318f36SChris Fallin } 1251a0318f36SChris Fallin 1252a0318f36SChris Fallin value_labels_ranges 1253c84d6be6SChris Fallin } 1254c84d6be6SChris Fallin 12553da7fc8eSSingleAccretion fn log_value_labels_ranges(&self, regalloc: ®alloc2::Output, inst_offsets: &[CodeOffset]) { 12563da7fc8eSSingleAccretion debug_assert!(trace_log_enabled!()); 12573da7fc8eSSingleAccretion 12583da7fc8eSSingleAccretion // What debug labels do we have? Note we'll skip those that have not been 12593da7fc8eSSingleAccretion // allocated any location at all. They will show up as numeric gaps in the table. 12603da7fc8eSSingleAccretion let mut labels = vec![]; 12613da7fc8eSSingleAccretion for &(label, _, _, _) in ®alloc.debug_locations { 12623da7fc8eSSingleAccretion if Some(&label) == labels.last() { 12633da7fc8eSSingleAccretion continue; 12643da7fc8eSSingleAccretion } 12653da7fc8eSSingleAccretion labels.push(label); 12663da7fc8eSSingleAccretion } 12673da7fc8eSSingleAccretion 12683da7fc8eSSingleAccretion // Reformat the data on what VRegs were the VLs assigned to by lowering, since 12693da7fc8eSSingleAccretion // the array we have is sorted by VReg, and we want it sorted by VL for easy 12703da7fc8eSSingleAccretion // access in the loop below. 12713da7fc8eSSingleAccretion let mut vregs = vec![]; 12723da7fc8eSSingleAccretion for &(vreg, start, end, label) in &self.debug_value_labels { 12733da7fc8eSSingleAccretion if matches!(labels.binary_search(&label), Ok(_)) { 12743da7fc8eSSingleAccretion vregs.push((label, start, end, vreg)); 12753da7fc8eSSingleAccretion } 12763da7fc8eSSingleAccretion } 12773da7fc8eSSingleAccretion vregs.sort_unstable_by( 12783da7fc8eSSingleAccretion |(l_label, l_start, _, _), (r_label, r_start, _, _)| match l_label.cmp(r_label) { 12793da7fc8eSSingleAccretion Ordering::Equal => l_start.cmp(r_start), 12803da7fc8eSSingleAccretion cmp => cmp, 12813da7fc8eSSingleAccretion }, 12823da7fc8eSSingleAccretion ); 12833da7fc8eSSingleAccretion 12843da7fc8eSSingleAccretion #[derive(PartialEq)] 12853da7fc8eSSingleAccretion enum Mode { 12863da7fc8eSSingleAccretion Measure, 12873da7fc8eSSingleAccretion Emit, 12883da7fc8eSSingleAccretion } 12893da7fc8eSSingleAccretion #[derive(PartialEq)] 12903da7fc8eSSingleAccretion enum Row { 12913da7fc8eSSingleAccretion Head, 12923da7fc8eSSingleAccretion Line, 12935b63c874SSingleAccretion Inst(usize, usize), 12943da7fc8eSSingleAccretion } 12953da7fc8eSSingleAccretion 12965b63c874SSingleAccretion let mut widths = vec![0; 3 + 2 * labels.len()]; 12973da7fc8eSSingleAccretion let mut row = String::new(); 12983da7fc8eSSingleAccretion let mut output_row = |row_kind: Row, mode: Mode| { 12993da7fc8eSSingleAccretion let mut column_index = 0; 13003da7fc8eSSingleAccretion row.clear(); 13013da7fc8eSSingleAccretion 13023da7fc8eSSingleAccretion macro_rules! output_cell_impl { 13033da7fc8eSSingleAccretion ($fill:literal, $span:literal, $($cell_fmt:tt)*) => { 13043da7fc8eSSingleAccretion let column_start = row.len(); 13053da7fc8eSSingleAccretion { 13063da7fc8eSSingleAccretion row.push('|'); 13073da7fc8eSSingleAccretion write!(row, $($cell_fmt)*).unwrap(); 13083da7fc8eSSingleAccretion } 13093da7fc8eSSingleAccretion 13103da7fc8eSSingleAccretion let next_column_index = column_index + $span; 13113da7fc8eSSingleAccretion let expected_width: usize = widths[column_index..next_column_index].iter().sum(); 13123da7fc8eSSingleAccretion if mode == Mode::Measure { 13133da7fc8eSSingleAccretion let actual_width = row.len() - column_start; 13143da7fc8eSSingleAccretion if actual_width > expected_width { 13153da7fc8eSSingleAccretion widths[next_column_index - 1] += actual_width - expected_width; 13163da7fc8eSSingleAccretion } 13173da7fc8eSSingleAccretion } else { 13183da7fc8eSSingleAccretion let column_end = column_start + expected_width; 13193da7fc8eSSingleAccretion while row.len() != column_end { 13203da7fc8eSSingleAccretion row.push($fill); 13213da7fc8eSSingleAccretion } 13223da7fc8eSSingleAccretion } 13233da7fc8eSSingleAccretion column_index = next_column_index; 13243da7fc8eSSingleAccretion }; 13253da7fc8eSSingleAccretion } 13263da7fc8eSSingleAccretion macro_rules! output_cell { 13273da7fc8eSSingleAccretion ($($cell_fmt:tt)*) => { 13283da7fc8eSSingleAccretion output_cell_impl!(' ', 1, $($cell_fmt)*); 13293da7fc8eSSingleAccretion }; 13303da7fc8eSSingleAccretion } 13313da7fc8eSSingleAccretion 13323da7fc8eSSingleAccretion match row_kind { 13333da7fc8eSSingleAccretion Row::Head => { 13345b63c874SSingleAccretion output_cell!("BB"); 13353da7fc8eSSingleAccretion output_cell!("Inst"); 13363da7fc8eSSingleAccretion output_cell!("IP"); 13373da7fc8eSSingleAccretion for label in &labels { 13383da7fc8eSSingleAccretion output_cell_impl!(' ', 2, "{:?}", ValueLabel::from_u32(*label)); 13393da7fc8eSSingleAccretion } 13403da7fc8eSSingleAccretion } 13413da7fc8eSSingleAccretion Row::Line => { 13423da7fc8eSSingleAccretion debug_assert!(mode == Mode::Emit); 13435b63c874SSingleAccretion for _ in 0..3 { 13443da7fc8eSSingleAccretion output_cell_impl!('-', 1, ""); 13455b63c874SSingleAccretion } 13463da7fc8eSSingleAccretion for _ in &labels { 13473da7fc8eSSingleAccretion output_cell_impl!('-', 2, ""); 13483da7fc8eSSingleAccretion } 13493da7fc8eSSingleAccretion } 13505b63c874SSingleAccretion Row::Inst(block_index, inst_index) => { 13515b63c874SSingleAccretion debug_assert!(inst_index < self.num_insts()); 13525b63c874SSingleAccretion if self.block_ranges.get(block_index).start == inst_index { 13535b63c874SSingleAccretion output_cell!("B{}", block_index); 13545b63c874SSingleAccretion } else { 13555b63c874SSingleAccretion output_cell!(""); 13565b63c874SSingleAccretion } 13573da7fc8eSSingleAccretion output_cell!("Inst {inst_index} "); 13583da7fc8eSSingleAccretion output_cell!("{} ", inst_offsets[inst_index]); 13593da7fc8eSSingleAccretion 13603da7fc8eSSingleAccretion for label in &labels { 13613da7fc8eSSingleAccretion // First, the VReg. 13623da7fc8eSSingleAccretion use regalloc2::Inst; 13633da7fc8eSSingleAccretion let vreg_cmp = |inst: usize, 13643da7fc8eSSingleAccretion vreg_label: &u32, 13653da7fc8eSSingleAccretion range_start: &Inst, 13663da7fc8eSSingleAccretion range_end: &Inst| { 13673da7fc8eSSingleAccretion match vreg_label.cmp(&label) { 13683da7fc8eSSingleAccretion Ordering::Equal => { 13693da7fc8eSSingleAccretion if range_end.index() <= inst { 13703da7fc8eSSingleAccretion Ordering::Less 13713da7fc8eSSingleAccretion } else if range_start.index() > inst { 13723da7fc8eSSingleAccretion Ordering::Greater 13733da7fc8eSSingleAccretion } else { 13743da7fc8eSSingleAccretion Ordering::Equal 13753da7fc8eSSingleAccretion } 13763da7fc8eSSingleAccretion } 13773da7fc8eSSingleAccretion cmp => cmp, 13783da7fc8eSSingleAccretion } 13793da7fc8eSSingleAccretion }; 13803da7fc8eSSingleAccretion let vreg_index = 13815b63c874SSingleAccretion vregs.binary_search_by(|(l, s, e, _)| vreg_cmp(inst_index, l, s, e)); 13823da7fc8eSSingleAccretion if let Ok(vreg_index) = vreg_index { 13833da7fc8eSSingleAccretion let mut prev_vreg = None; 13845b63c874SSingleAccretion if inst_index > 0 { 13853da7fc8eSSingleAccretion let prev_vreg_index = vregs.binary_search_by(|(l, s, e, _)| { 13865b63c874SSingleAccretion vreg_cmp(inst_index - 1, l, s, e) 13873da7fc8eSSingleAccretion }); 13883da7fc8eSSingleAccretion if let Ok(prev_vreg_index) = prev_vreg_index { 13893da7fc8eSSingleAccretion prev_vreg = Some(vregs[prev_vreg_index].3); 13903da7fc8eSSingleAccretion } 13913da7fc8eSSingleAccretion } 13923da7fc8eSSingleAccretion 13933da7fc8eSSingleAccretion let vreg = vregs[vreg_index].3; 13943da7fc8eSSingleAccretion if Some(vreg) == prev_vreg { 13953da7fc8eSSingleAccretion output_cell!("*"); 13963da7fc8eSSingleAccretion } else { 13973da7fc8eSSingleAccretion output_cell!("{}", vreg); 13983da7fc8eSSingleAccretion } 13993da7fc8eSSingleAccretion } else { 14003da7fc8eSSingleAccretion output_cell!(""); 14013da7fc8eSSingleAccretion } 14023da7fc8eSSingleAccretion 14033da7fc8eSSingleAccretion // Second, the allocated location. 14045b63c874SSingleAccretion let inst_prog_point = ProgPoint::before(Inst::new(inst_index)); 14053da7fc8eSSingleAccretion let range_index = regalloc.debug_locations.binary_search_by( 14063da7fc8eSSingleAccretion |(range_label, range_start, range_end, _)| match range_label.cmp(label) 14073da7fc8eSSingleAccretion { 14083da7fc8eSSingleAccretion Ordering::Equal => { 14095b63c874SSingleAccretion if *range_end <= inst_prog_point { 14103da7fc8eSSingleAccretion Ordering::Less 14115b63c874SSingleAccretion } else if *range_start > inst_prog_point { 14123da7fc8eSSingleAccretion Ordering::Greater 14133da7fc8eSSingleAccretion } else { 14143da7fc8eSSingleAccretion Ordering::Equal 14153da7fc8eSSingleAccretion } 14163da7fc8eSSingleAccretion } 14173da7fc8eSSingleAccretion cmp => cmp, 14183da7fc8eSSingleAccretion }, 14193da7fc8eSSingleAccretion ); 14203da7fc8eSSingleAccretion if let Ok(range_index) = range_index { 14213da7fc8eSSingleAccretion // Live at this instruction, print the location. 14223da7fc8eSSingleAccretion if let Some(reg) = regalloc.debug_locations[range_index].3.as_reg() { 14233da7fc8eSSingleAccretion output_cell!("{:?}", Reg::from(reg)); 14243da7fc8eSSingleAccretion } else { 14253da7fc8eSSingleAccretion output_cell!("Stk"); 14263da7fc8eSSingleAccretion } 14273da7fc8eSSingleAccretion } else { 14283da7fc8eSSingleAccretion // Not live at this instruction. 14293da7fc8eSSingleAccretion output_cell!(""); 14303da7fc8eSSingleAccretion } 14313da7fc8eSSingleAccretion } 14323da7fc8eSSingleAccretion } 14333da7fc8eSSingleAccretion } 14343da7fc8eSSingleAccretion row.push('|'); 14353da7fc8eSSingleAccretion 14363da7fc8eSSingleAccretion if mode == Mode::Emit { 14373da7fc8eSSingleAccretion trace!("{}", row.as_str()); 14383da7fc8eSSingleAccretion } 14393da7fc8eSSingleAccretion }; 14403da7fc8eSSingleAccretion 14415b63c874SSingleAccretion for block_index in 0..self.num_blocks() { 14425b63c874SSingleAccretion for inst_index in self.block_ranges.get(block_index) { 14435b63c874SSingleAccretion output_row(Row::Inst(block_index, inst_index), Mode::Measure); 14445b63c874SSingleAccretion } 14453da7fc8eSSingleAccretion } 14463da7fc8eSSingleAccretion output_row(Row::Head, Mode::Measure); 14473da7fc8eSSingleAccretion 14483da7fc8eSSingleAccretion output_row(Row::Head, Mode::Emit); 14493da7fc8eSSingleAccretion output_row(Row::Line, Mode::Emit); 14505b63c874SSingleAccretion for block_index in 0..self.num_blocks() { 14515b63c874SSingleAccretion for inst_index in self.block_ranges.get(block_index) { 14525b63c874SSingleAccretion output_row(Row::Inst(block_index, inst_index), Mode::Emit); 14535b63c874SSingleAccretion } 14543da7fc8eSSingleAccretion } 14553da7fc8eSSingleAccretion } 14563da7fc8eSSingleAccretion 1457d8357426SChris Fallin /// Get the IR block for a BlockIndex, if one exists. 1458d8357426SChris Fallin pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> { 1459a0318f36SChris Fallin self.block_order.lowered_order()[block.index()].orig_block() 1460d8357426SChris Fallin } 14612154c63dSAlex Crichton 14629e4d4462SChris Fallin /// Get the type of a VReg. 14639e4d4462SChris Fallin pub fn vreg_type(&self, vreg: VReg) -> Type { 14649e4d4462SChris Fallin self.vreg_types[vreg.vreg()] 14659e4d4462SChris Fallin } 14669e4d4462SChris Fallin 1467f466aa26SChris Fallin /// Get the fact, if any, for a given VReg. 1468f466aa26SChris Fallin pub fn vreg_fact(&self, vreg: VReg) -> Option<&Fact> { 14699e4d4462SChris Fallin self.facts[vreg.vreg()].as_ref() 1470f466aa26SChris Fallin } 1471f466aa26SChris Fallin 14728d19280aSChris Fallin /// Set the fact for a given VReg. 14738d19280aSChris Fallin pub fn set_vreg_fact(&mut self, vreg: VReg, fact: Fact) { 1474f262c311SChris Fallin trace!("set fact on {}: {:?}", vreg, fact); 14758d19280aSChris Fallin self.facts[vreg.vreg()] = Some(fact); 14768d19280aSChris Fallin } 14778d19280aSChris Fallin 1478f466aa26SChris Fallin /// Does a given instruction define any facts? 1479f466aa26SChris Fallin pub fn inst_defines_facts(&self, inst: InsnIndex) -> bool { 1480f466aa26SChris Fallin self.inst_operands(inst) 1481f466aa26SChris Fallin .iter() 1482f466aa26SChris Fallin .filter(|o| o.kind() == OperandKind::Def) 1483f466aa26SChris Fallin .map(|o| o.vreg()) 14842e7f9414SChris Fallin .any(|vreg| self.facts[vreg.vreg()].is_some()) 1485f466aa26SChris Fallin } 1486e20b4244SNick Fitzgerald 1487e20b4244SNick Fitzgerald /// Get the user stack map associated with the given forward instruction index. 1488e20b4244SNick Fitzgerald pub fn get_user_stack_map(&self, inst: InsnIndex) -> Option<&ir::UserStackMap> { 1489e20b4244SNick Fitzgerald let index = inst.to_backwards_insn_index(self.num_insts()); 1490e20b4244SNick Fitzgerald self.user_stack_maps.get(&index) 1491e20b4244SNick Fitzgerald } 1492f466aa26SChris Fallin } 1493f466aa26SChris Fallin 1494f466aa26SChris Fallin impl<I: VCodeInst> std::ops::Index<InsnIndex> for VCode<I> { 1495f466aa26SChris Fallin type Output = I; 1496f466aa26SChris Fallin fn index(&self, idx: InsnIndex) -> &Self::Output { 1497f466aa26SChris Fallin &self.insts[idx.index()] 1498f466aa26SChris Fallin } 1499d8357426SChris Fallin } 1500d8357426SChris Fallin 1501d8357426SChris Fallin impl<I: VCodeInst> RegallocFunction for VCode<I> { 1502a0318f36SChris Fallin fn num_insts(&self) -> usize { 1503a0318f36SChris Fallin self.insts.len() 1504d8357426SChris Fallin } 1505d8357426SChris Fallin 1506a0318f36SChris Fallin fn num_blocks(&self) -> usize { 1507a0318f36SChris Fallin self.block_ranges.len() 1508d8357426SChris Fallin } 1509d8357426SChris Fallin 1510a0318f36SChris Fallin fn entry_block(&self) -> BlockIndex { 1511a0318f36SChris Fallin self.entry 1512d8357426SChris Fallin } 1513d8357426SChris Fallin 1514a0318f36SChris Fallin fn block_insns(&self, block: BlockIndex) -> InstRange { 15152c409535SJamey Sharp let range = self.block_ranges.get(block.index()); 15161854929dSTrevor Elliott InstRange::new(InsnIndex::new(range.start), InsnIndex::new(range.end)) 1517d8357426SChris Fallin } 1518d8357426SChris Fallin 1519a0318f36SChris Fallin fn block_succs(&self, block: BlockIndex) -> &[BlockIndex] { 15202c409535SJamey Sharp let range = self.block_succ_range.get(block.index()); 15212c409535SJamey Sharp &self.block_succs[range] 1522d8357426SChris Fallin } 1523d8357426SChris Fallin 1524a0318f36SChris Fallin fn block_preds(&self, block: BlockIndex) -> &[BlockIndex] { 15252c409535SJamey Sharp let range = self.block_pred_range.get(block.index()); 15262c409535SJamey Sharp &self.block_preds[range] 1527d8357426SChris Fallin } 1528d8357426SChris Fallin 1529a0318f36SChris Fallin fn block_params(&self, block: BlockIndex) -> &[VReg] { 1530c5379051STrevor Elliott // As a special case we don't return block params for the entry block, as all the arguments 1531c5379051STrevor Elliott // will be defined by the `Inst::Args` instruction. 1532c5379051STrevor Elliott if block == self.entry { 1533c5379051STrevor Elliott return &[]; 1534c5379051STrevor Elliott } 1535c5379051STrevor Elliott 15362c409535SJamey Sharp let range = self.block_params_range.get(block.index()); 15372c409535SJamey Sharp &self.block_params[range] 1538d8357426SChris Fallin } 1539d8357426SChris Fallin 1540a0318f36SChris Fallin fn branch_blockparams(&self, block: BlockIndex, _insn: InsnIndex, succ_idx: usize) -> &[VReg] { 15412c409535SJamey Sharp let succ_range = self.branch_block_arg_succ_range.get(block.index()); 15422c409535SJamey Sharp debug_assert!(succ_idx < succ_range.len()); 15432c409535SJamey Sharp let branch_block_args = self.branch_block_arg_range.get(succ_range.start + succ_idx); 15442c409535SJamey Sharp &self.branch_block_args[branch_block_args] 1545d8357426SChris Fallin } 1546d8357426SChris Fallin 1547a0318f36SChris Fallin fn is_ret(&self, insn: InsnIndex) -> bool { 1548a0318f36SChris Fallin match self.insts[insn.index()].is_term() { 1549c5379051STrevor Elliott // We treat blocks terminated by an unconditional trap like a return for regalloc. 1550c5379051STrevor Elliott MachTerminator::None => self.insts[insn.index()].is_trap(), 15514154fa47SNick Fitzgerald MachTerminator::Ret | MachTerminator::RetCall => true, 155294ec88eaSChris Fallin MachTerminator::Branch => false, 1553d8357426SChris Fallin } 1554d8357426SChris Fallin } 1555d8357426SChris Fallin 1556a0318f36SChris Fallin fn is_branch(&self, insn: InsnIndex) -> bool { 1557a0318f36SChris Fallin match self.insts[insn.index()].is_term() { 155894ec88eaSChris Fallin MachTerminator::Branch => true, 1559a0318f36SChris Fallin _ => false, 1560a0318f36SChris Fallin } 156171768bb6SChris Fallin } 156271768bb6SChris Fallin 1563a0318f36SChris Fallin fn inst_operands(&self, insn: InsnIndex) -> &[Operand] { 15642c409535SJamey Sharp let range = self.operand_ranges.get(insn.index()); 15652c409535SJamey Sharp &self.operands[range] 1566d8357426SChris Fallin } 1567d8357426SChris Fallin 1568b2e28b91SChris Fallin fn inst_clobbers(&self, insn: InsnIndex) -> PRegSet { 1569b2e28b91SChris Fallin self.clobbers.get(&insn).cloned().unwrap_or_default() 1570be6f060aSChris Fallin } 1571be6f060aSChris Fallin 1572a0318f36SChris Fallin fn num_vregs(&self) -> usize { 1573b1307638SJamey Sharp self.vreg_types.len() 1574d8357426SChris Fallin } 1575d8357426SChris Fallin 1576a0318f36SChris Fallin fn debug_value_labels(&self) -> &[(VReg, InsnIndex, InsnIndex, u32)] { 15773aa32064SJamey Sharp &self.debug_value_labels 1578d8357426SChris Fallin } 1579d8357426SChris Fallin 1580a0318f36SChris Fallin fn spillslot_size(&self, regclass: RegClass) -> usize { 1581a0318f36SChris Fallin self.abi.get_spillslot_size(regclass) as usize 1582d8357426SChris Fallin } 1583d8357426SChris Fallin 1584a0318f36SChris Fallin fn allow_multiple_vreg_defs(&self) -> bool { 1585a0318f36SChris Fallin // At least the s390x backend requires this, because the 1586a0318f36SChris Fallin // `Loop` pseudo-instruction aggregates all Operands so pinned 1587a0318f36SChris Fallin // vregs (RealRegs) may occur more than once. 1588a0318f36SChris Fallin true 1589d8357426SChris Fallin } 1590d8357426SChris Fallin } 1591d8357426SChris Fallin 15923aa32064SJamey Sharp impl<I: VCodeInst> Debug for VRegAllocator<I> { 1593d8357426SChris Fallin fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 15943aa32064SJamey Sharp writeln!(f, "VRegAllocator {{")?; 1595a0318f36SChris Fallin 1596a0318f36SChris Fallin let mut alias_keys = self.vreg_aliases.keys().cloned().collect::<Vec<_>>(); 1597a0318f36SChris Fallin alias_keys.sort_unstable(); 1598a0318f36SChris Fallin for key in alias_keys { 1599a0318f36SChris Fallin let dest = self.vreg_aliases.get(&key).unwrap(); 1600a0318f36SChris Fallin writeln!(f, " {:?} := {:?}", Reg::from(key), Reg::from(*dest))?; 1601a0318f36SChris Fallin } 1602d8357426SChris Fallin 16033aa32064SJamey Sharp for (vreg, fact) in self.facts.iter().enumerate() { 16043aa32064SJamey Sharp if let Some(fact) = fact { 1605a0442ea0SHamir Mahal writeln!(f, " v{vreg} ! {fact}")?; 16063aa32064SJamey Sharp } 16073aa32064SJamey Sharp } 16083aa32064SJamey Sharp 16093aa32064SJamey Sharp writeln!(f, "}}") 16103aa32064SJamey Sharp } 16113aa32064SJamey Sharp } 16123aa32064SJamey Sharp 16133aa32064SJamey Sharp impl<I: VCodeInst> fmt::Debug for VCode<I> { 16143aa32064SJamey Sharp fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 16153aa32064SJamey Sharp writeln!(f, "VCode {{")?; 16163aa32064SJamey Sharp writeln!(f, " Entry block: {}", self.entry.index())?; 16173aa32064SJamey Sharp 16183aa32064SJamey Sharp let mut state = Default::default(); 16193aa32064SJamey Sharp 1620d8357426SChris Fallin for block in 0..self.num_blocks() { 1621a0318f36SChris Fallin let block = BlockIndex::new(block); 1622c510a2b9Sbjorn3 writeln!( 1623c510a2b9Sbjorn3 f, 1624c510a2b9Sbjorn3 "Block {}({:?}):", 1625c510a2b9Sbjorn3 block.index(), 1626c510a2b9Sbjorn3 self.block_params(block) 1627c510a2b9Sbjorn3 )?; 1628a0318f36SChris Fallin if let Some(bb) = self.bindex_to_bb(block) { 1629a0442ea0SHamir Mahal writeln!(f, " (original IR block: {bb})")?; 1630d8357426SChris Fallin } 1631c510a2b9Sbjorn3 for (succ_idx, succ) in self.block_succs(block).iter().enumerate() { 1632c510a2b9Sbjorn3 writeln!( 1633c510a2b9Sbjorn3 f, 1634c510a2b9Sbjorn3 " (successor: Block {}({:?}))", 1635c510a2b9Sbjorn3 succ.index(), 1636c510a2b9Sbjorn3 self.branch_blockparams(block, InsnIndex::new(0) /* dummy */, succ_idx) 1637c510a2b9Sbjorn3 )?; 1638a0318f36SChris Fallin } 16392c409535SJamey Sharp for inst in self.block_ranges.get(block.index()) { 1640a0318f36SChris Fallin writeln!( 1641a0318f36SChris Fallin f, 1642a0318f36SChris Fallin " Inst {}: {}", 1643a0318f36SChris Fallin inst, 16447d703191SJamey Sharp self.insts[inst].pretty_print_inst(&mut state) 1645a0318f36SChris Fallin )?; 16463aa32064SJamey Sharp if !self.operands.is_empty() { 1647f466aa26SChris Fallin for operand in self.inst_operands(InsnIndex::new(inst)) { 1648f466aa26SChris Fallin if operand.kind() == OperandKind::Def { 1649f466aa26SChris Fallin if let Some(fact) = &self.facts[operand.vreg().vreg()] { 1650fef8a90fSChris Fallin writeln!(f, " v{} ! {}", operand.vreg().vreg(), fact)?; 1651f466aa26SChris Fallin } 1652f466aa26SChris Fallin } 1653f466aa26SChris Fallin } 1654d8357426SChris Fallin } 1655e20b4244SNick Fitzgerald if let Some(user_stack_map) = self.get_user_stack_map(InsnIndex::new(inst)) { 1656e20b4244SNick Fitzgerald writeln!(f, " {user_stack_map:?}")?; 1657e20b4244SNick Fitzgerald } 1658d8357426SChris Fallin } 16593aa32064SJamey Sharp } 1660d8357426SChris Fallin 1661d8357426SChris Fallin writeln!(f, "}}")?; 1662d8357426SChris Fallin Ok(()) 1663d8357426SChris Fallin } 1664d8357426SChris Fallin } 1665d8357426SChris Fallin 1666d94173eaSTrevor Elliott /// This structure manages VReg allocation during the lifetime of the VCodeBuilder. 1667d94173eaSTrevor Elliott pub struct VRegAllocator<I> { 1668d94173eaSTrevor Elliott /// VReg IR-level types. 1669d94173eaSTrevor Elliott vreg_types: Vec<Type>, 1670d94173eaSTrevor Elliott 16713aa32064SJamey Sharp /// VReg aliases. When the final VCode is built we rewrite all 16723aa32064SJamey Sharp /// uses of the keys in this table to their replacement values. 16733aa32064SJamey Sharp /// 16743aa32064SJamey Sharp /// We use these aliases to rename an instruction's expected 16753aa32064SJamey Sharp /// result vregs to the returned vregs from lowering, which are 16763aa32064SJamey Sharp /// usually freshly-allocated temps. 16773aa32064SJamey Sharp vreg_aliases: FxHashMap<regalloc2::VReg, regalloc2::VReg>, 16783aa32064SJamey Sharp 167917eeba0eSChris Fallin /// A deferred error, to be bubbled up to the top level of the 168017eeba0eSChris Fallin /// lowering algorithm. We take this approach because we cannot 168117eeba0eSChris Fallin /// currently propagate a `Result` upward through ISLE code (the 168217eeba0eSChris Fallin /// lowering rules) or some ABI code. 168317eeba0eSChris Fallin deferred_error: Option<CodegenError>, 168417eeba0eSChris Fallin 1685f466aa26SChris Fallin /// Facts on VRegs, for proof-carrying code. 1686f466aa26SChris Fallin facts: Vec<Option<Fact>>, 1687f466aa26SChris Fallin 1688d94173eaSTrevor Elliott /// The type of instruction that this allocator makes registers for. 1689d94173eaSTrevor Elliott _inst: core::marker::PhantomData<I>, 1690d94173eaSTrevor Elliott } 1691d94173eaSTrevor Elliott 1692d94173eaSTrevor Elliott impl<I: VCodeInst> VRegAllocator<I> { 1693d94173eaSTrevor Elliott /// Make a new VRegAllocator. 16943aa32064SJamey Sharp pub fn with_capacity(capacity: usize) -> Self { 16953aa32064SJamey Sharp let capacity = first_user_vreg_index() + capacity; 16963aa32064SJamey Sharp let mut vreg_types = Vec::with_capacity(capacity); 16973aa32064SJamey Sharp vreg_types.resize(first_user_vreg_index(), types::INVALID); 1698d94173eaSTrevor Elliott Self { 16993aa32064SJamey Sharp vreg_types, 17003aa32064SJamey Sharp vreg_aliases: FxHashMap::with_capacity_and_hasher(capacity, Default::default()), 170117eeba0eSChris Fallin deferred_error: None, 17023aa32064SJamey Sharp facts: Vec::with_capacity(capacity), 1703d94173eaSTrevor Elliott _inst: core::marker::PhantomData::default(), 1704d94173eaSTrevor Elliott } 1705d94173eaSTrevor Elliott } 1706d94173eaSTrevor Elliott 1707d94173eaSTrevor Elliott /// Allocate a fresh ValueRegs. 1708d94173eaSTrevor Elliott pub fn alloc(&mut self, ty: Type) -> CodegenResult<ValueRegs<Reg>> { 170917eeba0eSChris Fallin if self.deferred_error.is_some() { 171017eeba0eSChris Fallin return Err(CodegenError::CodeTooLarge); 171117eeba0eSChris Fallin } 1712b1307638SJamey Sharp let v = self.vreg_types.len(); 1713d94173eaSTrevor Elliott let (regclasses, tys) = I::rc_for_type(ty)?; 1714b1307638SJamey Sharp if v + regclasses.len() >= VReg::MAX { 1715d94173eaSTrevor Elliott return Err(CodegenError::CodeTooLarge); 1716d94173eaSTrevor Elliott } 1717d94173eaSTrevor Elliott 1718d94173eaSTrevor Elliott let regs: ValueRegs<Reg> = match regclasses { 1719d94173eaSTrevor Elliott &[rc0] => ValueRegs::one(VReg::new(v, rc0).into()), 1720d94173eaSTrevor Elliott &[rc0, rc1] => ValueRegs::two(VReg::new(v, rc0).into(), VReg::new(v + 1, rc1).into()), 1721d94173eaSTrevor Elliott // We can extend this if/when we support 32-bit targets; e.g., 1722d94173eaSTrevor Elliott // an i128 on a 32-bit machine will need up to four machine regs 1723d94173eaSTrevor Elliott // for a `Value`. 1724d94173eaSTrevor Elliott _ => panic!("Value must reside in 1 or 2 registers"), 1725d94173eaSTrevor Elliott }; 1726d94173eaSTrevor Elliott for (®_ty, ®) in tys.iter().zip(regs.regs().iter()) { 1727b1307638SJamey Sharp let vreg = reg.to_virtual_reg().unwrap(); 1728b1307638SJamey Sharp debug_assert_eq!(self.vreg_types.len(), vreg.index()); 1729b1307638SJamey Sharp self.vreg_types.push(reg_ty); 1730d94173eaSTrevor Elliott } 1731f466aa26SChris Fallin 1732f466aa26SChris Fallin // Create empty facts for each allocated vreg. 1733b1307638SJamey Sharp self.facts.resize(self.vreg_types.len(), None); 1734f466aa26SChris Fallin 1735d94173eaSTrevor Elliott Ok(regs) 1736d94173eaSTrevor Elliott } 1737d94173eaSTrevor Elliott 173817eeba0eSChris Fallin /// Allocate a fresh ValueRegs, deferring any out-of-vregs 173917eeba0eSChris Fallin /// errors. This is useful in places where we cannot bubble a 174017eeba0eSChris Fallin /// `CodegenResult` upward easily, and which are known to be 174117eeba0eSChris Fallin /// invoked from within the lowering loop that checks the deferred 174217eeba0eSChris Fallin /// error status below. 174317eeba0eSChris Fallin pub fn alloc_with_deferred_error(&mut self, ty: Type) -> ValueRegs<Reg> { 174417eeba0eSChris Fallin match self.alloc(ty) { 174517eeba0eSChris Fallin Ok(x) => x, 174617eeba0eSChris Fallin Err(e) => { 174717eeba0eSChris Fallin self.deferred_error = Some(e); 174817eeba0eSChris Fallin self.bogus_for_deferred_error(ty) 174917eeba0eSChris Fallin } 175017eeba0eSChris Fallin } 175117eeba0eSChris Fallin } 175217eeba0eSChris Fallin 175317eeba0eSChris Fallin /// Take any deferred error that was accumulated by `alloc_with_deferred_error`. 175417eeba0eSChris Fallin pub fn take_deferred_error(&mut self) -> Option<CodegenError> { 175517eeba0eSChris Fallin self.deferred_error.take() 175617eeba0eSChris Fallin } 175717eeba0eSChris Fallin 175817eeba0eSChris Fallin /// Produce an bogus VReg placeholder with the proper number of 175917eeba0eSChris Fallin /// registers for the given type. This is meant to be used with 176017eeba0eSChris Fallin /// deferred allocation errors (see `Lower::alloc_tmp()`). 176117eeba0eSChris Fallin fn bogus_for_deferred_error(&self, ty: Type) -> ValueRegs<Reg> { 176217eeba0eSChris Fallin let (regclasses, _tys) = I::rc_for_type(ty).expect("must have valid type"); 176317eeba0eSChris Fallin match regclasses { 176417eeba0eSChris Fallin &[rc0] => ValueRegs::one(VReg::new(0, rc0).into()), 176517eeba0eSChris Fallin &[rc0, rc1] => ValueRegs::two(VReg::new(0, rc0).into(), VReg::new(1, rc1).into()), 176617eeba0eSChris Fallin _ => panic!("Value must reside in 1 or 2 registers"), 176717eeba0eSChris Fallin } 176817eeba0eSChris Fallin } 176917eeba0eSChris Fallin 17703aa32064SJamey Sharp /// Rewrite any mention of `from` into `to`. 17713aa32064SJamey Sharp pub fn set_vreg_alias(&mut self, from: Reg, to: Reg) { 17723aa32064SJamey Sharp let from = from.into(); 17733aa32064SJamey Sharp let resolved_to = self.resolve_vreg_alias(to.into()); 17743aa32064SJamey Sharp // Disallow cycles (see below). 17753aa32064SJamey Sharp assert_ne!(resolved_to, from); 17763aa32064SJamey Sharp 17773aa32064SJamey Sharp // Maintain the invariant that PCC facts only exist on vregs 17783aa32064SJamey Sharp // which aren't aliases. We want to preserve whatever was 17793aa32064SJamey Sharp // stated about the vreg before its producer was lowered. 17803aa32064SJamey Sharp if let Some(fact) = self.facts[from.vreg()].take() { 17813aa32064SJamey Sharp self.set_fact(resolved_to, fact); 17823aa32064SJamey Sharp } 17833aa32064SJamey Sharp 17843aa32064SJamey Sharp let old_alias = self.vreg_aliases.insert(from, resolved_to); 17853aa32064SJamey Sharp debug_assert_eq!(old_alias, None); 17863aa32064SJamey Sharp } 17873aa32064SJamey Sharp 17883aa32064SJamey Sharp fn resolve_vreg_alias(&self, mut vreg: regalloc2::VReg) -> regalloc2::VReg { 17893aa32064SJamey Sharp // We prevent cycles from existing by resolving targets of 17903aa32064SJamey Sharp // aliases eagerly before setting them. If the target resolves 17913aa32064SJamey Sharp // to the origin of the alias, then a cycle would be created 17923aa32064SJamey Sharp // and the alias is disallowed. Because of the structure of 17933aa32064SJamey Sharp // SSA code (one instruction can refer to another's defs but 17943aa32064SJamey Sharp // not vice-versa, except indirectly through 17953aa32064SJamey Sharp // phis/blockparams), cycles should not occur as we use 17963aa32064SJamey Sharp // aliases to redirect vregs to the temps that actually define 17973aa32064SJamey Sharp // them. 17983aa32064SJamey Sharp while let Some(to) = self.vreg_aliases.get(&vreg) { 17993aa32064SJamey Sharp vreg = *to; 18003aa32064SJamey Sharp } 18013aa32064SJamey Sharp vreg 18023aa32064SJamey Sharp } 18033aa32064SJamey Sharp 18043aa32064SJamey Sharp #[inline] 18053aa32064SJamey Sharp fn debug_assert_no_vreg_aliases(&self, mut list: impl Iterator<Item = VReg>) { 18063aa32064SJamey Sharp debug_assert!(list.all(|vreg| !self.vreg_aliases.contains_key(&vreg))); 18073aa32064SJamey Sharp } 18083aa32064SJamey Sharp 1809f466aa26SChris Fallin /// Set the proof-carrying code fact on a given virtual register. 1810f466aa26SChris Fallin /// 1811f466aa26SChris Fallin /// Returns the old fact, if any (only one fact can be stored). 18123aa32064SJamey Sharp fn set_fact(&mut self, vreg: regalloc2::VReg, fact: Fact) -> Option<Fact> { 1813fef8a90fSChris Fallin trace!("vreg {:?} has fact: {:?}", vreg, fact); 18143aa32064SJamey Sharp debug_assert!(!self.vreg_aliases.contains_key(&vreg)); 18153aa32064SJamey Sharp self.facts[vreg.vreg()].replace(fact) 1816fef8a90fSChris Fallin } 1817fef8a90fSChris Fallin 1818f262c311SChris Fallin /// Set a fact only if one doesn't already exist. 1819f262c311SChris Fallin pub fn set_fact_if_missing(&mut self, vreg: VirtualReg, fact: Fact) { 18203aa32064SJamey Sharp let vreg = self.resolve_vreg_alias(vreg.into()); 18213aa32064SJamey Sharp if self.facts[vreg.vreg()].is_none() { 1822f262c311SChris Fallin self.set_fact(vreg, fact); 1823f262c311SChris Fallin } 1824f262c311SChris Fallin } 1825f262c311SChris Fallin 1826f466aa26SChris Fallin /// Allocate a fresh ValueRegs, with a given fact to apply if 1827f466aa26SChris Fallin /// the value fits in one VReg. 1828f466aa26SChris Fallin pub fn alloc_with_maybe_fact( 1829f466aa26SChris Fallin &mut self, 1830f466aa26SChris Fallin ty: Type, 1831f466aa26SChris Fallin fact: Option<Fact>, 1832f466aa26SChris Fallin ) -> CodegenResult<ValueRegs<Reg>> { 1833f466aa26SChris Fallin let result = self.alloc(ty)?; 1834f466aa26SChris Fallin 1835f466aa26SChris Fallin // Ensure that we don't lose a fact on a value that splits 1836f466aa26SChris Fallin // into multiple VRegs. 1837f466aa26SChris Fallin assert!(result.len() == 1 || fact.is_none()); 1838f466aa26SChris Fallin if let Some(fact) = fact { 18393aa32064SJamey Sharp self.set_fact(result.regs()[0].into(), fact); 1840f466aa26SChris Fallin } 1841f466aa26SChris Fallin 1842f466aa26SChris Fallin Ok(result) 1843f466aa26SChris Fallin } 1844d94173eaSTrevor Elliott } 1845d94173eaSTrevor Elliott 184683f182b3SAndrew Brown /// This structure tracks the large constants used in VCode that will be emitted separately by the 184783f182b3SAndrew Brown /// [MachBuffer]. 184883f182b3SAndrew Brown /// 184983f182b3SAndrew Brown /// First, during the lowering phase, constants are inserted using 1850d38d387aSAlex Crichton /// [VCodeConstants.insert]; an intermediate handle, `VCodeConstant`, tracks what constants are 185183f182b3SAndrew Brown /// used in this phase. Some deduplication is performed, when possible, as constant 185283f182b3SAndrew Brown /// values are inserted. 185383f182b3SAndrew Brown /// 185483f182b3SAndrew Brown /// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the 185583f182b3SAndrew Brown /// constants so that instructions can refer to the value's memory location. The [MachBuffer] 185683f182b3SAndrew Brown /// then writes the constant values to the buffer. 185783f182b3SAndrew Brown #[derive(Default)] 185883f182b3SAndrew Brown pub struct VCodeConstants { 185983f182b3SAndrew Brown constants: PrimaryMap<VCodeConstant, VCodeConstantData>, 186083f182b3SAndrew Brown pool_uses: HashMap<Constant, VCodeConstant>, 186183f182b3SAndrew Brown well_known_uses: HashMap<*const [u8], VCodeConstant>, 1862eb435f30SChris Fallin u64s: HashMap<[u8; 8], VCodeConstant>, 186383f182b3SAndrew Brown } 186483f182b3SAndrew Brown impl VCodeConstants { 186583f182b3SAndrew Brown /// Initialize the structure with the expected number of constants. 186683f182b3SAndrew Brown pub fn with_capacity(expected_num_constants: usize) -> Self { 186783f182b3SAndrew Brown Self { 186883f182b3SAndrew Brown constants: PrimaryMap::with_capacity(expected_num_constants), 186983f182b3SAndrew Brown pool_uses: HashMap::with_capacity(expected_num_constants), 187083f182b3SAndrew Brown well_known_uses: HashMap::new(), 1871eb435f30SChris Fallin u64s: HashMap::new(), 187283f182b3SAndrew Brown } 187383f182b3SAndrew Brown } 187483f182b3SAndrew Brown 187583f182b3SAndrew Brown /// Insert a constant; using this method indicates that a constant value will be used and thus 187683f182b3SAndrew Brown /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants 187783f182b3SAndrew Brown /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not 187883f182b3SAndrew Brown /// [VCodeConstantData::Generated]. 187983f182b3SAndrew Brown pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant { 188083f182b3SAndrew Brown match data { 188183f182b3SAndrew Brown VCodeConstantData::Generated(_) => self.constants.push(data), 188283f182b3SAndrew Brown VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) { 188383f182b3SAndrew Brown None => { 188483f182b3SAndrew Brown let vcode_constant = self.constants.push(data); 188583f182b3SAndrew Brown self.pool_uses.insert(constant, vcode_constant); 188683f182b3SAndrew Brown vcode_constant 188783f182b3SAndrew Brown } 188883f182b3SAndrew Brown Some(&vcode_constant) => vcode_constant, 188983f182b3SAndrew Brown }, 189083f182b3SAndrew Brown VCodeConstantData::WellKnown(data_ref) => { 1891eb435f30SChris Fallin match self.well_known_uses.entry(data_ref as *const [u8]) { 1892eb435f30SChris Fallin Entry::Vacant(v) => { 189383f182b3SAndrew Brown let vcode_constant = self.constants.push(data); 1894eb435f30SChris Fallin v.insert(vcode_constant); 189583f182b3SAndrew Brown vcode_constant 189683f182b3SAndrew Brown } 1897eb435f30SChris Fallin Entry::Occupied(o) => *o.get(), 189883f182b3SAndrew Brown } 189983f182b3SAndrew Brown } 1900eb435f30SChris Fallin VCodeConstantData::U64(value) => match self.u64s.entry(value) { 1901eb435f30SChris Fallin Entry::Vacant(v) => { 1902eb435f30SChris Fallin let vcode_constant = self.constants.push(data); 1903eb435f30SChris Fallin v.insert(vcode_constant); 1904eb435f30SChris Fallin vcode_constant 1905eb435f30SChris Fallin } 1906eb435f30SChris Fallin Entry::Occupied(o) => *o.get(), 1907eb435f30SChris Fallin }, 190883f182b3SAndrew Brown } 190983f182b3SAndrew Brown } 191083f182b3SAndrew Brown 191183f182b3SAndrew Brown /// Return the number of constants inserted. 191283f182b3SAndrew Brown pub fn len(&self) -> usize { 191383f182b3SAndrew Brown self.constants.len() 191483f182b3SAndrew Brown } 191583f182b3SAndrew Brown 1916d38d387aSAlex Crichton /// Iterate over the `VCodeConstant` keys inserted in this structure. 191783f182b3SAndrew Brown pub fn keys(&self) -> Keys<VCodeConstant> { 191883f182b3SAndrew Brown self.constants.keys() 191983f182b3SAndrew Brown } 192083f182b3SAndrew Brown 1921d38d387aSAlex Crichton /// Iterate over the `VCodeConstant` keys and the data (as a byte slice) inserted in this 192283f182b3SAndrew Brown /// structure. 192383f182b3SAndrew Brown pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> { 192483f182b3SAndrew Brown self.constants.iter() 192583f182b3SAndrew Brown } 192649dd8fd7SAlex Crichton 192749dd8fd7SAlex Crichton /// Returns the data associated with the specified constant. 192849dd8fd7SAlex Crichton pub fn get(&self, c: VCodeConstant) -> &VCodeConstantData { 192949dd8fd7SAlex Crichton &self.constants[c] 193049dd8fd7SAlex Crichton } 193197f6a8b3SSaúl Cabrera 193297f6a8b3SSaúl Cabrera /// Checks if the given [VCodeConstantData] is registered as 193397f6a8b3SSaúl Cabrera /// used by the pool. 193497f6a8b3SSaúl Cabrera pub fn pool_uses(&self, constant: &VCodeConstantData) -> bool { 193597f6a8b3SSaúl Cabrera match constant { 193697f6a8b3SSaúl Cabrera VCodeConstantData::Pool(c, _) => self.pool_uses.contains_key(c), 193797f6a8b3SSaúl Cabrera _ => false, 193897f6a8b3SSaúl Cabrera } 193997f6a8b3SSaúl Cabrera } 194083f182b3SAndrew Brown } 194183f182b3SAndrew Brown 194283f182b3SAndrew Brown /// A use of a constant by one or more VCode instructions; see [VCodeConstants]. 194383f182b3SAndrew Brown #[derive(Clone, Copy, Debug, PartialEq, Eq)] 194483f182b3SAndrew Brown pub struct VCodeConstant(u32); 194583f182b3SAndrew Brown entity_impl!(VCodeConstant); 194683f182b3SAndrew Brown 194783f182b3SAndrew Brown /// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking 194883f182b3SAndrew Brown /// these separately instead of as raw byte buffers allows us to avoid some duplication. 194983f182b3SAndrew Brown pub enum VCodeConstantData { 195083f182b3SAndrew Brown /// A constant already present in the Cranelift IR 195183f182b3SAndrew Brown /// [ConstantPool](crate::ir::constant::ConstantPool). 195283f182b3SAndrew Brown Pool(Constant, ConstantData), 195383f182b3SAndrew Brown /// A reference to a well-known constant value that is statically encoded within the compiler. 195483f182b3SAndrew Brown WellKnown(&'static [u8]), 195583f182b3SAndrew Brown /// A constant value generated during lowering; the value may depend on the instruction context 195683f182b3SAndrew Brown /// which makes it difficult to de-duplicate--if possible, use other variants. 195783f182b3SAndrew Brown Generated(ConstantData), 1958eb435f30SChris Fallin /// A constant of at most 64 bits. These are deduplicated as 1959eb435f30SChris Fallin /// well. Stored as a fixed-size array of `u8` so that we do not 1960eb435f30SChris Fallin /// encounter endianness problems when cross-compiling. 1961eb435f30SChris Fallin U64([u8; 8]), 196283f182b3SAndrew Brown } 196383f182b3SAndrew Brown impl VCodeConstantData { 196483f182b3SAndrew Brown /// Retrieve the constant data as a byte slice. 196583f182b3SAndrew Brown pub fn as_slice(&self) -> &[u8] { 196683f182b3SAndrew Brown match self { 196783f182b3SAndrew Brown VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(), 196883f182b3SAndrew Brown VCodeConstantData::WellKnown(d) => d, 1969eb435f30SChris Fallin VCodeConstantData::U64(value) => &value[..], 197083f182b3SAndrew Brown } 197183f182b3SAndrew Brown } 197283f182b3SAndrew Brown 197383f182b3SAndrew Brown /// Calculate the alignment of the constant data. 197483f182b3SAndrew Brown pub fn alignment(&self) -> u32 { 197583f182b3SAndrew Brown if self.as_slice().len() <= 8 { 197683f182b3SAndrew Brown 8 197783f182b3SAndrew Brown } else { 197883f182b3SAndrew Brown 16 197983f182b3SAndrew Brown } 198083f182b3SAndrew Brown } 198183f182b3SAndrew Brown } 198283f182b3SAndrew Brown 198383f182b3SAndrew Brown #[cfg(test)] 198483f182b3SAndrew Brown mod test { 198583f182b3SAndrew Brown use super::*; 19865e5e5206SChris Fallin use std::mem::size_of; 198783f182b3SAndrew Brown 198883f182b3SAndrew Brown #[test] 198983f182b3SAndrew Brown fn size_of_constant_structs() { 199083f182b3SAndrew Brown assert_eq!(size_of::<Constant>(), 4); 199183f182b3SAndrew Brown assert_eq!(size_of::<VCodeConstant>(), 4); 199248f4621fSAlex Crichton assert_eq!(size_of::<ConstantData>(), 3 * size_of::<usize>()); 199348f4621fSAlex Crichton assert_eq!(size_of::<VCodeConstantData>(), 4 * size_of::<usize>()); 199483f182b3SAndrew Brown assert_eq!( 199583f182b3SAndrew Brown size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(), 199648f4621fSAlex Crichton 3 * size_of::<usize>() 199783f182b3SAndrew Brown ); 19985e5e5206SChris Fallin // TODO The VCodeConstants structure's memory size could be further optimized. 19995e5e5206SChris Fallin // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at 20005e5e5206SChris Fallin // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes. 200183f182b3SAndrew Brown } 200283f182b3SAndrew Brown } 2003