1 //! This implements the VCode container: a CFG of Insts that have been lowered. 2 //! 3 //! VCode is virtual-register code. An instruction in VCode is almost a machine 4 //! instruction; however, its register slots can refer to virtual registers in 5 //! addition to real machine registers. 6 //! 7 //! VCode is structured with traditional basic blocks, and 8 //! each block must be terminated by an unconditional branch (one target), a 9 //! conditional branch (two targets), or a return (no targets). Note that this 10 //! slightly differs from the machine code of most ISAs: in most ISAs, a 11 //! conditional branch has one target (and the not-taken case falls through). 12 //! However, we expect that machine backends will elide branches to the following 13 //! block (i.e., zero-offset jumps), and will be able to codegen a branch-cond / 14 //! branch-uncond pair if *both* targets are not fallthrough. This allows us to 15 //! play with layout prior to final binary emission, as well, if we want. 16 //! 17 //! See the main module comment in `mod.rs` for more details on the VCode-based 18 //! backend pipeline. 19 20 use crate::fx::FxHashMap; 21 use crate::fx::FxHashSet; 22 use crate::ir::RelSourceLoc; 23 use crate::ir::{self, types, Constant, ConstantData, DynamicStackSlot, LabelValueLoc, ValueLabel}; 24 use crate::machinst::*; 25 use crate::timing; 26 use crate::trace; 27 use crate::ValueLocRange; 28 use regalloc2::{ 29 Edit, Function as RegallocFunction, InstOrEdit, InstRange, Operand, OperandKind, PReg, PRegSet, 30 RegClass, VReg, 31 }; 32 33 use alloc::vec::Vec; 34 use cranelift_entity::{entity_impl, Keys, PrimaryMap}; 35 use std::collections::hash_map::Entry; 36 use std::collections::HashMap; 37 use std::fmt; 38 39 /// Index referring to an instruction in VCode. 40 pub type InsnIndex = regalloc2::Inst; 41 42 /// Index referring to a basic block in VCode. 43 pub type BlockIndex = regalloc2::Block; 44 45 /// VCodeInst wraps all requirements for a MachInst to be in VCode: it must be 46 /// a `MachInst` and it must be able to emit itself at least to a `SizeCodeSink`. 47 pub trait VCodeInst: MachInst + MachInstEmit {} 48 impl<I: MachInst + MachInstEmit> VCodeInst for I {} 49 50 /// A function in "VCode" (virtualized-register code) form, after 51 /// lowering. This is essentially a standard CFG of basic blocks, 52 /// where each basic block consists of lowered instructions produced 53 /// by the machine-specific backend. 54 /// 55 /// Note that the VCode is immutable once produced, and is not 56 /// modified by register allocation in particular. Rather, register 57 /// allocation on the `VCode` produces a separate `regalloc2::Output` 58 /// struct, and this can be passed to `emit`. `emit` in turn does not 59 /// modify the vcode, but produces an `EmitResult`, which contains the 60 /// machine code itself, and the associated disassembly and/or 61 /// metadata as requested. 62 pub struct VCode<I: VCodeInst> { 63 /// VReg IR-level types. 64 vreg_types: Vec<Type>, 65 66 /// Do we have any ref values among our vregs? 67 have_ref_values: bool, 68 69 /// Lowered machine instructions in order corresponding to the original IR. 70 insts: Vec<I>, 71 72 /// Operands: pre-regalloc references to virtual registers with 73 /// constraints, in one flattened array. This allows the regalloc 74 /// to efficiently access all operands without requiring expensive 75 /// matches or method invocations on insts. 76 operands: Vec<Operand>, 77 78 /// Operand index ranges: for each instruction in `insts`, there 79 /// is a tuple here providing the range in `operands` for that 80 /// instruction's operands. 81 operand_ranges: Vec<(u32, u32)>, 82 83 /// Clobbers: a sparse map from instruction indices to clobber masks. 84 clobbers: FxHashMap<InsnIndex, PRegSet>, 85 86 /// Move information: for a given InsnIndex, (src, dst) operand pair. 87 is_move: FxHashMap<InsnIndex, (Operand, Operand)>, 88 89 /// Source locations for each instruction. (`SourceLoc` is a `u32`, so it is 90 /// reasonable to keep one of these per instruction.) 91 srclocs: Vec<RelSourceLoc>, 92 93 /// Entry block. 94 entry: BlockIndex, 95 96 /// Block instruction indices. 97 block_ranges: Vec<(InsnIndex, InsnIndex)>, 98 99 /// Block successors: index range in the `block_succs_preds` list. 100 block_succ_range: Vec<(u32, u32)>, 101 102 /// Block predecessors: index range in the `block_succs_preds` list. 103 block_pred_range: Vec<(u32, u32)>, 104 105 /// Block successor and predecessor lists, concatenated into one 106 /// Vec. The `block_succ_range` and `block_pred_range` lists of 107 /// tuples above give (start, end) ranges within this list that 108 /// correspond to each basic block's successors or predecessors, 109 /// respectively. 110 block_succs_preds: Vec<regalloc2::Block>, 111 112 /// Block parameters: index range in `block_params` below. 113 block_params_range: Vec<(u32, u32)>, 114 115 /// Block parameter lists, concatenated into one vec. The 116 /// `block_params_range` list of tuples above gives (start, end) 117 /// ranges within this list that correspond to each basic block's 118 /// blockparam vregs. 119 block_params: Vec<regalloc2::VReg>, 120 121 /// Outgoing block arguments on branch instructions, concatenated 122 /// into one list. 123 /// 124 /// Note that this is conceptually a 3D array: we have a VReg list 125 /// per block, per successor. We flatten those three dimensions 126 /// into this 1D vec, then store index ranges in two levels of 127 /// indirection. 128 /// 129 /// Indexed by the indices in `branch_block_arg_succ_range`. 130 branch_block_args: Vec<regalloc2::VReg>, 131 132 /// Array of sequences of (start, end) tuples in 133 /// `branch_block_args`, one for each successor; these sequences 134 /// for each block are concatenated. 135 /// 136 /// Indexed by the indices in `branch_block_arg_succ_range`. 137 branch_block_arg_range: Vec<(u32, u32)>, 138 139 /// For a given block, indices in `branch_block_arg_range` 140 /// corresponding to all of its successors. 141 branch_block_arg_succ_range: Vec<(u32, u32)>, 142 143 /// VReg aliases. Each key in this table is translated to its 144 /// value when gathering Operands from instructions. Aliases are 145 /// not chased transitively (we do not further look up the 146 /// translated reg to see if it is another alias). 147 /// 148 /// We use these aliases to rename an instruction's expected 149 /// result vregs to the returned vregs from lowering, which are 150 /// usually freshly-allocated temps. 151 /// 152 /// Operands and branch arguments will already have been 153 /// translated through this alias table; but it helps to make 154 /// sense of instructions when pretty-printed, for example. 155 vreg_aliases: FxHashMap<regalloc2::VReg, regalloc2::VReg>, 156 157 /// Block-order information. 158 block_order: BlockLoweringOrder, 159 160 /// ABI object. 161 abi: Callee<I::ABIMachineSpec>, 162 163 /// Constant information used during code emission. This should be 164 /// immutable across function compilations within the same module. 165 emit_info: I::Info, 166 167 /// Reference-typed `regalloc2::VReg`s. The regalloc requires 168 /// these in a dense slice (as opposed to querying the 169 /// reftype-status of each vreg) for efficient iteration. 170 reftyped_vregs: Vec<VReg>, 171 172 /// A set with the same contents as `reftyped_vregs`, in order to 173 /// avoid inserting more than once. 174 reftyped_vregs_set: FxHashSet<VReg>, 175 176 /// Constants. 177 constants: VCodeConstants, 178 179 /// Value labels for debuginfo attached to vregs. 180 debug_value_labels: Vec<(VReg, InsnIndex, InsnIndex, u32)>, 181 } 182 183 /// The result of `VCode::emit`. Contains all information computed 184 /// during emission: actual machine code, optionally a disassembly, 185 /// and optionally metadata about the code layout. 186 pub struct EmitResult<I: VCodeInst> { 187 /// The MachBuffer containing the machine code. 188 pub buffer: MachBuffer<I>, 189 190 /// Offset of each basic block, recorded during emission. Computed 191 /// only if `debug_value_labels` is non-empty. 192 pub bb_offsets: Vec<CodeOffset>, 193 194 /// Final basic-block edges, in terms of code offsets of 195 /// bb-starts. Computed only if `debug_value_labels` is non-empty. 196 pub bb_edges: Vec<(CodeOffset, CodeOffset)>, 197 198 /// Final instruction offsets, recorded during emission. Computed 199 /// only if `debug_value_labels` is non-empty. 200 pub inst_offsets: Vec<CodeOffset>, 201 202 /// Final length of function body. 203 pub func_body_len: CodeOffset, 204 205 /// The pretty-printed disassembly, if any. This uses the same 206 /// pretty-printing for MachInsts as the pre-regalloc VCode Debug 207 /// implementation, but additionally includes the prologue and 208 /// epilogue(s), and makes use of the regalloc results. 209 pub disasm: Option<String>, 210 211 /// Offsets of sized stackslots. 212 pub sized_stackslot_offsets: PrimaryMap<StackSlot, u32>, 213 214 /// Offsets of dynamic stackslots. 215 pub dynamic_stackslot_offsets: PrimaryMap<DynamicStackSlot, u32>, 216 217 /// Value-labels information (debug metadata). 218 pub value_labels_ranges: ValueLabelsRanges, 219 220 /// Stack frame size. 221 pub frame_size: u32, 222 } 223 224 /// A builder for a VCode function body. 225 /// 226 /// This builder has the ability to accept instructions in either 227 /// forward or reverse order, depending on the pass direction that 228 /// produces the VCode. The lowering from CLIF to VCode<MachInst> 229 /// ordinarily occurs in reverse order (in order to allow instructions 230 /// to be lowered only if used, and not merged) so a reversal will 231 /// occur at the end of lowering to ensure the VCode is in machine 232 /// order. 233 /// 234 /// If built in reverse, block and instruction indices used once the 235 /// VCode is built are relative to the final (reversed) order, not the 236 /// order of construction. Note that this means we do not know the 237 /// final block or instruction indices when building, so we do not 238 /// hand them out. (The user is assumed to know them when appending 239 /// terminator instructions with successor blocks.) 240 pub struct VCodeBuilder<I: VCodeInst> { 241 /// In-progress VCode. 242 vcode: VCode<I>, 243 244 /// In what direction is the build occuring? 245 direction: VCodeBuildDirection, 246 247 /// Index of the last block-start in the vcode. 248 block_start: usize, 249 250 /// Start of succs for the current block in the concatenated succs list. 251 succ_start: usize, 252 253 /// Start of blockparams for the current block in the concatenated 254 /// blockparams list. 255 block_params_start: usize, 256 257 /// Start of successor blockparam arg list entries in 258 /// the concatenated branch_block_arg_range list. 259 branch_block_arg_succ_start: usize, 260 261 /// Current source location. 262 cur_srcloc: RelSourceLoc, 263 264 /// Debug-value label in-progress map, keyed by label. For each 265 /// label, we keep disjoint ranges mapping to vregs. We'll flatten 266 /// this into (vreg, range, label) tuples when done. 267 debug_info: FxHashMap<ValueLabel, Vec<(InsnIndex, InsnIndex, VReg)>>, 268 } 269 270 /// Direction in which a VCodeBuilder builds VCode. 271 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 272 pub enum VCodeBuildDirection { 273 // TODO: add `Forward` once we need it and can test it adequately. 274 /// Backward-build pass: we expect the producer to call `emit()` 275 /// with instructions in reverse program order within each block. 276 Backward, 277 } 278 279 impl<I: VCodeInst> VCodeBuilder<I> { 280 /// Create a new VCodeBuilder. 281 pub fn new( 282 abi: Callee<I::ABIMachineSpec>, 283 emit_info: I::Info, 284 block_order: BlockLoweringOrder, 285 constants: VCodeConstants, 286 direction: VCodeBuildDirection, 287 ) -> VCodeBuilder<I> { 288 let vcode = VCode::new(abi, emit_info, block_order, constants); 289 290 VCodeBuilder { 291 vcode, 292 direction, 293 block_start: 0, 294 succ_start: 0, 295 block_params_start: 0, 296 branch_block_arg_succ_start: 0, 297 cur_srcloc: Default::default(), 298 debug_info: FxHashMap::default(), 299 } 300 } 301 302 /// Access the ABI object. 303 pub fn abi(&mut self) -> &mut Callee<I::ABIMachineSpec> { 304 &mut self.vcode.abi 305 } 306 307 /// Access to the BlockLoweringOrder object. 308 pub fn block_order(&self) -> &BlockLoweringOrder { 309 &self.vcode.block_order 310 } 311 312 /// Set the type of a VReg. 313 pub fn set_vreg_type(&mut self, vreg: VirtualReg, ty: Type) { 314 if self.vcode.vreg_types.len() <= vreg.index() { 315 self.vcode 316 .vreg_types 317 .resize(vreg.index() + 1, ir::types::I8); 318 } 319 self.vcode.vreg_types[vreg.index()] = ty; 320 if is_reftype(ty) { 321 let vreg: VReg = vreg.into(); 322 if self.vcode.reftyped_vregs_set.insert(vreg) { 323 self.vcode.reftyped_vregs.push(vreg); 324 } 325 self.vcode.have_ref_values = true; 326 } 327 } 328 329 /// Get the type of a VReg. 330 pub fn get_vreg_type(&self, vreg: VirtualReg) -> Type { 331 self.vcode.vreg_types[vreg.index()] 332 } 333 334 /// Set the current block as the entry block. 335 pub fn set_entry(&mut self, block: BlockIndex) { 336 self.vcode.entry = block; 337 } 338 339 /// End the current basic block. Must be called after emitting vcode insts 340 /// for IR insts and prior to ending the function (building the VCode). 341 pub fn end_bb(&mut self) { 342 let start_idx = self.block_start; 343 let end_idx = self.vcode.insts.len(); 344 self.block_start = end_idx; 345 // Add the instruction index range to the list of blocks. 346 self.vcode 347 .block_ranges 348 .push((InsnIndex::new(start_idx), InsnIndex::new(end_idx))); 349 // End the successors list. 350 let succ_end = self.vcode.block_succs_preds.len(); 351 self.vcode 352 .block_succ_range 353 .push((self.succ_start as u32, succ_end as u32)); 354 self.succ_start = succ_end; 355 // End the blockparams list. 356 let block_params_end = self.vcode.block_params.len(); 357 self.vcode 358 .block_params_range 359 .push((self.block_params_start as u32, block_params_end as u32)); 360 self.block_params_start = block_params_end; 361 // End the branch blockparam args list. 362 let branch_block_arg_succ_end = self.vcode.branch_block_arg_range.len(); 363 self.vcode.branch_block_arg_succ_range.push(( 364 self.branch_block_arg_succ_start as u32, 365 branch_block_arg_succ_end as u32, 366 )); 367 self.branch_block_arg_succ_start = branch_block_arg_succ_end; 368 } 369 370 pub fn add_block_param(&mut self, param: VirtualReg, ty: Type) { 371 self.set_vreg_type(param, ty); 372 self.vcode.block_params.push(param.into()); 373 } 374 375 fn add_branch_args_for_succ(&mut self, args: &[Reg]) { 376 let start = self.vcode.branch_block_args.len(); 377 self.vcode 378 .branch_block_args 379 .extend(args.iter().map(|&arg| VReg::from(arg))); 380 let end = self.vcode.branch_block_args.len(); 381 self.vcode 382 .branch_block_arg_range 383 .push((start as u32, end as u32)); 384 } 385 386 /// Push an instruction for the current BB and current IR inst 387 /// within the BB. 388 pub fn push(&mut self, insn: I) { 389 self.vcode.insts.push(insn); 390 self.vcode.srclocs.push(self.cur_srcloc); 391 } 392 393 /// Add a successor block with branch args. 394 pub fn add_succ(&mut self, block: BlockIndex, args: &[Reg]) { 395 self.vcode.block_succs_preds.push(block); 396 self.add_branch_args_for_succ(args); 397 } 398 399 /// Set the current source location. 400 pub fn set_srcloc(&mut self, srcloc: RelSourceLoc) { 401 self.cur_srcloc = srcloc; 402 } 403 404 /// Add a debug value label to a register. 405 pub fn add_value_label(&mut self, reg: Reg, label: ValueLabel) { 406 // We'll fix up labels in reverse(). Because we're generating 407 // code bottom-to-top, the liverange of the label goes *from* 408 // the last index at which was defined (or 0, which is the end 409 // of the eventual function) *to* just this instruction, and 410 // no further. 411 let inst = InsnIndex::new(self.vcode.insts.len()); 412 let labels = self.debug_info.entry(label).or_insert_with(|| vec![]); 413 let last = labels 414 .last() 415 .map(|(_start, end, _vreg)| *end) 416 .unwrap_or(InsnIndex::new(0)); 417 labels.push((last, inst, reg.into())); 418 } 419 420 pub fn set_vreg_alias(&mut self, from: Reg, to: Reg) { 421 let from = from.into(); 422 let resolved_to = self.resolve_vreg_alias(to.into()); 423 // Disallow cycles (see below). 424 assert_ne!(resolved_to, from); 425 self.vcode.vreg_aliases.insert(from, resolved_to); 426 } 427 428 pub fn resolve_vreg_alias(&self, from: regalloc2::VReg) -> regalloc2::VReg { 429 Self::resolve_vreg_alias_impl(&self.vcode.vreg_aliases, from) 430 } 431 432 fn resolve_vreg_alias_impl( 433 aliases: &FxHashMap<regalloc2::VReg, regalloc2::VReg>, 434 from: regalloc2::VReg, 435 ) -> regalloc2::VReg { 436 // We prevent cycles from existing by resolving targets of 437 // aliases eagerly before setting them. If the target resolves 438 // to the origin of the alias, then a cycle would be created 439 // and the alias is disallowed. Because of the structure of 440 // SSA code (one instruction can refer to another's defs but 441 // not vice-versa, except indirectly through 442 // phis/blockparams), cycles should not occur as we use 443 // aliases to redirect vregs to the temps that actually define 444 // them. 445 446 let mut vreg = from; 447 while let Some(to) = aliases.get(&vreg) { 448 vreg = *to; 449 } 450 vreg 451 } 452 453 /// Access the constants. 454 pub fn constants(&mut self) -> &mut VCodeConstants { 455 &mut self.vcode.constants 456 } 457 458 fn compute_preds_from_succs(&mut self) { 459 // Compute predecessors from successors. In order to gather 460 // all preds for a block into a contiguous sequence, we build 461 // a list of (succ, pred) tuples and then sort. 462 let mut succ_pred_edges: Vec<(BlockIndex, BlockIndex)> = 463 Vec::with_capacity(self.vcode.block_succs_preds.len()); 464 for (pred, &(start, end)) in self.vcode.block_succ_range.iter().enumerate() { 465 let pred = BlockIndex::new(pred); 466 for i in start..end { 467 let succ = BlockIndex::new(self.vcode.block_succs_preds[i as usize].index()); 468 succ_pred_edges.push((succ, pred)); 469 } 470 } 471 succ_pred_edges.sort_unstable(); 472 473 let mut i = 0; 474 for succ in 0..self.vcode.num_blocks() { 475 let succ = BlockIndex::new(succ); 476 let start = self.vcode.block_succs_preds.len(); 477 while i < succ_pred_edges.len() && succ_pred_edges[i].0 == succ { 478 let pred = succ_pred_edges[i].1; 479 self.vcode.block_succs_preds.push(pred); 480 i += 1; 481 } 482 let end = self.vcode.block_succs_preds.len(); 483 self.vcode.block_pred_range.push((start as u32, end as u32)); 484 } 485 } 486 487 /// Called once, when a build in Backward order is complete, to 488 /// perform the overall reversal (into final forward order) and 489 /// finalize metadata accordingly. 490 fn reverse_and_finalize(&mut self) { 491 let n_insts = self.vcode.insts.len(); 492 if n_insts == 0 { 493 return; 494 } 495 496 // Reverse the per-block and per-inst sequences. 497 self.vcode.block_ranges.reverse(); 498 // block_params_range is indexed by block (and blocks were 499 // traversed in reverse) so we reverse it; but block-param 500 // sequences in the concatenated vec can remain in reverse 501 // order (it is effectively an arena of arbitrarily-placed 502 // referenced sequences). 503 self.vcode.block_params_range.reverse(); 504 // Likewise, we reverse block_succ_range, but the block_succ 505 // concatenated array can remain as-is. 506 self.vcode.block_succ_range.reverse(); 507 self.vcode.insts.reverse(); 508 self.vcode.srclocs.reverse(); 509 // Likewise, branch_block_arg_succ_range is indexed by block 510 // so must be reversed. 511 self.vcode.branch_block_arg_succ_range.reverse(); 512 513 // To translate an instruction index *endpoint* in reversed 514 // order to forward order, compute `n_insts - i`. 515 // 516 // Why not `n_insts - 1 - i`? That would be correct to 517 // translate an individual instruction index (for ten insts 0 518 // to 9 inclusive, inst 0 becomes 9, and inst 9 becomes 519 // 0). But for the usual inclusive-start, exclusive-end range 520 // idiom, inclusive starts become exclusive ends and 521 // vice-versa, so e.g. an (inclusive) start of 0 becomes an 522 // (exclusive) end of 10. 523 let translate = |inst: InsnIndex| InsnIndex::new(n_insts - inst.index()); 524 525 // Edit the block-range instruction indices. 526 for tuple in &mut self.vcode.block_ranges { 527 let (start, end) = *tuple; 528 *tuple = (translate(end), translate(start)); // Note reversed order. 529 } 530 531 // Generate debug-value labels based on per-label maps. 532 for (label, tuples) in &self.debug_info { 533 for &(start, end, vreg) in tuples { 534 let vreg = self.resolve_vreg_alias(vreg); 535 let fwd_start = translate(end); 536 let fwd_end = translate(start); 537 self.vcode 538 .debug_value_labels 539 .push((vreg, fwd_start, fwd_end, label.as_u32())); 540 } 541 } 542 543 // Now sort debug value labels by VReg, as required 544 // by regalloc2. 545 self.vcode 546 .debug_value_labels 547 .sort_unstable_by_key(|(vreg, _, _, _)| *vreg); 548 } 549 550 fn collect_operands(&mut self) { 551 for (i, insn) in self.vcode.insts.iter().enumerate() { 552 // Push operands from the instruction onto the operand list. 553 // 554 // We rename through the vreg alias table as we collect 555 // the operands. This is better than a separate post-pass 556 // over operands, because it has more cache locality: 557 // operands only need to pass through L1 once. This is 558 // also better than renaming instructions' 559 // operands/registers while lowering, because here we only 560 // need to do the `match` over the instruction to visit 561 // its register fields (which is slow, branchy code) once. 562 563 let vreg_aliases = &self.vcode.vreg_aliases; 564 let mut op_collector = OperandCollector::new(&mut self.vcode.operands, |vreg| { 565 Self::resolve_vreg_alias_impl(vreg_aliases, vreg) 566 }); 567 insn.get_operands(&mut op_collector); 568 let (ops, clobbers) = op_collector.finish(); 569 self.vcode.operand_ranges.push(ops); 570 571 if clobbers != PRegSet::default() { 572 self.vcode.clobbers.insert(InsnIndex::new(i), clobbers); 573 } 574 575 if let Some((dst, src)) = insn.is_move() { 576 let src = Operand::reg_use(Self::resolve_vreg_alias_impl(vreg_aliases, src.into())); 577 let dst = Operand::reg_def(Self::resolve_vreg_alias_impl( 578 vreg_aliases, 579 dst.to_reg().into(), 580 )); 581 // Note that regalloc2 requires these in (src, dst) order. 582 self.vcode.is_move.insert(InsnIndex::new(i), (src, dst)); 583 } 584 } 585 586 // Translate blockparam args via the vreg aliases table as well. 587 for arg in &mut self.vcode.branch_block_args { 588 let new_arg = Self::resolve_vreg_alias_impl(&self.vcode.vreg_aliases, *arg); 589 trace!("operandcollector: block arg {:?} -> {:?}", arg, new_arg); 590 *arg = new_arg; 591 } 592 } 593 594 /// Build the final VCode. 595 pub fn build(mut self) -> VCode<I> { 596 if self.direction == VCodeBuildDirection::Backward { 597 self.reverse_and_finalize(); 598 } 599 self.collect_operands(); 600 601 // Apply register aliases to the `reftyped_vregs` list since this list 602 // will be returned directly to `regalloc2` eventually and all 603 // operands/results of instructions will use the alias-resolved vregs 604 // from `regalloc2`'s perspective. 605 // 606 // Also note that `reftyped_vregs` can't have duplicates, so after the 607 // aliases are applied duplicates are removed. 608 for reg in self.vcode.reftyped_vregs.iter_mut() { 609 *reg = Self::resolve_vreg_alias_impl(&self.vcode.vreg_aliases, *reg); 610 } 611 self.vcode.reftyped_vregs.sort(); 612 self.vcode.reftyped_vregs.dedup(); 613 614 self.compute_preds_from_succs(); 615 self.vcode.debug_value_labels.sort_unstable(); 616 self.vcode 617 } 618 } 619 620 /// Is this type a reference type? 621 fn is_reftype(ty: Type) -> bool { 622 ty == types::R64 || ty == types::R32 623 } 624 625 impl<I: VCodeInst> VCode<I> { 626 /// New empty VCode. 627 fn new( 628 abi: Callee<I::ABIMachineSpec>, 629 emit_info: I::Info, 630 block_order: BlockLoweringOrder, 631 constants: VCodeConstants, 632 ) -> VCode<I> { 633 let n_blocks = block_order.lowered_order().len(); 634 VCode { 635 vreg_types: vec![], 636 have_ref_values: false, 637 insts: Vec::with_capacity(10 * n_blocks), 638 operands: Vec::with_capacity(30 * n_blocks), 639 operand_ranges: Vec::with_capacity(10 * n_blocks), 640 clobbers: FxHashMap::default(), 641 is_move: FxHashMap::default(), 642 srclocs: Vec::with_capacity(10 * n_blocks), 643 entry: BlockIndex::new(0), 644 block_ranges: Vec::with_capacity(n_blocks), 645 block_succ_range: Vec::with_capacity(n_blocks), 646 block_succs_preds: Vec::with_capacity(2 * n_blocks), 647 block_pred_range: Vec::with_capacity(n_blocks), 648 block_params_range: Vec::with_capacity(n_blocks), 649 block_params: Vec::with_capacity(5 * n_blocks), 650 branch_block_args: Vec::with_capacity(10 * n_blocks), 651 branch_block_arg_range: Vec::with_capacity(2 * n_blocks), 652 branch_block_arg_succ_range: Vec::with_capacity(n_blocks), 653 block_order, 654 abi, 655 emit_info, 656 reftyped_vregs: vec![], 657 reftyped_vregs_set: FxHashSet::default(), 658 constants, 659 debug_value_labels: vec![], 660 vreg_aliases: FxHashMap::with_capacity_and_hasher(10 * n_blocks, Default::default()), 661 } 662 } 663 664 /// Get the number of blocks. Block indices will be in the range `0 .. 665 /// (self.num_blocks() - 1)`. 666 pub fn num_blocks(&self) -> usize { 667 self.block_ranges.len() 668 } 669 670 /// Get the successors for a block. 671 pub fn succs(&self, block: BlockIndex) -> &[BlockIndex] { 672 let (start, end) = self.block_succ_range[block.index()]; 673 &self.block_succs_preds[start as usize..end as usize] 674 } 675 676 fn compute_clobbers(&self, regalloc: ®alloc2::Output) -> Vec<Writable<RealReg>> { 677 // Compute clobbered registers. 678 let mut clobbered = vec![]; 679 let mut clobbered_set = FxHashSet::default(); 680 681 // All moves are included in clobbers. 682 for edit in ®alloc.edits { 683 let Edit::Move { to, .. } = edit.1; 684 if let Some(preg) = to.as_reg() { 685 let reg = RealReg::from(preg); 686 if clobbered_set.insert(reg) { 687 clobbered.push(Writable::from_reg(reg)); 688 } 689 } 690 } 691 692 for (i, (start, end)) in self.operand_ranges.iter().enumerate() { 693 // Skip this instruction if not "included in clobbers" as 694 // per the MachInst. (Some backends use this to implement 695 // ABI specifics; e.g., excluding calls of the same ABI as 696 // the current function from clobbers, because by 697 // definition everything clobbered by the call can be 698 // clobbered by this function without saving as well.) 699 if !self.insts[i].is_included_in_clobbers() { 700 continue; 701 } 702 703 let start = *start as usize; 704 let end = *end as usize; 705 let operands = &self.operands[start..end]; 706 let allocs = ®alloc.allocs[start..end]; 707 for (operand, alloc) in operands.iter().zip(allocs.iter()) { 708 // We're interested only in writes (Mods or Defs). 709 if operand.kind() == OperandKind::Use { 710 continue; 711 } 712 if let Some(preg) = alloc.as_reg() { 713 let reg = RealReg::from(preg); 714 if clobbered_set.insert(reg) { 715 clobbered.push(Writable::from_reg(reg)); 716 } 717 } 718 } 719 720 // Also add explicitly-clobbered registers. 721 for preg in self 722 .clobbers 723 .get(&InsnIndex::new(i)) 724 .cloned() 725 .unwrap_or_default() 726 { 727 let reg = RealReg::from(preg); 728 if clobbered_set.insert(reg) { 729 clobbered.push(Writable::from_reg(reg)); 730 } 731 } 732 } 733 734 clobbered 735 } 736 737 /// Emit the instructions to a `MachBuffer`, containing fixed-up 738 /// code and external reloc/trap/etc. records ready for use. Takes 739 /// the regalloc results as well. 740 /// 741 /// Returns the machine code itself, and optionally metadata 742 /// and/or a disassembly, as an `EmitResult`. The `VCode` itself 743 /// is consumed by the emission process. 744 pub fn emit( 745 mut self, 746 regalloc: ®alloc2::Output, 747 want_disasm: bool, 748 want_metadata: bool, 749 ) -> EmitResult<I> 750 where 751 I: MachInstEmit, 752 { 753 // To write into disasm string. 754 use core::fmt::Write; 755 756 let _tt = timing::vcode_emit(); 757 let mut buffer = MachBuffer::new(); 758 let mut bb_starts: Vec<Option<CodeOffset>> = vec![]; 759 760 // The first M MachLabels are reserved for block indices, the next N MachLabels for 761 // constants. 762 buffer.reserve_labels_for_blocks(self.num_blocks()); 763 buffer.reserve_labels_for_constants(&self.constants); 764 765 // Construct the final order we emit code in: cold blocks at the end. 766 let mut final_order: SmallVec<[BlockIndex; 16]> = smallvec![]; 767 let mut cold_blocks: SmallVec<[BlockIndex; 16]> = smallvec![]; 768 for block in 0..self.num_blocks() { 769 let block = BlockIndex::new(block); 770 if self.block_order.is_cold(block) { 771 cold_blocks.push(block); 772 } else { 773 final_order.push(block); 774 } 775 } 776 final_order.extend(cold_blocks.clone()); 777 778 // Compute/save info we need for the prologue: clobbers and 779 // number of spillslots. 780 // 781 // We clone `abi` here because we will mutate it as we 782 // generate the prologue and set other info, but we can't 783 // mutate `VCode`. The info it usually carries prior to 784 // setting clobbers is fairly minimal so this should be 785 // relatively cheap. 786 let clobbers = self.compute_clobbers(regalloc); 787 self.abi.set_num_spillslots(regalloc.num_spillslots); 788 self.abi.set_clobbered(clobbers); 789 790 // We need to generate the prologue in order to get the ABI 791 // object into the right state first. We'll emit it when we 792 // hit the right block below. 793 let prologue_insts = self.abi.gen_prologue(); 794 795 // Emit blocks. 796 let mut cur_srcloc = None; 797 let mut last_offset = None; 798 let mut inst_offsets = vec![]; 799 let mut state = I::State::new(&self.abi); 800 801 let mut disasm = String::new(); 802 803 if !self.debug_value_labels.is_empty() { 804 inst_offsets.resize(self.insts.len(), 0); 805 } 806 807 // Count edits per block ahead of time; this is needed for 808 // lookahead island emission. (We could derive it per-block 809 // with binary search in the edit list, but it's more 810 // efficient to do it in one pass here.) 811 let mut ra_edits_per_block: SmallVec<[u32; 64]> = smallvec![]; 812 let mut edit_idx = 0; 813 for block in 0..self.num_blocks() { 814 let end_inst = self.block_ranges[block].1; 815 let start_edit_idx = edit_idx; 816 while edit_idx < regalloc.edits.len() && regalloc.edits[edit_idx].0.inst() < end_inst { 817 edit_idx += 1; 818 } 819 let end_edit_idx = edit_idx; 820 ra_edits_per_block.push((end_edit_idx - start_edit_idx) as u32); 821 } 822 823 for (block_order_idx, &block) in final_order.iter().enumerate() { 824 trace!("emitting block {:?}", block); 825 let new_offset = I::align_basic_block(buffer.cur_offset()); 826 while new_offset > buffer.cur_offset() { 827 // Pad with NOPs up to the aligned block offset. 828 let nop = I::gen_nop((new_offset - buffer.cur_offset()) as usize); 829 nop.emit(&[], &mut buffer, &self.emit_info, &mut Default::default()); 830 } 831 assert_eq!(buffer.cur_offset(), new_offset); 832 833 let do_emit = |inst: &I, 834 allocs: &[Allocation], 835 disasm: &mut String, 836 buffer: &mut MachBuffer<I>, 837 state: &mut I::State| { 838 if want_disasm { 839 let mut s = state.clone(); 840 writeln!(disasm, " {}", inst.pretty_print_inst(allocs, &mut s)).unwrap(); 841 } 842 inst.emit(allocs, buffer, &self.emit_info, state); 843 }; 844 845 // Is this the first block? Emit the prologue directly if so. 846 if block == self.entry { 847 trace!(" -> entry block"); 848 buffer.start_srcloc(Default::default()); 849 state.pre_sourceloc(Default::default()); 850 for inst in &prologue_insts { 851 do_emit(&inst, &[], &mut disasm, &mut buffer, &mut state); 852 } 853 buffer.end_srcloc(); 854 } 855 856 // Now emit the regular block body. 857 858 buffer.bind_label(MachLabel::from_block(block)); 859 860 if want_disasm { 861 writeln!(&mut disasm, "block{}:", block.index()).unwrap(); 862 } 863 864 if want_metadata { 865 // Track BB starts. If we have backed up due to MachBuffer 866 // branch opts, note that the removed blocks were removed. 867 let cur_offset = buffer.cur_offset(); 868 if last_offset.is_some() && cur_offset <= last_offset.unwrap() { 869 for i in (0..bb_starts.len()).rev() { 870 if bb_starts[i].is_some() && cur_offset > bb_starts[i].unwrap() { 871 break; 872 } 873 bb_starts[i] = None; 874 } 875 } 876 bb_starts.push(Some(cur_offset)); 877 last_offset = Some(cur_offset); 878 } 879 880 for inst_or_edit in regalloc.block_insts_and_edits(&self, block) { 881 match inst_or_edit { 882 InstOrEdit::Inst(iix) => { 883 if !self.debug_value_labels.is_empty() { 884 // If we need to produce debug info, 885 // record the offset of each instruction 886 // so that we can translate value-label 887 // ranges to machine-code offsets. 888 889 // Cold blocks violate monotonicity 890 // assumptions elsewhere (that 891 // instructions in inst-index order are in 892 // order in machine code), so we omit 893 // their offsets here. Value-label range 894 // generation below will skip empty ranges 895 // and ranges with to-offsets of zero. 896 if !self.block_order.is_cold(block) { 897 inst_offsets[iix.index()] = buffer.cur_offset(); 898 } 899 } 900 901 if self.insts[iix.index()].is_move().is_some() { 902 // Skip moves in the pre-regalloc program; 903 // all of these are incorporated by the 904 // regalloc into its unified move handling 905 // and they come out the other end, if 906 // still needed (not elided), as 907 // regalloc-inserted moves. 908 continue; 909 } 910 911 // Update the srcloc at this point in the buffer. 912 let srcloc = self.srclocs[iix.index()]; 913 if cur_srcloc != Some(srcloc) { 914 if cur_srcloc.is_some() { 915 buffer.end_srcloc(); 916 } 917 buffer.start_srcloc(srcloc); 918 cur_srcloc = Some(srcloc); 919 } 920 state.pre_sourceloc(cur_srcloc.unwrap_or_default()); 921 922 // If this is a safepoint, compute a stack map 923 // and pass it to the emit state. 924 if self.insts[iix.index()].is_safepoint() { 925 let mut safepoint_slots: SmallVec<[SpillSlot; 8]> = smallvec![]; 926 // Find the contiguous range of 927 // (progpoint, allocation) safepoint slot 928 // records in `regalloc.safepoint_slots` 929 // for this instruction index. 930 let safepoint_slots_start = regalloc 931 .safepoint_slots 932 .binary_search_by(|(progpoint, _alloc)| { 933 if progpoint.inst() >= iix { 934 std::cmp::Ordering::Greater 935 } else { 936 std::cmp::Ordering::Less 937 } 938 }) 939 .unwrap_err(); 940 941 for (_, alloc) in regalloc.safepoint_slots[safepoint_slots_start..] 942 .iter() 943 .take_while(|(progpoint, _)| progpoint.inst() == iix) 944 { 945 let slot = alloc.as_stack().unwrap(); 946 safepoint_slots.push(slot); 947 } 948 if !safepoint_slots.is_empty() { 949 let stack_map = self 950 .abi 951 .spillslots_to_stack_map(&safepoint_slots[..], &state); 952 state.pre_safepoint(stack_map); 953 } 954 } 955 956 // Get the allocations for this inst from the regalloc result. 957 let allocs = regalloc.inst_allocs(iix); 958 959 // If the instruction we are about to emit is 960 // a return, place an epilogue at this point 961 // (and don't emit the return; the actual 962 // epilogue will contain it). 963 if self.insts[iix.index()].is_term() == MachTerminator::Ret { 964 for inst in self.abi.gen_epilogue() { 965 do_emit(&inst, &[], &mut disasm, &mut buffer, &mut state); 966 } 967 } else { 968 // Emit the instruction! 969 do_emit( 970 &self.insts[iix.index()], 971 allocs, 972 &mut disasm, 973 &mut buffer, 974 &mut state, 975 ); 976 } 977 } 978 979 InstOrEdit::Edit(Edit::Move { from, to }) => { 980 // Create a move/spill/reload instruction and 981 // immediately emit it. 982 match (from.as_reg(), to.as_reg()) { 983 (Some(from), Some(to)) => { 984 // Reg-to-reg move. 985 let from_rreg = Reg::from(from); 986 let to_rreg = Writable::from_reg(Reg::from(to)); 987 debug_assert_eq!(from.class(), to.class()); 988 let ty = I::canonical_type_for_rc(from.class()); 989 let mv = I::gen_move(to_rreg, from_rreg, ty); 990 do_emit(&mv, &[], &mut disasm, &mut buffer, &mut state); 991 } 992 (Some(from), None) => { 993 // Spill from register to spillslot. 994 let to = to.as_stack().unwrap(); 995 let from_rreg = RealReg::from(from); 996 debug_assert_eq!(from.class(), to.class()); 997 let spill = self.abi.gen_spill(to, from_rreg); 998 do_emit(&spill, &[], &mut disasm, &mut buffer, &mut state); 999 } 1000 (None, Some(to)) => { 1001 // Load from spillslot to register. 1002 let from = from.as_stack().unwrap(); 1003 let to_rreg = Writable::from_reg(RealReg::from(to)); 1004 debug_assert_eq!(from.class(), to.class()); 1005 let reload = self.abi.gen_reload(to_rreg, from); 1006 do_emit(&reload, &[], &mut disasm, &mut buffer, &mut state); 1007 } 1008 (None, None) => { 1009 panic!("regalloc2 should have eliminated stack-to-stack moves!"); 1010 } 1011 } 1012 } 1013 } 1014 } 1015 1016 if cur_srcloc.is_some() { 1017 buffer.end_srcloc(); 1018 cur_srcloc = None; 1019 } 1020 1021 // Do we need an island? Get the worst-case size of the 1022 // next BB and see if, having emitted that many bytes, we 1023 // will be beyond the deadline. 1024 if block_order_idx < final_order.len() - 1 { 1025 let next_block = final_order[block_order_idx + 1]; 1026 let next_block_range = self.block_ranges[next_block.index()]; 1027 let next_block_size = 1028 (next_block_range.1.index() - next_block_range.0.index()) as u32; 1029 let next_block_ra_insertions = ra_edits_per_block[next_block.index()]; 1030 let worst_case_next_bb = 1031 I::worst_case_size() * (next_block_size + next_block_ra_insertions); 1032 if buffer.island_needed(worst_case_next_bb) { 1033 buffer.emit_island(worst_case_next_bb); 1034 } 1035 } 1036 } 1037 1038 // Emit the constants used by the function. 1039 for (constant, data) in self.constants.iter() { 1040 let label = buffer.get_label_for_constant(constant); 1041 buffer.defer_constant(label, data.alignment(), data.as_slice(), u32::max_value()); 1042 } 1043 1044 let func_body_len = buffer.cur_offset(); 1045 1046 // Create `bb_edges` and final (filtered) `bb_starts`. 1047 let mut bb_edges = vec![]; 1048 let mut bb_offsets = vec![]; 1049 if want_metadata { 1050 for block in 0..self.num_blocks() { 1051 if bb_starts[block].is_none() { 1052 // Block was deleted by MachBuffer; skip. 1053 continue; 1054 } 1055 let from = bb_starts[block].unwrap(); 1056 1057 bb_offsets.push(from); 1058 // Resolve each `succ` label and add edges. 1059 let succs = self.block_succs(BlockIndex::new(block)); 1060 for &succ in succs.iter() { 1061 let to = buffer.resolve_label_offset(MachLabel::from_block(succ)); 1062 bb_edges.push((from, to)); 1063 } 1064 } 1065 } 1066 1067 let value_labels_ranges = 1068 self.compute_value_labels_ranges(regalloc, &inst_offsets[..], func_body_len); 1069 let frame_size = self.abi.frame_size(); 1070 1071 EmitResult { 1072 buffer, 1073 bb_offsets, 1074 bb_edges, 1075 inst_offsets, 1076 func_body_len, 1077 disasm: if want_disasm { Some(disasm) } else { None }, 1078 sized_stackslot_offsets: self.abi.sized_stackslot_offsets().clone(), 1079 dynamic_stackslot_offsets: self.abi.dynamic_stackslot_offsets().clone(), 1080 value_labels_ranges, 1081 frame_size, 1082 } 1083 } 1084 1085 fn compute_value_labels_ranges( 1086 &self, 1087 regalloc: ®alloc2::Output, 1088 inst_offsets: &[CodeOffset], 1089 func_body_len: u32, 1090 ) -> ValueLabelsRanges { 1091 if self.debug_value_labels.is_empty() { 1092 return ValueLabelsRanges::default(); 1093 } 1094 1095 let mut value_labels_ranges: ValueLabelsRanges = HashMap::new(); 1096 for &(label, from, to, alloc) in ®alloc.debug_locations { 1097 let ranges = value_labels_ranges 1098 .entry(ValueLabel::from_u32(label)) 1099 .or_insert_with(|| vec![]); 1100 let from_offset = inst_offsets[from.inst().index()]; 1101 let to_offset = if to.inst().index() == inst_offsets.len() { 1102 func_body_len 1103 } else { 1104 inst_offsets[to.inst().index()] 1105 }; 1106 1107 // Empty range or to-offset of zero can happen because of 1108 // cold blocks (see above). 1109 if to_offset == 0 || from_offset == to_offset { 1110 continue; 1111 } 1112 1113 let loc = if let Some(preg) = alloc.as_reg() { 1114 LabelValueLoc::Reg(Reg::from(preg)) 1115 } else { 1116 // We can't translate spillslot locations at the 1117 // moment because ValueLabelLoc requires an 1118 // instantaneous SP offset, and this can *change* 1119 // within the range we have here because of callsites 1120 // adjusting SP temporarily. To avoid the complexity 1121 // of accurately plumbing through nominal-SP 1122 // adjustment sites, we just omit debug info for 1123 // values that are spilled. Not ideal, but debug info 1124 // is best-effort. 1125 continue; 1126 }; 1127 1128 ranges.push(ValueLocRange { 1129 loc, 1130 // ValueLocRanges are recorded by *instruction-end 1131 // offset*. `from_offset` is the *start* of the 1132 // instruction; that is the same as the end of another 1133 // instruction, so we only want to begin coverage once 1134 // we are past the previous instruction's end. 1135 start: from_offset + 1, 1136 // Likewise, `end` is exclusive, but we want to 1137 // *include* the end of the last 1138 // instruction. `to_offset` is the start of the 1139 // `to`-instruction, which is the exclusive end, i.e., 1140 // the first instruction not covered. That 1141 // instruction's start is the same as the end of the 1142 // last instruction that is included, so we go one 1143 // byte further to be sure to include it. 1144 end: to_offset + 1, 1145 }); 1146 } 1147 1148 value_labels_ranges 1149 } 1150 1151 /// Get the IR block for a BlockIndex, if one exists. 1152 pub fn bindex_to_bb(&self, block: BlockIndex) -> Option<ir::Block> { 1153 self.block_order.lowered_order()[block.index()].orig_block() 1154 } 1155 1156 #[inline] 1157 fn assert_no_vreg_aliases<'a>(&self, list: &'a [VReg]) -> &'a [VReg] { 1158 for vreg in list { 1159 self.assert_not_vreg_alias(*vreg); 1160 } 1161 list 1162 } 1163 1164 #[inline] 1165 fn assert_not_vreg_alias(&self, vreg: VReg) -> VReg { 1166 debug_assert!(VCodeBuilder::<I>::resolve_vreg_alias_impl(&self.vreg_aliases, vreg) == vreg); 1167 vreg 1168 } 1169 1170 #[inline] 1171 fn assert_operand_not_vreg_alias(&self, op: Operand) -> Operand { 1172 // It should be true by construction that `Operand`s do not contain any 1173 // aliased vregs since they're all collected and mapped when the VCode 1174 // is itself constructed. 1175 self.assert_not_vreg_alias(op.vreg()); 1176 op 1177 } 1178 } 1179 1180 impl<I: VCodeInst> RegallocFunction for VCode<I> { 1181 fn num_insts(&self) -> usize { 1182 self.insts.len() 1183 } 1184 1185 fn num_blocks(&self) -> usize { 1186 self.block_ranges.len() 1187 } 1188 1189 fn entry_block(&self) -> BlockIndex { 1190 self.entry 1191 } 1192 1193 fn block_insns(&self, block: BlockIndex) -> InstRange { 1194 let (start, end) = self.block_ranges[block.index()]; 1195 InstRange::forward(start, end) 1196 } 1197 1198 fn block_succs(&self, block: BlockIndex) -> &[BlockIndex] { 1199 let (start, end) = self.block_succ_range[block.index()]; 1200 &self.block_succs_preds[start as usize..end as usize] 1201 } 1202 1203 fn block_preds(&self, block: BlockIndex) -> &[BlockIndex] { 1204 let (start, end) = self.block_pred_range[block.index()]; 1205 &self.block_succs_preds[start as usize..end as usize] 1206 } 1207 1208 fn block_params(&self, block: BlockIndex) -> &[VReg] { 1209 let (start, end) = self.block_params_range[block.index()]; 1210 let ret = &self.block_params[start as usize..end as usize]; 1211 // Currently block params are never aliased to another vreg, but 1212 // double-check just to be sure. 1213 self.assert_no_vreg_aliases(ret) 1214 } 1215 1216 fn branch_blockparams(&self, block: BlockIndex, _insn: InsnIndex, succ_idx: usize) -> &[VReg] { 1217 let (succ_range_start, succ_range_end) = self.branch_block_arg_succ_range[block.index()]; 1218 let succ_ranges = 1219 &self.branch_block_arg_range[succ_range_start as usize..succ_range_end as usize]; 1220 let (branch_block_args_start, branch_block_args_end) = succ_ranges[succ_idx]; 1221 let ret = &self.branch_block_args 1222 [branch_block_args_start as usize..branch_block_args_end as usize]; 1223 self.assert_no_vreg_aliases(ret) 1224 } 1225 1226 fn is_ret(&self, insn: InsnIndex) -> bool { 1227 match self.insts[insn.index()].is_term() { 1228 MachTerminator::Ret => true, 1229 _ => false, 1230 } 1231 } 1232 1233 fn is_branch(&self, insn: InsnIndex) -> bool { 1234 match self.insts[insn.index()].is_term() { 1235 MachTerminator::Cond | MachTerminator::Uncond | MachTerminator::Indirect => true, 1236 _ => false, 1237 } 1238 } 1239 1240 fn requires_refs_on_stack(&self, insn: InsnIndex) -> bool { 1241 self.insts[insn.index()].is_safepoint() 1242 } 1243 1244 fn is_move(&self, insn: InsnIndex) -> Option<(Operand, Operand)> { 1245 let (a, b) = self.is_move.get(&insn)?; 1246 Some(( 1247 self.assert_operand_not_vreg_alias(*a), 1248 self.assert_operand_not_vreg_alias(*b), 1249 )) 1250 } 1251 1252 fn inst_operands(&self, insn: InsnIndex) -> &[Operand] { 1253 let (start, end) = self.operand_ranges[insn.index()]; 1254 let ret = &self.operands[start as usize..end as usize]; 1255 for op in ret { 1256 self.assert_operand_not_vreg_alias(*op); 1257 } 1258 ret 1259 } 1260 1261 fn inst_clobbers(&self, insn: InsnIndex) -> PRegSet { 1262 self.clobbers.get(&insn).cloned().unwrap_or_default() 1263 } 1264 1265 fn num_vregs(&self) -> usize { 1266 std::cmp::max(self.vreg_types.len(), first_user_vreg_index()) 1267 } 1268 1269 fn reftype_vregs(&self) -> &[VReg] { 1270 self.assert_no_vreg_aliases(&self.reftyped_vregs[..]) 1271 } 1272 1273 fn debug_value_labels(&self) -> &[(VReg, InsnIndex, InsnIndex, u32)] { 1274 // VRegs here are inserted into `debug_value_labels` after code is 1275 // generated and aliases are fully defined, so no double-check that 1276 // aliases are not lingering. 1277 for (vreg, ..) in self.debug_value_labels.iter() { 1278 self.assert_not_vreg_alias(*vreg); 1279 } 1280 &self.debug_value_labels[..] 1281 } 1282 1283 fn is_pinned_vreg(&self, vreg: VReg) -> Option<PReg> { 1284 pinned_vreg_to_preg(vreg) 1285 } 1286 1287 fn spillslot_size(&self, regclass: RegClass) -> usize { 1288 self.abi.get_spillslot_size(regclass) as usize 1289 } 1290 1291 fn allow_multiple_vreg_defs(&self) -> bool { 1292 // At least the s390x backend requires this, because the 1293 // `Loop` pseudo-instruction aggregates all Operands so pinned 1294 // vregs (RealRegs) may occur more than once. 1295 true 1296 } 1297 } 1298 1299 impl<I: VCodeInst> fmt::Debug for VCode<I> { 1300 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { 1301 writeln!(f, "VCode {{")?; 1302 writeln!(f, " Entry block: {}", self.entry.index())?; 1303 1304 let mut state = Default::default(); 1305 1306 let mut alias_keys = self.vreg_aliases.keys().cloned().collect::<Vec<_>>(); 1307 alias_keys.sort_unstable(); 1308 for key in alias_keys { 1309 let dest = self.vreg_aliases.get(&key).unwrap(); 1310 writeln!(f, " {:?} := {:?}", Reg::from(key), Reg::from(*dest))?; 1311 } 1312 1313 for block in 0..self.num_blocks() { 1314 let block = BlockIndex::new(block); 1315 writeln!(f, "Block {}:", block.index())?; 1316 if let Some(bb) = self.bindex_to_bb(block) { 1317 writeln!(f, " (original IR block: {})", bb)?; 1318 } 1319 for succ in self.succs(block) { 1320 writeln!(f, " (successor: Block {})", succ.index())?; 1321 } 1322 let (start, end) = self.block_ranges[block.index()]; 1323 writeln!( 1324 f, 1325 " (instruction range: {} .. {})", 1326 start.index(), 1327 end.index() 1328 )?; 1329 for inst in start.index()..end.index() { 1330 writeln!( 1331 f, 1332 " Inst {}: {}", 1333 inst, 1334 self.insts[inst].pretty_print_inst(&[], &mut state) 1335 )?; 1336 } 1337 } 1338 1339 writeln!(f, "}}")?; 1340 Ok(()) 1341 } 1342 } 1343 1344 /// This structure tracks the large constants used in VCode that will be emitted separately by the 1345 /// [MachBuffer]. 1346 /// 1347 /// First, during the lowering phase, constants are inserted using 1348 /// [VCodeConstants.insert]; an intermediate handle, [VCodeConstant], tracks what constants are 1349 /// used in this phase. Some deduplication is performed, when possible, as constant 1350 /// values are inserted. 1351 /// 1352 /// Secondly, during the emission phase, the [MachBuffer] assigns [MachLabel]s for each of the 1353 /// constants so that instructions can refer to the value's memory location. The [MachBuffer] 1354 /// then writes the constant values to the buffer. 1355 #[derive(Default)] 1356 pub struct VCodeConstants { 1357 constants: PrimaryMap<VCodeConstant, VCodeConstantData>, 1358 pool_uses: HashMap<Constant, VCodeConstant>, 1359 well_known_uses: HashMap<*const [u8], VCodeConstant>, 1360 u64s: HashMap<[u8; 8], VCodeConstant>, 1361 } 1362 impl VCodeConstants { 1363 /// Initialize the structure with the expected number of constants. 1364 pub fn with_capacity(expected_num_constants: usize) -> Self { 1365 Self { 1366 constants: PrimaryMap::with_capacity(expected_num_constants), 1367 pool_uses: HashMap::with_capacity(expected_num_constants), 1368 well_known_uses: HashMap::new(), 1369 u64s: HashMap::new(), 1370 } 1371 } 1372 1373 /// Insert a constant; using this method indicates that a constant value will be used and thus 1374 /// will be emitted to the `MachBuffer`. The current implementation can deduplicate constants 1375 /// that are [VCodeConstantData::Pool] or [VCodeConstantData::WellKnown] but not 1376 /// [VCodeConstantData::Generated]. 1377 pub fn insert(&mut self, data: VCodeConstantData) -> VCodeConstant { 1378 match data { 1379 VCodeConstantData::Generated(_) => self.constants.push(data), 1380 VCodeConstantData::Pool(constant, _) => match self.pool_uses.get(&constant) { 1381 None => { 1382 let vcode_constant = self.constants.push(data); 1383 self.pool_uses.insert(constant, vcode_constant); 1384 vcode_constant 1385 } 1386 Some(&vcode_constant) => vcode_constant, 1387 }, 1388 VCodeConstantData::WellKnown(data_ref) => { 1389 match self.well_known_uses.entry(data_ref as *const [u8]) { 1390 Entry::Vacant(v) => { 1391 let vcode_constant = self.constants.push(data); 1392 v.insert(vcode_constant); 1393 vcode_constant 1394 } 1395 Entry::Occupied(o) => *o.get(), 1396 } 1397 } 1398 VCodeConstantData::U64(value) => match self.u64s.entry(value) { 1399 Entry::Vacant(v) => { 1400 let vcode_constant = self.constants.push(data); 1401 v.insert(vcode_constant); 1402 vcode_constant 1403 } 1404 Entry::Occupied(o) => *o.get(), 1405 }, 1406 } 1407 } 1408 1409 /// Return the number of constants inserted. 1410 pub fn len(&self) -> usize { 1411 self.constants.len() 1412 } 1413 1414 /// Iterate over the [VCodeConstant] keys inserted in this structure. 1415 pub fn keys(&self) -> Keys<VCodeConstant> { 1416 self.constants.keys() 1417 } 1418 1419 /// Iterate over the [VCodeConstant] keys and the data (as a byte slice) inserted in this 1420 /// structure. 1421 pub fn iter(&self) -> impl Iterator<Item = (VCodeConstant, &VCodeConstantData)> { 1422 self.constants.iter() 1423 } 1424 } 1425 1426 /// A use of a constant by one or more VCode instructions; see [VCodeConstants]. 1427 #[derive(Clone, Copy, Debug, PartialEq, Eq)] 1428 pub struct VCodeConstant(u32); 1429 entity_impl!(VCodeConstant); 1430 1431 /// Identify the different types of constant that can be inserted into [VCodeConstants]. Tracking 1432 /// these separately instead of as raw byte buffers allows us to avoid some duplication. 1433 pub enum VCodeConstantData { 1434 /// A constant already present in the Cranelift IR 1435 /// [ConstantPool](crate::ir::constant::ConstantPool). 1436 Pool(Constant, ConstantData), 1437 /// A reference to a well-known constant value that is statically encoded within the compiler. 1438 WellKnown(&'static [u8]), 1439 /// A constant value generated during lowering; the value may depend on the instruction context 1440 /// which makes it difficult to de-duplicate--if possible, use other variants. 1441 Generated(ConstantData), 1442 /// A constant of at most 64 bits. These are deduplicated as 1443 /// well. Stored as a fixed-size array of `u8` so that we do not 1444 /// encounter endianness problems when cross-compiling. 1445 U64([u8; 8]), 1446 } 1447 impl VCodeConstantData { 1448 /// Retrieve the constant data as a byte slice. 1449 pub fn as_slice(&self) -> &[u8] { 1450 match self { 1451 VCodeConstantData::Pool(_, d) | VCodeConstantData::Generated(d) => d.as_slice(), 1452 VCodeConstantData::WellKnown(d) => d, 1453 VCodeConstantData::U64(value) => &value[..], 1454 } 1455 } 1456 1457 /// Calculate the alignment of the constant data. 1458 pub fn alignment(&self) -> u32 { 1459 if self.as_slice().len() <= 8 { 1460 8 1461 } else { 1462 16 1463 } 1464 } 1465 } 1466 1467 #[cfg(test)] 1468 mod test { 1469 use super::*; 1470 use std::mem::size_of; 1471 1472 #[test] 1473 fn size_of_constant_structs() { 1474 assert_eq!(size_of::<Constant>(), 4); 1475 assert_eq!(size_of::<VCodeConstant>(), 4); 1476 assert_eq!(size_of::<ConstantData>(), 24); 1477 assert_eq!(size_of::<VCodeConstantData>(), 32); 1478 assert_eq!( 1479 size_of::<PrimaryMap<VCodeConstant, VCodeConstantData>>(), 1480 24 1481 ); 1482 // TODO The VCodeConstants structure's memory size could be further optimized. 1483 // With certain versions of Rust, each `HashMap` in `VCodeConstants` occupied at 1484 // least 48 bytes, making an empty `VCodeConstants` cost 120 bytes. 1485 } 1486 } 1487