midenc-hir 0.9.2

High-level Intermediate Representation for Miden Assembly
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
use alloc::format;
use core::str::FromStr;

use crate::{
    AsValueRange, BlockRef, CallConv, CallableOpInterface, CallableSymbol, EntityRef, IdentAttr,
    Immediate, ImmediateAttr, Op, OpParser, OpPrinter, Operation, RegionKind, RegionKindInterface,
    RegionRef, SmallVec, Symbol, SymbolUse, SymbolUseList, Type, UnsafeIntrusiveEntityRef, Usable,
    Visibility,
    derive::operation,
    dialects::builtin::{
        BuiltinDialect,
        attributes::{
            AdviceEffectArrayAttr, AdviceResourceKind, LocalVariable, MemoryEffectArrayAttr,
            Signature, SignatureAttr, TypeArrayAttr, VisibilityAttr,
        },
    },
    effects::{
        AdviceEffect, AdviceEffectOpInterface, AdviceMapResource, AdviceStackResource,
        EffectInstance, EffectIterator, EffectOpInterface, HasRecursiveAdviceEffects,
        HasRecursiveMemoryEffects, MemoryEffect, MemoryEffectOpInterface, MerkleStoreResource,
    },
    interner,
    parse::ParserExt,
    print::AsmPrinter,
    traits::{
        AnyType, IsolatedFromAbove, OperandRangeRequirement, OperandRangeRequirementOpInterface,
        ReturnLike, SingleRegion, Terminator,
    },
};

trait UsableSymbol = Usable<Use = SymbolUse>;

pub type FunctionRef = UnsafeIntrusiveEntityRef<Function>;

#[operation(
    dialect = BuiltinDialect,
    traits(SingleRegion, IsolatedFromAbove, HasRecursiveMemoryEffects, HasRecursiveAdviceEffects),
    implements(
        UsableSymbol,
        Symbol,
        CallableOpInterface,
        CallableSymbol,
        RegionKindInterface,
        MemoryEffectOpInterface,
        AdviceEffectOpInterface,
        OpPrinter
    )
)]
pub struct Function {
    #[attr]
    name: IdentAttr,
    #[attr]
    linkage: VisibilityAttr,
    #[attr]
    signature: SignatureAttr,
    #[region]
    body: RegionRef,
    #[attr]
    #[default]
    memory_effects: MemoryEffectArrayAttr,
    #[attr]
    #[default]
    advice_effects: AdviceEffectArrayAttr,
    /// The set of local variables allocated within this function
    #[attr]
    #[default]
    locals: TypeArrayAttr,
    /// The uses of this function as a symbol
    #[default]
    uses: SymbolUseList,
}

impl EffectOpInterface<MemoryEffect> for Function {
    fn effects(&self) -> EffectIterator<MemoryEffect> {
        if self.is_declaration() {
            let memory_effects = self.memory_effects();
            EffectIterator::new(
                memory_effects.as_value().iter().map(|desc| EffectInstance::new(desc.effect)),
            )
        } else {
            EffectIterator::new(
                self.as_operation()
                    .get_effects_recursively::<MemoryEffect>()
                    .unwrap_or_default(),
            )
        }
    }
}

impl EffectOpInterface<AdviceEffect> for Function {
    fn effects(&self) -> crate::effects::EffectIterator<AdviceEffect> {
        if self.is_declaration() {
            let advice_effects = self.advice_effects();
            EffectIterator::new(advice_effects.as_value().iter().map(|desc| match desc.resource {
                AdviceResourceKind::Map => {
                    EffectInstance::new_with_resource(desc.effect, AdviceMapResource)
                }
                AdviceResourceKind::Stack => {
                    EffectInstance::new_with_resource(desc.effect, AdviceStackResource)
                }
                AdviceResourceKind::MerkleStore => {
                    EffectInstance::new_with_resource(desc.effect, MerkleStoreResource)
                }
            }))
        } else {
            EffectIterator::new(
                self.as_operation()
                    .get_effects_recursively::<AdviceEffect>()
                    .unwrap_or_default(),
            )
        }
    }
}

impl OpParser for Function {
    fn parse(
        state: &mut crate::OperationState,
        parser: &mut dyn crate::OpAsmParser<'_>,
    ) -> crate::ParseResult {
        use alloc::string::ToString;

        use crate::parse::{Delimiter, ParserError, Token};

        let visibility = match parser.parse_optional_keyword()? {
            Some(tok) => match tok.inner() {
                Token::BareIdent("public") => Visibility::Public,
                Token::BareIdent("private") => Visibility::Private,
                Token::BareIdent("internal") => Visibility::Internal,
                invalid => {
                    return Err(ParserError::UnexpectedToken {
                        span: tok.span(),
                        token: invalid.to_string(),
                        expected: Some("visibility keyword".to_string()),
                    });
                }
            },
            None => Visibility::Private,
        };

        let extern_keyword = parser.parse_optional_keyword()?;
        match extern_keyword.map(|tok| tok.into_parts()) {
            None => (),
            Some((_, Token::BareIdent("extern"))) => (),
            Some((span, invalid)) => {
                return Err(ParserError::UnexpectedToken {
                    span,
                    token: invalid.to_string(),
                    expected: Some("extern keyword".to_string()),
                });
            }
        }

        parser.parse_lparen()?;
        let cc_string = parser.parse_string()?;
        let cc = CallConv::from_str(cc_string.as_str()).map_err(|_| {
            let (span, cc_string) = cc_string.into_parts();
            ParserError::UnexpectedToken {
                span,
                token: cc_string.into_string(),
                expected: Some("calling convention string".to_string()),
            }
        })?;
        parser.parse_rparen()?;

        let name = parser.parse_symbol_name()?;

        let mut args = SmallVec::new_const();
        parser.parse_argument_list(Delimiter::Paren, true, true, &mut args)?;

        let mut results = SmallVec::new_const();
        parser.parse_optional_arrow_type_list(&mut results)?;

        let sig = Signature::with_convention(
            &parser.context_rc(),
            cc,
            args.iter().map(|arg| arg.ty.clone()),
            results,
        );

        let name = parser.context_rc().create_attribute::<IdentAttr, _>(name);
        state.add_attribute("name", name);

        let visibility = parser.context_rc().create_attribute::<VisibilityAttr, _>(visibility);
        state.add_attribute("linkage", visibility);

        let ty = parser.context_rc().create_attribute::<SignatureAttr, _>(sig);
        state.add_attribute("signature", ty);

        let locals = parser.context_rc().create_attribute::<TypeArrayAttr, _>([]);
        state.add_attribute("locals", locals);

        let memory_effects = parser.context_rc().create_attribute::<MemoryEffectArrayAttr, _>([]);
        state.add_attribute("memory_effects", memory_effects);

        let advice_effects = parser.context_rc().create_attribute::<AdviceEffectArrayAttr, _>([]);
        state.add_attribute("advice_effects", advice_effects);

        if let Some(body) = parser.parse_optional_region(&args, false)? {
            state.add_region(body);
        }
        Ok(())
    }
}

impl OpPrinter for Function {
    fn print(&self, printer: &mut AsmPrinter<'_>) {
        use alloc::borrow::Cow;
        let sig = self.get_signature();

        printer.print_space();
        printer.print_keyword(self.get_linkage().as_str());
        printer.print_space();
        printer.print_keyword("extern");
        printer.print_lparen();
        printer.print_string(sig.calling_convention().as_str());
        printer.print_rparen();
        printer.print_space();

        printer.print_symbol_name(self.get_name().as_symbol());
        if self.is_declaration() {
            printer.print_function_type_parts(
                sig.params().iter().map(|p| &p.ty),
                sig.results().iter().map(|p| &p.ty),
            );
        } else {
            let body = self.body();
            let entry = body.entry();
            printer.print_value_id_and_type_list(entry.argument_values());
            if !sig.results().is_empty() {
                printer.print_space();
                printer.print_arrow_type_list(
                    /*elide_single_type_parens=*/ true,
                    sig.results().iter().map(|p| Cow::Borrowed(&p.ty)),
                );
            }
            printer.print_space();
            printer.print_region(&body);
        }
    }
}

/// Builders
impl Function {
    /// Conver this function from a declaration (no body) to a definition (has a body) by creating
    /// the entry block based on the function signature.
    ///
    /// NOTE: The resulting function is _invalid_ until the block has a terminator inserted into it.
    ///
    /// This function will panic if an entry block has already been created
    pub fn create_entry_block(&mut self) -> BlockRef {
        assert!(self.body().is_empty(), "entry block already exists");
        let signature = self.get_signature();
        let block = self
            .as_operation()
            .context_rc()
            .create_block_with_params(signature.params().iter().map(|p| p.ty.clone()));
        drop(signature);
        let mut body = self.body_mut();
        body.push_back(block);
        block
    }
}

/// Accessors
impl Function {
    #[inline]
    pub fn entry_block(&self) -> BlockRef {
        self.body()
            .body()
            .front()
            .as_pointer()
            .expect("cannot get entry block for declaration")
    }

    pub fn last_block(&self) -> BlockRef {
        self.body()
            .body()
            .back()
            .as_pointer()
            .expect("cannot access blocks of a function declaration")
    }

    pub fn num_locals(&self) -> usize {
        self.locals().len()
    }

    pub fn get_local(&self, id: &LocalVariable) -> EntityRef<'_, Type> {
        assert_eq!(
            self.as_operation_ref(),
            id.function().as_operation_ref(),
            "attempted to use local variable reference from different function"
        );
        EntityRef::map(self.get_locals(), |locals| &locals[id.as_usize()])
    }

    pub fn alloc_local(&mut self, ty: Type) -> LocalVariable {
        let mut locals = self.get_locals_mut();
        let id = locals.len();
        locals.push(ty);
        drop(locals);
        LocalVariable::new(self.as_function_ref(), id)
    }

    pub fn iter_locals(&self) -> impl ExactSizeIterator<Item = LocalVariable> {
        let fun = self.as_function_ref();
        (0..self.locals().len()).map(move |i| LocalVariable::new(fun, i))
    }

    #[inline(always)]
    pub fn as_function_ref(&self) -> FunctionRef {
        unsafe { FunctionRef::from_raw(self) }
    }

    #[inline(always)]
    pub const fn signature_ref(&self) -> UnsafeIntrusiveEntityRef<SignatureAttr> {
        self.signature
    }
}

impl RegionKindInterface for Function {
    #[inline(always)]
    fn kind(&self) -> RegionKind {
        RegionKind::SSA
    }
}

impl Usable for Function {
    type Use = SymbolUse;

    #[inline(always)]
    fn uses(&self) -> &SymbolUseList {
        &self.uses
    }

    #[inline(always)]
    fn uses_mut(&mut self) -> &mut SymbolUseList {
        &mut self.uses
    }
}

impl Symbol for Function {
    #[inline(always)]
    fn as_symbol_operation(&self) -> &Operation {
        &self.op
    }

    #[inline(always)]
    fn as_symbol_operation_mut(&mut self) -> &mut Operation {
        &mut self.op
    }

    fn name(&self) -> interner::Symbol {
        self.get_name().as_symbol()
    }

    fn set_name(&mut self, name: interner::Symbol) {
        self.get_name_mut().name = name;
    }

    fn visibility(&self) -> Visibility {
        *self.get_linkage()
    }

    fn set_visibility(&mut self, visibility: Visibility) {
        *self.get_linkage_mut() = visibility;
    }

    /// Returns true if this operation is a declaration, rather than a definition, of a symbol
    ///
    /// The default implementation assumes that all operations are definitions
    #[inline]
    fn is_declaration(&self) -> bool {
        self.body().is_empty()
    }
}

impl CallableOpInterface for Function {
    fn get_callable_region(&self) -> Option<RegionRef> {
        if self.is_declaration() {
            None
        } else {
            self.op.regions().front().as_pointer()
        }
    }

    fn signature(&self) -> Signature {
        self.get_signature().clone()
    }
}

/// Returns from the enclosing function with the provided operands as its results.
#[operation(
    dialect = BuiltinDialect,
    traits(Terminator, ReturnLike),
    implements(OperandRangeRequirementOpInterface, OpPrinter)
)]
pub struct Ret {
    #[operands]
    values: AnyType,
}

impl OperandRangeRequirementOpInterface for Ret {
    fn operand_range_requirement(&self, _operand_index: usize) -> OperandRangeRequirement {
        OperandRangeRequirement::None
    }
}

impl OpPrinter for Ret {
    fn print(&self, printer: &mut AsmPrinter<'_>) {
        use alloc::borrow::Cow;

        let returning = self.values();
        if returning.is_empty() {
            return;
        }

        printer.print_space();
        printer.print_value_uses(returning.as_value_range());
        printer.print_space();
        printer.print_colon_type_list(returning.iter().map(|r| Cow::Owned(r.borrow().ty())));
    }
}

impl OpParser for Ret {
    fn parse(
        state: &mut crate::OperationState,
        parser: &mut dyn crate::OpAsmParser<'_>,
    ) -> crate::ParseResult {
        use crate::{
            diagnostics::SourceSpan,
            parse::{Delimiter, Token},
        };

        if !parser.token_stream_mut().is_next(|tok| matches!(tok, Token::PercentIdent(_))) {
            return Ok(());
        }

        let start = parser.token_stream().current_position();
        let mut args = SmallVec::default();
        parser.parse_operand_list(
            &mut args,
            Delimiter::None,
            /*allow_result_number=*/ true,
            None,
        )?;

        let mut types = SmallVec::default();
        parser.parse_colon_type_list(&mut types)?;

        let end = parser.token_stream().current_span();
        let span = SourceSpan::new(end.source_id(), start..end.end());

        let mut operands = SmallVec::default();
        parser.resolve_operands(span, &args, &types, &mut operands)?;

        state.operands.push(operands);

        Ok(())
    }
}

/// Returns from the enclosing function with the provided immediate value as its result.
#[operation(
    dialect = BuiltinDialect,
    traits(Terminator, ReturnLike),
    implements(OpPrinter)
)]
pub struct RetImm {
    #[attr(hidden)]
    value: ImmediateAttr,
}

impl OpPrinter for RetImm {
    fn print(&self, printer: &mut AsmPrinter<'_>) {
        use crate::{attributes::IntegerLikeAttr, formatter::const_text};

        // Print the immediate as `<value> : <type>`, mirroring the grammar accepted by the
        // `OpParser` implementation below, so the output can be re-parsed.
        let value = self.value().as_ref().as_immediate();
        printer.print_space();
        printer.print_decimal_integer(value);
        *printer += const_text(" : ");
        printer.print_type(&value.ty());
    }
}

impl OpParser for RetImm {
    fn parse(
        state: &mut crate::OperationState,
        parser: &mut dyn crate::OpAsmParser<'_>,
    ) -> crate::ParseResult {
        use crate::{diagnostics::SourceSpan, parse::ParserError};

        let start = parser.token_stream().current_position();
        let imm = parser.parse_integer::<Immediate>()?;
        let ty = parser.parse_colon_type()?;
        let end = parser.token_stream().current_span();
        let span = SourceSpan::new(end.source_id(), start..end.end());

        // Re-type the parsed literal to the declared type: integer parsing infers the narrowest
        // representation, which would otherwise survive into the attribute and reprint with the
        // wrong type.
        let Some(imm) = imm.into_inner().coerced_to(&ty) else {
            return Err(ParserError::InvalidOperationType {
                span,
                ty_span: ty.span(),
                reason: format!(
                    "expected a numeric type able to represent the immediate, got {ty}"
                ),
            });
        };

        let attr = parser
            .context_rc()
            .create_attribute_with_type::<ImmediateAttr, _>(imm, ty.into_inner());
        state.add_attribute("value", attr);

        Ok(())
    }
}