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
use std::fmt::Write;

use orzir_core::{
    ArenaPtr,
    Context,
    Dialect,
    Op,
    OpMetadata,
    Parse,
    Region,
    RegionInterface,
    RegionKind,
    RunVerifiers,
    Symbol,
    TyObj,
    Value,
    Verify,
    VerifyResult,
};
use orzir_macros::{ControlFlow, DataFlow, Op, Parse, Print, RegionInterface, Verify};

use crate::verifiers::{control_flow::*, *};

/// A function operation.
///
/// This represents a function definition.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print)]
#[mnemonic = "func.func"]
#[verifiers(IsIsolatedFromAbove, NumRegions<1>, NumResults<0>)]
#[format(pattern = "{symbol} : {ty} {region}", kind = "op", num_results = 0)]
pub struct FuncOp {
    #[metadata]
    metadata: OpMetadata,
    /// The region of the function.
    #[region(0, kind = RegionKind::SsaCfg)]
    region: ArenaPtr<Region>,
    /// The symbol of the function, this is mandatory.
    symbol: Symbol,
    /// The type of the function.
    ty: ArenaPtr<TyObj>,
}

impl Verify for FuncOp {
    fn verify(&self, ctx: &Context) -> VerifyResult<()> {
        self.run_verifiers(ctx)?;
        self.ty.deref(&ctx.tys).as_ref().verify(ctx)?;
        self.get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .verify(ctx)?;
        Ok(())
    }
}

/// A return operation.
///
/// This represents a return statement in a function.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "func.return"]
#[verifiers(NumResults<0>, VariadicOperands, NumRegions<0>, IsTerminator)]
#[format(pattern = "{operands}", kind = "op", num_results = 0)]
pub struct ReturnOp {
    #[metadata]
    metadata: OpMetadata,
    /// The operands to return.
    #[operand(...)]
    #[repeat(sep = ",")]
    operands: Vec<ArenaPtr<Value>>,
}

/// A direct call operation.
///
/// This represents a direct call to a function by the symbol.
#[derive(Op, DataFlow, RegionInterface, ControlFlow, Parse, Print, Verify)]
#[mnemonic = "func.call"]
#[verifiers(VariadicResults, VariadicOperands, NumRegions<0>)]
#[format(pattern = "{callee} {operands}", kind = "op")]
pub struct CallOp {
    #[metadata]
    metadata: OpMetadata,
    /// The results of the call.
    #[result(...)]
    results: Vec<ArenaPtr<Value>>,
    /// The operands of the call.
    #[operand(...)]
    #[repeat(sep = ",", leading = "(", trailing = ")")]
    operands: Vec<ArenaPtr<Value>>,
    /// The symbol of the callee.
    callee: Symbol,
}

/// Register the `func` dialect.
pub fn register(ctx: &mut Context) {
    let dialect = Dialect::new("func".into());
    ctx.register_dialect(dialect);

    FuncOp::register(ctx, FuncOp::parse);
    ReturnOp::register(ctx, ReturnOp::parse);
    CallOp::register(ctx, CallOp::parse);
}

#[cfg(test)]
mod tests {
    use orzir_core::{
        Context,
        OpObj,
        Parse,
        ParseState,
        Print,
        PrintState,
        RegionInterface,
        RegionKind,
        TokenStream,
    };

    use crate::dialects::std::{
        arith,
        builtin::{self, ModuleOp},
        cf,
        func,
        register_std_dialects,
    };

    #[test]
    fn test_func_op() {
        let src = r#"
        module {
            func.func @foo :  fn() -> (int<32>, float) {
            ^entry:
                %x = arith.iconst 123i32 : int<32>
                %y = arith.iconst 123i32 : int<32>
            ^return:
                func.return %x, %y
            ^single:
                func.return %x
            ^null:
                func.return
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        register_std_dialects(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();

        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "foo")
            .is_some());
    }

    #[test]
    fn test_call_op() {
        let src = r#"
        module {
            func.func @bar : fn(int<32>) -> int<32> {
            ^entry(%0 : int<32>):
                func.return %0
            }

            func.func @foo : fn() -> (int<32>, int<32>) {
            ^entry:
                %x = arith.iconst 123i32 : int<32>
                %y = arith.iconst 123i32 : int<32>
                %z = func.call @bar(%x) : int<32>
                cf.jump ^return(%x, %y)
            ^return:
                func.return %x, %y
            }
        }
        "#;

        let stream = TokenStream::new(src);
        let mut state = ParseState::new(stream);
        let mut ctx = Context::default();

        builtin::register(&mut ctx);
        func::register(&mut ctx);
        cf::register(&mut ctx);
        arith::register(&mut ctx);

        let op = OpObj::parse(&mut ctx, &mut state).unwrap();
        let mut state = PrintState::new("    ");
        op.deref(&ctx.ops).as_ref().verify(&ctx).unwrap();
        op.deref(&ctx.ops).print(&ctx, &mut state).unwrap();
        println!("{}", state.buffer);

        let module_op = op.deref(&ctx.ops).as_a::<ModuleOp>().unwrap();

        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "foo")
            .is_some());

        assert!(module_op
            .get_region(0)
            .unwrap()
            .deref(&ctx.regions)
            .lookup_symbol(&ctx, "bar")
            .is_some());

        assert!(module_op.get_region_kind(&ctx, 0) == RegionKind::Graph);
    }
}