midenc-codegen-masm 0.7.2

Miden Assembly backend for the Miden compiler
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
use midenc_dialect_arith as arith;
use midenc_dialect_cf as cf;
use midenc_dialect_hir as hir;
use midenc_dialect_scf as scf;
use midenc_dialect_ub as ub;
use midenc_dialect_wasm as wasm;
use midenc_hir::{
    Op, OpExt, Span, SymbolTable, Type, Value, ValueRange, ValueRef,
    dialects::builtin,
    traits::{BinaryOp, Commutative},
};
use midenc_session::diagnostics::{Report, Severity, Spanned};
use smallvec::smallvec;

use super::*;
use crate::{
    Constraint, emit::OpEmitter, emitter::BlockEmitter, masm, opt::operands::SolverOptions,
};

/// Convert a resolved callee [`midenc_hir::SymbolPath`] into a MASM [`masm::InvocationTarget`].
fn invocation_target_from_symbol_path(
    callee_path: &midenc_hir::SymbolPath,
    span: midenc_hir::SourceSpan,
) -> masm::InvocationTarget {
    let proc_name = callee_path.name();
    let proc_name = masm::ProcedureName::from_raw_parts(masm::Ident::from_raw_parts(
        masm::Span::new(span, proc_name.as_ref().into()),
    ));
    let module = callee_path.without_leaf().to_library_path();
    let qualified = masm::QualifiedProcedureName::new(module.as_path(), proc_name);
    masm::InvocationTarget::Path(masm::Span::new(span, qualified.into_inner()))
}

/// This trait is registered with all ops, of all dialects, which are legal for lowering to MASM.
///
/// The [BlockEmitter] is responsible for then invoking the methods of this trait to facilitate
/// the lowering to Miden Assembly of whole components.
pub trait HirLowering: Op {
    /// This method is invoked once operands have been scheduled for this operation.
    ///
    /// Implementations are expected to:
    ///
    /// * Emit Miden Assembly that matches the semantics of the HIR instruction
    /// * Ensure that the operand stack reflects any effects the operation has (both when consuming
    ///   its operands, and producing results). However, it is permitted to elide stack effects
    ///   that are transient during execution of the operation, so long as those effects are not
    ///   visible outside the instruction (i.e. it should not be possible for other instructions
    ///   to witness such transient effects).
    /// * Ensure that the operand stack state is consistent at control flow join points, i.e. it
    ///   is not valid to allow the stack to diverge based on conditional control flow, in terms
    ///   of where each SSA value is found, and in terms of stack depth.
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report>;

    /// This method is invoked in order to emit any necessary operand stack manipulation sequences,
    /// such that the instruction operands are in their place.
    ///
    /// By default, this uses our operand stack constraint solver to generate a solution for
    /// moving the instruction operands into place in the order they are expected, using liveness
    /// information to compute constraints.
    ///
    /// For operations that can support more efficient schedules due to their semantics, such as
    /// the commutativity property, this method can be overridden to incorporate that information,
    /// and provide a custom schedule.
    fn schedule_operands(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let op = self.as_operation();
        let trace_target = emitter.trace_target.clone().with_topic("operand-scheduling");

        // Move instruction operands into place, minimizing unnecessary stack manipulation ops
        //
        // NOTE: This does not include block arguments for control flow instructions, those are
        // handled separately within the specific handlers for those instructions
        let args = self.required_operands();
        if args.is_empty() {
            return Ok(());
        }

        let mut constraints = emitter.constraints_for(op, &args);
        let mut args = args.into_smallvec();

        // All of Miden's binary ops expect the right-hand operand on top of the stack, this
        // requires us to invert the expected order of operands from the standard ordering in the
        // IR
        //
        // TODO(pauls): We should probably assign a dedicated trait for this type of argument
        // ordering override, rather than assuming that all BinaryOp impls need it
        if op.implements::<dyn BinaryOp>() {
            args.swap(0, 1);
            constraints.swap(0, 1);
        }

        log::trace!(target: &trace_target, "scheduling operands for {op}");
        for arg in args.iter() {
            log::trace!(target: &trace_target, "{arg} is live at/after entry: {}", emitter.liveness.is_live_after_entry(*arg, op));
        }
        log::trace!(target: &trace_target, "starting with stack: {:#?}", &emitter.stack);
        emitter
            .schedule_operands(
                &args,
                &constraints,
                op.span(),
                SolverOptions {
                    strict: !op.implements::<dyn Commutative>(),
                    ..Default::default()
                },
            )
            .unwrap_or_else(|err| {
                panic!(
                    "failed to schedule operands: {args:?}\nfor inst '{}'\nwith error: \
                     {err:?}\nconstraints: {constraints:?}\nstack: {:#?}",
                    op.name(),
                    &emitter.stack,
                )
            });
        log::trace!(target: &trace_target, "stack after scheduling: {:#?}", &emitter.stack);

        Ok(())
    }

    /// Returns the set of operands that must be scheduled on entry to this operation.
    ///
    /// Typically, this excludes successor operands, but it depends on the specific operation. In
    /// order to abstract over these details, this function can be used to customize just this
    /// detail of operand scheduling.
    fn required_operands(&self) -> ValueRange<'_, 4> {
        ValueRange::from(self.operands().all())
    }
}

impl HirLowering for builtin::Ret {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let span = self.span();
        let argc = self.num_operands();

        // Upon return, the operand stack should only contain the function result(s),
        // so empty the stack before proceeding.
        emitter.emitter().truncate_stack(argc, span);

        Ok(())
    }
}

impl HirLowering for builtin::RetImm {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let span = self.span();
        let mut emitter = emitter.emitter();

        // Upon return, the operand stack should only contain the function result(s),
        // so empty the stack before proceeding.
        emitter.truncate_stack(0, span);

        // We need to push the return value on the stack at this point.
        emitter.literal(*self.get_value(), span);

        Ok(())
    }
}

impl HirLowering for scf::If {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let cond = self.condition().as_value_ref();

        // Ensure `cond` is on top of the stack, and remove it at the same time
        assert_eq!(
            emitter.stack.pop().unwrap().as_value(),
            Some(cond),
            "expected {cond} on top of the stack"
        );

        let then_body = self.then_body();
        let else_body = self.else_body();

        utils::emit_if(emitter, self.as_operation(), &then_body, &else_body)
    }
}

impl HirLowering for scf::While {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let span = self.span();

        // Emit as follows:
        //
        // hir.while <operands> {
        //     <before>
        // } do {
        //     <after>
        // }
        //
        // to:
        //
        // push.1
        // while.true
        //     <before>
        //     if.true
        //         <after>
        //         push.1
        //     else
        //         push.0
        //     end
        // end
        let num_condition_forwarded_operands = self.condition_op().borrow().forwarded().len();
        let (stack_on_loop_exit, loop_body) = {
            let before = self.before();
            let before_block = before.entry();
            let input_stack = emitter.stack.clone();

            let mut body_emitter = emitter.nest();

            // Rename the 'hir.while' operands to match the 'before' region's entry block args
            assert_eq!(self.operands().len(), before_block.num_arguments());
            for (index, arg) in before_block.arguments().iter().copied().enumerate() {
                body_emitter.stack.rename(index, arg as ValueRef);
            }
            let before_stack = body_emitter.stack.clone();

            // Emit the 'before' block, which represents the loop header
            body_emitter.emit_inline(&before_block);

            // Remove the 'hir.condition' condition flag from the operand stack, but do not emit any
            // instructions to do so, as this will be handled by the 'if.true' instruction
            body_emitter.stack.drop();

            // Take a snapshot of the stack at this point, as it represents the state of the stack
            // on exit from the loop, and perform the following modifications:
            //
            // 1. Rename the forwarded condition operands to the 'hir.while' results
            // 2. Check that all values on the operand stack at this point have definitions which
            //    dominate the successor (i.e. the next op after the 'hir.while' op). We can do this
            //    cheaply by asserting that all of the operands were present on the stack before the
            //    'hir.while', or are a result, as any new operands are by definition something
            //    introduced within the loop itself
            let mut stack_on_loop_exit = body_emitter.stack.clone();
            // 1
            assert_eq!(num_condition_forwarded_operands, self.num_results());
            for (index, result) in self.results().all().iter().copied().enumerate() {
                stack_on_loop_exit.rename(index, result as ValueRef);
            }
            // 2
            for (index, value) in stack_on_loop_exit.iter().rev().enumerate() {
                let value = value.as_value().unwrap();
                let is_result = self.results().all().iter().any(|r| *r as ValueRef == value);
                let is_dominating_def = input_stack.find(&value).is_some();
                assert!(
                    is_result || is_dominating_def,
                    "{value} at stack depth {index} incorrectly escapes its dominance frontier"
                );
            }

            let enter_loop_body = {
                let mut body_emitter = body_emitter.nest();

                // Rename the `hir.condition` forwarded operands to match the 'after' region's entry block args
                let after = self.after();
                let after_block = after.entry();
                assert_eq!(num_condition_forwarded_operands, after_block.num_arguments());
                for (index, arg) in after_block.arguments().iter().copied().enumerate() {
                    body_emitter.stack.rename(index, arg as ValueRef);
                }

                // Emit the "after" block
                body_emitter.emit_inline(&after_block);

                // At this point, control yields from "after" back to "before" to re-evaluate the loop
                // condition. We must ensure that the yielded operands are renamed just as before, then
                // push a `push.1` on the stack to re-enter the loop to retry the condition
                assert_eq!(self.yield_op().borrow().yielded().len(), before_block.num_arguments());
                for (index, arg) in before_block.arguments().iter().copied().enumerate() {
                    body_emitter.stack.rename(index, arg as ValueRef);
                }

                if before_stack != body_emitter.stack {
                    panic!(
                        "unexpected observable stack effect leaked from regions of {}

stack on entry to 'before': {before_stack:#?}
stack on exit from 'after': {:#?}
                            ",
                        self.as_operation(),
                        &body_emitter.stack
                    );
                }

                // Re-enter the "before" block to retry the condition
                body_emitter.emitter().push_immediate(true.into(), span);

                body_emitter.into_emitted_block(span)
            };

            let exit_loop_body = {
                let mut body_emitter = body_emitter.nest();

                // Exit the loop
                body_emitter.emitter().push_immediate(false.into(), span);

                body_emitter.into_emitted_block(span)
            };

            body_emitter.emit_op(masm::Op::If {
                span,
                then_blk: enter_loop_body,
                else_blk: exit_loop_body,
            });

            (stack_on_loop_exit, body_emitter.into_emitted_block(span))
        };

        emitter.stack = stack_on_loop_exit;

        // Always enter loop on first iteration
        emitter.emit_op(masm::Op::Inst(Span::new(
            span,
            masm::Instruction::Push(masm::Immediate::Value(Span::new(span, 1u8.into()))),
        )));
        emitter.emit_op(masm::Op::While {
            span,
            body: loop_body,
        });

        Ok(())
    }

    fn required_operands(&self) -> ValueRange<'_, 4> {
        ValueRange::from(self.inits())
    }
}

impl HirLowering for scf::IndexSwitch {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        // Lowering `hir.index_switch` is done with nested `if.true`/`else` regions that either
        // compare the selector to each explicit case or partition a contiguous selector range.
        let cases = utils::sorted_switch_cases(self);
        let is_contiguous = utils::are_switch_cases_contiguous(&cases);

        // We have N cases, plus a default case
        //
        // 1. If we have exactly 1 non-default case, we can lower to an `hir.if`
        // 2. If the explicit cases are sparse, or if there are fewer than 3 contiguous cases,
        //    lower to a linear search:
        //
        //      if selector == case1 {
        //          <case1 body>
        //      } else {
        //          if selector == case2 {
        //              <case2 body>
        //          } else {
        //              if selector == caseN {
        //                  <caseN body>
        //              } else {
        //                  <default>
        //              }
        //          }
        //      }
        //
        // 3. If we have at least 3 contiguous non-default cases, use binary search to reduce the
        //    search space. The lowering emits a single out-of-range guard up front, then
        //    partitions the remaining interval recursively:
        //
        //      if selector < case3 {
        //         if selector == case1 {
        //             <case1 body>
        //         } else {
        //             <case2 body>
        //         }
        //      } else {
        //         if selector < case4 {
        //            <case3 body>
        //         } else {
        //            if selector == case4 {
        //               <case4 body>
        //            } else {
        //               <default>
        //            }
        //         }
        //      }
        //
        assert!(!cases.is_empty());
        if cases.len() < 3 || !is_contiguous {
            return utils::emit_linear_search(self, emitter, &cases);
        }

        utils::emit_binary_search(self, emitter, &cases)
    }

    fn required_operands(&self) -> ValueRange<'_, 4> {
        ValueRange::from(self.operands().group(0))
    }
}

impl HirLowering for scf::Yield {
    fn emit(&self, _emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        // Lowering 'hir.yield' is a no-op, as it is simply forwarding operands to another region,
        // and the semantics of that are handled by the lowering of the containing op
        Ok(())
    }
}

impl HirLowering for scf::Condition {
    fn emit(&self, _emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        // Lowering 'hir.condition' is a no-op, as it is simply forwarding operands to another
        // region, and the semantics of that are handled by the lowering of the containing op
        Ok(())
    }
}

impl HirLowering for arith::Constant {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let value = *self.get_value();

        emitter.inst_emitter(self.as_operation()).literal(value, self.span());

        Ok(())
    }
}

impl HirLowering for hir::Assert {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let code = *self.get_code();

        emitter.emitter().assert(Some(code), self.span());

        Ok(())
    }
}

impl HirLowering for hir::Assertz {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let code = *self.get_code();

        emitter.emitter().assertz(Some(code), self.span());

        Ok(())
    }
}

impl HirLowering for hir::AssertEq {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let code = *self.get_code();

        emitter.emitter().assert_eq(Some(code), self.span());

        Ok(())
    }
}

impl HirLowering for ub::Unreachable {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        // This instruction, if reached, must cause the VM to trap, so we emit an assertion that
        // always fails to guarantee this, i.e. assert(false)
        let span = self.span();
        let mut op_emitter = emitter.emitter();
        op_emitter.emit_push(0u32, span);
        op_emitter
            .emit(OpEmitter::assert_with_message_inst("entered unreachable code", span), span);

        Ok(())
    }
}

impl HirLowering for ub::Poison {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        use midenc_hir::Type;

        // This instruction represents a value that results from undefined behavior in a program.
        // The presence of it does not indicate that a program is invalid, but rather, the fact that
        // undefined behavior resulting from control flow to unreachable code produces effectively
        // any value in the domain of the type associated with the poison result.
        //
        // For our purposes, we choose a value that will appear obvious in a debugger, should it
        // ever appear as an operand to an instruction; and a value that we could emit debug asserts
        // for should we ever wish to do so. We could also catch the evaluation of poison under an
        // emulator for the IR itself.
        let span = self.span();
        let mut op_emitter = emitter.inst_emitter(self.as_operation());
        op_emitter.literal(
            {
                match self.value().as_immediate() {
                    Some(imm) => imm,
                    None => match self.value().as_value() {
                        Type::U256 => {
                            return Err(self
                                .as_operation()
                                .context()
                                .diagnostics()
                                .diagnostic(Severity::Error)
                                .with_message("invalid operation")
                                .with_primary_label(
                                    span,
                                    "the lowering for u256 immediates is not yet implemented",
                                )
                                .into_report());
                        }
                        Type::F64 => {
                            return Err(self
                                .as_operation()
                                .context()
                                .diagnostics()
                                .diagnostic(Severity::Error)
                                .with_message("invalid operation")
                                .with_primary_label(
                                    span,
                                    "the lowering for f64 immediates is not yet implemented",
                                )
                                .into_report());
                        }
                        ty => panic!("unexpected poison type: {ty}"),
                    },
                }
            },
            span,
        );

        Ok(())
    }
}

impl HirLowering for arith::Add {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).add(*self.get_overflow(), self.span());
        Ok(())
    }
}

impl HirLowering for arith::AddOverflowing {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter
            .inst_emitter(self.as_operation())
            .add(midenc_hir::Overflow::Overflowing, self.span());
        Ok(())
    }
}

impl HirLowering for arith::Sub {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).sub(*self.get_overflow(), self.span());
        Ok(())
    }
}

impl HirLowering for arith::SubOverflowing {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter
            .inst_emitter(self.as_operation())
            .sub(midenc_hir::Overflow::Overflowing, self.span());
        Ok(())
    }
}

impl HirLowering for arith::Mul {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).mul(*self.get_overflow(), self.span());
        Ok(())
    }
}

impl HirLowering for arith::MulOverflowing {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter
            .inst_emitter(self.as_operation())
            .mul(midenc_hir::Overflow::Overflowing, self.span());
        Ok(())
    }
}

impl HirLowering for arith::Exp {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).exp(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Div {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).checked_div(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Sdiv {
    fn emit(&self, _emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        todo!("signed division lowering not implemented yet");
    }
}

impl HirLowering for arith::Mod {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).checked_mod(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Smod {
    fn emit(&self, _emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        todo!("signed modular division lowering not implemented yet");
    }
}

impl HirLowering for arith::Divmod {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).checked_divmod(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Sdivmod {
    fn emit(&self, _emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        todo!("signed division + modular division lowering not implemented yet");
    }
}

impl HirLowering for arith::And {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).and(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Or {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).or(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Xor {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).xor(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Band {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).band(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Bor {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).bor(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Bxor {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).bxor(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Shl {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).shl(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Shr {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).shr(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Ashr {
    fn emit(&self, _emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        todo!("arithmetic shift right not yet implemented");
    }
}

impl HirLowering for arith::Rotl {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).rotl(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Rotr {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).rotr(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Eq {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).eq(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Neq {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).neq(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Gt {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).gt(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Gte {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).gte(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Lt {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).lt(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Lte {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).lte(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Min {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).min(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Max {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).max(self.span());
        Ok(())
    }
}

impl HirLowering for hir::PtrToInt {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result_ty = self.result().ty().clone();
        let mut inst_emitter = emitter.inst_emitter(self.as_operation());
        inst_emitter.pop().expect("operand stack is empty");
        inst_emitter.push(result_ty);
        Ok(())
    }
}

impl HirLowering for hir::IntToPtr {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).inttoptr(result.ty(), self.span());
        Ok(())
    }
}

impl HirLowering for hir::Cast {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).cast(result.ty(), self.span());
        Ok(())
    }
}

impl HirLowering for hir::Bitcast {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).bitcast(result.ty(), self.span());
        Ok(())
    }
}

impl HirLowering for arith::Trunc {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).trunc(result.ty(), self.span());
        Ok(())
    }
}

impl HirLowering for arith::Zext {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).zext(result.ty(), self.span());
        Ok(())
    }
}

impl HirLowering for arith::Sext {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).sext(result.ty(), self.span());
        Ok(())
    }
}

impl HirLowering for hir::Exec {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        use midenc_hir::{CallOpInterface, CallableOpInterface};

        let callee = self.resolve().ok_or_else(|| {
            let context = self.as_operation().context();
            context
                .diagnostics()
                .diagnostic(Severity::Error)
                .with_message("invalid call operation: unable to resolve callee")
                .with_primary_label(
                    self.span(),
                    "this symbol path is not resolvable from this operation",
                )
                .with_help(
                    "Make sure that all referenced symbols are reachable via the root symbol \
                     table, and use absolute paths to refer to symbols in ancestor/sibling modules",
                )
                .into_report()
        })?;
        let callee = callee.borrow();
        let callee_path = callee.path();
        let signature = match callee.as_symbol_operation().as_trait::<dyn CallableOpInterface>() {
            Some(callable) => callable.signature(),
            None => {
                let context = self.as_operation().context();
                return Err(context
                    .diagnostics()
                    .diagnostic(Severity::Error)
                    .with_message("invalid call operation: callee is not a callable op")
                    .with_primary_label(
                        self.span(),
                        format!(
                            "this symbol resolved to a '{}' op, which does not implement Callable",
                            callee.as_symbol_operation().name()
                        ),
                    )
                    .into_report());
            }
        };

        // Convert the symbol path to a fully-qualified procedure path
        let callee = invocation_target_from_symbol_path(&callee_path, self.span());

        emitter.inst_emitter(self.as_operation()).exec(callee, &signature, self.span());

        Ok(())
    }
}

impl HirLowering for hir::Call {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        use midenc_hir::{CallOpInterface, CallableOpInterface};

        let callee = self.resolve().ok_or_else(|| {
            let context = self.as_operation().context();
            context
                .diagnostics()
                .diagnostic(Severity::Error)
                .with_message("invalid call operation: unable to resolve callee")
                .with_primary_label(
                    self.span(),
                    "this symbol path is not resolvable from this operation",
                )
                .with_help(
                    "Make sure that all referenced symbols are reachable via the root symbol \
                     table, and use absolute paths to refer to symbols in ancestor/sibling modules",
                )
                .into_report()
        })?;
        let callee = callee.borrow();
        let callee_path = callee.path();
        let signature = match callee.as_symbol_operation().as_trait::<dyn CallableOpInterface>() {
            Some(callable) => callable.signature(),
            None => {
                let context = self.as_operation().context();
                return Err(context
                    .diagnostics()
                    .diagnostic(Severity::Error)
                    .with_message("invalid call operation: callee is not a callable op")
                    .with_primary_label(
                        self.span(),
                        format!(
                            "this symbol resolved to a '{}' op, which does not implement Callable",
                            callee.as_symbol_operation().name()
                        ),
                    )
                    .into_report());
            }
        };

        // Convert the symbol path to a fully-qualified procedure path
        let callee = invocation_target_from_symbol_path(&callee_path, self.span());

        emitter.inst_emitter(self.as_operation()).call(callee, &signature, self.span());

        Ok(())
    }
}

impl HirLowering for hir::Load {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let result = self.result();
        emitter.inst_emitter(self.as_operation()).load(result.ty().clone(), self.span());
        Ok(())
    }
}

impl HirLowering for hir::LoadLocal {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter
            .inst_emitter(self.as_operation())
            .load_local(&self.get_local(), self.span());
        Ok(())
    }
}

impl HirLowering for hir::Store {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.emitter().store(self.span());
        Ok(())
    }
}

impl HirLowering for hir::StoreLocal {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.emitter().store_local(&self.get_local(), self.span());
        Ok(())
    }
}

impl HirLowering for hir::MemGrow {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).mem_grow(self.span());
        Ok(())
    }
}

impl HirLowering for hir::MemSize {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).mem_size(self.span());
        Ok(())
    }
}

impl HirLowering for hir::MemSet {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).memset(self.span());
        Ok(())
    }
}

impl HirLowering for hir::MemCpy {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).memcpy(self.span());
        Ok(())
    }
}

impl HirLowering for cf::Select {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).select(self.span());
        Ok(())
    }
}

impl HirLowering for cf::CondBr {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let then_dest = self.then_dest().successor();
        let else_dest = self.else_dest().successor();

        // This lowering is only legal if it represents a choice between multiple exits
        assert_eq!(
            then_dest.borrow().num_successors(),
            0,
            "illegal cf.cond_br: only exit blocks are supported"
        );
        assert_eq!(
            else_dest.borrow().num_successors(),
            0,
            "illegal cf.cond_br: only exit blocks are supported"
        );

        // Drop the condition if no longer live
        if !emitter
            .liveness
            .is_live_after(self.condition().as_value_ref(), self.as_operation())
        {
            emitter.stack.drop();
        }

        let span = self.span();
        let then_blk = {
            let mut emitter = emitter.nest();

            // At this point is when we need to schedule the successor operands for this block
            let then_operand = self.then_dest();
            let successor_operands = ValueRange::from(then_operand.arguments);
            let constraints = emitter.constraints_for(self.as_operation(), &successor_operands);
            let successor_operands = successor_operands.into_smallvec();
            emitter
                .schedule_operands(&successor_operands, &constraints, span, Default::default())
                .unwrap_or_else(|err| {
                    panic!(
                        "failed to schedule operands: {successor_operands:?}\nfor inst '{}'\nwith \
                         error: {err:?}\nconstraints: {constraints:?}\nstack: {:#?}",
                        self.as_operation().name(),
                        &emitter.stack,
                    )
                });

            // Rename any uses of the block arguments of `then_dest` to the values given as
            // successor operands.
            let then_block = then_dest.borrow();
            for (index, block_argument) in then_block.arguments().iter().copied().enumerate() {
                emitter.stack.rename(index, block_argument as ValueRef);
            }

            emitter.emit(&then_dest.borrow())
        };

        let else_blk = {
            let mut emitter = emitter.nest();

            // At this point is when we need to schedule the successor operands for this block
            let else_operand = self.else_dest();
            let successor_operands = ValueRange::from(else_operand.arguments);
            let constraints = emitter.constraints_for(self.as_operation(), &successor_operands);
            let successor_operands = successor_operands.into_smallvec();
            emitter
                .schedule_operands(&successor_operands, &constraints, span, Default::default())
                .unwrap_or_else(|err| {
                    panic!(
                        "failed to schedule operands: {successor_operands:?}\nfor inst '{}'\nwith \
                         error: {err:?}\nconstraints: {constraints:?}\nstack: {:#?}",
                        self.as_operation().name(),
                        &emitter.stack,
                    )
                });

            // Rename any uses of the block arguments of `else_dest` to the values given as
            // successor operands.
            let else_block = else_dest.borrow();
            for (index, block_argument) in else_block.arguments().iter().copied().enumerate() {
                emitter.stack.rename(index, block_argument as ValueRef);
            }

            emitter.emit(&else_dest.borrow())
        };

        let span = self.span();
        emitter.emit_op(masm::Op::If {
            span,
            then_blk,
            else_blk,
        });

        Ok(())
    }

    fn required_operands(&self) -> ValueRange<'_, 4> {
        ValueRange::from(smallvec![self.condition().as_value_ref()])
    }

    // We only schedule the condition here
    fn schedule_operands(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let op = self.as_operation();

        let condition = self.condition().as_value_ref();
        let constraints = emitter.constraints_for(op, &ValueRange::Borrowed(&[condition]));

        let span = op.span();
        let top = emitter.stack[0].as_value();
        if top == Some(condition) {
            if matches!(constraints[0], Constraint::Copy) {
                emitter.emitter().dup(0, span);
            }
            return Ok(());
        } else {
            let index = emitter.stack.find(&condition).unwrap() as u8;
            match constraints[0] {
                Constraint::Copy => {
                    emitter.emitter().dup(index, span);
                }
                Constraint::Move => {
                    if index == 1 {
                        emitter.emitter().swap(1, span);
                    } else {
                        emitter.emitter().movup(index, span);
                    }
                }
            }
        }

        Ok(())
    }
}

impl HirLowering for arith::Incr {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).incr(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Neg {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).neg(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Inv {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).inv(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Ilog2 {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).ilog2(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Pow2 {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).pow2(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Not {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).not(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Bnot {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).bnot(self.span());
        Ok(())
    }
}

impl HirLowering for arith::IsOdd {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).is_odd(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Popcnt {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).popcnt(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Clz {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).clz(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Ctz {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).ctz(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Clo {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).clo(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Cto {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        emitter.inst_emitter(self.as_operation()).cto(self.span());
        Ok(())
    }
}

impl HirLowering for arith::Join {
    fn schedule_operands(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let op = self.as_operation();

        let args = self.required_operands();
        if args.is_empty() {
            return Ok(());
        }

        let mut constraints = emitter.constraints_for(op, &args);
        let mut args = args.into_smallvec();

        // For `i128`/`u128` we use a different stack order for 64-bit limbs.
        //
        // The IR specifies limbs most-significant to least-significant, but the runtime stack
        // representation for two 64-bit limbs is (lo, hi).
        if args.len() == 2 && matches!(&*self.get_ty(), Type::I128 | Type::U128) {
            args.swap(0, 1);
            constraints.swap(0, 1);
        }

        emitter
            .schedule_operands(
                &args,
                &constraints,
                op.span(),
                SolverOptions {
                    strict: true,
                    ..Default::default()
                },
            )
            .unwrap_or_else(|err| {
                panic!(
                    "failed to schedule operands: {args:?}\nfor inst '{}'\nwith error: \
                     {err:?}\nconstraints: {constraints:?}\nstack: {:#?}",
                    op.name(),
                    &emitter.stack,
                )
            });

        Ok(())
    }

    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let mut inst_emitter = emitter.inst_emitter(self.as_operation());
        for _ in 0..self.num_operands() {
            inst_emitter.pop().expect("operand stack is empty");
        }
        inst_emitter.push(self.result().as_value_ref());
        Ok(())
    }
}

impl HirLowering for arith::Split {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let mut inst_emitter = emitter.inst_emitter(self.as_operation());
        inst_emitter.pop().expect("operand stack is empty");
        // `arith.split` defines results in most-significant to least-significant order, but the
        // underlying runtime stack representation is little-endian (least-significant parts are
        // closer to the top of the stack). Since `arith.split` does not emit runtime instructions,
        // we must update the operand stack to match the existing raw-part order, which means
        // leaving the least-significant limb on top.
        for limb in self.limbs().iter() {
            inst_emitter.push(limb.borrow().as_value_ref());
        }
        Ok(())
    }
}

impl HirLowering for builtin::GlobalSymbol {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        let context = self.as_operation().context();

        // 1. Resolve symbol to computed address in global layout
        let current_module = self
            .nearest_parent_op::<builtin::Module>()
            .expect("expected 'hir.global_symbol' op to have a module ancestor");
        let symbol = current_module.borrow().resolve(self.symbol().path()).ok_or_else(|| {
            context
                .diagnostics()
                .diagnostic(Severity::Error)
                .with_message("invalid symbol reference")
                .with_primary_label(
                    self.span(),
                    "unable to resolve this symbol in the current module",
                )
                .into_report()
        })?;

        let global_variable = symbol
            .borrow()
            .downcast_ref::<builtin::GlobalVariable>()
            .map(|gv| unsafe { builtin::GlobalVariableRef::from_raw(gv) })
            .ok_or_else(|| {
                context
                    .diagnostics()
                    .diagnostic(Severity::Error)
                    .with_message("invalid symbol reference")
                    .with_primary_label(
                        self.span(),
                        format!(
                            "this symbol resolves to a '{}', but a 'hir.global_variable' was \
                             expected",
                            symbol.borrow().as_symbol_operation().name()
                        ),
                    )
                    .into_report()
            })?;

        let computed_addr = emitter
            .link_info
            .globals_layout()
            .get_computed_addr(global_variable)
            .expect("link error: missing global variable in computed global layout");
        let addr = computed_addr.checked_add_signed(*self.get_offset()).ok_or_else(|| {
            context
                .diagnostics()
                .diagnostic(Severity::Error)
                .with_message("invalid global symbol offset")
                .with_primary_label(
                    self.span(),
                    "the specified offset is invalid for the referenced symbol",
                )
                .with_help(
                    "the offset is invalid because the computed address under/overflows the \
                     address space",
                )
                .into_report()
        })?;

        // 2. Push computed address on the stack as the result
        emitter.inst_emitter(self.as_operation()).literal(addr, self.span());

        Ok(())
    }
}

impl HirLowering for wasm::SignExtend {
    fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
        // We're sign-extending a value of the source type contained in an I32/I64 operand, where
        // the destination type is wider than the source type. Wasm does not specify the contents of
        // the excess bits. However the `sext` instruction requires them to be zero, so we truncate
        // to meet that requirement.
        let mut inst_emitter = emitter.inst_emitter(self.as_operation());
        inst_emitter.trunc(&self.get_src_ty(), self.span());
        inst_emitter.sext(&self.get_dst_ty(), self.span());

        Ok(())
    }
}

macro_rules! impl_hir_lowering_load_sext {
    ($op:ty) => {
        impl HirLowering for $op {
            fn emit(&self, emitter: &mut BlockEmitter<'_>) -> Result<(), Report> {
                let pointee_ty =
                    self.addr().ty().pointee().expect("pointer should have been verified").clone();
                let mut inst_emitter = emitter.inst_emitter(self.as_operation());
                inst_emitter.load(pointee_ty, self.span());
                inst_emitter.sext(self.result().ty(), self.span());
                Ok(())
            }
        }
    };
}

impl_hir_lowering_load_sext!(wasm::I32Load8S);
impl_hir_lowering_load_sext!(wasm::I32Load16S);
impl_hir_lowering_load_sext!(wasm::I64Load8S);
impl_hir_lowering_load_sext!(wasm::I64Load16S);
impl_hir_lowering_load_sext!(wasm::I64Load32S);