Skip to main content

cranelift_codegen/machinst/
lower.rs

1//! This module implements lowering (instruction selection) from Cranelift IR
2//! to machine instructions with virtual registers. This is *almost* the final
3//! machine code, except for register allocation.
4
5// TODO: separate the IR-query core of `Lower` from the lowering logic built on
6// top of it, e.g. the side-effect/coloring analysis and the scan support.
7
8use crate::entity::SecondaryMap;
9use crate::inst_predicates::{
10    has_lowering_side_effect, is_constant_64bit, must_lower_even_if_unused,
11};
12use crate::ir::{
13    ArgumentPurpose, Block, BlockArg, Constant, ConstantData, DataFlowGraph, ExternalName,
14    Function, GlobalValue, GlobalValueData, Immediate, Inst, InstructionData, RelSourceLoc, SigRef,
15    Signature, Type, Value, ValueDef, ValueLabelAssignments, ValueLabelStart,
16};
17use crate::machinst::valueregs::InvalidSentinel;
18use crate::machinst::{
19    ABIMachineSpec, BackwardsInsnIndex, BlockIndex, BlockLoweringOrder, CallArgList, CallInfo,
20    CallRetList, Callee, InsnIndex, LoweredBlock, MachLabel, MachMemFlags, Reg, Sig, SigSet,
21    TryCallInfo, VCode, VCodeBuilder, VCodeConstant, VCodeConstantData, VCodeConstants, VCodeInst,
22    ValueRegs, Writable, writable_value_regs,
23};
24use crate::settings::Flags;
25use crate::{CodegenError, CodegenResult, trace};
26use crate::{FxHashMap, FxHashSet};
27use alloc::vec::Vec;
28use core::fmt::Debug;
29use cranelift_control::ControlPlane;
30use smallvec::{SmallVec, smallvec};
31
32use super::{VCodeBuildDirection, VRegAllocator};
33
34/// A vector of ValueRegs, used to represent the outputs of an instruction.
35pub type InstOutput = SmallVec<[ValueRegs<Reg>; 2]>;
36
37/// An "instruction color" partitions CLIF instructions by side-effecting ops.
38/// All instructions with the same "color" are guaranteed not to be separated by
39/// any side-effecting op (for this purpose, loads are also considered
40/// side-effecting, to avoid subtle questions w.r.t. the memory model), and
41/// furthermore, it is guaranteed that for any two instructions A and B such
42/// that color(A) == color(B), either A dominates B and B postdominates A, or
43/// vice-versa. (For now, in practice, only ops in the same basic block can ever
44/// have the same color, trivially providing the second condition.) Intuitively,
45/// this means that the ops of the same color must always execute "together", as
46/// part of one atomic contiguous section of the dynamic execution trace, and
47/// they can be freely permuted (modulo true dataflow dependencies) without
48/// affecting program behavior.
49#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
50struct InstColor(u32);
51impl InstColor {
52    fn new(n: u32) -> InstColor {
53        InstColor(n)
54    }
55
56    /// Get an arbitrary index representing this color. The index is unique
57    /// *within a single function compilation*, but indices may be reused across
58    /// functions.
59    pub fn get(self) -> u32 {
60        self.0
61    }
62}
63
64/// A representation of all of the ways in which a value is available, aside
65/// from as a direct register.
66///
67/// - An instruction, if it would be allowed to occur at the current location
68///   instead (see [Lower::get_input_as_source_or_const()] for more details).
69///
70/// - A constant, if the value is known to be a constant.
71#[derive(Clone, Copy, Debug)]
72pub struct NonRegInput {
73    /// An instruction produces this value (as the given output), and its
74    /// computation (and side-effect if applicable) could occur at the
75    /// current instruction's location instead.
76    ///
77    /// If this instruction's operation is merged into the current instruction,
78    /// the backend must call [Lower::sink_inst()].
79    ///
80    /// This enum indicates whether this use of the source instruction
81    /// is unique or not.
82    pub inst: InputSourceInst,
83    /// The value is a known constant.
84    pub constant: Option<u64>,
85}
86
87/// When examining an input to an instruction, this enum provides one
88/// of several options: there is or isn't a single instruction (that
89/// we can see and merge with) that produces that input's value, and
90/// we are or aren't the single user of that instruction.
91#[derive(Clone, Copy, Debug)]
92pub enum InputSourceInst {
93    /// The input in question is the single, unique use of the given
94    /// instruction and output index, and it can be sunk to the
95    /// location of this input.
96    UniqueUse(Inst, usize),
97    /// The input in question is one of multiple uses of the given
98    /// instruction. It can still be sunk to the location of this
99    /// input.
100    Use(Inst, usize),
101    /// We cannot determine which instruction produced the input, or
102    /// it is one of several instructions (e.g., due to a control-flow
103    /// merge and blockparam), or the source instruction cannot be
104    /// allowed to sink to the current location due to side-effects.
105    None,
106}
107
108impl InputSourceInst {
109    /// Get the instruction and output index for this source, whether
110    /// we are its single or one of many users.
111    pub fn as_inst(&self) -> Option<(Inst, usize)> {
112        match self {
113            &InputSourceInst::UniqueUse(inst, output_idx)
114            | &InputSourceInst::Use(inst, output_idx) => Some((inst, output_idx)),
115            &InputSourceInst::None => None,
116        }
117    }
118}
119
120/// A machine backend.
121pub trait LowerBackend {
122    /// The machine instruction type.
123    type MInst: VCodeInst;
124
125    /// Lower a single instruction.
126    ///
127    /// For a branch, this function should not generate the actual branch
128    /// instruction. However, it must force any values it needs for the branch
129    /// edge (block-param actuals) into registers, because the actual branch
130    /// generation (`lower_branch()`) happens *after* any possible merged
131    /// out-edge.
132    ///
133    /// Returns `None` if no lowering for the instruction was found.
134    fn lower(&self, ctx: &mut Lower<Self::MInst>, inst: Inst) -> Option<InstOutput>;
135
136    /// Lower a block-terminating group of branches (which together can be seen
137    /// as one N-way branch), given a vcode MachLabel for each target.
138    ///
139    /// Returns `None` if no lowering for the branch was found.
140    fn lower_branch(
141        &self,
142        ctx: &mut Lower<Self::MInst>,
143        inst: Inst,
144        targets: &[MachLabel],
145    ) -> Option<()>;
146
147    /// A bit of a hack: give a fixed register that always holds the result of a
148    /// `get_pinned_reg` instruction, if known.  This allows elision of moves
149    /// into the associated vreg, instead using the real reg directly.
150    fn maybe_pinned_reg(&self) -> Option<Reg> {
151        None
152    }
153}
154
155/// Machine-independent lowering driver / machine-instruction container. Maintains a correspondence
156/// from original Inst to MachInsts.
157pub struct Lower<'func, I: VCodeInst> {
158    /// The function to lower.
159    pub(crate) f: &'func Function,
160
161    /// Lowered machine instructions.
162    vcode: VCodeBuilder<I>,
163
164    /// VReg allocation context, given to the vcode field at build time to finalize the vcode.
165    vregs: VRegAllocator<I>,
166
167    /// Mapping from `Value` (SSA value in IR) to virtual register.
168    value_regs: SecondaryMap<Value, ValueRegs<Reg>>,
169
170    /// sret registers, if needed.
171    sret_reg: Option<ValueRegs<Reg>>,
172
173    /// Instruction colors at block exits. From this map, we can recover all
174    /// instruction colors by scanning backward from the block end and
175    /// decrementing on any color-changing (side-effecting) instruction.
176    block_end_colors: SecondaryMap<Block, InstColor>,
177
178    /// Instruction colors at side-effecting ops. This is the *entry* color,
179    /// i.e., the version of global state that exists before an instruction
180    /// executes.  For each side-effecting instruction, the *exit* color is its
181    /// entry color plus one.
182    ///
183    /// The current color is incremented to at least 1 before any instruction is
184    /// processed, so every side-effecting instruction has a color `>= 1`, and
185    /// the default `InstColor::new(0)` serves as a "not side-effecting"
186    /// sentinel.
187    side_effect_inst_entry_colors: SecondaryMap<Inst, InstColor>,
188
189    /// Current color as we scan during lowering. While we are lowering an
190    /// instruction, this is equal to the color *at entry to* the instruction.
191    cur_scan_entry_color: Option<InstColor>,
192
193    /// Current instruction as we scan during lowering.
194    cur_inst: Option<Inst>,
195
196    /// Use-counts per SSA value, as counted in the input IR. These
197    /// are "coarsened", in the abstract-interpretation sense: we only
198    /// care about "0, 1, many" states, as this is all we need and
199    /// this lets us do an efficient fixpoint analysis.
200    ///
201    /// See doc comment on `ValueUseState` for more details.
202    value_ir_uses: SecondaryMap<Value, ValueUseState>,
203
204    /// Actual uses of each SSA value so far, incremented while lowering.
205    value_lowered_uses: SecondaryMap<Value, u32>,
206
207    /// Effectful instructions that have been sunk; they are not codegen'd at
208    /// their original locations.
209    inst_sunk: FxHashSet<Inst>,
210
211    /// Instructions collected for the CLIF inst in progress, in forward order.
212    ir_insts: Vec<I>,
213
214    /// Try-call block arg normal-return values, indexed by instruction.
215    try_call_rets: FxHashMap<Inst, SmallVec<[ValueRegs<Writable<Reg>>; 2]>>,
216
217    /// Try-call block arg exceptional-return payloads, indexed by
218    /// instruction. Payloads are carried in registers per the ABI and
219    /// can only be one register each.
220    try_call_payloads: FxHashMap<Inst, SmallVec<[Writable<Reg>; 2]>>,
221
222    /// The register to use for GetPinnedReg, if any, on this architecture.
223    pinned_reg: Option<Reg>,
224
225    /// Compilation flags.
226    flags: Flags,
227}
228
229/// How is a value used in the IR?
230///
231/// This can be seen as a coarsening of an integer count. We only need
232/// distinct states for zero, one, or many.
233///
234/// This analysis deserves further explanation. The basic idea is that
235/// we want to allow instruction lowering to know whether a value that
236/// an instruction references is *only* referenced by that one use, or
237/// by others as well. This is necessary to know when we might want to
238/// move a side-effect: we cannot, for example, duplicate a load, so
239/// we cannot let instruction lowering match a load as part of a
240/// subpattern and potentially incorporate it.
241///
242/// Note that a lot of subtlety comes into play once we have
243/// *indirect* uses. The classical example of this in our development
244/// history was the x86 compare instruction, which is incorporated
245/// into flags users (e.g. `selectif`, `trueif`, branches) and can
246/// subsequently incorporate loads, or at least we would like it
247/// to. However, danger awaits: the compare might be the only user of
248/// a load, so we might think we can just move the load (and nothing
249/// is duplicated -- success!), except that the compare itself is
250/// codegen'd in multiple places, where it is incorporated as a
251/// subpattern itself.
252///
253/// So we really want a notion of "unique all the way along the
254/// matching path". Rust's `&T` and `&mut T` offer a partial analogy
255/// to the semantics that we want here: we want to know when we've
256/// matched a unique use of an instruction, and that instruction's
257/// unique use of another instruction, etc, just as `&mut T` can only
258/// be obtained by going through a chain of `&mut T`. If one has a
259/// `&T` to a struct containing `&mut T` (one of several uses of an
260/// instruction that itself has a unique use of an instruction), one
261/// can only get a `&T` (one can only get a "I am one of several users
262/// of this instruction" result).
263///
264/// We could track these paths, either dynamically as one "looks up the operand
265/// tree" or precomputed. But the former requires state and means that the
266/// `Lower` API carries that state implicitly, which we'd like to avoid if we
267/// can. And the latter implies O(n^2) storage: it is an all-pairs property (is
268/// inst `i` unique from the point of view of `j`).
269///
270/// To make matters even a little more complex still, a value that is
271/// not uniquely used when initially viewing the IR can *become*
272/// uniquely used, at least as a root allowing further unique uses of
273/// e.g. loads to merge, if no other instruction actually merges
274/// it. To be more concrete, if we have `v1 := load; v2 := op v1; v3
275/// := op v2; v4 := op v2` then `v2` is non-uniquely used, so from the
276/// point of view of lowering `v4` or `v3`, we cannot merge the load
277/// at `v1`. But if we decide just to use the assigned register for
278/// `v2` at both `v3` and `v4`, then we only actually codegen `v2`
279/// once, so it *is* a unique root at that point and we *can* merge
280/// the load.
281///
282/// Note also that the color scheme is not sufficient to give us this
283/// information, for various reasons: reasoning about side-effects
284/// does not tell us about potential duplication of uses through pure
285/// ops.
286///
287/// To keep things simple and avoid error-prone lowering APIs that
288/// would extract more information about whether instruction merging
289/// happens or not (we don't have that info now, and it would be
290/// difficult to refactor to get it and make that refactor 100%
291/// correct), we give up on the above "can become unique if not
292/// actually merged" point. Instead, we compute a
293/// transitive-uniqueness. That is what this enum represents.
294///
295/// There is one final caveat as well to the result of this analysis.  Notably,
296/// we define some instructions to be "root" instructions, which means that we
297/// assume they will always be codegen'd at the root of a matching tree, and not
298/// matched. (This comes with the caveat that we actually enforce this property
299/// by making them "opaque" to subtree matching in
300/// `get_value_as_source_or_const`). Because they will always be codegen'd once,
301/// they in some sense "reset" multiplicity: these root instructions can be used
302/// many times, but because their result(s) are only computed once, they only
303/// use their inputs once.
304///
305/// We currently define all multi-result instructions to be "root" instructions,
306/// because it is too complex to reason about matching through them, and they
307/// cause too-coarse-grained approximation of multiplicity otherwise: the
308/// analysis would have to assume (as it used to!) that they are always
309/// multiply-used, simply because they have multiple outputs even if those
310/// outputs are used only once.
311///
312/// In the future we could define other instructions to be "root" instructions
313/// as well, if we make the corresponding change to get_value_as_source_or_const
314/// as well.
315///
316/// To define `ValueUseState` more plainly: a value is `Unused` if no references
317/// exist to it; `Once` if only one other op refers to it, *and* that other op
318/// is `Unused` or `Once`; and `Multiple` otherwise. In other words, `Multiple`
319/// is contagious (except through root instructions): even if an op's result
320/// value is directly used only once in the CLIF, that value is `Multiple` if
321/// the op that uses it is itself used multiple times (hence could be codegen'd
322/// multiple times). In brief, this analysis tells us whether, if every op
323/// merged all of its operand tree, a given op could be codegen'd in more than
324/// one place.
325///
326/// To compute this, we first consider direct uses. At this point
327/// `Unused` answers are correct, `Multiple` answers are correct, but
328/// some `Once`s may change to `Multiple`s. Then we propagate
329/// `Multiple` transitively using a workqueue/fixpoint algorithm.
330#[derive(Clone, Copy, Debug, PartialEq, Eq)]
331enum ValueUseState {
332    /// Not used at all.
333    Unused,
334    /// Used exactly once.
335    Once,
336    /// Used multiple times.
337    Multiple,
338}
339
340impl ValueUseState {
341    /// Add one use.
342    fn inc(&mut self) {
343        let new = match self {
344            Self::Unused => Self::Once,
345            Self::Once | Self::Multiple => Self::Multiple,
346        };
347        *self = new;
348    }
349}
350
351/// Notion of "relocation distance". This gives an estimate of how far away a symbol will be from a
352/// reference.
353#[derive(Clone, Copy, Debug, PartialEq, Eq)]
354pub enum RelocDistance {
355    /// Target of relocation is "nearby". The threshold for this is fuzzy but should be interpreted
356    /// as approximately "within the compiled output of one module"; e.g., within AArch64's +/-
357    /// 128MB offset. If unsure, use `Far` instead.
358    Near,
359    /// Target of relocation could be anywhere in the address space.
360    Far,
361}
362
363impl<'func, I: VCodeInst> Lower<'func, I> {
364    /// Prepare a new lowering context for the given IR function.
365    pub fn new(
366        f: &'func Function,
367        abi: Callee<I::ABIMachineSpec>,
368        emit_info: I::Info,
369        block_order: BlockLoweringOrder,
370        sigs: SigSet,
371        flags: Flags,
372    ) -> CodegenResult<Self> {
373        let constants = VCodeConstants::with_capacity(f.dfg.constants.len());
374        let vcode = VCodeBuilder::new(
375            sigs,
376            abi,
377            emit_info,
378            block_order,
379            constants,
380            VCodeBuildDirection::Backward,
381            flags.log2_min_function_alignment(),
382        );
383
384        // We usually need two VRegs per instruction result, plus extras for
385        // various temporaries, but two per Value is a good starting point.
386        let mut vregs = VRegAllocator::with_capacity(f.dfg.num_values() * 2);
387
388        let mut value_regs = SecondaryMap::with_default(ValueRegs::invalid());
389        let mut try_call_rets = FxHashMap::default();
390        let mut try_call_payloads = FxHashMap::default();
391
392        // Assign a vreg to each block param, each inst result, and
393        // each edge-defined block-call arg.
394        for bb in f.layout.blocks() {
395            for &param in f.dfg.block_params(bb) {
396                let ty = f.dfg.value_type(param);
397                if value_regs[param].is_invalid() {
398                    let regs = vregs.alloc(ty)?;
399                    value_regs[param] = regs;
400                    trace!("bb {} param {}: regs {:?}", bb, param, regs);
401                }
402            }
403            for inst in f.layout.block_insts(bb) {
404                for &result in f.dfg.inst_results(inst) {
405                    let ty = f.dfg.value_type(result);
406                    if value_regs[result].is_invalid() && !ty.is_invalid() {
407                        let regs = vregs.alloc(ty)?;
408                        value_regs[result] = regs;
409                        trace!(
410                            "bb {} inst {} ({:?}): result {} regs {:?}",
411                            bb, inst, f.dfg.insts[inst], result, regs,
412                        );
413                    }
414                }
415
416                if let Some(et) = f.dfg.insts[inst].exception_table() {
417                    let exdata = &f.dfg.exception_tables[et];
418                    let sig = &f.dfg.signatures[exdata.signature()];
419
420                    let mut rets = smallvec![];
421                    for ty in sig.returns.iter().map(|ret| ret.value_type) {
422                        rets.push(vregs.alloc(ty)?.map(|r| Writable::from_reg(r)));
423                    }
424                    try_call_rets.insert(inst, rets);
425
426                    let mut payloads = smallvec![];
427                    // Note that this is intentionally using the calling
428                    // convention of the callee to determine what payload types
429                    // are available. The callee defines that, not the calling
430                    // convention of the caller.
431                    for &ty in sig
432                        .call_conv
433                        .exception_payload_types(I::ABIMachineSpec::word_type())
434                    {
435                        payloads.push(Writable::from_reg(vregs.alloc(ty)?.only_reg().unwrap()));
436                    }
437                    try_call_payloads.insert(inst, payloads);
438                }
439            }
440        }
441
442        // Find the sret register, if it's used.
443        let mut sret_param = None;
444        for ret in vcode.abi().signature().returns.iter() {
445            if ret.purpose == ArgumentPurpose::StructReturn {
446                let entry_bb = f.stencil.layout.entry_block().unwrap();
447                for (&param, sig_param) in f
448                    .dfg
449                    .block_params(entry_bb)
450                    .iter()
451                    .zip(vcode.abi().signature().params.iter())
452                {
453                    if sig_param.purpose == ArgumentPurpose::StructReturn {
454                        assert!(sret_param.is_none());
455                        sret_param = Some(param);
456                    }
457                }
458
459                assert!(sret_param.is_some());
460            }
461        }
462
463        let sret_reg = sret_param.map(|param| {
464            let regs = value_regs[param];
465            assert!(regs.len() == 1);
466            regs
467        });
468
469        // Compute instruction colors and find instructions with side-effects.
470        let mut cur_color = 0;
471        let mut block_end_colors = SecondaryMap::with_default(InstColor::new(0));
472        let mut side_effect_inst_entry_colors = SecondaryMap::with_default(InstColor::new(0));
473        for bb in f.layout.blocks() {
474            cur_color += 1;
475            for inst in f.layout.block_insts(bb) {
476                let side_effect = has_lowering_side_effect(f, inst);
477
478                trace!("bb {} inst {} has color {}", bb, inst, cur_color);
479                if side_effect {
480                    side_effect_inst_entry_colors[inst] = InstColor::new(cur_color);
481                    trace!(" -> side-effecting; incrementing color for next inst");
482                    cur_color += 1;
483                }
484            }
485
486            block_end_colors[bb] = InstColor::new(cur_color);
487        }
488
489        let value_ir_uses = compute_use_states(f, sret_param);
490
491        Ok(Lower {
492            f,
493            vcode,
494            vregs,
495            value_regs,
496            sret_reg,
497            block_end_colors,
498            side_effect_inst_entry_colors,
499            value_ir_uses,
500            value_lowered_uses: SecondaryMap::default(),
501            inst_sunk: FxHashSet::default(),
502            cur_scan_entry_color: None,
503            cur_inst: None,
504            ir_insts: vec![],
505            try_call_rets,
506            try_call_payloads,
507            pinned_reg: None,
508            flags,
509        })
510    }
511
512    pub fn sigs(&self) -> &SigSet {
513        self.vcode.sigs()
514    }
515
516    pub fn sigs_mut(&mut self) -> &mut SigSet {
517        self.vcode.sigs_mut()
518    }
519
520    fn gen_arg_setup(&mut self) {
521        if let Some(entry_bb) = self.f.layout.entry_block() {
522            trace!(
523                "gen_arg_setup: entry BB {} args are:\n{:?}",
524                entry_bb,
525                self.f.dfg.block_params(entry_bb)
526            );
527
528            for (i, param) in self.f.dfg.block_params(entry_bb).iter().enumerate() {
529                if self.value_ir_uses[*param] == ValueUseState::Unused {
530                    continue;
531                }
532                let regs = writable_value_regs(self.value_regs[*param]);
533                for insn in self
534                    .vcode
535                    .vcode
536                    .abi
537                    .gen_copy_arg_to_regs(&self.vcode.vcode.sigs, i, regs, &mut self.vregs)
538                    .into_iter()
539                {
540                    self.emit(insn);
541                }
542            }
543            if let Some(insn) = self
544                .vcode
545                .vcode
546                .abi
547                .gen_retval_area_setup(&self.vcode.vcode.sigs, &mut self.vregs)
548            {
549                self.emit(insn);
550            }
551
552            // The `args` instruction below must come first. Finish
553            // the current "IR inst" (with a default source location,
554            // as for other special instructions inserted during
555            // lowering) and continue the scan backward.
556            self.finish_ir_inst(Default::default());
557
558            if let Some(insn) = self.vcode.vcode.abi.take_args() {
559                self.emit(insn);
560            }
561        }
562    }
563
564    /// Generate the return instruction.
565    pub fn gen_return(&mut self, rets: &[ValueRegs<Reg>]) {
566        let mut out_rets = vec![];
567
568        let mut rets = rets.into_iter();
569        for (i, ret) in self
570            .abi()
571            .signature()
572            .returns
573            .clone()
574            .into_iter()
575            .enumerate()
576        {
577            let regs = if ret.purpose == ArgumentPurpose::StructReturn {
578                self.sret_reg.unwrap()
579            } else {
580                *rets.next().unwrap()
581            };
582
583            let (regs, insns) = self.vcode.abi().gen_copy_regs_to_retval(
584                self.vcode.sigs(),
585                i,
586                regs,
587                &mut self.vregs,
588            );
589            out_rets.extend(regs);
590            for insn in insns {
591                self.emit(insn);
592            }
593        }
594
595        // Hack: generate a virtual instruction that uses vmctx in
596        // order to keep it alive for the duration of the function,
597        // for the benefit of debuginfo.
598        if self.f.dfg.values_labels.is_some() {
599            if let Some(vmctx_val) = self.f.special_param(ArgumentPurpose::VMContext) {
600                if self.value_ir_uses[vmctx_val] != ValueUseState::Unused {
601                    let vmctx_reg = self.value_regs[vmctx_val].only_reg().unwrap();
602                    self.emit(I::gen_dummy_use(vmctx_reg));
603                }
604            }
605        }
606
607        let inst = self.abi().gen_rets(out_rets);
608        self.emit(inst);
609    }
610
611    /// Generate list of registers to hold the output of a call with
612    /// signature `sig`.
613    pub fn gen_call_output(&mut self, sig: &Signature) -> InstOutput {
614        let mut rets = smallvec![];
615        for ty in sig.returns.iter().map(|ret| ret.value_type) {
616            rets.push(self.vregs.alloc_with_deferred_error(ty));
617        }
618        rets
619    }
620
621    /// Likewise, but for a `SigRef` instead.
622    pub fn gen_call_output_from_sig_ref(&mut self, sig_ref: SigRef) -> InstOutput {
623        self.gen_call_output(&self.f.dfg.signatures[sig_ref])
624    }
625
626    /// Set up arguments values `args` for a call with signature `sig`.
627    pub fn gen_call_args(&mut self, sig: Sig, args: &[ValueRegs<Reg>]) -> CallArgList {
628        let (uses, insts) = self.vcode.abi().gen_call_args(
629            self.vcode.sigs(),
630            sig,
631            args,
632            /* is_tail_call */ false,
633            &self.flags,
634            &mut self.vregs,
635        );
636        for insn in insts {
637            self.emit(insn);
638        }
639        uses
640    }
641
642    /// Likewise, but for a `return_call`.
643    pub fn gen_return_call_args(&mut self, sig: Sig, args: &[ValueRegs<Reg>]) -> CallArgList {
644        let (uses, insts) = self.vcode.abi().gen_call_args(
645            self.vcode.sigs(),
646            sig,
647            args,
648            /* is_tail_call */ true,
649            &self.flags,
650            &mut self.vregs,
651        );
652        for insn in insts {
653            self.emit(insn);
654        }
655        uses
656    }
657
658    /// Set up return values `outputs` for a call with signature `sig`.
659    pub fn gen_call_rets(&mut self, sig: Sig, outputs: &[ValueRegs<Reg>]) -> CallRetList {
660        self.vcode
661            .abi()
662            .gen_call_rets(self.vcode.sigs(), sig, outputs, None, &mut self.vregs)
663    }
664
665    /// Likewise, but for a `try_call`.
666    pub fn gen_try_call_rets(&mut self, sig: Sig) -> CallRetList {
667        let ir_inst = self.cur_inst.unwrap();
668        let mut outputs: SmallVec<[ValueRegs<Reg>; 2]> = smallvec![];
669        for return_def in self.try_call_rets.get(&ir_inst).unwrap() {
670            outputs.push(return_def.map(|r| r.to_reg()));
671        }
672        let payloads = Some(&self.try_call_payloads.get(&ir_inst).unwrap()[..]);
673
674        self.vcode
675            .abi()
676            .gen_call_rets(self.vcode.sigs(), sig, &outputs, payloads, &mut self.vregs)
677    }
678
679    /// Populate a `CallInfo` for a call with signature `sig`.
680    pub fn gen_call_info<T>(
681        &mut self,
682        sig: Sig,
683        dest: T,
684        uses: CallArgList,
685        defs: CallRetList,
686        try_call_info: Option<TryCallInfo>,
687        patchable: bool,
688    ) -> CallInfo<T> {
689        self.vcode.abi().gen_call_info(
690            self.vcode.sigs(),
691            sig,
692            dest,
693            uses,
694            defs,
695            try_call_info,
696            patchable,
697        )
698    }
699
700    /// Has this instruction been sunk to a use-site (i.e., away from its
701    /// original location)?
702    fn is_inst_sunk(&self, inst: Inst) -> bool {
703        self.inst_sunk.contains(&inst)
704    }
705
706    // Is any result of this instruction needed?
707    fn is_any_inst_result_needed(&self, inst: Inst) -> bool {
708        self.f
709            .dfg
710            .inst_results(inst)
711            .iter()
712            .any(|&result| self.value_lowered_uses[result] > 0)
713    }
714
715    fn lower_clif_block<B: LowerBackend<MInst = I>>(
716        &mut self,
717        backend: &B,
718        block: Block,
719        ctrl_plane: &mut ControlPlane,
720    ) -> CodegenResult<()> {
721        self.cur_scan_entry_color = Some(self.block_end_colors[block]);
722        // Lowering loop:
723        // - For each non-branch instruction, in reverse order:
724        //   - If side-effecting (load, store, branch/call/return,
725        //     possible trap), or if used outside of this block, or if
726        //     demanded by another inst, then lower.
727        //
728        // That's it! Lowering of side-effecting ops will force all *needed*
729        // (live) non-side-effecting ops to be lowered at the right places, via
730        // the `use_input_reg()` callback on the `Lower` (that's us). That's
731        // because `use_input_reg()` sets the eager/demand bit for any insts
732        // whose result registers are used.
733        //
734        // We set the VCodeBuilder to "backward" mode, so we emit
735        // blocks in reverse order wrt the BlockIndex sequence, and
736        // emit instructions in reverse order within blocks.  Because
737        // the machine backend calls `ctx.emit()` in forward order, we
738        // collect per-IR-inst lowered instructions in `ir_insts`,
739        // then reverse these and append to the VCode at the end of
740        // each IR instruction.
741        for inst in self.f.layout.block_insts(block).rev() {
742            let data = &self.f.dfg.insts[inst];
743            // A non-zero entry color marks a side-effecting instruction (see the
744            // field's doc comment).
745            let entry_color = self.side_effect_inst_entry_colors[inst];
746            let has_side_effect = entry_color.get() != 0;
747
748            // If  inst has been sunk to another location, skip it.
749            if self.is_inst_sunk(inst) {
750                continue;
751            }
752
753            // Are any outputs used at least once?
754            let value_needed = self.is_any_inst_result_needed(inst);
755
756            // Do we have to emit this instruction even though nothing uses its
757            // results? Note that this is not the same question as
758            // `has_side_effect` above: loads are colored as side-effecting so
759            // that load merging cannot move one across a store, but a load that
760            // is defined not to trap can simply be dropped when it is dead.
761            let must_lower = must_lower_even_if_unused(self.f, inst);
762
763            trace!(
764                "lower_clif_block: {block}, {inst}, ({data:?}), is_branch {}, \
765                 has_side_effect {has_side_effect}, must_lower {must_lower}, \
766                 value_needed {value_needed}",
767                data.opcode().is_branch(),
768            );
769
770            // Update scan state to color prior to this inst (as we are scanning
771            // backward).
772            self.cur_inst = Some(inst);
773            if has_side_effect {
774                self.cur_scan_entry_color = Some(entry_color);
775            }
776
777            // Skip lowering branches; these are handled separately
778            // (see `lower_clif_branches()` below).
779            if self.f.dfg.insts[inst].opcode().is_branch() {
780                continue;
781            }
782
783            // Value defined by "inst" becomes live after it in normal
784            // order, and therefore **before** in reversed order.
785            // Only emit value label aliases if the instruction will be lowered
786            // (otherwise we want to keep using the earlier label instead).
787            self.emit_value_label_live_range_start_for_inst(inst, must_lower || value_needed);
788
789            // Normal instruction: codegen if the instruction is side-effecting
790            // or any of its outputs is used.
791            if must_lower || value_needed {
792                trace!("lowering: inst {}: {}", inst, self.f.dfg.display_inst(inst));
793                let temp_regs = match backend.lower(self, inst) {
794                    Some(regs) => regs,
795                    None => {
796                        let ty = if self.num_outputs(inst) > 0 {
797                            Some(self.output_ty(inst, 0))
798                        } else {
799                            None
800                        };
801                        return Err(CodegenError::Unsupported(format!(
802                            "should be implemented in ISLE: inst = `{}`, type = `{:?}`",
803                            self.f.dfg.display_inst(inst),
804                            ty
805                        )));
806                    }
807                };
808
809                // The ISLE generated code emits its own registers to define the
810                // instruction's lowered values in. However, other instructions
811                // that use this SSA value will be lowered assuming that the value
812                // is generated into a pre-assigned, different, register.
813                //
814                // To connect the two, we set up "aliases" in the VCodeBuilder
815                // that apply when it is building the Operand table for the
816                // regalloc to use. These aliases effectively rewrite any use of
817                // the pre-assigned register to the register that was returned by
818                // the ISLE lowering logic.
819                let results = self.f.dfg.inst_results(inst);
820                debug_assert_eq!(temp_regs.len(), results.len());
821                for (regs, &result) in temp_regs.iter().zip(results) {
822                    let dsts = self.value_regs[result];
823                    let mut regs = regs.regs().iter();
824                    for &dst in dsts.regs().iter() {
825                        let temp = regs.next().copied().unwrap_or(Reg::invalid_sentinel());
826                        trace!("set vreg alias: {result:?} = {dst:?}, lowering = {temp:?}");
827                        self.vregs.set_vreg_alias(dst, temp);
828                    }
829                }
830            }
831
832            let start = self.vcode.vcode.num_insts();
833            let loc = self.srcloc(inst);
834            self.finish_ir_inst(loc);
835
836            // If the instruction had a user stack map, forward it from the CLIF
837            // to the vcode.
838            if let Some(entries) = self.f.dfg.user_stack_map_entries(inst) {
839                let end = self.vcode.vcode.num_insts();
840                debug_assert!(end > start);
841                debug_assert_eq!(
842                    (start..end)
843                        .filter(|i| self.vcode.vcode[InsnIndex::new(*i)].is_safepoint())
844                        .count(),
845                    1
846                );
847                for i in start..end {
848                    let iix = InsnIndex::new(i);
849                    if self.vcode.vcode[iix].is_safepoint() {
850                        trace!(
851                            "Adding user stack map from clif\n\n\
852                                 {inst:?} `{}`\n\n\
853                             to vcode\n\n\
854                                 {iix:?} `{}`",
855                            self.f.dfg.display_inst(inst),
856                            &self.vcode.vcode[iix].pretty_print_inst(&mut Default::default()),
857                        );
858                        self.vcode
859                            .add_user_stack_map(BackwardsInsnIndex::new(iix.index()), entries);
860                        break;
861                    }
862                }
863            }
864
865            // If the CLIF instruction had debug tags, copy them to
866            // the VCode. Place on all VCode instructions lowered from
867            // this CLIF instruction.
868            let debug_tags = self.f.debug_tags.get(inst);
869            if !debug_tags.is_empty() && self.vcode.vcode.num_insts() > 0 {
870                let end = self.vcode.vcode.num_insts();
871                for i in start..end {
872                    let backwards_index = BackwardsInsnIndex::new(i);
873                    log::trace!(
874                        "debug tags on {inst}; associating {debug_tags:?} with {backwards_index:?}"
875                    );
876                    self.vcode.add_debug_tags(backwards_index, debug_tags);
877                }
878            }
879
880            // maybe insert random instruction
881            if ctrl_plane.get_decision() {
882                if ctrl_plane.get_decision() {
883                    let imm: u64 = ctrl_plane.get_arbitrary();
884                    let reg = self.alloc_tmp(crate::ir::types::I64).regs()[0];
885                    I::gen_imm_u64(imm, reg).map(|inst| self.emit(inst));
886                } else {
887                    let imm: f64 = ctrl_plane.get_arbitrary();
888                    let tmp = self.alloc_tmp(crate::ir::types::I64).regs()[0];
889                    let reg = self.alloc_tmp(crate::ir::types::F64).regs()[0];
890                    for inst in I::gen_imm_f64(imm, tmp, reg) {
891                        self.emit(inst);
892                    }
893                }
894            }
895        }
896
897        // Add the block params to this block.
898        self.add_block_params(block)?;
899
900        self.cur_scan_entry_color = None;
901        Ok(())
902    }
903
904    fn add_block_params(&mut self, block: Block) -> CodegenResult<()> {
905        for &param in self.f.dfg.block_params(block) {
906            for &reg in self.value_regs[param].regs() {
907                let vreg = reg.to_virtual_reg().unwrap();
908                self.vcode.add_block_param(vreg);
909            }
910        }
911        Ok(())
912    }
913
914    fn get_value_labels<'a>(&'a self, val: Value, depth: usize) -> Option<&'a [ValueLabelStart]> {
915        if let Some(ref values_labels) = self.f.dfg.values_labels {
916            debug_assert!(self.f.dfg.value_is_real(val));
917            trace!(
918                "get_value_labels: val {} -> {:?}",
919                val,
920                values_labels.get(&val)
921            );
922            match values_labels.get(&val) {
923                Some(&ValueLabelAssignments::Starts(ref list)) => Some(&list[..]),
924                Some(&ValueLabelAssignments::Alias { value, .. }) if depth < 10 => {
925                    self.get_value_labels(value, depth + 1)
926                }
927                _ => None,
928            }
929        } else {
930            None
931        }
932    }
933
934    fn emit_value_label_marks_for_value(&mut self, val: Value, allow_alias: bool) {
935        let regs = self.value_regs[val];
936        if regs.len() > 1 {
937            return;
938        }
939        let reg = regs.only_reg().unwrap();
940
941        if let Some(label_starts) = self.get_value_labels(val, if allow_alias { 0 } else { !0 }) {
942            let labels = label_starts
943                .iter()
944                .map(|&ValueLabelStart { label, .. }| label)
945                .collect::<FxHashSet<_>>();
946            for label in labels {
947                trace!(
948                    "value labeling: defines val {:?} -> reg {:?} -> label {:?}",
949                    val, reg, label,
950                );
951                self.vcode.add_value_label(reg, label);
952            }
953        }
954    }
955
956    fn emit_value_label_live_range_start_for_inst(&mut self, inst: Inst, allow_alias: bool) {
957        if self.f.dfg.values_labels.is_none() {
958            return;
959        }
960
961        trace!(
962            "value labeling: srcloc {}: inst {}",
963            self.srcloc(inst),
964            inst
965        );
966        for &val in self.f.dfg.inst_results(inst) {
967            self.emit_value_label_marks_for_value(val, allow_alias);
968        }
969    }
970
971    fn emit_value_label_live_range_start_for_block_args(&mut self, block: Block) {
972        if self.f.dfg.values_labels.is_none() {
973            return;
974        }
975
976        trace!("value labeling: block {}", block);
977        for &arg in self.f.dfg.block_params(block) {
978            self.emit_value_label_marks_for_value(arg, true);
979        }
980        self.finish_ir_inst(Default::default());
981    }
982
983    fn finish_ir_inst(&mut self, loc: RelSourceLoc) {
984        // The VCodeBuilder builds in reverse order (and reverses at
985        // the end), but `ir_insts` is in forward order, so reverse
986        // it.
987        for inst in self.ir_insts.drain(..).rev() {
988            self.vcode.push(inst, loc);
989        }
990    }
991
992    fn finish_bb(&mut self) {
993        self.vcode.end_bb();
994    }
995
996    fn lower_clif_branch<B: LowerBackend<MInst = I>>(
997        &mut self,
998        backend: &B,
999        // Lowered block index:
1000        bindex: BlockIndex,
1001        // Original CLIF block:
1002        block: Block,
1003        branch: Inst,
1004        targets: &[MachLabel],
1005    ) -> CodegenResult<()> {
1006        trace!(
1007            "lower_clif_branch: block {} branch {:?} targets {:?}",
1008            block, branch, targets,
1009        );
1010        // When considering code-motion opportunities, consider the current
1011        // program point to be this branch.
1012        self.cur_inst = Some(branch);
1013
1014        // Lower the branch in ISLE.
1015        backend
1016            .lower_branch(self, branch, targets)
1017            .unwrap_or_else(|| {
1018                panic!(
1019                    "should be implemented in ISLE: branch = `{}`",
1020                    self.f.dfg.display_inst(branch),
1021                )
1022            });
1023        let loc = self.srcloc(branch);
1024        self.finish_ir_inst(loc);
1025        // Add block param outputs for current block.
1026        self.lower_branch_blockparam_args(bindex);
1027        Ok(())
1028    }
1029
1030    fn lower_branch_blockparam_args(&mut self, block: BlockIndex) {
1031        let mut branch_arg_vregs: SmallVec<[Reg; 16]> = smallvec![];
1032
1033        // TODO: why not make `block_order` public?
1034        for succ_idx in 0..self.vcode.block_order().succ_indices(block).1.len() {
1035            branch_arg_vregs.clear();
1036            let (succ, args) = self.collect_block_call(block, succ_idx, &mut branch_arg_vregs);
1037            self.vcode.add_succ(succ, args);
1038        }
1039    }
1040
1041    fn collect_branch_and_targets(
1042        &self,
1043        bindex: BlockIndex,
1044        _bb: Block,
1045        targets: &mut SmallVec<[MachLabel; 2]>,
1046    ) -> Option<Inst> {
1047        targets.clear();
1048        let (opt_inst, succs) = self.vcode.block_order().succ_indices(bindex);
1049        targets.extend(succs.iter().map(|succ| MachLabel::from_block(*succ)));
1050        opt_inst
1051    }
1052
1053    /// Collect the outgoing block-call arguments for a given edge out
1054    /// of a lowered block.
1055    fn collect_block_call<'a>(
1056        &mut self,
1057        block: BlockIndex,
1058        succ_idx: usize,
1059        buffer: &'a mut SmallVec<[Reg; 16]>,
1060    ) -> (BlockIndex, &'a [Reg]) {
1061        let block_order = self.vcode.block_order();
1062        let (_, succs) = block_order.succ_indices(block);
1063        let succ = succs[succ_idx];
1064        let this_lb = block_order.lowered_order()[block.index()];
1065        let succ_lb = block_order.lowered_order()[succ.index()];
1066
1067        let (branch_inst, succ_idx) = match (this_lb, succ_lb) {
1068            (_, LoweredBlock::CriticalEdge { .. }) => {
1069                // The successor is a split-critical-edge block. In this
1070                // case, this block-call has no arguments, and the
1071                // arguments go on the critical edge block's unconditional
1072                // branch instead.
1073                return (succ, &[]);
1074            }
1075            (LoweredBlock::CriticalEdge { pred, succ_idx, .. }, _) => {
1076                // This is a split-critical-edge block. In this case, our
1077                // block-call has the arguments that in the CLIF appear in
1078                // the predecessor's branch to this edge.
1079                let branch_inst = self.f.layout.last_inst(pred).unwrap();
1080                (branch_inst, succ_idx as usize)
1081            }
1082
1083            (this, _) => {
1084                let block = this.orig_block().unwrap();
1085                // Ordinary block, with an ordinary block as
1086                // successor. Take the arguments from the branch.
1087                let branch_inst = self.f.layout.last_inst(block).unwrap();
1088                (branch_inst, succ_idx)
1089            }
1090        };
1091
1092        let block_call = self.f.dfg.insts[branch_inst]
1093            .branch_destination(&self.f.dfg.jump_tables, &self.f.dfg.exception_tables)[succ_idx];
1094        for arg in block_call.args(&self.f.dfg.value_lists) {
1095            match arg {
1096                BlockArg::Value(arg) => {
1097                    debug_assert!(self.f.dfg.value_is_real(arg));
1098                    let regs = self.put_value_in_regs(arg);
1099                    buffer.extend_from_slice(regs.regs());
1100                }
1101                BlockArg::TryCallRet(i) => {
1102                    let regs = self.try_call_rets.get(&branch_inst).unwrap()[i as usize]
1103                        .map(|r| r.to_reg());
1104                    buffer.extend_from_slice(regs.regs());
1105                }
1106                BlockArg::TryCallExn(i) => {
1107                    let reg =
1108                        self.try_call_payloads.get(&branch_inst).unwrap()[i as usize].to_reg();
1109                    buffer.push(reg);
1110                }
1111            }
1112        }
1113        (succ, &buffer[..])
1114    }
1115
1116    /// Lower the function.
1117    pub fn lower<B: LowerBackend<MInst = I>>(
1118        mut self,
1119        backend: &B,
1120        ctrl_plane: &mut ControlPlane,
1121    ) -> CodegenResult<VCode<I>> {
1122        trace!("about to lower function: {:?}", self.f);
1123
1124        self.vcode.init_retval_area(&mut self.vregs)?;
1125
1126        // Get the pinned reg here (we only parameterize this function on `B`,
1127        // not the whole `Lower` impl).
1128        self.pinned_reg = backend.maybe_pinned_reg();
1129
1130        self.vcode.set_entry(BlockIndex::new(0));
1131
1132        // Reused vectors for branch lowering.
1133        let mut targets: SmallVec<[MachLabel; 2]> = SmallVec::new();
1134
1135        // Main lowering loop over lowered blocks.
1136        let num_blocks = self.vcode.block_order().lowered_order().len();
1137        for i in (0..num_blocks).rev() {
1138            // We index into the (immutable) lowered order one block at a time,
1139            // copying the block out, so that the immutable borrow of
1140            // `self.vcode` ends immediately and leaves `&mut self` free for
1141            // lowering below.
1142            let bindex = BlockIndex::new(i);
1143            let lb = self.vcode.block_order().lowered_order()[i];
1144
1145            // Lower the block body in reverse order (see comment in
1146            // `lower_clif_block()` for rationale).
1147
1148            // End branch.
1149            if let Some(bb) = lb.orig_block() {
1150                if let Some(branch) = self.collect_branch_and_targets(bindex, bb, &mut targets) {
1151                    let branch_start = self.vcode.vcode.num_insts();
1152                    self.lower_clif_branch(backend, bindex, bb, branch, &targets)?;
1153                    self.finish_ir_inst(self.srcloc(branch));
1154
1155                    // Branch instructions like try_call can also be safepoints
1156                    // that need stack maps. Forward the stack map from the CLIF
1157                    // branch to the VCode safepoint, just like we do for
1158                    // non-branch instructions in `lower_clif_block`.
1159                    if let Some(entries) = self.f.dfg.user_stack_map_entries(branch) {
1160                        let branch_end = self.vcode.vcode.num_insts();
1161                        for i in branch_start..branch_end {
1162                            let iix = InsnIndex::new(i);
1163                            if self.vcode.vcode[iix].is_safepoint() {
1164                                self.vcode.add_user_stack_map(
1165                                    BackwardsInsnIndex::new(iix.index()),
1166                                    entries,
1167                                );
1168                                break;
1169                            }
1170                        }
1171                    }
1172                }
1173            } else {
1174                // If no orig block, this must be a pure edge block;
1175                // get the successor and emit a jump. This block has
1176                // no block params; and this jump's block-call args
1177                // will be filled in by
1178                // `lower_branch_blockparam_args`.
1179                let succ = self.vcode.block_order().succ_indices(bindex).1[0];
1180                self.emit(I::gen_jump(MachLabel::from_block(succ)));
1181                self.finish_ir_inst(Default::default());
1182                self.lower_branch_blockparam_args(bindex);
1183            }
1184
1185            // Original block body.
1186            if let Some(bb) = lb.orig_block() {
1187                self.lower_clif_block(backend, bb, ctrl_plane)?;
1188                self.emit_value_label_live_range_start_for_block_args(bb);
1189            }
1190
1191            if bindex.index() == 0 {
1192                // Set up the function with arg vreg inits.
1193                self.gen_arg_setup();
1194                self.finish_ir_inst(Default::default());
1195            }
1196
1197            self.finish_bb();
1198
1199            // Check for any deferred vreg-temp allocation errors, and
1200            // bubble one up at this time if it exists.
1201            if let Some(e) = self.vregs.take_deferred_error() {
1202                return Err(e);
1203            }
1204        }
1205
1206        // Now that we've emitted all instructions into the
1207        // VCodeBuilder, let's build the VCode.
1208        trace!(
1209            "built vcode:\n{:?}Backwards {:?}",
1210            &self.vregs, &self.vcode.vcode
1211        );
1212        let vcode = self.vcode.build(self.vregs);
1213
1214        Ok(vcode)
1215    }
1216
1217    pub fn value_is_unused(&self, val: Value) -> bool {
1218        match self.value_ir_uses[val] {
1219            ValueUseState::Unused => true,
1220            _ => false,
1221        }
1222    }
1223
1224    pub fn block_successor_label(&self, block: Block, succ: usize) -> MachLabel {
1225        trace!("block_successor_label: block {block} succ {succ}");
1226        let lowered = self
1227            .vcode
1228            .block_order()
1229            .lowered_index_for_block(block)
1230            .expect("Unreachable block");
1231        trace!(" -> lowered block {lowered:?}");
1232        let (_, succs) = self.vcode.block_order().succ_indices(lowered);
1233        trace!(" -> succs {succs:?}");
1234        let succ_block = *succs.get(succ).expect("Successor index out of range");
1235        MachLabel::from_block(succ_block)
1236    }
1237}
1238
1239/// Pre-analysis: compute `value_ir_uses`. See comment on
1240/// `ValueUseState` for a description of what this analysis
1241/// computes.
1242fn compute_use_states(
1243    f: &Function,
1244    sret_param: Option<Value>,
1245) -> SecondaryMap<Value, ValueUseState> {
1246    // We perform the analysis without recursion, so we don't
1247    // overflow the stack on long chains of ops in the input.
1248    //
1249    // This is sort of a hybrid of a "shallow use-count" pass and
1250    // a DFS. We iterate over all instructions and mark their args
1251    // as used. However when we increment a use-count to
1252    // "Multiple" we push its args onto the stack and do a DFS,
1253    // immediately marking the whole dependency tree as
1254    // Multiple. Doing both (shallow use-counting over all insts,
1255    // and deep Multiple propagation) lets us trim both
1256    // traversals, stopping recursion when a node is already at
1257    // the appropriate state.
1258    //
1259    // In particular, note that the *coarsening* into {Unused,
1260    // Once, Multiple} is part of what makes this pass more
1261    // efficient than a full indirect-use-counting pass.
1262
1263    let mut value_ir_uses = SecondaryMap::with_default(ValueUseState::Unused);
1264
1265    if let Some(sret_param) = sret_param {
1266        // There's an implicit use of the struct-return parameter in each
1267        // copy of the function epilogue, which we count here.
1268        value_ir_uses[sret_param] = ValueUseState::Multiple;
1269    }
1270
1271    // Stack of iterators over Values as we do DFS to mark
1272    // Multiple-state subtrees. The iterator type is whatever is
1273    // returned by `uses` below.
1274    let mut stack: SmallVec<[_; 16]> = smallvec![];
1275
1276    // Find the args for the inst corresponding to the given value.
1277    //
1278    // Note that "root" instructions are skipped here. This means that multiple
1279    // uses of any result of a multi-result instruction are not considered
1280    // multiple uses of the operands of a multi-result instruction. This
1281    // requires tight coupling with `get_value_as_source_or_const` above which
1282    // is the consumer of the map that this function is producing.
1283    let uses = |value| {
1284        trace!(" -> pushing args for {} onto stack", value);
1285        if let ValueDef::Result(src_inst, _) = f.dfg.value_def(value) {
1286            if is_value_use_root(f, src_inst) {
1287                None
1288            } else {
1289                Some(f.dfg.inst_values(src_inst))
1290            }
1291        } else {
1292            None
1293        }
1294    };
1295
1296    // Do a DFS through `value_ir_uses` to mark a subtree as
1297    // Multiple.
1298    for inst in f
1299        .layout
1300        .blocks()
1301        .flat_map(|block| f.layout.block_insts(block))
1302    {
1303        // Iterate over all values used by all instructions, noting an
1304        // additional use on each operand.
1305        for arg in f.dfg.inst_values(inst) {
1306            debug_assert!(f.dfg.value_is_real(arg));
1307            let old = value_ir_uses[arg];
1308            value_ir_uses[arg].inc();
1309            let new = value_ir_uses[arg];
1310            trace!("arg {} used, old state {:?}, new {:?}", arg, old, new);
1311
1312            // On transition to Multiple, do DFS.
1313            if old == ValueUseState::Multiple || new != ValueUseState::Multiple {
1314                continue;
1315            }
1316            if let Some(iter) = uses(arg) {
1317                stack.push(iter);
1318            }
1319            while let Some(iter) = stack.last_mut() {
1320                if let Some(value) = iter.next() {
1321                    debug_assert!(f.dfg.value_is_real(value));
1322                    trace!(" -> DFS reaches {}", value);
1323                    if value_ir_uses[value] == ValueUseState::Multiple {
1324                        // Truncate DFS here: no need to go further,
1325                        // as whole subtree must already be Multiple.
1326                        // With debug asserts, check one level of
1327                        // that invariant at least.
1328                        debug_assert!(uses(value).into_iter().flatten().all(|arg| {
1329                            debug_assert!(f.dfg.value_is_real(arg));
1330                            value_ir_uses[arg] == ValueUseState::Multiple
1331                        }));
1332                        continue;
1333                    }
1334                    value_ir_uses[value] = ValueUseState::Multiple;
1335                    trace!(" -> became Multiple");
1336                    if let Some(iter) = uses(value) {
1337                        stack.push(iter);
1338                    }
1339                } else {
1340                    // Empty iterator, discard.
1341                    stack.pop();
1342                }
1343            }
1344        }
1345    }
1346
1347    value_ir_uses
1348}
1349
1350/// Definition of a "root" instruction for the calculation of `ValueUseState`.
1351///
1352/// This function calculates whether `inst` is considered a "root" for value-use
1353/// information. This concept is used to forcibly prevent looking-through the
1354/// instruction during `get_value_as_source_or_const` as it additionally
1355/// prevents propagating `Multiple`-used results of the `inst` here to the
1356/// operands of the instruction.
1357///
1358/// Currently this is defined as multi-result instructions. That means that
1359/// lowerings are never allowed to look through a multi-result instruction to
1360/// generate patterns. Note that this isn't possible in ISLE today anyway so
1361/// this isn't currently much of a loss.
1362///
1363/// The main purpose of this function is to prevent the operands of a
1364/// multi-result instruction from being forcibly considered `Multiple`-used
1365/// regardless of circumstances.
1366fn is_value_use_root(f: &Function, inst: Inst) -> bool {
1367    f.dfg.inst_results(inst).len() > 1
1368}
1369
1370/// Function-level queries.
1371impl<'func, I: VCodeInst> Lower<'func, I> {
1372    pub fn dfg(&self) -> &DataFlowGraph {
1373        &self.f.dfg
1374    }
1375
1376    /// Get the `Callee`.
1377    pub fn abi(&self) -> &Callee<I::ABIMachineSpec> {
1378        self.vcode.abi()
1379    }
1380
1381    /// Get the `Callee`.
1382    pub fn abi_mut(&mut self) -> &mut Callee<I::ABIMachineSpec> {
1383        self.vcode.abi_mut()
1384    }
1385}
1386
1387/// Instruction input/output queries.
1388impl<'func, I: VCodeInst> Lower<'func, I> {
1389    /// Get the instdata for a given IR instruction.
1390    pub fn data(&self, ir_inst: Inst) -> &InstructionData {
1391        &self.f.dfg.insts[ir_inst]
1392    }
1393
1394    /// Likewise, but starting with a GlobalValue identifier.
1395    pub fn symbol_value_data<'b>(
1396        &'b self,
1397        global_value: GlobalValue,
1398    ) -> Option<(&'b ExternalName, RelocDistance, i64)> {
1399        let gvdata = &self.f.global_values[global_value];
1400        match gvdata {
1401            &GlobalValueData::Symbol {
1402                ref name,
1403                ref offset,
1404                colocated,
1405                ..
1406            } => {
1407                let offset = offset.bits();
1408                let dist = if colocated {
1409                    RelocDistance::Near
1410                } else {
1411                    RelocDistance::Far
1412                };
1413                Some((name, dist, offset))
1414            }
1415            _ => None,
1416        }
1417    }
1418
1419    /// Returns the memory flags of a given memory access.
1420    pub fn memflags(&self, ir_inst: Inst) -> Option<MachMemFlags> {
1421        match &self.f.dfg.insts[ir_inst] {
1422            &InstructionData::AtomicCas { flags, .. } => Some(self.f.dfg.mem_flags[flags].into()),
1423            &InstructionData::AtomicRmw { flags, .. } => Some(self.f.dfg.mem_flags[flags].into()),
1424            &InstructionData::Load { flags, .. }
1425            | &InstructionData::LoadNoOffset { flags, .. }
1426            | &InstructionData::Store { flags, .. } => Some(self.f.dfg.mem_flags[flags].into()),
1427            &InstructionData::StoreNoOffset { flags, .. } => {
1428                Some(self.f.dfg.mem_flags[flags].into())
1429            }
1430            _ => None,
1431        }
1432    }
1433
1434    /// Get the source location for a given instruction.
1435    pub fn srcloc(&self, ir_inst: Inst) -> RelSourceLoc {
1436        self.f.rel_srclocs()[ir_inst]
1437    }
1438
1439    /// Get the number of inputs to the given IR instruction. This is a count only of the Value
1440    /// arguments to the instruction: block arguments will not be included in this count.
1441    pub fn num_inputs(&self, ir_inst: Inst) -> usize {
1442        self.f.dfg.inst_args(ir_inst).len()
1443    }
1444
1445    /// Get the number of outputs to the given IR instruction.
1446    pub fn num_outputs(&self, ir_inst: Inst) -> usize {
1447        self.f.dfg.inst_results(ir_inst).len()
1448    }
1449
1450    /// Get the type for an instruction's input.
1451    pub fn input_ty(&self, ir_inst: Inst, idx: usize) -> Type {
1452        self.value_ty(self.input_as_value(ir_inst, idx))
1453    }
1454
1455    /// Get the type for a value.
1456    pub fn value_ty(&self, val: Value) -> Type {
1457        self.f.dfg.value_type(val)
1458    }
1459
1460    /// Get the type for an instruction's output.
1461    pub fn output_ty(&self, ir_inst: Inst, idx: usize) -> Type {
1462        self.f.dfg.value_type(self.f.dfg.inst_results(ir_inst)[idx])
1463    }
1464
1465    /// Get the value of a constant instruction (`iconst`, etc.) as a 64-bit
1466    /// value, if possible.
1467    pub fn get_constant(&self, ir_inst: Inst) -> Option<u64> {
1468        let c = is_constant_64bit(self.f, ir_inst)?;
1469
1470        // The upper bits must be zero, enforced during legalization and by
1471        // the CLIF verifier.
1472        debug_assert_eq!(c, {
1473            let input_size = self.output_ty(ir_inst, 0).bits() as u64;
1474            let shift = 64 - input_size;
1475            (c << shift) >> shift
1476        });
1477
1478        Some(c)
1479    }
1480
1481    /// Get the input as one of two options other than a direct register:
1482    ///
1483    /// - An instruction, given that it is effect-free or able to sink its
1484    ///   effect to the current instruction being lowered, and given it has only
1485    ///   one output, and if effect-ful, given that this is the only use;
1486    /// - A constant, if the value is a constant.
1487    ///
1488    /// The instruction input may be available in either of these forms.  It may
1489    /// be available in neither form, if the conditions are not met; if so, use
1490    /// `put_input_in_regs()` instead to get it in a register.
1491    ///
1492    /// If the backend merges the effect of a side-effecting instruction, it
1493    /// must call `sink_inst()`. When this is called, it indicates that the
1494    /// effect has been sunk to the current scan location. The sunk
1495    /// instruction's result(s) must have *no* uses remaining, because it will
1496    /// not be codegen'd (it has been integrated into the current instruction).
1497    pub fn input_as_value(&self, ir_inst: Inst, idx: usize) -> Value {
1498        let val = self.f.dfg.inst_args(ir_inst)[idx];
1499        debug_assert!(self.f.dfg.value_is_real(val));
1500        val
1501    }
1502
1503    /// Resolves a particular input of an instruction to the `Value` that it is
1504    /// represented with.
1505    ///
1506    /// For more information see [`Lower::get_value_as_source_or_const`].
1507    pub fn get_input_as_source_or_const(&self, ir_inst: Inst, idx: usize) -> NonRegInput {
1508        let val = self.input_as_value(ir_inst, idx);
1509        self.get_value_as_source_or_const(val)
1510    }
1511
1512    /// Resolves a `Value` definition to the source instruction it came from
1513    /// plus whether it's a unique-use of that instruction.
1514    ///
1515    /// This function is the workhorse of pattern-matching in ISLE which enables
1516    /// combining multiple instructions together. This is used implicitly in
1517    /// patterns such as `(iadd x (iconst y))` where this function is used to
1518    /// extract the `(iconst y)` operand.
1519    ///
1520    /// At its core this function is a wrapper around
1521    /// [`DataFlowGraph::value_def`]. This function applies a filter on top of
1522    /// that, however, to determine when it is actually safe to "look through"
1523    /// the `val` definition here and view the underlying instruction. This
1524    /// protects against duplicating side effects, such as loads, for example.
1525    ///
1526    /// Internally this uses the data computed from `compute_use_states` along
1527    /// with other instruction properties to know what to return.
1528    pub fn get_value_as_source_or_const(&self, val: Value) -> NonRegInput {
1529        trace!(
1530            "get_input_for_val: val {} at cur_inst {:?} cur_scan_entry_color {:?}",
1531            val, self.cur_inst, self.cur_scan_entry_color,
1532        );
1533        let inst = match self.f.dfg.value_def(val) {
1534            // OK to merge source instruction if we have a source
1535            // instruction, and one of these two conditions hold:
1536            //
1537            // - It has no side-effects and this instruction is not a "value-use
1538            //   root" instruction. Instructions which are considered "roots"
1539            //   for value-use calculations do not have accurate information
1540            //   known about the `ValueUseState` of their operands. This is
1541            //   currently done for multi-result instructions to prevent a use
1542            //   of each result from forcing all operands of the multi-result
1543            //   instruction to also be `Multiple`. This in turn means that the
1544            //   `ValueUseState` for operands of a "root" instruction to be a
1545            //   lie if pattern matching were to look through the multi-result
1546            //   instruction. As a result the "look through this instruction"
1547            //   logic only succeeds if it's not a root instruction.
1548            //
1549            // - It has a side-effect, has one output value, that one
1550            //   output has only one use, directly or indirectly (so
1551            //   cannot be duplicated -- see comment on
1552            //   `ValueUseState`), and the instruction's color is *one
1553            //   less than* the current scan color.
1554            //
1555            //   This latter set of conditions is testing whether a
1556            //   side-effecting instruction can sink to the current scan
1557            //   location; this is possible if the in-color of this inst is
1558            //   equal to the out-color of the producing inst, so no other
1559            //   side-effecting ops occur between them (which will only be true
1560            //   if they are in the same BB, because color increments at each BB
1561            //   start).
1562            //
1563            //   If it is actually sunk, then in `merge_inst()`, we update the
1564            //   scan color so that as we scan over the range past which the
1565            //   instruction was sunk, we allow other instructions (that came
1566            //   prior to the sunk instruction) to sink.
1567            ValueDef::Result(src_inst, result_idx) => {
1568                // A non-zero entry color marks a side-effecting instruction (see
1569                // the field's doc comment).
1570                let src_entry_color = self.side_effect_inst_entry_colors[src_inst];
1571                let src_side_effect = src_entry_color.get() != 0;
1572                trace!(" -> src inst {}", self.f.dfg.display_inst(src_inst));
1573                trace!(" -> has lowering side effect: {}", src_side_effect);
1574                if is_value_use_root(self.f, src_inst) {
1575                    // If this instruction is a "root instruction" then it's
1576                    // required that we can't look through it to see the
1577                    // definition. This means that the `ValueUseState` for the
1578                    // operands of this result assume that this instruction is
1579                    // generated exactly once which might get violated were we
1580                    // to allow looking through it.
1581                    trace!(" -> is a root instruction");
1582                    InputSourceInst::None
1583                } else if !src_side_effect {
1584                    // Otherwise if this instruction has no side effects and the
1585                    // value is used only once then we can look through it with
1586                    // a "unique" tag. A non-unique `Use` can be shown for other
1587                    // values ensuring consumers know how it's computed but that
1588                    // it's not available to omit.
1589                    if self.value_ir_uses[val] == ValueUseState::Once {
1590                        InputSourceInst::UniqueUse(src_inst, result_idx)
1591                    } else {
1592                        InputSourceInst::Use(src_inst, result_idx)
1593                    }
1594                } else {
1595                    // Side-effect: test whether this is the only use of the
1596                    // only result of the instruction, and whether colors allow
1597                    // the code-motion.
1598                    trace!(
1599                        " -> side-effecting op {} for val {}: use state {:?}",
1600                        src_inst, val, self.value_ir_uses[val]
1601                    );
1602                    if self.cur_scan_entry_color.is_some()
1603                        && self.value_ir_uses[val] == ValueUseState::Once
1604                        && self.num_outputs(src_inst) == 1
1605                        && src_entry_color.get() + 1 == self.cur_scan_entry_color.unwrap().get()
1606                    {
1607                        InputSourceInst::UniqueUse(src_inst, 0)
1608                    } else {
1609                        InputSourceInst::None
1610                    }
1611                }
1612            }
1613            _ => InputSourceInst::None,
1614        };
1615        let constant = inst.as_inst().and_then(|(inst, _)| self.get_constant(inst));
1616
1617        NonRegInput { inst, constant }
1618    }
1619
1620    /// Increment the reference count for the Value, ensuring that it gets lowered.
1621    #[cfg(any(
1622        feature = "x86",
1623        feature = "arm64",
1624        feature = "riscv64",
1625        feature = "s390x",
1626        feature = "pulley"
1627    ))]
1628    pub fn increment_lowered_uses(&mut self, val: Value) {
1629        self.value_lowered_uses[val] += 1
1630    }
1631
1632    /// Put the `idx`th input into register(s) and return the assigned register.
1633    pub fn put_input_in_regs(&mut self, ir_inst: Inst, idx: usize) -> ValueRegs<Reg> {
1634        let val = self.f.dfg.inst_args(ir_inst)[idx];
1635        self.put_value_in_regs(val)
1636    }
1637
1638    /// Put the given value into register(s) and return the assigned register.
1639    pub fn put_value_in_regs(&mut self, val: Value) -> ValueRegs<Reg> {
1640        debug_assert!(self.f.dfg.value_is_real(val));
1641        trace!("put_value_in_regs: val {}", val);
1642
1643        if let Some(inst) = self.f.dfg.value_def(val).inst() {
1644            assert!(!self.inst_sunk.contains(&inst));
1645        }
1646
1647        let regs = self.value_regs[val];
1648        trace!(" -> regs {:?}", regs);
1649        assert!(regs.is_valid());
1650
1651        self.value_lowered_uses[val] += 1;
1652
1653        regs
1654    }
1655}
1656
1657/// Codegen primitives: allocate temps, emit instructions, set result registers,
1658/// ask for an input to be gen'd into a register.
1659impl<'func, I: VCodeInst> Lower<'func, I> {
1660    /// Get a new temp.
1661    pub fn alloc_tmp(&mut self, ty: Type) -> ValueRegs<Writable<Reg>> {
1662        writable_value_regs(self.vregs.alloc_with_deferred_error(ty))
1663    }
1664
1665    /// Emit a machine instruction.
1666    pub fn emit(&mut self, mach_inst: I) {
1667        trace!("emit: {:?}", mach_inst);
1668        self.ir_insts.push(mach_inst);
1669    }
1670
1671    /// Indicate that the side-effect of an instruction has been sunk to the
1672    /// current scan location. This should only be done with the instruction's
1673    /// original results are not used (i.e., `put_input_in_regs` is not invoked
1674    /// for the input produced by the sunk instruction), otherwise the
1675    /// side-effect will occur twice.
1676    pub fn sink_inst(&mut self, ir_inst: Inst) {
1677        assert!(has_lowering_side_effect(self.f, ir_inst));
1678        assert!(self.cur_scan_entry_color.is_some());
1679
1680        for result in self.dfg().inst_results(ir_inst) {
1681            assert!(self.value_lowered_uses[*result] == 0);
1682        }
1683
1684        let sunk_inst_entry_color = self.side_effect_inst_entry_colors[ir_inst];
1685        let sunk_inst_exit_color = InstColor::new(sunk_inst_entry_color.get() + 1);
1686        assert!(sunk_inst_exit_color == self.cur_scan_entry_color.unwrap());
1687        self.cur_scan_entry_color = Some(sunk_inst_entry_color);
1688        self.inst_sunk.insert(ir_inst);
1689    }
1690
1691    /// Retrieve immediate data given a handle.
1692    pub fn get_immediate_data(&self, imm: Immediate) -> &ConstantData {
1693        self.f.dfg.immediates.get(imm).unwrap()
1694    }
1695
1696    /// Retrieve constant data given a handle.
1697    pub fn get_constant_data(&self, constant_handle: Constant) -> &ConstantData {
1698        self.f.dfg.constants.get(constant_handle)
1699    }
1700
1701    /// Indicate that a constant should be emitted.
1702    pub fn use_constant(&mut self, constant: VCodeConstantData) -> VCodeConstant {
1703        self.vcode.constants().insert(constant)
1704    }
1705}
1706
1707#[cfg(test)]
1708mod tests {
1709    use super::ValueUseState;
1710    use crate::cursor::{Cursor, FuncCursor};
1711    use crate::ir::types;
1712    use crate::ir::{Function, InstBuilder};
1713
1714    #[test]
1715    fn multi_result_use_once() {
1716        let mut func = Function::new();
1717        let block0 = func.dfg.make_block();
1718        let mut pos = FuncCursor::new(&mut func);
1719        pos.insert_block(block0);
1720        let v1 = pos.ins().iconst(types::I64, 0);
1721        let v2 = pos.ins().iconst(types::I64, 1);
1722        let v3 = pos.ins().iconcat(v1, v2);
1723        let (v4, v5) = pos.ins().isplit(v3);
1724        pos.ins().return_(&[v4, v5]);
1725        let func = pos.func;
1726
1727        let uses = super::compute_use_states(&func, None);
1728        assert_eq!(uses[v1], ValueUseState::Once);
1729        assert_eq!(uses[v2], ValueUseState::Once);
1730        assert_eq!(uses[v3], ValueUseState::Once);
1731        assert_eq!(uses[v4], ValueUseState::Once);
1732        assert_eq!(uses[v5], ValueUseState::Once);
1733    }
1734
1735    #[test]
1736    fn results_used_twice_but_not_operands() {
1737        let mut func = Function::new();
1738        let block0 = func.dfg.make_block();
1739        let mut pos = FuncCursor::new(&mut func);
1740        pos.insert_block(block0);
1741        let v1 = pos.ins().iconst(types::I64, 0);
1742        let v2 = pos.ins().iconst(types::I64, 1);
1743        let v3 = pos.ins().iconcat(v1, v2);
1744        let (v4, v5) = pos.ins().isplit(v3);
1745        pos.ins().return_(&[v4, v4]);
1746        let func = pos.func;
1747
1748        let uses = super::compute_use_states(&func, None);
1749        assert_eq!(uses[v1], ValueUseState::Once);
1750        assert_eq!(uses[v2], ValueUseState::Once);
1751        assert_eq!(uses[v3], ValueUseState::Once);
1752        assert_eq!(uses[v4], ValueUseState::Multiple);
1753        assert_eq!(uses[v5], ValueUseState::Unused);
1754    }
1755}