sway_ir/
value.rs

1//! The base descriptor for various values within the IR.
2//!
3//! [`Value`]s can be function arguments, constants and instructions. [`Instruction`]s generally
4//! refer to each other and to constants via the [`Value`] wrapper.
5//!
6//! Like most IR data structures they are `Copy` and cheap to pass around by value. They are
7//! therefore also easy to replace, a common practice for optimization passes.
8
9use rustc_hash::FxHashMap;
10
11use crate::{
12    block::BlockArgument,
13    context::Context,
14    instruction::InstOp,
15    irtype::Type,
16    metadata::{combine, MetadataIndex},
17    pretty::DebugWithContext,
18    Block, Constant, Instruction,
19};
20
21/// A wrapper around an [ECS](https://github.com/orlp/slotmap) handle into the
22/// [`Context`].
23#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, DebugWithContext)]
24pub struct Value(#[in_context(values)] pub slotmap::DefaultKey);
25
26#[doc(hidden)]
27#[derive(Debug, Clone, DebugWithContext)]
28pub struct ValueContent {
29    pub value: ValueDatum,
30    pub metadata: Option<MetadataIndex>,
31}
32
33#[doc(hidden)]
34#[derive(Debug, Clone, DebugWithContext)]
35pub enum ValueDatum {
36    Argument(BlockArgument),
37    Constant(Constant),
38    Instruction(Instruction),
39}
40
41impl Value {
42    /// Return a new argument [`Value`].
43    pub fn new_argument(context: &mut Context, arg: BlockArgument) -> Value {
44        let content = ValueContent {
45            value: ValueDatum::Argument(arg),
46            metadata: None,
47        };
48        Value(context.values.insert(content))
49    }
50
51    /// Return a new constant [`Value`].
52    pub fn new_constant(context: &mut Context, constant: Constant) -> Value {
53        let content = ValueContent {
54            value: ValueDatum::Constant(constant),
55            metadata: None,
56        };
57        Value(context.values.insert(content))
58    }
59
60    /// Return a new instruction [`Value`].
61    pub fn new_instruction(context: &mut Context, block: Block, instruction: InstOp) -> Value {
62        let content = ValueContent {
63            value: ValueDatum::Instruction(Instruction {
64                op: instruction,
65                parent: block,
66            }),
67            metadata: None,
68        };
69        Value(context.values.insert(content))
70    }
71
72    /// Add some metadata to this value.
73    ///
74    /// As a convenience the `md_idx` argument is an `Option`, in which case this function is a
75    /// no-op.
76    ///
77    /// If there is no existing metadata then the new metadata are added alone. Otherwise the new
78    /// metadatum are added to the list of metadata.
79    pub fn add_metadatum(self, context: &mut Context, md_idx: Option<MetadataIndex>) -> Self {
80        if md_idx.is_some() {
81            let orig_md = context.values[self.0].metadata;
82            let new_md = combine(context, &orig_md, &md_idx);
83            context.values[self.0].metadata = new_md;
84        }
85        self
86    }
87
88    /// Return this value's metadata.
89    pub fn get_metadata(&self, context: &Context) -> Option<MetadataIndex> {
90        context.values[self.0].metadata
91    }
92
93    /// Return whether this is a constant value.
94    pub fn is_constant(&self, context: &Context) -> bool {
95        matches!(context.values[self.0].value, ValueDatum::Constant(_))
96    }
97
98    /// Return whether this value is an instruction, and specifically a 'terminator'.
99    ///
100    /// A terminator is always the last instruction in a block (and may not appear anywhere else)
101    /// and is either a branch or return.
102    pub fn is_terminator(&self, context: &Context) -> bool {
103        match &context.values[self.0].value {
104            ValueDatum::Instruction(Instruction { op, .. }) => op.is_terminator(),
105            ValueDatum::Argument(..) | ValueDatum::Constant(..) => false,
106        }
107    }
108
109    /// If this value is an instruction and if any of its parameters is `old_val` then replace them
110    /// with `new_val`.
111    pub fn replace_instruction_value(&self, context: &mut Context, old_val: Value, new_val: Value) {
112        self.replace_instruction_values(context, &FxHashMap::from_iter([(old_val, new_val)]))
113    }
114
115    /// If this value is an instruction and if any of its parameters is in `replace_map` as
116    /// a key, replace it with the mapped value.
117    pub fn replace_instruction_values(
118        &self,
119        context: &mut Context,
120        replace_map: &FxHashMap<Value, Value>,
121    ) {
122        if let ValueDatum::Instruction(instruction) =
123            &mut context.values.get_mut(self.0).unwrap().value
124        {
125            instruction.op.replace_values(replace_map);
126        }
127    }
128
129    /// Replace this value with another one, in-place.
130    pub fn replace(&self, context: &mut Context, other: ValueDatum) {
131        context.values[self.0].value = other;
132    }
133
134    /// Get a reference to this value as an instruction, iff it is one.
135    pub fn get_instruction<'a>(&self, context: &'a Context) -> Option<&'a Instruction> {
136        if let ValueDatum::Instruction(instruction) = &context.values[self.0].value {
137            Some(instruction)
138        } else {
139            None
140        }
141    }
142
143    /// Get a mutable reference to this value as an instruction, iff it is one.
144    pub fn get_instruction_mut<'a>(&self, context: &'a mut Context) -> Option<&'a mut Instruction> {
145        if let ValueDatum::Instruction(instruction) =
146            &mut context.values.get_mut(self.0).unwrap().value
147        {
148            Some(instruction)
149        } else {
150            None
151        }
152    }
153
154    /// Get a reference to this value as a constant, iff it is one.
155    pub fn get_constant<'a>(&self, context: &'a Context) -> Option<&'a Constant> {
156        if let ValueDatum::Constant(cn) = &context.values[self.0].value {
157            Some(cn)
158        } else {
159            None
160        }
161    }
162
163    /// Get a reference to this value as an argument, iff it is one.
164    pub fn get_argument<'a>(&self, context: &'a Context) -> Option<&'a BlockArgument> {
165        if let ValueDatum::Argument(arg) = &context.values[self.0].value {
166            Some(arg)
167        } else {
168            None
169        }
170    }
171
172    /// Get a mutable reference to this value as an argument, iff it is one.
173    pub fn get_argument_mut<'a>(&self, context: &'a mut Context) -> Option<&'a mut BlockArgument> {
174        if let ValueDatum::Argument(arg) = &mut context.values[self.0].value {
175            Some(arg)
176        } else {
177            None
178        }
179    }
180
181    /// Get the type for this value, if found.
182    ///
183    /// Arguments and constants always have a type, but only some instructions do.
184    pub fn get_type(&self, context: &Context) -> Option<Type> {
185        match &context.values[self.0].value {
186            ValueDatum::Argument(BlockArgument { ty, .. }) => Some(*ty),
187            ValueDatum::Constant(c) => Some(c.get_content(context).ty),
188            ValueDatum::Instruction(ins) => ins.get_type(context),
189        }
190    }
191
192    /// Get the pointer inner type for this value, iff it is a pointer.
193    pub fn match_ptr_type(&self, context: &Context) -> Option<Type> {
194        self.get_type(context)
195            .and_then(|ty| ty.get_pointee_type(context))
196    }
197}