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