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