cranelift-codegen-meta 0.123.8

Metaprogram for cranelift-codegen code generator library
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
use cranelift_srcgen::error::Error;
use std::path::Path;

struct Inst<'a> {
    snake_name: &'a str,
    name: &'a str,
    fields: &'a [(&'a str, &'a str)],
}

macro_rules! define {
    (
        $(
            $( #[$attr:meta] )*
            $snake_name:ident = $name:ident $( { $( $field:ident : $field_ty:ty ),* } )? ;
        )*
    ) => {
        &[$(Inst {
            snake_name: stringify!($snake_name),
            name: stringify!($name),
            fields: &[$($( (stringify!($field), stringify!($field_ty)), )*)?],
        }),*]
        // helpers.push_str(concat!("(define pulley_", stringify!($snake_name), " ("));
    };
}

const OPS: &[Inst<'_>] = pulley_interpreter::for_each_op!(define);
const EXTENDED_OPS: &[Inst<'_>] = pulley_interpreter::for_each_extended_op!(define);

enum Operand<'a> {
    Normal {
        name: &'a str,
        ty: &'a str,
    },
    Writable {
        name: &'a str,
        ty: &'a str,
    },
    TrapCode {
        name: &'a str,
        ty: &'a str,
    },
    Binop {
        dst: &'a str,
        src1: &'a str,
        src2: &'a str,
    },
}

impl Inst<'_> {
    fn operands(&self) -> impl Iterator<Item = Operand<'_>> + use<'_> {
        self.fields
            .iter()
            .map(|(name, ty)| match (*name, *ty) {
                ("operands", binop) => {
                    // Parse "BinaryOperands < A >"` as A/A/A
                    // Parse "BinaryOperands < A, B >"` as A/B/A
                    // Parse "BinaryOperands < A, B, C >"` as A/B/C
                    let mut parts = binop
                        .strip_prefix("BinaryOperands <")
                        .unwrap()
                        .strip_suffix(">")
                        .unwrap()
                        .trim()
                        .split(',')
                        .map(|x| x.trim());
                    let dst = parts.next().unwrap();
                    let src1 = parts.next().unwrap_or(dst);
                    let src2 = parts.next().unwrap_or(dst);
                    Operand::Binop { dst, src1, src2 }
                }
                (name, ty) if name.starts_with("dst") => Operand::Writable { name, ty },
                (name, "UpperRegSet < XReg >") => Operand::Normal {
                    name,
                    ty: "UpperXRegSet",
                },
                (name, ty) => Operand::Normal { name, ty },
            })
            .chain(if self.name.contains("Trap") {
                Some(Operand::TrapCode {
                    name: "code",
                    ty: "TrapCode",
                })
            } else {
                None
            })
    }

    fn skip(&self) -> bool {
        match self.name {
            // Skip instructions related to control-flow as those require
            // special handling with `MachBuffer`.
            "Jump" => true,
            n if n.starts_with("Call") => true,

            // Skip special instructions not used in Cranelift.
            "XPush32Many" | "XPush64Many" | "XPop32Many" | "XPop64Many" => true,

            // Skip more branching-related instructions.
            n => n.starts_with("Br"),
        }
    }
}

pub fn generate_rust(filename: &str, out_dir: &Path) -> Result<(), Error> {
    let mut rust = String::new();

    // Generate a pretty-printing method for debugging.
    rust.push_str("pub fn print(inst: &RawInst) -> String {\n");
    rust.push_str("match inst {\n");
    for inst @ Inst { name, .. } in OPS.iter().chain(EXTENDED_OPS) {
        if inst.skip() {
            continue;
        }

        let mut pat = String::new();
        let mut locals = String::new();
        let mut format_string = String::new();
        format_string.push_str(inst.snake_name);
        for (i, op) in inst.operands().enumerate() {
            match op {
                Operand::Normal { name, ty } | Operand::Writable { name, ty } => {
                    pat.push_str(name);
                    pat.push_str(",");

                    if i > 0 {
                        format_string.push_str(",");
                    }

                    if ty == "UpperXRegSet" {
                        format_string.push_str(" {");
                        format_string.push_str(name);
                        format_string.push_str(":?}");
                        continue;
                    }

                    format_string.push_str(" {");
                    format_string.push_str(name);
                    format_string.push_str("}");
                    if ty.contains("Reg") {
                        if matches!(op, Operand::Writable { .. }) {
                            locals.push_str(&format!("let {name} = reg_name(*{name}.to_reg());\n"));
                        } else {
                            locals.push_str(&format!("let {name} = reg_name(**{name});\n"));
                        }
                    }
                }
                Operand::TrapCode { name, ty: _ } => {
                    pat.push_str(name);
                    pat.push_str(",");
                    format_string.push_str(&format!(" // trap={{{name}:?}}"));
                }
                Operand::Binop { src2, .. } => {
                    pat.push_str("dst, src1, src2,");
                    format_string.push_str(" {dst}, {src1}, {src2}");
                    locals.push_str(&format!("let dst = reg_name(*dst.to_reg());\n"));
                    locals.push_str(&format!("let src1 = reg_name(**src1);\n"));
                    if src2.contains("Reg") {
                        locals.push_str(&format!("let src2 = reg_name(**src2);\n"));
                    }
                }
            }
        }

        rust.push_str(&format!(
            "
        RawInst::{name} {{ {pat} }} => {{
            {locals}
            format!(\"{format_string}\")
        }}
        "
        ));
    }
    rust.push_str("}\n");
    rust.push_str("}\n");

    // Generate `get_operands` to feed information to regalloc
    rust.push_str(
        "pub fn get_operands(inst: &mut RawInst, collector: &mut impl OperandVisitor) {\n",
    );
    rust.push_str("match inst {\n");
    for inst @ Inst { name, .. } in OPS.iter().chain(EXTENDED_OPS) {
        if inst.skip() {
            continue;
        }

        let mut pat = String::new();
        let mut uses = Vec::new();
        let mut defs = Vec::new();
        let mut addrs = Vec::new();
        for op in inst.operands() {
            match op {
                // `{Push,Pop}Frame{Save,Restore}` doesn't participate in
                // register allocation.
                Operand::Normal {
                    name: _,
                    ty: "UpperXRegSet",
                } if *name == "PushFrameSave" || *name == "PopFrameRestore" => {}

                Operand::Normal { name, ty } => {
                    if ty.contains("Reg") {
                        uses.push(name);
                        pat.push_str(name);
                        pat.push_str(",");
                    } else if ty.starts_with("Addr") {
                        addrs.push(name);
                        pat.push_str(name);
                        pat.push_str(",");
                    }
                }
                Operand::Writable { name, ty } => {
                    if ty.contains("Reg") {
                        defs.push(name);
                        pat.push_str(name);
                        pat.push_str(",");
                    }
                }
                Operand::TrapCode { .. } => {}
                Operand::Binop { src2, .. } => {
                    pat.push_str("dst, src1,");
                    uses.push("src1");
                    defs.push("dst");
                    if src2.contains("Reg") {
                        pat.push_str("src2,");
                        uses.push("src2");
                    }
                }
            }
        }

        let uses = uses
            .iter()
            .map(|u| format!("collector.reg_use({u});\n"))
            .collect::<String>();
        let defs = defs
            .iter()
            .map(|u| format!("collector.reg_def({u});\n"))
            .collect::<String>();
        let addrs = addrs
            .iter()
            .map(|u| format!("{u}.collect_operands(collector);\n"))
            .collect::<String>();

        rust.push_str(&format!(
            "
        RawInst::{name} {{ {pat} .. }} => {{
            {uses}
            {defs}
            {addrs}
        }}
        "
        ));
    }
    rust.push_str("}\n");
    rust.push_str("}\n");

    // Generate an emission method
    rust.push_str("pub fn emit<P>(inst: &RawInst, sink: &mut MachBuffer<InstAndKind<P>>)\n");
    rust.push_str("  where P: PulleyTargetKind,\n");
    rust.push_str("{\n");
    rust.push_str("match *inst {\n");
    for inst @ Inst {
        name, snake_name, ..
    } in OPS.iter().chain(EXTENDED_OPS)
    {
        if inst.skip() {
            continue;
        }

        let mut pat = String::new();
        let mut args = String::new();
        let mut trap = String::new();
        for op in inst.operands() {
            match op {
                Operand::Normal { name, ty: _ } | Operand::Writable { name, ty: _ } => {
                    pat.push_str(name);
                    pat.push_str(",");

                    args.push_str(name);
                    args.push_str(",");
                }
                Operand::TrapCode { name, ty: _ } => {
                    pat.push_str(name);
                    pat.push_str(",");
                    trap.push_str(&format!("sink.add_trap({name});\n"));
                }
                Operand::Binop { .. } => {
                    pat.push_str("dst, src1, src2,");
                    args.push_str(
                        "pulley_interpreter::regs::BinaryOperands::new(dst, src1, src2),",
                    );
                }
            }
        }

        rust.push_str(&format!(
            "
        RawInst::{name} {{ {pat} }} => {{
            {trap}
            pulley_interpreter::encode::{snake_name}(sink, {args})
        }}
        "
        ));
    }
    rust.push_str("}\n");
    rust.push_str("}\n");

    std::fs::write(out_dir.join(filename), rust)?;
    Ok(())
}

pub fn generate_isle(filename: &str, out_dir: &Path) -> Result<(), Error> {
    let mut isle = String::new();

    // Generate the `RawInst` enum
    isle.push_str("(type RawInst (enum\n");
    for inst in OPS.iter().chain(EXTENDED_OPS) {
        if inst.skip() {
            continue;
        }
        isle.push_str("  (");
        isle.push_str(inst.name);
        for op in inst.operands() {
            match op {
                Operand::Normal { name, ty } | Operand::TrapCode { name, ty } => {
                    isle.push_str(&format!("\n    ({name} {ty})"));
                }
                Operand::Writable { name, ty } => {
                    isle.push_str(&format!("\n    ({name} Writable{ty})"));
                }
                Operand::Binop { dst, src1, src2 } => {
                    isle.push_str(&format!("\n    (dst Writable{dst})"));
                    isle.push_str(&format!("\n    (src1 {src1})"));
                    isle.push_str(&format!("\n    (src2 {src2})"));
                }
            }
        }
        isle.push_str(")\n");
    }
    isle.push_str("))\n");

    // Generate the `pulley_*` constructors with a `decl` and a `rule`.
    for inst @ Inst {
        name, snake_name, ..
    } in OPS.iter().chain(EXTENDED_OPS)
    {
        if inst.skip() {
            continue;
        }
        // generate `decl` and `rule` at the same time, placing the `rule` in
        // temporary storage on the side. Makes generation a bit easier to read
        // as opposed to doing the decl first then the rule.
        let mut rule = String::new();
        isle.push_str(&format!("(decl pulley_{snake_name} ("));
        rule.push_str(&format!("(rule (pulley_{snake_name} "));
        let mut results = Vec::new();
        let mut ops = Vec::new();
        for op in inst.operands() {
            match op {
                Operand::Normal { name, ty } | Operand::TrapCode { name, ty } => {
                    isle.push_str(ty);
                    rule.push_str(name);
                    ops.push(name);
                }
                Operand::Writable { name: _, ty } => {
                    results.push(ty);
                }
                Operand::Binop { dst, src1, src2 } => {
                    isle.push_str(&format!("{src1} {src2}"));
                    rule.push_str("src1 src2");
                    ops.push("src1");
                    ops.push("src2");
                    results.push(dst);
                }
            }
            isle.push_str(" ");
            rule.push_str(" ");
        }
        isle.push_str(") ");
        rule.push_str(")");
        let ops = ops.join(" ");
        match &results[..] {
            [result] => {
                isle.push_str(result);
                rule.push_str(&format!(
                    "
  (let (
      (dst Writable{result} (temp_writable_{}))
      (_ Unit (emit (RawInst.{name} dst {ops})))
    )
    dst))\
\n",
                    result.to_lowercase()
                ));
            }
            [a, b] => {
                isle.push_str("ValueRegs");
                rule.push_str(&format!(
                    "
  (let (
      (dst1 Writable{a} (temp_writable_{}))
      (dst2 Writable{b} (temp_writable_{}))
      (_ Unit (emit (RawInst.{name} dst1 dst2 {ops})))
    )
    (value_regs dst1 dst2)))\
\n",
                    a.to_lowercase(),
                    b.to_lowercase(),
                ));
            }
            [] => {
                isle.push_str("SideEffectNoResult");
                rule.push_str(&format!(
                    "  (SideEffectNoResult.Inst (RawInst.{name} {ops})))\n",
                ));
            }
            other => panic!("cannot codegen results {other:?}"),
        }
        isle.push_str(")\n");

        isle.push_str(&rule);
    }

    std::fs::write(out_dir.join(filename), isle)?;
    Ok(())
}