lamina 0.0.10

High-performance compiler backend for Lamina Intermediate Representation
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
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
pub mod abi;
pub mod regalloc;
pub mod util;

use std::fs;
use std::io::Write;
use std::result::Result;

use crate::mir::{Instruction as MirInst, Module as MirModule, Register};
use crate::mir_codegen::{
    Codegen, CodegenError, CodegenOptions, assemble, capability::CapabilitySet,
};
use abi::WasmABI;
use lamina_platform::{TargetArchitecture, TargetOperatingSystem};
use util::{
    emit_float_binary_op, emit_float_cmp_op, emit_float_unary_op, emit_int_binary_op,
    emit_int_cmp_op, load_fp_operand_wasm, load_operand_wasm, load_register_wasm,
    store_fp_to_register_wasm, store_to_register_wasm,
};

use crate::mir_codegen::common::CodegenBase;

/// Trait-backed MIR ⇒ WebAssembly code generator.
pub struct WasmCodegen<'a> {
    base: CodegenBase<'a>,
}

impl<'a> WasmCodegen<'a> {
    pub fn new(target_os: TargetOperatingSystem) -> Self {
        Self {
            base: CodegenBase::new(target_os),
        }
    }

    /// Attach the MIR module that should be emitted in the next codegen pass.
    pub fn set_module(&mut self, module: &'a MirModule) {
        self.base.set_module(module);
    }

    /// Drain the internal WASM buffer produced by `emit_asm`.
    pub fn drain_output(&mut self) -> Vec<u8> {
        self.base.drain_output()
    }

    /// Emit WASM for the provided module directly into the supplied writer.
    pub fn emit_into<W: Write>(
        &mut self,
        module: &'a MirModule,
        writer: &mut W,
        codegen_units: usize,
    ) -> Result<(), crate::error::LaminaError> {
        generate_mir_wasm_with_units(module, writer, self.base.target_os, codegen_units)
    }
}

impl<'a> Codegen for WasmCodegen<'a> {
    const BIN_EXT: &'static str = "wasm";
    const CAN_OUTPUT_ASM: bool = true;
    const CAN_OUTPUT_BIN: bool = true;
    const SUPPORTED_CODEGEN_OPTS: &'static [CodegenOptions] =
        &[CodegenOptions::Debug, CodegenOptions::Release];
    const TARGET_OS: TargetOperatingSystem = TargetOperatingSystem::Linux;
    const MAX_BIT_WIDTH: u8 = 64;

    fn capabilities() -> CapabilitySet {
        CapabilitySet::wasm()
    }

    fn prepare(
        &mut self,
        types: &std::collections::HashMap<String, crate::mir::MirType>,
        globals: &std::collections::HashMap<String, crate::mir::Global>,
        funcs: &std::collections::HashMap<String, crate::mir::Signature>,
        codegen_units: usize,
        verbose: bool,
        options: &[CodegenOptions],
        input_name: &str,
    ) -> Result<(), CodegenError> {
        self.base.prepare_base(
            types,
            globals,
            funcs,
            codegen_units,
            verbose,
            options,
            input_name,
        )
    }

    fn compile(&mut self) -> Result<(), CodegenError> {
        self.base.compile_base()
    }

    fn finalize(&mut self) -> Result<(), CodegenError> {
        self.base.finalize_base()
    }

    fn emit_asm(&mut self) -> Result<(), CodegenError> {
        self.base.emit_asm_base(generate_mir_wasm, "WASM")
    }

    fn emit_bin(&mut self) -> Result<(), CodegenError> {
        // WASM codegen matches other targets: emit_asm generates WAT,
        // then assemble module handles wat2wasm conversion
        // This keeps the pipeline consistent: emit_asm -> assemble -> link

        // First generate WAT text format
        self.emit_asm()?;

        // Get the WAT content
        let wat_content = self.base.drain_output();

        // Write WAT to temporary file
        let temp_wat = std::env::temp_dir().join(format!("lamina_wasm_{}.wat", std::process::id()));
        fs::write(&temp_wat, &wat_content).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!(
                "Failed to write temporary WAT file: {}",
                e
            ))
        })?;

        // Convert WAT to binary WASM using wat2wasm
        let temp_wasm =
            std::env::temp_dir().join(format!("lamina_wasm_{}.wasm", std::process::id()));
        let _assemble_result = assemble::assemble(
            &temp_wat,
            &temp_wasm,
            TargetArchitecture::Wasm32,
            self.base.target_os,
            Some(assemble::AssemblerBackend::Wat2Wasm),
            &[],
            self.base.verbose,
        )
        .map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("Failed to assemble WASM: {}", e))
        })?;

        // Read binary WASM back into output buffer
        let wasm_binary = fs::read(&temp_wasm).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("Failed to read WASM binary: {}", e))
        })?;

        self.base.output = wasm_binary;

        // Clean up temporary files
        let _ = fs::remove_file(&temp_wat);
        let _ = fs::remove_file(&temp_wasm);

        Ok(())
    }
}

use crate::mir_codegen::common::{compile_functions_parallel, parallel_codegen_error};

fn compile_single_function_wasm(
    func_name: &str,
    func: &crate::mir::Function,
    target_os: TargetOperatingSystem,
) -> Result<Vec<u8>, CodegenError> {
    use std::io::Write;
    let mut output = Vec::new();
    let abi = WasmABI::new(target_os);

    let mangled_name = abi.mangle_function_name(func_name);
    writeln!(output, "  (func ${}", mangled_name).map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;

    for (i, _param) in func.sig.params.iter().enumerate() {
        writeln!(output, "    (param $p{} i64)", i).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    if func.sig.ret_ty.is_some() {
        writeln!(output, "    (result i64)").map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    let mut local_vregs = std::collections::HashSet::new();
    for block in &func.blocks {
        for inst in &block.instructions {
            if let Some(dst) = inst.def_reg()
                && let Register::Virtual(vreg) = dst
            {
                local_vregs.insert(vreg);
            }
            for reg in inst.use_regs() {
                if let Register::Virtual(vreg) = reg {
                    local_vregs.insert(vreg);
                }
            }
        }
    }

    let mut vreg_to_local: std::collections::HashMap<crate::mir::VirtualReg, usize> =
        std::collections::HashMap::new();
    for (local_idx, vreg) in local_vregs.into_iter().enumerate() {
        vreg_to_local.insert(*vreg, local_idx);
        writeln!(output, "{}", abi.generate_local_decl(local_idx)).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    let mut block_labels: std::collections::HashMap<&str, usize> = std::collections::HashMap::new();
    for (idx, block) in func.blocks.iter().enumerate() {
        block_labels.insert(&block.label, idx);
    }

    writeln!(output, "    (local $pc i64)").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;
    writeln!(output, "    i64.const 0").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;
    writeln!(output, "    local.set $pc").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;
    writeln!(output, "    (loop $dispatch_loop").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;

    let num_blocks = func.blocks.len();
    for i in (0..num_blocks).rev() {
        writeln!(output, "      (block $block_{}", i).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    writeln!(output, "        local.get $pc").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;
    writeln!(output, "        i32.wrap_i64").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;
    write!(output, "        br_table").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;
    for i in 0..num_blocks {
        write!(output, " {}", i).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }
    writeln!(output, " 0").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;

    for block in func.blocks.iter() {
        writeln!(output, "      )").map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
        writeln!(output, "      ;; Block: {}", block.label).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
        for inst in &block.instructions {
            emit_instruction_wasm(inst, &mut output, &vreg_to_local, &block_labels).map_err(
                |e| CodegenError::InvalidCodegenOptions(e.to_string()),
            )?;
        }
        writeln!(output, "      br $dispatch_loop").map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    writeln!(output, "    )").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;

    if func.sig.ret_ty.is_some() {
        writeln!(output, "    i64.const 0").map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    writeln!(output, "  )").map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;

    Ok(output)
}

pub fn generate_mir_wasm<W: Write>(
    module: &MirModule,
    writer: &mut W,
    target_os: TargetOperatingSystem,
) -> Result<(), crate::error::LaminaError> {
    generate_mir_wasm_with_units(module, writer, target_os, 1)
}

pub fn generate_mir_wasm_with_units<W: Write>(
    module: &MirModule,
    writer: &mut W,
    target_os: TargetOperatingSystem,
    codegen_units: usize,
) -> Result<(), crate::error::LaminaError> {
    crate::mir_codegen::validate_module_call_parameters(module, TargetArchitecture::Wasm64)?;
    let abi = WasmABI::new(target_os);

    // WASM module header
    writeln!(writer, "(module")?;
    writeln!(writer, "  {}", abi.get_print_import())?;

    // Emit import declarations for external functions
    for func_name in &module.external_functions {
        if let Some(func) = module.functions.get(func_name) {
            let mangled_name = abi.mangle_function_name(func_name);
            write!(
                writer,
                "  (import \"env\" \"{}\" (func ${}",
                func_name, mangled_name
            )?;

            // Parameters
            for _param in &func.sig.params {
                write!(writer, " (param i64)")?;
            }

            // Return type
            if func.sig.ret_ty.is_some() {
                write!(writer, " (result i64)")?;
            }

            writeln!(writer, ")")?;
        }
    }

    // Global variables for virtual registers
    let mut global_count = 0;
    for func in module.functions.values() {
        for block in &func.blocks {
            for inst in &block.instructions {
                if let Some(dst) = inst.def_reg()
                    && let Register::Virtual(_) = dst
                {
                    global_count += 1;
                }
            }
        }
    }

    for i in 0..global_count {
        writeln!(writer, "{}", abi.generate_global_decl(i))?;
    }

    let results = compile_functions_parallel(
        module,
        target_os,
        codegen_units,
        compile_single_function_wasm,
    )
    .map_err(parallel_codegen_error)?;

    for result in results {
        writer.write_all(&result.assembly)?;
    }

    for func_name in module.functions.keys() {
        if func_name == "main" {
            writeln!(writer, "  (export \"main\" (func $main))")?;
        }
    }

    writeln!(writer, ")")?;

    Ok(())
}

fn emit_instruction_wasm(
    inst: &MirInst,
    writer: &mut impl Write,
    vreg_to_local: &std::collections::HashMap<crate::mir::VirtualReg, usize>,
    block_labels: &std::collections::HashMap<&str, usize>,
) -> Result<(), crate::error::LaminaError> {
    match inst {
        MirInst::IntBinary {
            op,
            dst,
            lhs,
            rhs,
            ty: _,
        } => {
            load_operand_wasm(lhs, writer, vreg_to_local)?;
            load_operand_wasm(rhs, writer, vreg_to_local)?;

            emit_int_binary_op(op, writer)?;

            if let Register::Virtual(vreg) = dst {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::IntCmp {
            op,
            dst,
            lhs,
            rhs,
            ty: _,
        } => {
            load_operand_wasm(lhs, writer, vreg_to_local)?;
            load_operand_wasm(rhs, writer, vreg_to_local)?;

            emit_int_cmp_op(op, writer)?;

            // Convert i32 result to i64
            writeln!(writer, "      i64.extend_i32_u")?;

            if let Register::Virtual(vreg) = dst {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::Call { name, args, ret } => {
            if name == "print" {
                // Handle print intrinsic
                if let Some(arg) = args.first() {
                    load_operand_wasm(arg, writer, vreg_to_local)?;
                    writeln!(writer, "      call $log")?;
                }
            } else {
                // General function call implementation
                // WebAssembly passes all arguments on the stack in order
                for arg in args.iter() {
                    load_operand_wasm(arg, writer, vreg_to_local)?;
                }

                // Call the function
                writeln!(writer, "      call ${}", name)?;

                // Note: WebAssembly functions return values on the stack
                // If there's a return value, it's already on the stack
            }

            // Handle return value (already on stack if function returns)
            if let Some(ret_reg) = ret
                && let Register::Virtual(vreg) = ret_reg
            {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::Load {
            dst,
            addr,
            ty,
            attrs: _,
        } => {
            // Compute address: base + offset
            match addr {
                crate::mir::AddressMode::BaseOffset { base, offset } => {
                    // Load base address onto stack
                    load_register_wasm(base, writer, vreg_to_local)?;

                    // Add offset if non-zero
                    if *offset != 0 {
                        writeln!(writer, "      i64.const {}", *offset as i64)?;
                        writeln!(writer, "      i64.add")?;
                    }

                    // Emit load instruction based on type
                    match ty {
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I8) => {
                            writeln!(writer, "      i64.load8_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I16) => {
                            writeln!(writer, "      i64.load16_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I32) => {
                            writeln!(writer, "      i64.load32_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I64)
                        | crate::mir::MirType::Scalar(crate::mir::ScalarType::Ptr) => {
                            writeln!(writer, "      i64.load")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::F32) => {
                            writeln!(writer, "      f32.load")?;
                            // Convert to i64 for storage (WebAssembly uses separate stacks)
                            writeln!(writer, "      i32.reinterpret_f32")?;
                            writeln!(writer, "      i64.extend_i32_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::F64) => {
                            writeln!(writer, "      f64.load")?;
                            // Convert to i64 for storage
                            writeln!(writer, "      i64.reinterpret_f64")?;
                        }
                        _ => {
                            // Default to i64 for unknown types
                            writeln!(writer, "      i64.load")?;
                        }
                    }
                }
                crate::mir::AddressMode::BaseIndexScale {
                    base,
                    index,
                    scale,
                    offset,
                } => {
                    // Load base address
                    load_register_wasm(base, writer, vreg_to_local)?;

                    // Load index
                    load_register_wasm(index, writer, vreg_to_local)?;

                    // Scale index
                    writeln!(writer, "      i64.const {}", *scale as i64)?;
                    writeln!(writer, "      i64.mul")?;

                    // Add base + scaled index
                    writeln!(writer, "      i64.add")?;

                    // Add offset if non-zero
                    if *offset != 0 {
                        writeln!(writer, "      i64.const {}", *offset as i64)?;
                        writeln!(writer, "      i64.add")?;
                    }

                    // Emit load instruction based on type (same as BaseOffset)
                    match ty {
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I8) => {
                            writeln!(writer, "      i64.load8_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I16) => {
                            writeln!(writer, "      i64.load16_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I32) => {
                            writeln!(writer, "      i64.load32_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::I64)
                        | crate::mir::MirType::Scalar(crate::mir::ScalarType::Ptr) => {
                            writeln!(writer, "      i64.load")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::F32) => {
                            writeln!(writer, "      f32.load")?;
                            writeln!(writer, "      i32.reinterpret_f32")?;
                            writeln!(writer, "      i64.extend_i32_u")?;
                        }
                        crate::mir::MirType::Scalar(crate::mir::ScalarType::F64) => {
                            writeln!(writer, "      f64.load")?;
                            writeln!(writer, "      i64.reinterpret_f64")?;
                        }
                        _ => {
                            writeln!(writer, "      i64.load")?;
                        }
                    }
                }
            }

            // Store loaded value to destination register
            if let Register::Virtual(vreg) = dst {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::Store {
            addr,
            src,
            ty,
            attrs: _,
        } => {
            // WebAssembly store expects: address on stack, then value on top
            // So we compute address first, then load value

            // Compute address: base + offset
            match addr {
                crate::mir::AddressMode::BaseOffset { base, offset } => {
                    // Load base address onto stack
                    load_register_wasm(base, writer, vreg_to_local)?;

                    // Add offset if non-zero
                    if *offset != 0 {
                        writeln!(writer, "      i64.const {}", *offset as i64)?;
                        writeln!(writer, "      i64.add")?;
                    }
                }
                crate::mir::AddressMode::BaseIndexScale {
                    base,
                    index,
                    scale,
                    offset,
                } => {
                    // Load base address
                    load_register_wasm(base, writer, vreg_to_local)?;

                    // Load index
                    load_register_wasm(index, writer, vreg_to_local)?;

                    // Scale index
                    writeln!(writer, "      i64.const {}", *scale as i64)?;
                    writeln!(writer, "      i64.mul")?;

                    // Add base + scaled index
                    writeln!(writer, "      i64.add")?;

                    // Add offset if non-zero
                    if *offset != 0 {
                        writeln!(writer, "      i64.const {}", *offset as i64)?;
                        writeln!(writer, "      i64.add")?;
                    }
                }
            }

            // Now load value to store (goes on top of address)
            load_operand_wasm(src, writer, vreg_to_local)?;

            // Emit store instruction based on type
            // Stack now: address (bottom), value (top)
            match ty {
                crate::mir::MirType::Scalar(crate::mir::ScalarType::I8) => {
                    writeln!(writer, "      i64.store8")?;
                }
                crate::mir::MirType::Scalar(crate::mir::ScalarType::I16) => {
                    writeln!(writer, "      i64.store16")?;
                }
                crate::mir::MirType::Scalar(crate::mir::ScalarType::I32) => {
                    writeln!(writer, "      i64.store32")?;
                }
                crate::mir::MirType::Scalar(crate::mir::ScalarType::I64)
                | crate::mir::MirType::Scalar(crate::mir::ScalarType::Ptr) => {
                    writeln!(writer, "      i64.store")?;
                }
                crate::mir::MirType::Scalar(crate::mir::ScalarType::F32) => {
                    // Convert i64 to f32
                    writeln!(writer, "      i32.wrap_i64")?;
                    writeln!(writer, "      f32.reinterpret_i32")?;
                    writeln!(writer, "      f32.store")?;
                }
                crate::mir::MirType::Scalar(crate::mir::ScalarType::F64) => {
                    // Convert i64 to f64
                    writeln!(writer, "      f64.reinterpret_i64")?;
                    writeln!(writer, "      f64.store")?;
                }
                _ => {
                    // Default to i64 for unknown types
                    writeln!(writer, "      i64.store")?;
                }
            }
        }
        MirInst::Ret { value } => {
            if let Some(val) = value {
                // Load the return value
                load_operand_wasm(val, writer, vreg_to_local)?;
            } else {
                // No return value - use 0
                writeln!(writer, "        i64.const 0")?;
            }
            // Return exits the function
            writeln!(writer, "        return")?;
        }
        MirInst::Jmp { target } => {
            // Set PC to target block index and continue dispatch loop
            if let Some(&target_idx) = block_labels.get(target.as_str()) {
                writeln!(writer, "        i64.const {}", target_idx)?;
                writeln!(writer, "        local.set $pc")?;
                writeln!(writer, "        br $dispatch_loop")?;
            } else {
                return Err(crate::error::LaminaError::ValidationError(format!(
                    "Unknown block label: {}",
                    target
                )));
            }
        }
        MirInst::Br {
            cond,
            true_target,
            false_target,
        } => {
            load_register_wasm(cond, writer, vreg_to_local)?;
            // Convert i64 condition to i32 for WASM if statement
            writeln!(writer, "        i32.wrap_i64")?;
            writeln!(writer, "        (if")?;
            writeln!(writer, "          (then")?;
            if let Some(&true_idx) = block_labels.get(true_target.as_str()) {
                writeln!(writer, "            i64.const {}", true_idx)?;
                writeln!(writer, "            local.set $pc")?;
            } else {
                return Err(crate::error::LaminaError::ValidationError(format!(
                    "Unknown block label: {}",
                    true_target
                )));
            }
            writeln!(writer, "          )")?;
            writeln!(writer, "          (else")?;
            if let Some(&false_idx) = block_labels.get(false_target.as_str()) {
                writeln!(writer, "            i64.const {}", false_idx)?;
                writeln!(writer, "            local.set $pc")?;
            } else {
                return Err(crate::error::LaminaError::ValidationError(format!(
                    "Unknown block label: {}",
                    false_target
                )));
            }
            writeln!(writer, "          )")?;
            writeln!(writer, "        )")?;
            // Continue dispatch loop
            writeln!(writer, "        br $dispatch_loop")?;
        }
        MirInst::FloatBinary {
            op,
            dst,
            lhs,
            rhs,
            ty,
        } => {
            let is_f32 = ty.size_bytes() == 4;

            // Load operands as floats
            load_fp_operand_wasm(lhs, writer, vreg_to_local, is_f32)?;
            load_fp_operand_wasm(rhs, writer, vreg_to_local, is_f32)?;

            // Perform floating-point operation
            emit_float_binary_op(op, writer, is_f32)?;

            // Store result back to register
            if let Register::Virtual(vreg) = dst {
                store_fp_to_register_wasm(writer, vreg_to_local, vreg, is_f32)?;
            }
        }
        MirInst::FloatUnary { op, dst, src, ty } => {
            let is_f32 = ty.size_bytes() == 4;

            // Load operand as float
            load_fp_operand_wasm(src, writer, vreg_to_local, is_f32)?;

            // Perform floating-point unary operation
            emit_float_unary_op(op, writer, is_f32)?;

            // Store result back to register
            if let Register::Virtual(vreg) = dst {
                store_fp_to_register_wasm(writer, vreg_to_local, vreg, is_f32)?;
            }
        }
        MirInst::FloatCmp {
            op,
            dst,
            lhs,
            rhs,
            ty,
        } => {
            let is_f32 = ty.size_bytes() == 4;

            // Load operands as floats
            load_fp_operand_wasm(lhs, writer, vreg_to_local, is_f32)?;
            load_fp_operand_wasm(rhs, writer, vreg_to_local, is_f32)?;

            // Perform floating-point comparison (result is i32)
            emit_float_cmp_op(op, writer, is_f32)?;

            // Extend i32 result to i64 for storage
            writeln!(writer, "      i64.extend_i32_u")?;

            // Store result to destination
            if let Register::Virtual(vreg) = dst {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::Select {
            dst,
            cond,
            true_val,
            false_val,
            ty: _,
        } => {
            // WASM select: push true, false, then cond as i32.
            load_operand_wasm(true_val, writer, vreg_to_local)?;
            load_operand_wasm(false_val, writer, vreg_to_local)?;
            load_register_wasm(cond, writer, vreg_to_local)?;
            writeln!(writer, "        i32.wrap_i64")?;
            writeln!(writer, "        select")?;
            if let Register::Virtual(vreg) = dst {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::Switch {
            value,
            cases,
            default,
        } => {
            // Emit a linear cmp chain using WASM block/br_if.
            load_register_wasm(value, writer, vreg_to_local)?;
            for (case_val, case_label) in cases {
                if let Some(&target_idx) = block_labels.get(case_label.as_str()) {
                    writeln!(writer, "        i64.const {}", case_val)?;
                    // Load value again for comparison (stack-machine needs two copies).
                    load_register_wasm(value, writer, vreg_to_local)?;
                    writeln!(writer, "        i64.eq")?;
                    writeln!(writer, "        (if (then")?;
                    writeln!(writer, "          i64.const {}", target_idx)?;
                    writeln!(writer, "          local.set $pc")?;
                    writeln!(writer, "          br $dispatch_loop")?;
                    writeln!(writer, "        ))")?;
                }
            }
            // Fall through to default.
            if let Some(&default_idx) = block_labels.get(default.as_str()) {
                writeln!(writer, "        i64.const {}", default_idx)?;
                writeln!(writer, "        local.set $pc")?;
            }
            writeln!(writer, "        br $dispatch_loop")?;
        }
        MirInst::Comment { text } => {
            writeln!(writer, "        ;; {}", text)?;
        }
        MirInst::Lea { dst, base, offset } => {
            // In WASM linear memory there are no general-purpose effective-address
            // computations on integers, so we materialise base + offset as i64.
            load_register_wasm(base, writer, vreg_to_local)?;
            if *offset != 0 {
                writeln!(writer, "        i64.const {}", offset)?;
                writeln!(writer, "        i64.add")?;
            }
            if let Register::Virtual(vreg) = dst {
                store_to_register_wasm(&Register::Virtual(*vreg), writer, vreg_to_local)?;
            }
        }
        MirInst::TailCall { name, args } => {
            // WASM does not have a guaranteed tail-call instruction in baseline WAT,
            // so we emit a normal return_call if the target is known, otherwise
            // a regular call followed by return.
            for (i, arg) in args.iter().enumerate() {
                let _ = i;
                load_operand_wasm(arg, writer, vreg_to_local)?;
            }
            writeln!(writer, "        call ${}", name)?;
            writeln!(writer, "        return")?;
        }
        MirInst::Unreachable => {
            writeln!(writer, "        unreachable")?;
        }
        MirInst::SafePoint | MirInst::StackMap { .. } | MirInst::PatchPoint { .. } => {
            // No-op in AOT/WASM path.
        }
        other => {
            return Err(crate::error::LaminaError::CodegenError(
                CodegenError::UnsupportedFeature(format!(
                    "WASM backend: instruction not yet supported: {}",
                    other
                )),
            ));
        }
    }

    Ok(())
}

// Utility functions are now in the util module