midenc-hir 0.8.1

High-level Intermediate Representation for Miden Assembly
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
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
use alloc::rc::Rc;
use core::fmt;

use super::{DefaultResource, Effect, Resource};
use crate::{
    Attribute, AttributeRef, AttributeRegistration, BlockArgument, BlockArgumentRef, EntityRef,
    NamedAttribute, NamedAttributeList, OpOperand, OpOperandImpl, OpResult, OpResultRef, Symbol,
    SymbolRef, UnsafeIntrusiveEntityRef, Value, ValueRef, interner,
};

pub struct EffectInstance<T> {
    /// The specific effect being applied
    effect: T,
    /// The resource that the given value resides in
    resource: Rc<dyn Resource>,
    /// The [Symbol], [OpOperand], [OpResult], or [BlockArgument] that the effect applies to.
    value: Option<EffectValue>,
    /// Additional parameters of the effect instance.
    parameters: NamedAttributeList,
    /// The stage the side effect happens in.
    ///
    /// Side effects with a lower stage happen earlier than those with a higher stage.
    stage: u8,
    /// Indicates whether this side effect acts on every single value of the resource
    effect_on_full_region: bool,
}

impl<T: Clone> Clone for EffectInstance<T> {
    fn clone(&self) -> Self {
        let mut parameters = NamedAttributeList::new();
        for p in self.parameters.iter() {
            let v = p.value();
            let value = v.dyn_clone();
            let cloned = v.context_rc().alloc_tracked(NamedAttribute {
                name: p.name,
                value,
            });
            parameters.push_back(cloned);
        }
        Self {
            effect: self.effect.clone(),
            resource: Rc::clone(&self.resource),
            value: self.value,
            parameters,
            stage: self.stage,
            effect_on_full_region: self.effect_on_full_region,
        }
    }
}

impl<T> EffectInstance<T> {
    pub fn new(effect: T) -> Self {
        Self::new_with_resource(effect, DefaultResource)
    }

    pub fn new_for_value(effect: T, value: impl Into<EffectValue>) -> Self {
        Self::new_for_value_with_resource(effect, value, DefaultResource)
    }
}

impl<T> EffectInstance<T> {
    pub fn new_with_resource(effect: T, resource: impl Resource) -> Self {
        Self {
            effect,
            resource: Rc::new(resource),
            parameters: Default::default(),
            value: None,
            stage: 0,
            effect_on_full_region: false,
        }
    }

    #[inline]
    pub fn new_for_value_with_resource(
        effect: T,
        value: impl Into<EffectValue>,
        resource: impl Resource,
    ) -> Self {
        Self {
            effect,
            resource: Rc::new(resource),
            parameters: Default::default(),
            value: Some(value.into()),
            stage: 0,
            effect_on_full_region: false,
        }
    }

    #[inline(always)]
    pub fn with_parameter(
        mut self,
        name: impl Into<interner::Symbol>,
        value: AttributeRef,
    ) -> Self {
        let name = name.into();
        let mut params = self.parameters.front_mut();
        while let Some(mut next) = params.as_pointer() {
            let mut next = next.borrow_mut();
            if next.name == name {
                next.value = value;
                return self;
            }
            params.move_next();
        }
        let context = value.borrow().context_rc();
        let named_attr = context.alloc_tracked(NamedAttribute { name, value });
        self.parameters.push_back(named_attr);
        self
    }

    #[inline(always)]
    pub fn with_stage(mut self, stage: u8) -> Self {
        self.stage = stage;
        self
    }

    #[inline(always)]
    pub fn with_effect_on_full_region(mut self, yes: bool) -> Self {
        self.effect_on_full_region = yes;
        self
    }

    /// Get the effect being applied
    #[inline]
    pub fn effect(&self) -> &T {
        &self.effect
    }

    /// Get the resource that the effect applies to
    #[inline]
    pub fn resource(&self) -> &dyn Resource {
        self.resource.as_ref()
    }

    /// Get the parameters of the effect.
    #[inline]
    pub const fn parameters(&self) -> &NamedAttributeList {
        &self.parameters
    }

    /// Get the stage at which the effect happens.
    #[inline]
    pub const fn stage(&self) -> u8 {
        self.stage
    }

    /// Returns whether this efffect acts on every single value of the resource.
    #[inline]
    pub const fn is_effect_on_full_region(&self) -> bool {
        self.effect_on_full_region
    }

    /// Get the value the effect is being applied on, or `None` if there isn't a known value
    /// being affected.
    pub fn value(&self) -> Option<ValueRef> {
        match self.value.as_ref()? {
            EffectValue::Result(res) => Some(*res as ValueRef),
            EffectValue::BlockArgument(arg) => Some(*arg as ValueRef),
            EffectValue::Operand(operand) => Some(operand.borrow().as_value_ref()),
            _ => None,
        }
    }

    /// Get the value the effect is being applied on, or `None` if there isn't a known value
    /// being affected.
    #[allow(unused)]
    fn effect_value(&self) -> Option<&EffectValue> {
        self.value.as_ref()
    }

    /// Get the value the effect is being applied on, if it is of the specified type, or `None` if
    /// there isn't a known value being affected.
    pub fn value_of_kind<'a, 'b: 'a, V>(&'b self) -> Option<EntityRef<'a, V>>
    where
        V: Value,
        EntityRef<'a, V>: TryFrom<&'b EffectValue>,
    {
        self.value.as_ref().and_then(|value| value.try_as_ref())
    }

    /// Get the symbol reference the effect is applied on, or `None` if there isn't a known symbol
    /// being affected.
    pub fn symbol(&self) -> Option<SymbolRef> {
        match self.value.as_ref()? {
            EffectValue::Symbol(symbol_use) => Some(*symbol_use),
            _ => None,
        }
    }
}

impl<T: Effect> fmt::Debug for EffectInstance<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EffectInstance")
            .field("effect", &self.effect)
            .field("resource", &self.resource)
            .field("value", &self.value)
            .field("parameters", &self.parameters)
            .field("stage", &self.stage)
            .field("effect_on_full_region", &self.effect_on_full_region)
            .finish()
    }
}

#[derive(Copy, Clone, PartialEq, Eq)]
pub enum EffectValue {
    Attribute(AttributeRef),
    Symbol(SymbolRef),
    Operand(OpOperand),
    Result(OpResultRef),
    BlockArgument(BlockArgumentRef),
}

impl fmt::Debug for EffectValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Attribute(attr) => fmt::Debug::fmt(attr, f),
            Self::Symbol(symbol_use) => f
                .debug_tuple("Symbol")
                .field_with(|f| {
                    let symbol = symbol_use.borrow();
                    write!(f, "{}", &symbol.path())
                })
                .finish(),
            Self::Operand(operand) => {
                let value = operand.borrow().as_value_ref();
                f.debug_tuple("Operand").field(&value).finish()
            }
            Self::Result(result) => {
                let value = *result as ValueRef;
                f.debug_tuple("Result").field(&value).finish()
            }
            Self::BlockArgument(arg) => {
                let value = *arg as ValueRef;
                f.debug_tuple("BlockArgument").field(&value).finish()
            }
        }
    }
}

impl<T: AttributeRegistration> From<UnsafeIntrusiveEntityRef<T>> for EffectValue {
    default fn from(value: UnsafeIntrusiveEntityRef<T>) -> Self {
        Self::Attribute(value.as_attribute_ref())
    }
}

impl<T: AttributeRegistration> From<EntityRef<'_, T>> for EffectValue {
    fn from(value: EntityRef<'_, T>) -> Self {
        Self::Attribute(value.as_attribute_ref())
    }
}

impl From<AttributeRef> for EffectValue {
    fn from(value: AttributeRef) -> Self {
        Self::Attribute(value)
    }
}

impl From<EntityRef<'_, dyn Attribute>> for EffectValue {
    fn from(value: EntityRef<'_, dyn Attribute>) -> Self {
        Self::Attribute(value.as_attribute_ref())
    }
}

impl From<SymbolRef> for EffectValue {
    fn from(value: SymbolRef) -> Self {
        Self::Symbol(value)
    }
}

impl From<EntityRef<'_, dyn Symbol>> for EffectValue {
    fn from(value: EntityRef<'_, dyn Symbol>) -> Self {
        Self::Symbol(
            value
                .as_symbol_operation()
                .as_symbol_ref()
                .expect("effect values must be backed by symbol operations"),
        )
    }
}

impl From<OpOperand> for EffectValue {
    fn from(value: OpOperand) -> Self {
        Self::Operand(value)
    }
}

impl From<EntityRef<'_, OpOperandImpl>> for EffectValue {
    fn from(value: EntityRef<'_, OpOperandImpl>) -> Self {
        Self::Operand(value.as_operand_ref())
    }
}

impl From<OpResultRef> for EffectValue {
    fn from(value: OpResultRef) -> Self {
        Self::Result(value)
    }
}

impl From<EntityRef<'_, OpResult>> for EffectValue {
    fn from(value: EntityRef<'_, OpResult>) -> Self {
        Self::Result(value.as_op_result_ref())
    }
}

impl From<BlockArgumentRef> for EffectValue {
    fn from(value: BlockArgumentRef) -> Self {
        Self::BlockArgument(value)
    }
}

impl From<ValueRef> for EffectValue {
    fn from(value: ValueRef) -> Self {
        let value = value.borrow();
        if let Some(result) = value.downcast_ref::<OpResult>() {
            Self::Result(result.as_op_result_ref())
        } else {
            let arg = value.downcast_ref::<BlockArgument>().unwrap();
            Self::BlockArgument(arg.as_block_argument_ref())
        }
    }
}

impl EffectValue {
    pub fn try_as_ref<'a, 'b: 'a, V>(&'b self) -> Option<EntityRef<'a, V>>
    where
        V: Value,
        EntityRef<'a, V>: TryFrom<&'b Self>,
    {
        TryFrom::try_from(self).ok()
    }
}

impl<'a> core::convert::TryFrom<&'a EffectValue> for EntityRef<'a, OpOperandImpl> {
    type Error = ();

    fn try_from(value: &'a EffectValue) -> Result<Self, Self::Error> {
        match value {
            EffectValue::Operand(operand) => Ok(operand.borrow()),
            _ => Err(()),
        }
    }
}

impl<'a> core::convert::TryFrom<&'a EffectValue> for EntityRef<'a, BlockArgument> {
    type Error = ();

    fn try_from(value: &'a EffectValue) -> Result<Self, Self::Error> {
        match value {
            EffectValue::BlockArgument(operand) => Ok(operand.borrow()),
            _ => Err(()),
        }
    }
}

impl<'a> core::convert::TryFrom<&'a EffectValue> for EntityRef<'a, OpResult> {
    type Error = ();

    fn try_from(value: &'a EffectValue) -> Result<Self, Self::Error> {
        match value {
            EffectValue::Result(operand) => Ok(operand.borrow()),
            _ => Err(()),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::EffectValue;
    use crate::{
        Attribute, AttributeRef, EntityRef, Immediate, ImmediateAttr, Type,
        attributes::IntegerLikeAttr, testing::Test,
    };

    #[test]
    fn effect_value_from_typed_attribute_borrow_preserves_type() {
        let test = Test::default();
        let immediate = test.context_rc().create_attribute::<ImmediateAttr, _>(Immediate::I32(7));
        let expected = immediate.as_attribute_ref();
        let borrowed = immediate.borrow();

        let effect = EffectValue::from(borrowed);
        let EffectValue::Attribute(attr) = effect else {
            panic!("expected attribute effect value");
        };

        assert!(AttributeRef::ptr_eq(&attr, &expected));
        assert_eq!(attr.borrow().ty().clone(), Type::I32);
        let attr = attr.try_downcast_attr::<ImmediateAttr>().unwrap();
        assert_eq!(attr.borrow().as_immediate(), Immediate::I32(7));
    }

    #[test]
    fn effect_value_from_dyn_attribute_borrow_preserves_type() {
        let test = Test::default();
        let immediate = test.context_rc().create_attribute::<ImmediateAttr, _>(Immediate::I32(9));
        let expected = immediate.as_attribute_ref();
        let immediate = immediate.borrow();
        let immediate = EntityRef::map(immediate, |attr| attr as &dyn Attribute);

        let effect = EffectValue::from(immediate);
        let EffectValue::Attribute(attr) = effect else {
            panic!("expected attribute effect value");
        };

        assert!(AttributeRef::ptr_eq(&attr, &expected));
        assert_eq!(attr.borrow().ty().clone(), Type::I32);
        let attr = attr.try_downcast_attr::<ImmediateAttr>().unwrap();
        assert_eq!(attr.borrow().as_immediate(), Immediate::I32(9));
    }
}