Skip to main content

cranelift_codegen/ir/
dfg.rs

1//! Data flow graph tracking Instructions, Values, and blocks.
2
3use crate::entity::{self, PrimaryMap, SecondaryMap};
4use crate::ir;
5use crate::ir::dynamic_type::{DynamicTypeData, DynamicTypes};
6use crate::ir::instructions::{CallInfo, InstructionData};
7use crate::ir::user_stack_maps::{UserStackMapEntry, UserStackMapEntryVec};
8use crate::ir::{
9    AliasRegionSet, Block, BlockArg, BlockCall, ConstantData, ConstantPool, DynamicType,
10    ExceptionTables, ExtFuncData, FuncRef, Immediate, Inst, JumpTables, MemFlagsSet, RelSourceLoc,
11    SigRef, Signature, Type, Value, ValueLabelAssignments, ValueList, ValueListPool, types,
12};
13use crate::packed_option::ReservedValue;
14use crate::write::write_operands;
15use core::fmt;
16use core::iter;
17use core::mem;
18use core::ops::{Index, IndexMut};
19
20use alloc::collections::BTreeMap;
21#[cfg(feature = "enable-serde")]
22use serde_derive::{Deserialize, Serialize};
23use smallvec::SmallVec;
24
25/// Storage for instructions within the DFG.
26#[derive(Clone, PartialEq, Hash)]
27#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
28pub struct Insts(PrimaryMap<Inst, InstructionData>);
29
30/// Allow immutable access to instructions via indexing.
31impl Index<Inst> for Insts {
32    type Output = InstructionData;
33
34    fn index(&self, inst: Inst) -> &InstructionData {
35        self.0.index(inst)
36    }
37}
38
39/// Allow mutable access to instructions via indexing.
40impl IndexMut<Inst> for Insts {
41    fn index_mut(&mut self, inst: Inst) -> &mut InstructionData {
42        self.0.index_mut(inst)
43    }
44}
45
46/// Storage for basic blocks within the DFG.
47#[derive(Clone, PartialEq, Hash)]
48#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
49pub struct Blocks(PrimaryMap<Block, BlockData>);
50
51impl Blocks {
52    /// Create a new basic block.
53    pub fn add(&mut self) -> Block {
54        self.0.push(BlockData::new())
55    }
56
57    /// Get the total number of basic blocks created in this function, whether they are
58    /// currently inserted in the layout or not.
59    ///
60    /// This is intended for use with `SecondaryMap::with_capacity`.
61    pub fn len(&self) -> usize {
62        self.0.len()
63    }
64
65    /// Reserves capacity for at least `additional` more elements to be
66    /// inserted.
67    pub fn reserve(&mut self, additional: usize) {
68        self.0.reserve(additional);
69    }
70
71    /// Returns `true` if the given block reference is valid.
72    pub fn is_valid(&self, block: Block) -> bool {
73        self.0.is_valid(block)
74    }
75
76    /// Iterate over all blocks, regardless whether a block is actually inserted
77    /// in the layout or not.
78    ///
79    /// Iterates in creation order, not layout order.
80    pub fn iter(&self) -> impl Iterator<Item = Block> {
81        self.0.keys()
82    }
83}
84
85impl Index<Block> for Blocks {
86    type Output = BlockData;
87
88    fn index(&self, block: Block) -> &BlockData {
89        &self.0[block]
90    }
91}
92
93impl IndexMut<Block> for Blocks {
94    fn index_mut(&mut self, block: Block) -> &mut BlockData {
95        &mut self.0[block]
96    }
97}
98
99/// A data flow graph defines all instructions and basic blocks in a function as well as
100/// the data flow dependencies between them. The DFG also tracks values which can be either
101/// instruction results or block parameters.
102///
103/// The layout of blocks in the function and of instructions in each block is recorded by the
104/// `Layout` data structure which forms the other half of the function representation.
105///
106#[derive(Clone, PartialEq, Hash)]
107#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
108pub struct DataFlowGraph {
109    /// Data about all of the instructions in the function, including opcodes and operands.
110    /// The instructions in this map are not in program order. That is tracked by `Layout`, along
111    /// with the block containing each instruction.
112    pub insts: Insts,
113
114    /// List of result values for each instruction.
115    ///
116    /// This map gets resized automatically by `make_inst()` so it is always in sync with the
117    /// primary `insts` map.
118    results: SecondaryMap<Inst, ValueList>,
119
120    /// User-defined stack maps.
121    user_stack_maps: alloc::collections::BTreeMap<Inst, UserStackMapEntryVec>,
122
123    /// basic blocks in the function and their parameters.
124    ///
125    /// This map is not in program order. That is handled by `Layout`, and so is the sequence of
126    /// instructions contained in each block.
127    pub blocks: Blocks,
128
129    /// Dynamic types created.
130    pub dynamic_types: DynamicTypes,
131
132    /// Memory pool of value lists.
133    ///
134    /// The `ValueList` references into this pool appear in many places:
135    ///
136    /// - Instructions in `insts` that don't have room for their entire argument list inline.
137    /// - Instruction result values in `results`.
138    /// - block parameters in `blocks`.
139    pub value_lists: ValueListPool,
140
141    /// Primary value table with entries for all values.
142    values: PrimaryMap<Value, ValueDataPacked>,
143
144    /// Function signature table. These signatures are referenced by indirect call instructions as
145    /// well as the external function references.
146    pub signatures: PrimaryMap<SigRef, Signature>,
147
148    /// External function references. These are functions that can be called directly.
149    pub ext_funcs: PrimaryMap<FuncRef, ExtFuncData>,
150
151    /// Saves Value labels.
152    pub values_labels: Option<BTreeMap<Value, ValueLabelAssignments>>,
153
154    /// Constants used within the function.
155    pub constants: ConstantPool,
156
157    /// Stores large immediates that otherwise will not fit on InstructionData.
158    pub immediates: PrimaryMap<Immediate, ConstantData>,
159
160    /// Jump tables used in this function.
161    pub jump_tables: JumpTables,
162
163    /// Exception tables used in this function.
164    pub exception_tables: ExceptionTables,
165
166    /// Memory operation flags used in this function.
167    pub mem_flags: MemFlagsSet,
168
169    /// Alias regions used in this function.
170    pub alias_regions: AliasRegionSet,
171}
172
173impl DataFlowGraph {
174    /// Create a new empty `DataFlowGraph`.
175    pub fn new() -> Self {
176        Self {
177            insts: Insts(PrimaryMap::new()),
178            results: SecondaryMap::new(),
179            user_stack_maps: alloc::collections::BTreeMap::new(),
180            blocks: Blocks(PrimaryMap::new()),
181            dynamic_types: DynamicTypes::new(),
182            value_lists: ValueListPool::new(),
183            values: PrimaryMap::new(),
184            signatures: PrimaryMap::new(),
185            ext_funcs: PrimaryMap::new(),
186            values_labels: None,
187            constants: ConstantPool::new(),
188            immediates: PrimaryMap::new(),
189            jump_tables: JumpTables::new(),
190            exception_tables: ExceptionTables::new(),
191            mem_flags: MemFlagsSet::new(),
192            alias_regions: AliasRegionSet::new(),
193        }
194    }
195
196    /// Clear everything.
197    pub fn clear(&mut self) {
198        self.insts.0.clear();
199        self.results.clear();
200        self.user_stack_maps.clear();
201        self.blocks.0.clear();
202        self.dynamic_types.clear();
203        self.value_lists.clear();
204        self.values.clear();
205        self.signatures.clear();
206        self.ext_funcs.clear();
207        self.values_labels = None;
208        self.constants.clear();
209        self.immediates.clear();
210        self.jump_tables.clear();
211        self.mem_flags.clear();
212        self.alias_regions.clear();
213    }
214
215    /// Get the total number of instructions created in this function, whether they are currently
216    /// inserted in the layout or not.
217    ///
218    /// This is intended for use with `SecondaryMap::with_capacity`.
219    pub fn num_insts(&self) -> usize {
220        self.insts.0.len()
221    }
222
223    /// Returns `true` if the given instruction reference is valid.
224    pub fn inst_is_valid(&self, inst: Inst) -> bool {
225        self.insts.0.is_valid(inst)
226    }
227
228    /// Get the total number of basic blocks created in this function, whether they are
229    /// currently inserted in the layout or not.
230    ///
231    /// This is intended for use with `SecondaryMap::with_capacity`.
232    pub fn num_blocks(&self) -> usize {
233        self.blocks.len()
234    }
235
236    /// Returns `true` if the given block reference is valid.
237    pub fn block_is_valid(&self, block: Block) -> bool {
238        self.blocks.is_valid(block)
239    }
240
241    /// Make a BlockCall, bundling together the block and its arguments.
242    pub fn block_call<'a>(
243        &mut self,
244        block: Block,
245        args: impl IntoIterator<Item = &'a BlockArg>,
246    ) -> BlockCall {
247        BlockCall::new(block, args.into_iter().copied(), &mut self.value_lists)
248    }
249
250    /// Get the total number of values.
251    pub fn num_values(&self) -> usize {
252        self.values.len()
253    }
254
255    /// Get an iterator over all values and their definitions.
256    pub fn values_and_defs(&self) -> impl Iterator<Item = (Value, ValueDef)> + '_ {
257        self.values().map(|value| (value, self.value_def(value)))
258    }
259
260    /// Starts collection of debug information.
261    pub fn collect_debug_info(&mut self) {
262        if self.values_labels.is_none() {
263            self.values_labels = Some(Default::default());
264        }
265    }
266
267    /// Inserts a `ValueLabelAssignments::Alias` for `to_alias` if debug info
268    /// collection is enabled.
269    pub fn add_value_label_alias(&mut self, to_alias: Value, from: RelSourceLoc, value: Value) {
270        if let Some(values_labels) = self.values_labels.as_mut() {
271            values_labels.insert(to_alias, ir::ValueLabelAssignments::Alias { from, value });
272        }
273    }
274}
275
276/// Resolve value aliases.
277///
278/// Find the original SSA value that `value` aliases, or None if an
279/// alias cycle is detected.
280fn maybe_resolve_aliases(
281    values: &PrimaryMap<Value, ValueDataPacked>,
282    value: Value,
283) -> Option<Value> {
284    let mut v = value;
285
286    // Note that values may be empty here.
287    for _ in 0..=values.len() {
288        if let ValueData::Alias { original, .. } = ValueData::from(values[v]) {
289            v = original;
290        } else {
291            return Some(v);
292        }
293    }
294
295    None
296}
297
298/// Resolve value aliases.
299///
300/// Find the original SSA value that `value` aliases.
301fn resolve_aliases(values: &PrimaryMap<Value, ValueDataPacked>, value: Value) -> Value {
302    if let Some(v) = maybe_resolve_aliases(values, value) {
303        v
304    } else {
305        panic!("Value alias loop detected for {value}");
306    }
307}
308
309/// Iterator over all Values in a DFG.
310pub struct Values<'a> {
311    inner: entity::Iter<'a, Value, ValueDataPacked>,
312}
313
314/// Check for non-values.
315fn valid_valuedata(data: ValueDataPacked) -> bool {
316    let data = ValueData::from(data);
317    if let ValueData::Alias {
318        ty: types::INVALID,
319        original,
320    } = data
321    {
322        if original == Value::reserved_value() {
323            return false;
324        }
325    }
326    true
327}
328
329impl<'a> Iterator for Values<'a> {
330    type Item = Value;
331
332    fn next(&mut self) -> Option<Self::Item> {
333        self.inner
334            .by_ref()
335            .find(|kv| valid_valuedata(*kv.1))
336            .map(|kv| kv.0)
337    }
338
339    fn size_hint(&self) -> (usize, Option<usize>) {
340        self.inner.size_hint()
341    }
342}
343
344impl ExactSizeIterator for Values<'_> {
345    fn len(&self) -> usize {
346        self.inner.len()
347    }
348}
349
350/// Handling values.
351///
352/// Values are either block parameters or instruction results.
353impl DataFlowGraph {
354    /// Allocate an extended value entry.
355    fn make_value(&mut self, data: ValueData) -> Value {
356        self.values.push(data.into())
357    }
358
359    /// The number of values defined in this DFG.
360    pub fn len_values(&self) -> usize {
361        self.values.len()
362    }
363
364    /// Get an iterator over all values.
365    pub fn values<'a>(&'a self) -> Values<'a> {
366        Values {
367            inner: self.values.iter(),
368        }
369    }
370
371    /// Check if a value reference is valid.
372    pub fn value_is_valid(&self, v: Value) -> bool {
373        self.values.is_valid(v)
374    }
375
376    /// Check whether a value is valid and not an alias.
377    pub fn value_is_real(&self, value: Value) -> bool {
378        // Deleted or unused values are also stored as aliases so this excludes
379        // those as well.
380        self.value_is_valid(value) && !matches!(self.values[value].into(), ValueData::Alias { .. })
381    }
382
383    /// Is the given value an alias?
384    pub fn value_is_alias(&self, v: Value) -> bool {
385        match ValueData::from(self.values[v]) {
386            ValueData::Alias { .. } => true,
387            ValueData::Inst { .. } | ValueData::Param { .. } | ValueData::Union { .. } => false,
388        }
389    }
390
391    /// Get the type of a value.
392    pub fn value_type(&self, v: Value) -> Type {
393        self.values[v].ty()
394    }
395
396    /// Get the definition of a value.
397    ///
398    /// This is either the instruction that defined it or the Block that has the value as an
399    /// parameter.
400    pub fn value_def(&self, v: Value) -> ValueDef {
401        match ValueData::from(self.values[v]) {
402            ValueData::Inst { inst, num, .. } => ValueDef::Result(inst, num as usize),
403            ValueData::Param { block, num, .. } => ValueDef::Param(block, num as usize),
404            ValueData::Alias { original, .. } => {
405                // Make sure we only recurse one level. `resolve_aliases` has safeguards to
406                // detect alias loops without overrunning the stack.
407                self.value_def(self.resolve_aliases(original))
408            }
409            ValueData::Union { x, y, .. } => ValueDef::Union(x, y),
410        }
411    }
412
413    /// Determine if `v` is an attached instruction result / block parameter.
414    ///
415    /// An attached value can't be attached to something else without first being detached.
416    ///
417    /// Value aliases are not considered to be attached to anything. Use `resolve_aliases()` to
418    /// determine if the original aliased value is attached.
419    pub fn value_is_attached(&self, v: Value) -> bool {
420        use self::ValueData::*;
421        match ValueData::from(self.values[v]) {
422            Inst { inst, num, .. } => Some(&v) == self.inst_results(inst).get(num as usize),
423            Param { block, num, .. } => Some(&v) == self.block_params(block).get(num as usize),
424            Alias { .. } => false,
425            Union { .. } => false,
426        }
427    }
428
429    /// Resolve value aliases.
430    ///
431    /// Find the original SSA value that `value` aliases.
432    pub fn resolve_aliases(&self, value: Value) -> Value {
433        resolve_aliases(&self.values, value)
434    }
435
436    /// Replace all uses of value aliases with their resolved values, and delete
437    /// the aliases.
438    pub fn resolve_all_aliases(&mut self) {
439        let invalid_value = ValueDataPacked::from(ValueData::Alias {
440            ty: types::INVALID,
441            original: Value::reserved_value(),
442        });
443
444        // Rewrite each chain of aliases. Update every alias along the chain
445        // into an alias directly to the final value. Due to updating every
446        // alias that it looks at, this loop runs in time linear in the number
447        // of values.
448        for mut src in self.values.keys() {
449            let value_data = self.values[src];
450            if value_data == invalid_value {
451                continue;
452            }
453            if let ValueData::Alias { mut original, .. } = value_data.into() {
454                // We don't use the type after this, we just need some place to
455                // store the resolved aliases temporarily.
456                let resolved = ValueDataPacked::from(ValueData::Alias {
457                    ty: types::INVALID,
458                    original: resolve_aliases(&self.values, original),
459                });
460                // Walk the chain again, splatting the new alias everywhere.
461                // resolve_aliases panics if there's an alias cycle, so we don't
462                // need to guard against cycles here.
463                loop {
464                    self.values[src] = resolved;
465                    src = original;
466                    if let ValueData::Alias { original: next, .. } = self.values[src].into() {
467                        original = next;
468                    } else {
469                        break;
470                    }
471                }
472            }
473        }
474
475        // Now aliases don't point to other aliases, so we can replace any use
476        // of an alias with the final value in constant time.
477
478        // Rewrite InstructionData in `self.insts`.
479        for inst in self.insts.0.values_mut() {
480            inst.map_values(
481                &mut self.value_lists,
482                &mut self.jump_tables,
483                &mut self.exception_tables,
484                |arg| {
485                    if let ValueData::Alias { original, .. } = self.values[arg].into() {
486                        original
487                    } else {
488                        arg
489                    }
490                },
491            );
492        }
493
494        // - `results` and block-params in `blocks` are not aliases, by
495        //   definition.
496        // - `dynamic_types` has no values.
497        // - `value_lists` can only be accessed via references from elsewhere.
498        // - `values` only has value references in aliases (which we've
499        //   removed), and unions (but the egraph pass ensures there are no
500        //   aliases before creating unions).
501
502        // - `signatures` and `ext_funcs` have no values.
503
504        if let Some(values_labels) = &mut self.values_labels {
505            // Debug info is best-effort. If any is attached to value aliases,
506            // just discard it.
507            values_labels.retain(|&k, _| !matches!(self.values[k].into(), ValueData::Alias { .. }));
508
509            // If debug-info says a value should have the same labels as another
510            // value, then make sure that target is not a value alias.
511            for value_label in values_labels.values_mut() {
512                if let ValueLabelAssignments::Alias { value, .. } = value_label {
513                    if let ValueData::Alias { original, .. } = self.values[*value].into() {
514                        *value = original;
515                    }
516                }
517            }
518        }
519
520        // - `constants` and `immediates` have no values.
521        // - `jump_tables` is updated together with instruction-data above.
522
523        // Delete all aliases now that there are no uses left.
524        for value in self.values.values_mut() {
525            if let ValueData::Alias { .. } = ValueData::from(*value) {
526                *value = invalid_value;
527            }
528        }
529    }
530
531    /// Turn a value into an alias of another.
532    ///
533    /// Change the `dest` value to behave as an alias of `src`. This means that all uses of `dest`
534    /// will behave as if they used that value `src`.
535    ///
536    /// The `dest` value can't be attached to an instruction or block.
537    pub fn change_to_alias(&mut self, dest: Value, src: Value) {
538        debug_assert!(!self.value_is_attached(dest));
539        // Try to create short alias chains by finding the original source value.
540        // This also avoids the creation of loops.
541        let original = self.resolve_aliases(src);
542        debug_assert_ne!(
543            dest, original,
544            "Aliasing {dest} to {src} would create a loop"
545        );
546        let ty = self.value_type(original);
547        debug_assert_eq!(
548            self.value_type(dest),
549            ty,
550            "Aliasing {} to {} would change its type {} to {}",
551            dest,
552            src,
553            self.value_type(dest),
554            ty
555        );
556        debug_assert_ne!(ty, types::INVALID);
557
558        self.values[dest] = ValueData::Alias { ty, original }.into();
559    }
560
561    /// Replace the results of one instruction with aliases to the results of another.
562    ///
563    /// Change all the results of `dest_inst` to behave as aliases of
564    /// corresponding results of `src_inst`, as if calling change_to_alias for
565    /// each.
566    ///
567    /// After calling this instruction, `dest_inst` will have had its results
568    /// cleared, so it likely needs to be removed from the graph.
569    ///
570    pub fn replace_with_aliases(&mut self, dest_inst: Inst, original_inst: Inst) {
571        debug_assert_ne!(
572            dest_inst, original_inst,
573            "Replacing {dest_inst} with itself would create a loop"
574        );
575
576        let dest_results = self.results[dest_inst].as_slice(&self.value_lists);
577        let original_results = self.results[original_inst].as_slice(&self.value_lists);
578
579        debug_assert_eq!(
580            dest_results.len(),
581            original_results.len(),
582            "Replacing {dest_inst} with {original_inst} would produce a different number of results."
583        );
584
585        for (&dest, &original) in dest_results.iter().zip(original_results) {
586            let ty = self.value_type(original);
587            debug_assert_eq!(
588                self.value_type(dest),
589                ty,
590                "Aliasing {} to {} would change its type {} to {}",
591                dest,
592                original,
593                self.value_type(dest),
594                ty
595            );
596            debug_assert_ne!(ty, types::INVALID);
597
598            self.values[dest] = ValueData::Alias { ty, original }.into();
599        }
600
601        self.clear_results(dest_inst);
602    }
603
604    /// Get the stack map entries associated with the given instruction.
605    pub fn user_stack_map_entries(&self, inst: Inst) -> Option<&[UserStackMapEntry]> {
606        self.user_stack_maps.get(&inst).map(|es| &**es)
607    }
608
609    /// Append a new stack map entry for the given call instruction.
610    ///
611    /// # Panics
612    ///
613    /// Panics if the given instruction is not a (non-tail) call instruction.
614    pub fn append_user_stack_map_entry(&mut self, inst: Inst, entry: UserStackMapEntry) {
615        let opcode = self.insts[inst].opcode();
616        assert!(opcode.is_safepoint());
617        self.user_stack_maps.entry(inst).or_default().push(entry);
618    }
619
620    /// Append multiple stack map entries for the given call instruction.
621    ///
622    /// # Panics
623    ///
624    /// Panics if the given instruction is not a (non-tail) call instruction.
625    pub fn append_user_stack_map_entries(
626        &mut self,
627        inst: Inst,
628        entries: impl IntoIterator<Item = UserStackMapEntry>,
629    ) {
630        for entry in entries {
631            self.append_user_stack_map_entry(inst, entry);
632        }
633    }
634
635    /// Take the stack map entries for a given instruction, leaving the
636    /// instruction without stack maps.
637    pub(crate) fn take_user_stack_map_entries(
638        &mut self,
639        inst: Inst,
640    ) -> Option<UserStackMapEntryVec> {
641        self.user_stack_maps.remove(&inst)
642    }
643}
644
645/// Where did a value come from?
646#[derive(Clone, Copy, Debug, PartialEq, Eq)]
647pub enum ValueDef {
648    /// Value is the n'th result of an instruction.
649    Result(Inst, usize),
650    /// Value is the n'th parameter to a block.
651    Param(Block, usize),
652    /// Value is a union of two other values.
653    Union(Value, Value),
654}
655
656impl ValueDef {
657    /// Unwrap the instruction where the value was defined, or panic.
658    pub fn unwrap_inst(&self) -> Inst {
659        self.inst().expect("Value is not an instruction result")
660    }
661
662    /// Get the instruction where the value was defined, if any.
663    pub fn inst(&self) -> Option<Inst> {
664        match *self {
665            Self::Result(inst, _) => Some(inst),
666            _ => None,
667        }
668    }
669
670    /// Unwrap the block there the parameter is defined, or panic.
671    pub fn unwrap_block(&self) -> Block {
672        match *self {
673            Self::Param(block, _) => block,
674            _ => panic!("Value is not a block parameter"),
675        }
676    }
677
678    /// Get the number component of this definition.
679    ///
680    /// When multiple values are defined at the same program point, this indicates the index of
681    /// this value.
682    pub fn num(self) -> usize {
683        match self {
684            Self::Result(_, n) | Self::Param(_, n) => n,
685            Self::Union(_, _) => 0,
686        }
687    }
688}
689
690/// Internal table storage for extended values.
691#[derive(Clone, Debug, PartialEq, Hash)]
692#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
693enum ValueData {
694    /// Value is defined by an instruction.
695    Inst { ty: Type, num: u16, inst: Inst },
696
697    /// Value is a block parameter.
698    Param { ty: Type, num: u16, block: Block },
699
700    /// Value is an alias of another value.
701    /// An alias value can't be linked as an instruction result or block parameter. It is used as a
702    /// placeholder when the original instruction or block has been rewritten or modified.
703    Alias { ty: Type, original: Value },
704
705    /// Union is a "fork" in representation: the value can be
706    /// represented as either of the values named here. This is used
707    /// for aegraph (acyclic egraph) representation in the DFG.
708    Union { ty: Type, x: Value, y: Value },
709}
710
711/// Bit-packed version of ValueData, for efficiency.
712///
713/// Layout:
714///
715/// ```plain
716///        | tag:2 |  type:14        |    x:32       | y:32          |
717///
718/// Inst       00     ty               inst output     inst index
719/// Param      01     ty               blockparam num  block index
720/// Alias      10     ty               0               value index
721/// Union      11     ty               first value     second value
722/// ```
723#[derive(Clone, Copy, Debug, PartialEq, Hash)]
724#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
725#[repr(Rust, packed)]
726struct ValueDataPacked {
727    x: u32,
728    y: u32,
729    flags_and_type: u16,
730}
731
732impl ValueDataPacked {
733    const TYPE_SHIFT: u8 = 0;
734    const TYPE_BITS: u8 = 14;
735    const TAG_SHIFT: u8 = Self::TYPE_SHIFT + Self::TYPE_BITS;
736    const TAG_BITS: u8 = 2;
737
738    const TAG_INST: u16 = 0;
739    const TAG_PARAM: u16 = 1;
740    const TAG_ALIAS: u16 = 2;
741    const TAG_UNION: u16 = 3;
742
743    fn make(tag: u16, ty: Type, x: u32, y: u32) -> ValueDataPacked {
744        debug_assert!(tag < (1 << Self::TAG_BITS));
745        debug_assert!(ty.repr() < (1 << Self::TYPE_BITS));
746
747        ValueDataPacked {
748            x,
749            y,
750            flags_and_type: (tag << Self::TAG_SHIFT) | (ty.repr() << Self::TYPE_SHIFT),
751        }
752    }
753
754    #[inline(always)]
755    fn field(self, shift: u8, bits: u8) -> u16 {
756        (self.flags_and_type >> shift) & ((1 << bits) - 1)
757    }
758
759    #[inline(always)]
760    fn ty(self) -> Type {
761        let ty = self.field(ValueDataPacked::TYPE_SHIFT, ValueDataPacked::TYPE_BITS);
762        Type::from_repr(ty)
763    }
764
765    #[inline(always)]
766    fn set_type(&mut self, ty: Type) {
767        self.flags_and_type &= !(((1 << Self::TYPE_BITS) - 1) << Self::TYPE_SHIFT);
768        self.flags_and_type |= ty.repr() << Self::TYPE_SHIFT;
769    }
770}
771
772impl From<ValueData> for ValueDataPacked {
773    fn from(data: ValueData) -> Self {
774        match data {
775            ValueData::Inst { ty, num, inst } => {
776                Self::make(Self::TAG_INST, ty, num.into(), inst.as_bits())
777            }
778            ValueData::Param { ty, num, block } => {
779                Self::make(Self::TAG_PARAM, ty, num.into(), block.as_bits())
780            }
781            ValueData::Alias { ty, original } => {
782                Self::make(Self::TAG_ALIAS, ty, 0, original.as_bits())
783            }
784            ValueData::Union { ty, x, y } => {
785                Self::make(Self::TAG_UNION, ty, x.as_bits(), y.as_bits())
786            }
787        }
788    }
789}
790
791impl From<ValueDataPacked> for ValueData {
792    fn from(data: ValueDataPacked) -> Self {
793        let tag = data.field(ValueDataPacked::TAG_SHIFT, ValueDataPacked::TAG_BITS);
794        let ty = data.field(ValueDataPacked::TYPE_SHIFT, ValueDataPacked::TYPE_BITS);
795
796        let ty = Type::from_repr(ty);
797        match tag {
798            ValueDataPacked::TAG_INST => ValueData::Inst {
799                ty,
800                num: u16::try_from(data.x).expect("Inst result num should fit in u16"),
801                inst: Inst::from_bits(data.y),
802            },
803            ValueDataPacked::TAG_PARAM => ValueData::Param {
804                ty,
805                num: u16::try_from(data.x).expect("Blockparam index should fit in u16"),
806                block: Block::from_bits(data.y),
807            },
808            ValueDataPacked::TAG_ALIAS => ValueData::Alias {
809                ty,
810                original: Value::from_bits(data.y),
811            },
812            ValueDataPacked::TAG_UNION => ValueData::Union {
813                ty,
814                x: Value::from_bits(data.x),
815                y: Value::from_bits(data.y),
816            },
817            _ => panic!("Invalid tag {tag} in ValueDataPacked"),
818        }
819    }
820}
821
822/// Instructions.
823///
824impl DataFlowGraph {
825    /// Create a new instruction.
826    ///
827    /// The type of the first result is indicated by `data.ty`. If the
828    /// instruction produces multiple results, also call
829    /// `make_inst_results` to allocate value table entries. (It is
830    /// always safe to call `make_inst_results`, regardless of how
831    /// many results the instruction has.)
832    pub fn make_inst(&mut self, data: InstructionData) -> Inst {
833        let n = self.num_insts() + 1;
834        self.results.resize(n);
835        self.insts.0.push(data)
836    }
837
838    /// Declares a dynamic vector type
839    pub fn make_dynamic_ty(&mut self, data: DynamicTypeData) -> DynamicType {
840        self.dynamic_types.push(data)
841    }
842
843    /// Returns an object that displays `inst`.
844    pub fn display_inst<'a>(&'a self, inst: Inst) -> DisplayInst<'a> {
845        DisplayInst(self, inst)
846    }
847
848    /// Returns an object that displays the given `value`'s defining instruction.
849    ///
850    /// Panics if the value is not defined by an instruction (i.e. it is a basic
851    /// block argument).
852    pub fn display_value_inst(&self, value: Value) -> DisplayInst<'_> {
853        match self.value_def(value) {
854            ir::ValueDef::Result(inst, _) => self.display_inst(inst),
855            ir::ValueDef::Param(_, _) => panic!("value is not defined by an instruction"),
856            ir::ValueDef::Union(_, _) => panic!("value is a union of two other values"),
857        }
858    }
859
860    /// Construct a read-only visitor context for the values of this instruction.
861    pub fn inst_values<'dfg>(
862        &'dfg self,
863        inst: Inst,
864    ) -> impl DoubleEndedIterator<Item = Value> + 'dfg {
865        self.inst_args(inst)
866            .iter()
867            .copied()
868            .chain(
869                self.insts[inst]
870                    .branch_destination(&self.jump_tables, &self.exception_tables)
871                    .into_iter()
872                    .flat_map(|branch| {
873                        branch
874                            .args(&self.value_lists)
875                            .filter_map(|arg| arg.as_value())
876                    }),
877            )
878            .chain(
879                self.insts[inst]
880                    .exception_table()
881                    .into_iter()
882                    .flat_map(|et| self.exception_tables[et].contexts()),
883            )
884    }
885
886    /// Map a function over the values of the instruction.
887    pub fn map_inst_values<F>(&mut self, inst: Inst, body: F)
888    where
889        F: FnMut(Value) -> Value,
890    {
891        self.insts[inst].map_values(
892            &mut self.value_lists,
893            &mut self.jump_tables,
894            &mut self.exception_tables,
895            body,
896        );
897    }
898
899    /// Overwrite the instruction's value references with values from the iterator.
900    /// NOTE: the iterator provided is expected to yield at least as many values as the instruction
901    /// currently has.
902    pub fn overwrite_inst_values<I>(&mut self, inst: Inst, mut values: I)
903    where
904        I: Iterator<Item = Value>,
905    {
906        self.insts[inst].map_values(
907            &mut self.value_lists,
908            &mut self.jump_tables,
909            &mut self.exception_tables,
910            |_| values.next().unwrap(),
911        );
912    }
913
914    /// Get all value arguments on `inst` as a slice.
915    pub fn inst_args(&self, inst: Inst) -> &[Value] {
916        self.insts[inst].arguments(&self.value_lists)
917    }
918
919    /// Get all value arguments on `inst` as a mutable slice.
920    pub fn inst_args_mut(&mut self, inst: Inst) -> &mut [Value] {
921        self.insts[inst].arguments_mut(&mut self.value_lists)
922    }
923
924    /// Get the fixed value arguments on `inst` as a slice.
925    pub fn inst_fixed_args(&self, inst: Inst) -> &[Value] {
926        let num_fixed_args = self.insts[inst]
927            .opcode()
928            .constraints()
929            .num_fixed_value_arguments();
930        &self.inst_args(inst)[..num_fixed_args]
931    }
932
933    /// Get the fixed value arguments on `inst` as a mutable slice.
934    pub fn inst_fixed_args_mut(&mut self, inst: Inst) -> &mut [Value] {
935        let num_fixed_args = self.insts[inst]
936            .opcode()
937            .constraints()
938            .num_fixed_value_arguments();
939        &mut self.inst_args_mut(inst)[..num_fixed_args]
940    }
941
942    /// Get the variable value arguments on `inst` as a slice.
943    pub fn inst_variable_args(&self, inst: Inst) -> &[Value] {
944        let num_fixed_args = self.insts[inst]
945            .opcode()
946            .constraints()
947            .num_fixed_value_arguments();
948        &self.inst_args(inst)[num_fixed_args..]
949    }
950
951    /// Get the variable value arguments on `inst` as a mutable slice.
952    pub fn inst_variable_args_mut(&mut self, inst: Inst) -> &mut [Value] {
953        let num_fixed_args = self.insts[inst]
954            .opcode()
955            .constraints()
956            .num_fixed_value_arguments();
957        &mut self.inst_args_mut(inst)[num_fixed_args..]
958    }
959
960    /// Create result values for an instruction that produces multiple results.
961    ///
962    /// Instructions that produce no result values only need to be created with `make_inst`,
963    /// otherwise call `make_inst_results` to allocate value table entries for the results.
964    ///
965    /// The result value types are determined from the instruction's value type constraints and the
966    /// provided `ctrl_typevar` type for polymorphic instructions. For non-polymorphic
967    /// instructions, `ctrl_typevar` is ignored, and `INVALID` can be used.
968    ///
969    /// The type of the first result value is also set, even if it was already set in the
970    /// `InstructionData` passed to `make_inst`. If this function is called with a single-result
971    /// instruction, that is the only effect.
972    pub fn make_inst_results(&mut self, inst: Inst, ctrl_typevar: Type) -> usize {
973        self.make_inst_results_reusing(inst, ctrl_typevar, iter::empty())
974    }
975
976    /// Create result values for `inst`, reusing the provided detached values.
977    ///
978    /// Create a new set of result values for `inst` using `ctrl_typevar` to determine the result
979    /// types. Any values provided by `reuse` will be reused. When `reuse` is exhausted or when it
980    /// produces `None`, a new value is created.
981    pub fn make_inst_results_reusing<I>(
982        &mut self,
983        inst: Inst,
984        ctrl_typevar: Type,
985        reuse: I,
986    ) -> usize
987    where
988        I: Iterator<Item = Option<Value>>,
989    {
990        self.clear_results(inst);
991
992        let mut reuse = reuse.fuse();
993        let result_tys: SmallVec<[_; 16]> = self.inst_result_types(inst, ctrl_typevar).collect();
994
995        for (expected, &ty) in result_tys.iter().enumerate() {
996            let num = u16::try_from(expected).expect("Result value index should fit in u16");
997            let value_data = ValueData::Inst { ty, num, inst };
998            let v = if let Some(Some(v)) = reuse.next() {
999                debug_assert_eq!(self.value_type(v), ty, "Reused {ty} is wrong type");
1000                debug_assert!(!self.value_is_attached(v));
1001                self.values[v] = value_data.into();
1002                v
1003            } else {
1004                self.make_value(value_data)
1005            };
1006            let actual = self.results[inst].push(v, &mut self.value_lists);
1007            debug_assert_eq!(expected, actual);
1008        }
1009
1010        result_tys.len()
1011    }
1012
1013    /// Clear the list of result values from `inst`.
1014    ///
1015    /// This leaves `inst` without any result values. New result values can be created by calling
1016    /// `make_inst_results` or by using a `replace(inst)` builder.
1017    pub fn clear_results(&mut self, inst: Inst) {
1018        self.results[inst].clear(&mut self.value_lists)
1019    }
1020
1021    /// Replace an instruction result with a new value of type `new_type`.
1022    ///
1023    /// The `old_value` must be an attached instruction result.
1024    ///
1025    /// The old value is left detached, so it should probably be changed into something else.
1026    ///
1027    /// Returns the new value.
1028    pub fn replace_result(&mut self, old_value: Value, new_type: Type) -> Value {
1029        let (num, inst) = match ValueData::from(self.values[old_value]) {
1030            ValueData::Inst { num, inst, .. } => (num, inst),
1031            _ => panic!("{old_value} is not an instruction result value"),
1032        };
1033        let new_value = self.make_value(ValueData::Inst {
1034            ty: new_type,
1035            num,
1036            inst,
1037        });
1038        let num = num as usize;
1039        let attached = mem::replace(
1040            self.results[inst]
1041                .get_mut(num, &mut self.value_lists)
1042                .expect("Replacing detached result"),
1043            new_value,
1044        );
1045        debug_assert_eq!(
1046            attached,
1047            old_value,
1048            "{} wasn't detached from {}",
1049            old_value,
1050            self.display_inst(inst)
1051        );
1052        new_value
1053    }
1054
1055    /// Clone an instruction, attaching new result `Value`s and
1056    /// returning them.
1057    pub fn clone_inst(&mut self, inst: Inst) -> Inst {
1058        // First, add a clone of the InstructionData.
1059        let inst_data = self.insts[inst];
1060        // If the `inst_data` has a reference to a ValueList, clone it
1061        // as well, because we can't share these (otherwise mutating
1062        // one would affect the other).
1063        let inst_data = inst_data.deep_clone(&mut self.value_lists);
1064        let new_inst = self.make_inst(inst_data);
1065        // Get the controlling type variable.
1066        let ctrl_typevar = self.ctrl_typevar(inst);
1067        // Create new result values.
1068        self.make_inst_results(new_inst, ctrl_typevar);
1069        new_inst
1070    }
1071
1072    /// Get the first result of an instruction.
1073    ///
1074    /// This function panics if the instruction doesn't have any result.
1075    pub fn first_result(&self, inst: Inst) -> Value {
1076        self.results[inst]
1077            .first(&self.value_lists)
1078            .unwrap_or_else(|| panic!("{inst} has no results"))
1079    }
1080
1081    /// Test if `inst` has any result values currently.
1082    pub fn has_results(&self, inst: Inst) -> bool {
1083        !self.results[inst].is_empty()
1084    }
1085
1086    /// Return all the results of an instruction.
1087    pub fn inst_results(&self, inst: Inst) -> &[Value] {
1088        self.results[inst].as_slice(&self.value_lists)
1089    }
1090
1091    /// Return all the results of an instruction as ValueList.
1092    pub fn inst_results_list(&self, inst: Inst) -> ValueList {
1093        self.results[inst]
1094    }
1095
1096    /// Create a union of two values.
1097    pub fn union(&mut self, x: Value, y: Value) -> Value {
1098        // Get the type.
1099        let ty = self.value_type(x);
1100        debug_assert_eq!(ty, self.value_type(y));
1101        self.make_value(ValueData::Union { ty, x, y })
1102    }
1103
1104    /// Get the call signature of a direct or indirect call instruction.
1105    /// Returns `None` if `inst` is not a call instruction.
1106    pub fn call_signature(&self, inst: Inst) -> Option<SigRef> {
1107        match self.insts[inst].analyze_call(&self.value_lists, &self.exception_tables) {
1108            CallInfo::NotACall => None,
1109            CallInfo::Direct(f, _) => Some(self.ext_funcs[f].signature),
1110            CallInfo::DirectWithSig(_, s, _) => Some(s),
1111            CallInfo::Indirect(s, _) => Some(s),
1112        }
1113    }
1114
1115    /// Like `call_signature` but returns none for tail call
1116    /// instructions and try-call (exception-handling invoke)
1117    /// instructions.
1118    fn non_tail_call_or_try_call_signature(&self, inst: Inst) -> Option<SigRef> {
1119        let sig = self.call_signature(inst)?;
1120        match self.insts[inst].opcode() {
1121            ir::Opcode::ReturnCall | ir::Opcode::ReturnCallIndirect => None,
1122            ir::Opcode::TryCall | ir::Opcode::TryCallIndirect => None,
1123            _ => Some(sig),
1124        }
1125    }
1126
1127    // Only for use by the verifier. Everyone else should just use
1128    // `dfg.inst_results(inst).len()`.
1129    pub(crate) fn num_expected_results_for_verifier(&self, inst: Inst) -> usize {
1130        match self.non_tail_call_or_try_call_signature(inst) {
1131            Some(sig) => self.signatures[sig].returns.len(),
1132            None => {
1133                let constraints = self.insts[inst].opcode().constraints();
1134                constraints.num_fixed_results()
1135            }
1136        }
1137    }
1138
1139    /// Get the result types of the given instruction.
1140    pub fn inst_result_types<'a>(
1141        &'a self,
1142        inst: Inst,
1143        ctrl_typevar: Type,
1144    ) -> impl iter::ExactSizeIterator<Item = Type> + 'a {
1145        return match self.non_tail_call_or_try_call_signature(inst) {
1146            Some(sig) => InstResultTypes::Signature(self, sig, 0),
1147            None => {
1148                let constraints = self.insts[inst].opcode().constraints();
1149                InstResultTypes::Constraints(constraints, ctrl_typevar, 0)
1150            }
1151        };
1152
1153        enum InstResultTypes<'a> {
1154            Signature(&'a DataFlowGraph, SigRef, usize),
1155            Constraints(ir::instructions::OpcodeConstraints, Type, usize),
1156        }
1157
1158        impl Iterator for InstResultTypes<'_> {
1159            type Item = Type;
1160
1161            fn next(&mut self) -> Option<Type> {
1162                match self {
1163                    InstResultTypes::Signature(dfg, sig, i) => {
1164                        let param = dfg.signatures[*sig].returns.get(*i)?;
1165                        *i += 1;
1166                        Some(param.value_type)
1167                    }
1168                    InstResultTypes::Constraints(constraints, ctrl_ty, i) => {
1169                        if *i < constraints.num_fixed_results() {
1170                            let ty = constraints.result_type(*i, *ctrl_ty);
1171                            *i += 1;
1172                            Some(ty)
1173                        } else {
1174                            None
1175                        }
1176                    }
1177                }
1178            }
1179
1180            fn size_hint(&self) -> (usize, Option<usize>) {
1181                let len = match self {
1182                    InstResultTypes::Signature(dfg, sig, i) => {
1183                        dfg.signatures[*sig].returns.len() - *i
1184                    }
1185                    InstResultTypes::Constraints(constraints, _, i) => {
1186                        constraints.num_fixed_results() - *i
1187                    }
1188                };
1189                (len, Some(len))
1190            }
1191        }
1192
1193        impl ExactSizeIterator for InstResultTypes<'_> {}
1194    }
1195
1196    /// Compute the type of an instruction result from opcode constraints and call signatures.
1197    ///
1198    /// This computes the same sequence of result types that `make_inst_results()` above would
1199    /// assign to the created result values, but it does not depend on `make_inst_results()` being
1200    /// called first.
1201    ///
1202    /// Returns `None` if asked about a result index that is too large.
1203    pub fn compute_result_type(
1204        &self,
1205        inst: Inst,
1206        result_idx: usize,
1207        ctrl_typevar: Type,
1208    ) -> Option<Type> {
1209        self.inst_result_types(inst, ctrl_typevar).nth(result_idx)
1210    }
1211
1212    /// Get the controlling type variable, or `INVALID` if `inst` isn't polymorphic.
1213    pub fn ctrl_typevar(&self, inst: Inst) -> Type {
1214        let constraints = self.insts[inst].opcode().constraints();
1215
1216        if !constraints.is_polymorphic() {
1217            types::INVALID
1218        } else if constraints.requires_typevar_operand() {
1219            // Not all instruction formats have a designated operand, but in that case
1220            // `requires_typevar_operand()` should never be true.
1221            self.value_type(
1222                self.insts[inst]
1223                    .typevar_operand(&self.value_lists)
1224                    .unwrap_or_else(|| {
1225                        panic!(
1226                            "Instruction format for {:?} doesn't have a designated operand",
1227                            self.insts[inst]
1228                        )
1229                    }),
1230            )
1231        } else {
1232            self.value_type(self.first_result(inst))
1233        }
1234    }
1235}
1236
1237/// basic blocks.
1238impl DataFlowGraph {
1239    /// Create a new basic block.
1240    pub fn make_block(&mut self) -> Block {
1241        self.blocks.add()
1242    }
1243
1244    /// Get the number of parameters on `block`.
1245    pub fn num_block_params(&self, block: Block) -> usize {
1246        self.blocks[block].params(&self.value_lists).len()
1247    }
1248
1249    /// Get the parameters on `block`.
1250    pub fn block_params(&self, block: Block) -> &[Value] {
1251        self.blocks[block].params(&self.value_lists)
1252    }
1253
1254    /// Get the types of the parameters on `block`.
1255    pub fn block_param_types(&self, block: Block) -> impl Iterator<Item = Type> + '_ {
1256        self.block_params(block).iter().map(|&v| self.value_type(v))
1257    }
1258
1259    /// Append a parameter with type `ty` to `block`.
1260    pub fn append_block_param(&mut self, block: Block, ty: Type) -> Value {
1261        let param = self.values.next_key();
1262        let num = self.blocks[block].params.push(param, &mut self.value_lists);
1263        debug_assert!(num <= u16::MAX as usize, "Too many parameters on block");
1264        self.make_value(ValueData::Param {
1265            ty,
1266            num: num as u16,
1267            block,
1268        })
1269    }
1270
1271    /// Removes `val` from `block`'s parameters by swapping it with the last parameter on `block`.
1272    /// Returns the position of `val` before removal.
1273    ///
1274    /// *Important*: to ensure O(1) deletion, this method swaps the removed parameter with the
1275    /// last `block` parameter. This can disrupt all the branch instructions jumping to this
1276    /// `block` for which you have to change the branch argument order if necessary.
1277    ///
1278    /// Panics if `val` is not a block parameter.
1279    pub fn swap_remove_block_param(&mut self, val: Value) -> usize {
1280        let (block, num) =
1281            if let ValueData::Param { num, block, .. } = ValueData::from(self.values[val]) {
1282                (block, num)
1283            } else {
1284                panic!("{val} must be a block parameter");
1285            };
1286        self.blocks[block]
1287            .params
1288            .swap_remove(num as usize, &mut self.value_lists);
1289        if let Some(last_arg_val) = self.blocks[block]
1290            .params
1291            .get(num as usize, &self.value_lists)
1292        {
1293            // We update the position of the old last arg.
1294            let mut last_arg_data = ValueData::from(self.values[last_arg_val]);
1295            if let ValueData::Param { num: old_num, .. } = &mut last_arg_data {
1296                *old_num = num;
1297                self.values[last_arg_val] = last_arg_data.into();
1298            } else {
1299                panic!("{last_arg_val} should be a Block parameter");
1300            }
1301        }
1302        num as usize
1303    }
1304
1305    /// Removes `val` from `block`'s parameters by a standard linear time list removal which
1306    /// preserves ordering. Also updates the values' data.
1307    pub fn remove_block_param(&mut self, val: Value) {
1308        let (block, num) =
1309            if let ValueData::Param { num, block, .. } = ValueData::from(self.values[val]) {
1310                (block, num)
1311            } else {
1312                panic!("{val} must be a block parameter");
1313            };
1314        self.blocks[block]
1315            .params
1316            .remove(num as usize, &mut self.value_lists);
1317        for index in num..(self.num_block_params(block) as u16) {
1318            let packed = &mut self.values[self.blocks[block]
1319                .params
1320                .get(index as usize, &self.value_lists)
1321                .unwrap()];
1322            let mut data = ValueData::from(*packed);
1323            match &mut data {
1324                ValueData::Param { num, .. } => {
1325                    *num -= 1;
1326                    *packed = data.into();
1327                }
1328                _ => panic!(
1329                    "{} must be a block parameter",
1330                    self.blocks[block]
1331                        .params
1332                        .get(index as usize, &self.value_lists)
1333                        .unwrap()
1334                ),
1335            }
1336        }
1337    }
1338
1339    /// Append an existing value to `block`'s parameters.
1340    ///
1341    /// The appended value can't already be attached to something else.
1342    ///
1343    /// In almost all cases, you should be using `append_block_param()` instead of this method.
1344    pub fn attach_block_param(&mut self, block: Block, param: Value) {
1345        debug_assert!(!self.value_is_attached(param));
1346        let num = self.blocks[block].params.push(param, &mut self.value_lists);
1347        debug_assert!(num <= u16::MAX as usize, "Too many parameters on block");
1348        let ty = self.value_type(param);
1349        self.values[param] = ValueData::Param {
1350            ty,
1351            num: num as u16,
1352            block,
1353        }
1354        .into();
1355    }
1356
1357    /// Replace a block parameter with a new value of type `ty`.
1358    ///
1359    /// The `old_value` must be an attached block parameter. It is removed from its place in the list
1360    /// of parameters and replaced by a new value of type `new_type`. The new value gets the same
1361    /// position in the list, and other parameters are not disturbed.
1362    ///
1363    /// The old value is left detached, so it should probably be changed into something else.
1364    ///
1365    /// Returns the new value.
1366    pub fn replace_block_param(&mut self, old_value: Value, new_type: Type) -> Value {
1367        // Create new value identical to the old one except for the type.
1368        let (block, num) =
1369            if let ValueData::Param { num, block, .. } = ValueData::from(self.values[old_value]) {
1370                (block, num)
1371            } else {
1372                panic!("{old_value} must be a block parameter");
1373            };
1374        let new_arg = self.make_value(ValueData::Param {
1375            ty: new_type,
1376            num,
1377            block,
1378        });
1379
1380        self.blocks[block]
1381            .params
1382            .as_mut_slice(&mut self.value_lists)[num as usize] = new_arg;
1383        new_arg
1384    }
1385
1386    /// Detach all the parameters from `block` and return them as a `ValueList`.
1387    ///
1388    /// This is a quite low-level operation. Sensible things to do with the detached block parameters
1389    /// is to put them back on the same block with `attach_block_param()` or change them into aliases
1390    /// with `change_to_alias()`.
1391    pub fn detach_block_params(&mut self, block: Block) -> ValueList {
1392        self.blocks[block].params.take()
1393    }
1394
1395    /// Detach all of an instruction's result values.
1396    ///
1397    /// This is a quite low-level operation. A sensible thing to do with the
1398    /// detached results is to change them into aliases with
1399    /// `change_to_alias()`.
1400    pub fn detach_inst_results(&mut self, inst: Inst) {
1401        self.results[inst].clear(&mut self.value_lists);
1402    }
1403}
1404
1405/// Contents of a basic block.
1406///
1407/// Parameters on a basic block are values that dominate everything in the block. All
1408/// branches to this block must provide matching arguments, and the arguments to the entry block must
1409/// match the function arguments.
1410#[derive(Clone, PartialEq, Hash)]
1411#[cfg_attr(feature = "enable-serde", derive(Serialize, Deserialize))]
1412pub struct BlockData {
1413    /// List of parameters to this block.
1414    params: ValueList,
1415}
1416
1417impl BlockData {
1418    fn new() -> Self {
1419        Self {
1420            params: ValueList::new(),
1421        }
1422    }
1423
1424    /// Get the parameters on `block`.
1425    pub fn params<'a>(&self, pool: &'a ValueListPool) -> &'a [Value] {
1426        self.params.as_slice(pool)
1427    }
1428}
1429
1430/// Object that can display an instruction.
1431pub struct DisplayInst<'a>(&'a DataFlowGraph, Inst);
1432
1433impl<'a> fmt::Display for DisplayInst<'a> {
1434    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1435        let dfg = self.0;
1436        let inst = self.1;
1437
1438        if let Some((first, rest)) = dfg.inst_results(inst).split_first() {
1439            write!(f, "{first}")?;
1440            for v in rest {
1441                write!(f, ", {v}")?;
1442            }
1443            write!(f, " = ")?;
1444        }
1445
1446        let typevar = dfg.ctrl_typevar(inst);
1447        if typevar.is_invalid() {
1448            write!(f, "{}", dfg.insts[inst].opcode())?;
1449        } else {
1450            write!(f, "{}.{}", dfg.insts[inst].opcode(), typevar)?;
1451        }
1452        write_operands(f, dfg, inst)
1453    }
1454}
1455
1456/// Parser routines. These routines should not be used outside the parser.
1457impl DataFlowGraph {
1458    /// Set the type of a value. This is only for use in the parser, which needs
1459    /// to create invalid values for index padding which may be reassigned later.
1460    #[cold]
1461    fn set_value_type_for_parser(&mut self, v: Value, t: Type) {
1462        assert_eq!(
1463            self.value_type(v),
1464            types::INVALID,
1465            "this function is only for assigning types to previously invalid values"
1466        );
1467        self.values[v].set_type(t);
1468    }
1469
1470    /// Check that the given concrete `Type` has been defined in the function.
1471    pub fn check_dynamic_type(&mut self, ty: Type) -> Option<Type> {
1472        debug_assert!(ty.is_dynamic_vector());
1473        if self
1474            .dynamic_types
1475            .values()
1476            .any(|dyn_ty_data| dyn_ty_data.concrete().unwrap() == ty)
1477        {
1478            Some(ty)
1479        } else {
1480            None
1481        }
1482    }
1483
1484    /// Create result values for `inst`, reusing the provided detached values.
1485    /// This is similar to `make_inst_results_reusing` except it's only for use
1486    /// in the parser, which needs to reuse previously invalid values.
1487    #[cold]
1488    pub fn make_inst_results_for_parser(
1489        &mut self,
1490        inst: Inst,
1491        ctrl_typevar: Type,
1492        reuse: &[Value],
1493    ) -> usize {
1494        let mut reuse_iter = reuse.iter().copied();
1495        let result_tys: SmallVec<[_; 16]> = self.inst_result_types(inst, ctrl_typevar).collect();
1496        for ty in result_tys {
1497            if ty.is_dynamic_vector() {
1498                self.check_dynamic_type(ty)
1499                    .unwrap_or_else(|| panic!("Use of undeclared dynamic type: {ty}"));
1500            }
1501            if let Some(v) = reuse_iter.next() {
1502                self.set_value_type_for_parser(v, ty);
1503            }
1504        }
1505
1506        self.make_inst_results_reusing(inst, ctrl_typevar, reuse.iter().map(|x| Some(*x)))
1507    }
1508
1509    /// Similar to `append_block_param`, append a parameter with type `ty` to
1510    /// `block`, but using value `val`. This is only for use by the parser to
1511    /// create parameters with specific values.
1512    #[cold]
1513    pub fn append_block_param_for_parser(&mut self, block: Block, ty: Type, val: Value) {
1514        let num = self.blocks[block].params.push(val, &mut self.value_lists);
1515        assert!(num <= u16::MAX as usize, "Too many parameters on block");
1516        self.values[val] = ValueData::Param {
1517            ty,
1518            num: num as u16,
1519            block,
1520        }
1521        .into();
1522    }
1523
1524    /// Create a new value alias. This is only for use by the parser to create
1525    /// aliases with specific values, and the printer for testing.
1526    #[cold]
1527    pub fn make_value_alias_for_serialization(&mut self, src: Value, dest: Value) {
1528        assert_ne!(src, Value::reserved_value());
1529        assert_ne!(dest, Value::reserved_value());
1530
1531        let ty = if self.values.is_valid(src) {
1532            self.value_type(src)
1533        } else {
1534            // As a special case, if we can't resolve the aliasee yet, use INVALID
1535            // temporarily. It will be resolved later in parsing.
1536            types::INVALID
1537        };
1538        let data = ValueData::Alias { ty, original: src };
1539        self.values[dest] = data.into();
1540    }
1541
1542    /// If `v` is already defined as an alias, return its destination value.
1543    /// Otherwise return None. This allows the parser to coalesce identical
1544    /// alias definitions, and the printer to identify an alias's immediate target.
1545    #[cold]
1546    pub fn value_alias_dest_for_serialization(&self, v: Value) -> Option<Value> {
1547        if let ValueData::Alias { original, .. } = ValueData::from(self.values[v]) {
1548            Some(original)
1549        } else {
1550            None
1551        }
1552    }
1553
1554    /// Compute the type of an alias. This is only for use in the parser.
1555    /// Returns false if an alias cycle was encountered.
1556    #[cold]
1557    pub fn set_alias_type_for_parser(&mut self, v: Value) -> bool {
1558        if let Some(resolved) = maybe_resolve_aliases(&self.values, v) {
1559            let old_ty = self.value_type(v);
1560            let new_ty = self.value_type(resolved);
1561            if old_ty == types::INVALID {
1562                self.set_value_type_for_parser(v, new_ty);
1563            } else {
1564                assert_eq!(old_ty, new_ty);
1565            }
1566            true
1567        } else {
1568            false
1569        }
1570    }
1571
1572    /// Create an invalid value, to pad the index space. This is only for use by
1573    /// the parser to pad out the value index space.
1574    #[cold]
1575    pub fn make_invalid_value_for_parser(&mut self) {
1576        let data = ValueData::Alias {
1577            ty: types::INVALID,
1578            original: Value::reserved_value(),
1579        };
1580        self.make_value(data);
1581    }
1582
1583    /// Check if a value reference is valid, while being aware of aliases which
1584    /// may be unresolved while parsing.
1585    #[cold]
1586    pub fn value_is_valid_for_parser(&self, v: Value) -> bool {
1587        if !self.value_is_valid(v) {
1588            return false;
1589        }
1590        if let ValueData::Alias { ty, .. } = ValueData::from(self.values[v]) {
1591            ty != types::INVALID
1592        } else {
1593            true
1594        }
1595    }
1596}
1597
1598#[cfg(test)]
1599mod tests {
1600    use super::*;
1601    use crate::cursor::{Cursor, FuncCursor};
1602    use crate::ir::{Function, Opcode, TrapCode};
1603    use alloc::string::ToString;
1604
1605    #[test]
1606    fn make_inst() {
1607        let mut dfg = DataFlowGraph::new();
1608
1609        let idata = InstructionData::UnaryImm {
1610            opcode: Opcode::Iconst,
1611            imm: 0.into(),
1612        };
1613        let inst = dfg.make_inst(idata);
1614
1615        dfg.make_inst_results(inst, types::I32);
1616        assert_eq!(inst.to_string(), "inst0");
1617        assert_eq!(dfg.display_inst(inst).to_string(), "v0 = iconst.i32 0");
1618
1619        // Immutable reference resolution.
1620        {
1621            let immdfg = &dfg;
1622            let ins = &immdfg.insts[inst];
1623            assert_eq!(ins.opcode(), Opcode::Iconst);
1624        }
1625
1626        // Results.
1627        let val = dfg.first_result(inst);
1628        assert_eq!(dfg.inst_results(inst), &[val]);
1629
1630        assert_eq!(dfg.value_def(val), ValueDef::Result(inst, 0));
1631        assert_eq!(dfg.value_type(val), types::I32);
1632
1633        // Replacing results.
1634        assert!(dfg.value_is_attached(val));
1635        let v2 = dfg.replace_result(val, types::F64);
1636        assert!(!dfg.value_is_attached(val));
1637        assert!(dfg.value_is_attached(v2));
1638        assert_eq!(dfg.inst_results(inst), &[v2]);
1639        assert_eq!(dfg.value_def(v2), ValueDef::Result(inst, 0));
1640        assert_eq!(dfg.value_type(v2), types::F64);
1641    }
1642
1643    #[test]
1644    fn no_results() {
1645        let mut dfg = DataFlowGraph::new();
1646
1647        let idata = InstructionData::Trap {
1648            opcode: Opcode::Trap,
1649            code: TrapCode::unwrap_user(1),
1650        };
1651        let inst = dfg.make_inst(idata);
1652        assert_eq!(dfg.display_inst(inst).to_string(), "trap user1");
1653
1654        // Result slice should be empty.
1655        assert_eq!(dfg.inst_results(inst), &[]);
1656    }
1657
1658    #[test]
1659    fn block() {
1660        let mut dfg = DataFlowGraph::new();
1661
1662        let block = dfg.make_block();
1663        assert_eq!(block.to_string(), "block0");
1664        assert_eq!(dfg.num_block_params(block), 0);
1665        assert_eq!(dfg.block_params(block), &[]);
1666        assert!(dfg.detach_block_params(block).is_empty());
1667        assert_eq!(dfg.num_block_params(block), 0);
1668        assert_eq!(dfg.block_params(block), &[]);
1669
1670        let arg1 = dfg.append_block_param(block, types::F32);
1671        assert_eq!(arg1.to_string(), "v0");
1672        assert_eq!(dfg.num_block_params(block), 1);
1673        assert_eq!(dfg.block_params(block), &[arg1]);
1674
1675        let arg2 = dfg.append_block_param(block, types::I16);
1676        assert_eq!(arg2.to_string(), "v1");
1677        assert_eq!(dfg.num_block_params(block), 2);
1678        assert_eq!(dfg.block_params(block), &[arg1, arg2]);
1679
1680        assert_eq!(dfg.value_def(arg1), ValueDef::Param(block, 0));
1681        assert_eq!(dfg.value_def(arg2), ValueDef::Param(block, 1));
1682        assert_eq!(dfg.value_type(arg1), types::F32);
1683        assert_eq!(dfg.value_type(arg2), types::I16);
1684
1685        // Swap the two block parameters.
1686        let vlist = dfg.detach_block_params(block);
1687        assert_eq!(dfg.num_block_params(block), 0);
1688        assert_eq!(dfg.block_params(block), &[]);
1689        assert_eq!(vlist.as_slice(&dfg.value_lists), &[arg1, arg2]);
1690        dfg.attach_block_param(block, arg2);
1691        let arg3 = dfg.append_block_param(block, types::I32);
1692        dfg.attach_block_param(block, arg1);
1693        assert_eq!(dfg.block_params(block), &[arg2, arg3, arg1]);
1694    }
1695
1696    #[test]
1697    fn replace_block_params() {
1698        let mut dfg = DataFlowGraph::new();
1699
1700        let block = dfg.make_block();
1701        let arg1 = dfg.append_block_param(block, types::F32);
1702
1703        let new1 = dfg.replace_block_param(arg1, types::I64);
1704        assert_eq!(dfg.value_type(arg1), types::F32);
1705        assert_eq!(dfg.value_type(new1), types::I64);
1706        assert_eq!(dfg.block_params(block), &[new1]);
1707
1708        dfg.attach_block_param(block, arg1);
1709        assert_eq!(dfg.block_params(block), &[new1, arg1]);
1710
1711        let new2 = dfg.replace_block_param(arg1, types::I8);
1712        assert_eq!(dfg.value_type(arg1), types::F32);
1713        assert_eq!(dfg.value_type(new2), types::I8);
1714        assert_eq!(dfg.block_params(block), &[new1, new2]);
1715
1716        dfg.attach_block_param(block, arg1);
1717        assert_eq!(dfg.block_params(block), &[new1, new2, arg1]);
1718
1719        let new3 = dfg.replace_block_param(new2, types::I16);
1720        assert_eq!(dfg.value_type(new1), types::I64);
1721        assert_eq!(dfg.value_type(new2), types::I8);
1722        assert_eq!(dfg.value_type(new3), types::I16);
1723        assert_eq!(dfg.block_params(block), &[new1, new3, arg1]);
1724    }
1725
1726    #[test]
1727    fn swap_remove_block_params() {
1728        let mut dfg = DataFlowGraph::new();
1729
1730        let block = dfg.make_block();
1731        let arg1 = dfg.append_block_param(block, types::F32);
1732        let arg2 = dfg.append_block_param(block, types::F32);
1733        let arg3 = dfg.append_block_param(block, types::F32);
1734        assert_eq!(dfg.block_params(block), &[arg1, arg2, arg3]);
1735
1736        dfg.swap_remove_block_param(arg1);
1737        assert_eq!(dfg.value_is_attached(arg1), false);
1738        assert_eq!(dfg.value_is_attached(arg2), true);
1739        assert_eq!(dfg.value_is_attached(arg3), true);
1740        assert_eq!(dfg.block_params(block), &[arg3, arg2]);
1741        dfg.swap_remove_block_param(arg2);
1742        assert_eq!(dfg.value_is_attached(arg2), false);
1743        assert_eq!(dfg.value_is_attached(arg3), true);
1744        assert_eq!(dfg.block_params(block), &[arg3]);
1745        dfg.swap_remove_block_param(arg3);
1746        assert_eq!(dfg.value_is_attached(arg3), false);
1747        assert_eq!(dfg.block_params(block), &[]);
1748    }
1749
1750    #[test]
1751    fn aliases() {
1752        use crate::ir::InstBuilder;
1753        use crate::ir::condcodes::IntCC;
1754
1755        let mut func = Function::new();
1756        let block0 = func.dfg.make_block();
1757        let mut pos = FuncCursor::new(&mut func);
1758        pos.insert_block(block0);
1759
1760        // Build a little test program.
1761        let v1 = pos.ins().iconst(types::I32, 42);
1762
1763        // Make sure we can resolve value aliases even when values is empty.
1764        assert_eq!(pos.func.dfg.resolve_aliases(v1), v1);
1765
1766        let arg0 = pos.func.dfg.append_block_param(block0, types::I32);
1767        let (s, c) = pos.ins().uadd_overflow(v1, arg0);
1768        let iadd = match pos.func.dfg.value_def(s) {
1769            ValueDef::Result(i, 0) => i,
1770            _ => panic!(),
1771        };
1772
1773        // Remove `c` from the result list.
1774        pos.func.stencil.dfg.results[iadd].remove(1, &mut pos.func.stencil.dfg.value_lists);
1775
1776        // Replace `uadd_overflow` with a normal `iadd` and an `icmp`.
1777        pos.func.replace(iadd).iadd(v1, arg0);
1778        let c2 = pos.ins().icmp(IntCC::Equal, s, v1);
1779        pos.func.dfg.change_to_alias(c, c2);
1780
1781        assert_eq!(pos.func.dfg.resolve_aliases(c2), c2);
1782        assert_eq!(pos.func.dfg.resolve_aliases(c), c2);
1783    }
1784
1785    #[test]
1786    fn cloning() {
1787        use crate::ir::InstBuilder;
1788
1789        let mut func = Function::new();
1790        let mut sig = Signature::new(crate::isa::CallConv::SystemV);
1791        sig.params.push(ir::AbiParam::new(types::I32));
1792        let sig = func.import_signature(sig);
1793        let block0 = func.dfg.make_block();
1794        let mut pos = FuncCursor::new(&mut func);
1795        pos.insert_block(block0);
1796        let v1 = pos.ins().iconst(types::I32, 0);
1797        let v2 = pos.ins().iconst(types::I32, 1);
1798        let call_inst = pos.ins().call_indirect(sig, v1, &[v1]);
1799        let func = pos.func;
1800
1801        let call_inst_dup = func.dfg.clone_inst(call_inst);
1802        func.dfg.inst_args_mut(call_inst)[0] = v2;
1803        assert_eq!(v1, func.dfg.inst_args(call_inst_dup)[0]);
1804    }
1805}