1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
//! The base descriptor for various values within the IR.
//!
//! [`Value`]s can be function arguments, constants and instructions.  [`Instruction`]s generally
//! refer to each other and to constants via the [`Value`] wrapper.
//!
//! Like most IR data structures they are `Copy` and cheap to pass around by value.  They are
//! therefore also easy to replace, a common practice for optimization passes.

use rustc_hash::FxHashMap;

use crate::{
    block::BlockArgument,
    constant::Constant,
    context::Context,
    instruction::{FuelVmInstruction, Instruction},
    irtype::Type,
    metadata::{combine, MetadataIndex},
    pretty::DebugWithContext,
};

/// A wrapper around an [ECS](https://github.com/fitzgen/generational-arena) handle into the
/// [`Context`].
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, DebugWithContext)]
pub struct Value(#[in_context(values)] pub generational_arena::Index);

#[doc(hidden)]
#[derive(Debug, Clone, DebugWithContext)]
pub struct ValueContent {
    pub value: ValueDatum,
    pub metadata: Option<MetadataIndex>,
}

#[doc(hidden)]
#[derive(Debug, Clone, DebugWithContext)]
pub enum ValueDatum {
    Argument(BlockArgument),
    Configurable(Constant),
    Constant(Constant),
    Instruction(Instruction),
}

impl Value {
    /// Return a new argument [`Value`].
    pub fn new_argument(context: &mut Context, arg: BlockArgument) -> Value {
        let content = ValueContent {
            value: ValueDatum::Argument(arg),
            metadata: None,
        };
        Value(context.values.insert(content))
    }

    /// Return a new constant [`Value`].
    pub fn new_configurable(context: &mut Context, constant: Constant) -> Value {
        let content = ValueContent {
            value: ValueDatum::Configurable(constant),
            metadata: None,
        };
        Value(context.values.insert(content))
    }

    /// Return a new constant [`Value`].
    pub fn new_constant(context: &mut Context, constant: Constant) -> Value {
        let content = ValueContent {
            value: ValueDatum::Constant(constant),
            metadata: None,
        };
        Value(context.values.insert(content))
    }

    /// Return a new instruction [`Value`].
    pub fn new_instruction(context: &mut Context, instruction: Instruction) -> Value {
        let content = ValueContent {
            value: ValueDatum::Instruction(instruction),
            metadata: None,
        };
        Value(context.values.insert(content))
    }

    /// Add some metadata to this value.
    ///
    /// As a convenience the `md_idx` argument is an `Option`, in which case this function is a
    /// no-op.
    ///
    /// If there is no existing metadata then the new metadata are added alone. Otherwise the new
    /// metadatum are added to the list of metadata.
    pub fn add_metadatum(self, context: &mut Context, md_idx: Option<MetadataIndex>) -> Self {
        if md_idx.is_some() {
            let orig_md = context.values[self.0].metadata;
            let new_md = combine(context, &orig_md, &md_idx);
            context.values[self.0].metadata = new_md;
        }
        self
    }

    /// Return this value's metadata.
    pub fn get_metadata(&self, context: &Context) -> Option<MetadataIndex> {
        context.values[self.0].metadata
    }

    /// Return whether this is a constant value.
    pub fn is_configurable(&self, context: &Context) -> bool {
        matches!(context.values[self.0].value, ValueDatum::Configurable(_))
    }

    /// Return whether this is a constant value.
    pub fn is_constant(&self, context: &Context) -> bool {
        matches!(context.values[self.0].value, ValueDatum::Constant(_))
    }

    /// Return whether this value is an instruction, and specifically a 'terminator'.
    ///
    /// A terminator is always the last instruction in a block (and may not appear anywhere else)
    /// and is either a branch or return.
    pub fn is_terminator(&self, context: &Context) -> bool {
        match &context.values[self.0].value {
            ValueDatum::Instruction(ins) => matches!(
                ins,
                Instruction::Branch(_)
                    | Instruction::ConditionalBranch { .. }
                    | Instruction::Ret(_, _)
                    | Instruction::FuelVm(FuelVmInstruction::Revert(_))
            ),
            _ => false,
        }
    }

    pub fn is_diverging(&self, context: &Context) -> bool {
        match &context.values[self.0].value {
            ValueDatum::Instruction(ins) => matches!(
                ins,
                Instruction::Branch(..)
                    | Instruction::ConditionalBranch { .. }
                    | Instruction::Ret(..)
                    | Instruction::FuelVm(FuelVmInstruction::Revert(..))
            ),
            ValueDatum::Argument(..) | ValueDatum::Configurable(..) | ValueDatum::Constant(..) => {
                false
            }
        }
    }

    /// If this value is an instruction and if any of its parameters is `old_val` then replace them
    /// with `new_val`.
    pub fn replace_instruction_value(&self, context: &mut Context, old_val: Value, new_val: Value) {
        self.replace_instruction_values(context, &FxHashMap::from_iter([(old_val, new_val)]))
    }

    pub fn replace_instruction_values(
        &self,
        context: &mut Context,
        replace_map: &FxHashMap<Value, Value>,
    ) {
        if let ValueDatum::Instruction(instruction) =
            &mut context.values.get_mut(self.0).unwrap().value
        {
            instruction.replace_values(replace_map);
        }
    }

    /// Replace this value with another one, in-place.
    pub fn replace(&self, context: &mut Context, other: ValueDatum) {
        context.values[self.0].value = other;
    }

    /// Get a reference to this value as an instruction, iff it is one.
    pub fn get_instruction<'a>(&self, context: &'a Context) -> Option<&'a Instruction> {
        if let ValueDatum::Instruction(instruction) = &context.values[self.0].value {
            Some(instruction)
        } else {
            None
        }
    }

    /// Get a mutable reference to this value as an instruction, iff it is one.
    pub fn get_instruction_mut<'a>(&self, context: &'a mut Context) -> Option<&'a mut Instruction> {
        if let ValueDatum::Instruction(instruction) =
            &mut context.values.get_mut(self.0).unwrap().value
        {
            Some(instruction)
        } else {
            None
        }
    }

    /// Get a reference to this value as a constant, iff it is one.
    pub fn get_configurable<'a>(&self, context: &'a Context) -> Option<&'a Constant> {
        if let ValueDatum::Configurable(cn) = &context.values[self.0].value {
            Some(cn)
        } else {
            None
        }
    }

    /// Get a reference to this value as a constant, iff it is one.
    pub fn get_constant<'a>(&self, context: &'a Context) -> Option<&'a Constant> {
        if let ValueDatum::Constant(cn) = &context.values[self.0].value {
            Some(cn)
        } else {
            None
        }
    }

    /// Get a reference to this value as an argument, iff it is one.
    pub fn get_argument<'a>(&self, context: &'a Context) -> Option<&'a BlockArgument> {
        if let ValueDatum::Argument(arg) = &context.values[self.0].value {
            Some(arg)
        } else {
            None
        }
    }

    /// Get a reference to this value as a constant or as a configurable, iff it is one of the two.
    pub fn get_constant_or_configurable<'a>(&self, context: &'a Context) -> Option<&'a Constant> {
        match &context.values[self.0].value {
            ValueDatum::Constant(cn) => Some(cn),
            ValueDatum::Configurable(cn) => Some(cn),
            _ => None,
        }
    }

    /// Get the type for this value, if found.
    ///
    /// Arguments and constants always have a type, but only some instructions do.
    pub fn get_type(&self, context: &Context) -> Option<Type> {
        match &context.values[self.0].value {
            ValueDatum::Argument(BlockArgument { ty, .. }) => Some(*ty),
            ValueDatum::Configurable(c) => Some(c.ty),
            ValueDatum::Constant(c) => Some(c.ty),
            ValueDatum::Instruction(ins) => ins.get_type(context),
        }
    }

    /// Get the pointer inner type for this value, iff it is a pointer.
    pub fn match_ptr_type(&self, context: &Context) -> Option<Type> {
        self.get_type(context)
            .and_then(|ty| ty.get_pointee_type(context))
    }
}