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
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
//! x86_64 code generation for MIR (Mid-level IR).
//!
//! Code generation from MIR to x86_64 assembly,
//! supporting System V AMD64 and Microsoft x64 calling conventions.

pub mod abi;
pub mod constants;
pub mod frame;
pub mod regalloc;
pub mod util;

use abi::X86ABI;
use constants::{fd, linux, macos, stack, windows};
use frame::X86Frame;
use regalloc::X64RegAlloc;
use std::io::Write;
use std::result::Result;
use util::*;

use crate::error::LaminaError;
use crate::mir::register::RegisterClass;
use crate::mir::{Instruction as MirInst, MirType, Module as MirModule, Register};
use crate::mir_codegen::{
    Codegen, CodegenError, CodegenOptions, MirCodegenSettings, RegallocStrategy,
    capability::CapabilitySet,
};
use lamina_codegen::{Allocation as MirAllocation, GraphColorAllocator, LinearScanAllocator};
use lamina_platform::{TargetArchitecture, TargetOperatingSystem};
use std::sync::Arc;

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

/// MIR to x86_64 code generator implementing the `Codegen` trait.
pub struct X86Codegen<'a> {
    base: CodegenBase<'a>,
}

impl<'a> X86Codegen<'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 assembly buffer produced by `emit_asm`.
    pub fn drain_output(&mut self) -> Vec<u8> {
        self.base.drain_output()
    }

    /// Emit assembly 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<(), LaminaError> {
        generate_mir_x86_64_with_units(module, writer, self.base.target_os, codegen_units)
    }
}

impl<'a> Codegen for X86Codegen<'a> {
    const BIN_EXT: &'static str = "o";
    const CAN_OUTPUT_ASM: bool = true;
    const CAN_OUTPUT_BIN: bool = false;
    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::standard_native()
    }

    fn prepare(
        &mut self,
        types: &std::collections::HashMap<String, 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_with_units(
            |module, writer, target_os, codegen_units| {
                generate_mir_x86_64_with_units(module, writer, target_os, codegen_units)
            },
            "x86_64",
            self.base.codegen_units,
        )
    }

    fn emit_bin(&mut self) -> Result<(), CodegenError> {
        Err(CodegenError::UnsupportedFeature(
            "Binary emission not supported".to_string(),
        ))
    }
}

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

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

    ensure_signature_support(&func.sig)
        .map_err(|e| CodegenError::InvalidCodegenOptions(e.to_string()))?;

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

    if settings.emit_asm_debug_lines {
        let tag = settings.debug_file_tag.replace('\"', "'");
        writeln!(output, "    .file 1 \"{}\"", tag).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;
    }

    // Detect leaf function (no Call/TailCall instructions)
    let is_leaf = !func.blocks.iter().any(|b| {
        b.instructions
            .iter()
            .any(|i| matches!(i, MirInst::Call { .. } | MirInst::TailCall { .. }))
    });

    let mut reg_alloc = if is_leaf {
        X64RegAlloc::new_leaf(target_os)
    } else {
        X64RegAlloc::new(target_os)
    };

    let mut stack_slots: std::collections::HashMap<crate::mir::VirtualReg, i32> =
        std::collections::HashMap::new();
    let mut def_regs: std::collections::HashSet<crate::mir::VirtualReg> =
        std::collections::HashSet::new();
    let mut used_regs: std::collections::HashSet<crate::mir::VirtualReg> =
        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
            {
                def_regs.insert(*vreg);
            }
            for reg in inst.use_regs() {
                if let Register::Virtual(vreg) = reg {
                    used_regs.insert(*vreg);
                }
            }
        }
    }

    for vreg in &def_regs {
        if !stack_slots.contains_key(vreg) {
            let slot_index = stack_slots.len();
            stack_slots.insert(*vreg, X86Frame::calculate_stack_offset(slot_index));
        }
    }
    for vreg in used_regs {
        if !def_regs.contains(&vreg) && !stack_slots.contains_key(&vreg) {
            let slot_index = stack_slots.len();
            stack_slots.insert(vreg, X86Frame::calculate_stack_offset(slot_index));
        }
    }

    if settings.regalloc != RegallocStrategy::Incremental {
        let pool = X64RegAlloc::gpr_pool_for_global_allocation(target_os, is_leaf);
        let intervals: Vec<_> = LinearScanAllocator::compute_intervals(func)
            .into_iter()
            .filter(|i| i.vreg.class == RegisterClass::Gpr)
            .collect();
        let plan = match settings.regalloc {
            RegallocStrategy::LinearScanGlobal => {
                LinearScanAllocator::allocate(&intervals, pool.as_slice())
            }
            RegallocStrategy::GraphColorGlobal => {
                GraphColorAllocator::allocate(&intervals, pool.as_slice())
            }
            RegallocStrategy::Incremental => unreachable!(),
        };
        reg_alloc = X64RegAlloc::from_global_plan(target_os, is_leaf, &plan);
        for (v, a) in &plan {
            if let MirAllocation::Spill(off) = a {
                stack_slots.insert(*v, *off);
            }
        }
    }

    let stack_size = stack_slots.len() * 8;
    X86Frame::generate_prologue(&mut output, stack_size)
        .map_err(|e| CodegenError::InvalidCodegenOptions(e.to_string()))?;

    if !func.sig.params.is_empty() {
        let abi_for_func = X86ABI::new(target_os);
        let arg_regs = abi_for_func.arg_registers();

        for (index, param) in func.sig.params.iter().enumerate() {
            if let Register::Virtual(vreg) = &param.reg
                && let Some(slot_off) = stack_slots.get(vreg)
            {
                if index < arg_regs.len() {
                    let phys_arg = arg_regs[index];
                    writeln!(output, "    movq %{}, {}(%rbp)", phys_arg, slot_off).map_err(
                        |e| {
                            CodegenError::InvalidCodegenOptions(format!(
                                "IO error: {}",
                                e
                            ))
                        },
                    )?;
                } else {
                    let stack_index = index - arg_regs.len();
                    let caller_off = 16 + (stack_index as i32) * 8;
                    writeln!(output, "    movq {}(%rbp), %rax", caller_off).map_err(|e| {
                        CodegenError::InvalidCodegenOptions(format!(
                            "IO error: {}",
                            e
                        ))
                    })?;
                    writeln!(output, "    movq %rax, {}(%rbp)", slot_off).map_err(|e| {
                        CodegenError::InvalidCodegenOptions(format!(
                            "IO error: {}",
                            e
                        ))
                    })?;
                }
            }
        }
    }

    writeln!(output, "    jmp .L_{}_{}", func_name, func.entry).map_err(|e| {
        CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
    })?;

    let mut debug_line: u32 = 0;
    for block in &func.blocks {
        writeln!(output, ".L_{}_{}:", func_name, block.label).map_err(|e| {
            CodegenError::InvalidCodegenOptions(format!("IO error: {}", e))
        })?;

        for inst in &block.instructions {
            emit_instruction_x86_64(
                inst,
                &mut output,
                &mut reg_alloc,
                &stack_slots,
                stack_size,
                target_os,
                func_name,
                &def_regs,
                settings,
                &mut debug_line,
            )
            .map_err(|e| CodegenError::InvalidCodegenOptions(e.to_string()))?;
        }
    }

    Ok(output)
}

pub fn generate_mir_x86_64<W: Write>(
    module: &MirModule,
    writer: &mut W,
    target_os: TargetOperatingSystem,
) -> Result<(), LaminaError> {
    generate_mir_x86_64_with_units(module, writer, target_os, 1)
}

pub fn generate_mir_x86_64_with_units<W: Write>(
    module: &MirModule,
    writer: &mut W,
    target_os: TargetOperatingSystem,
    codegen_units: usize,
) -> Result<(), LaminaError> {
    generate_mir_x86_64_with_units_and_settings(
        module,
        writer,
        target_os,
        codegen_units,
        &MirCodegenSettings::default(),
    )
}

pub fn generate_mir_x86_64_with_units_and_settings<W: Write>(
    module: &MirModule,
    writer: &mut W,
    target_os: TargetOperatingSystem,
    codegen_units: usize,
    settings: &MirCodegenSettings,
) -> Result<(), LaminaError> {
    crate::mir_codegen::validate_module_call_parameters(module, TargetArchitecture::X86_64)?;
    let abi = X86ABI::new(target_os);

    emit_print_format_section(writer, target_os)?;

    // Emit external function declarations first
    for func_name in &module.external_functions {
        let label = abi.mangle_function_name(func_name);
        writeln!(writer, ".extern {}", label)?;
    }

    writeln!(writer, ".text")?;
    writeln!(writer, "{}", abi.get_main_global())?;

    let settings_arc = Arc::new(settings.clone());
    let results = compile_functions_parallel(module, target_os, codegen_units, {
        let settings_arc = settings_arc.clone();
        move |name, func, os| compile_single_function_x86_64(name, func, os, settings_arc.as_ref())
    })
    .map_err(parallel_codegen_error)?;

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

    Ok(())
}

fn ensure_signature_support(sig: &crate::mir::Signature) -> Result<(), LaminaError> {
    for (idx, param) in sig.params.iter().enumerate() {
        ensure_type_supported(&param.ty, &format!("parameter {} of '{}'", idx, sig.name))?;
    }

    if let Some(ret_ty) = &sig.ret_ty {
        ensure_type_supported(ret_ty, &format!("return type of '{}'", sig.name))?;
    }

    Ok(())
}

fn ensure_type_supported(ty: &MirType, context: &str) -> Result<(), LaminaError> {
    if ty.is_float() || ty.is_vector() {
        return Err(LaminaError::ValidationError(format!(
            "x86_64 backend does not support {} (type {})",
            context, ty
        )));
    }
    Ok(())
}

#[allow(clippy::too_many_arguments)]
fn emit_instruction_x86_64(
    inst: &MirInst,
    writer: &mut impl Write,
    reg_alloc: &mut X64RegAlloc,
    stack_slots: &std::collections::HashMap<crate::mir::VirtualReg, i32>,
    stack_size: usize,
    target_os: TargetOperatingSystem,
    func_name: &str,
    def_regs: &std::collections::HashSet<crate::mir::VirtualReg>,
    settings: &MirCodegenSettings,
    debug_line: &mut u32,
) -> Result<(), LaminaError> {
    if settings.emit_asm_debug_lines {
        *debug_line = debug_line.saturating_add(1);
        writeln!(writer, "    .loc 1 {} 0", *debug_line)?;
    }
    match inst {
        MirInst::IntBinary {
            op,
            dst,
            lhs,
            rhs,
            ty: _,
        } => {
            // Get dst physical register if available
            let dst_phys = match dst {
                Register::Virtual(v) => reg_alloc.get_mapping_for(v),
                Register::Physical(p) => Some(p.name),
            };

            if let Some(dp) = dst_phys {
                // Optimized path: emit directly into dp, avoiding rax bounce
                match op {
                    crate::mir::IntBinOp::Shl
                    | crate::mir::IntBinOp::AShr
                    | crate::mir::IntBinOp::LShr => {
                        // Load lhs into dp
                        load_operand_to_register(lhs, writer, reg_alloc, stack_slots, dp)?;
                        match rhs {
                            crate::mir::Operand::Immediate(imm) => {
                                let sv: u64 = match imm {
                                    crate::mir::instruction::Immediate::I8(v) => *v as u64,
                                    crate::mir::instruction::Immediate::I16(v) => *v as u64,
                                    crate::mir::instruction::Immediate::I32(v) => *v as u64,
                                    crate::mir::instruction::Immediate::I64(v) => *v as u64,
                                    _ => {
                                        return Err(LaminaError::ValidationError(
                                            "Shift count must be integer".to_string(),
                                        ));
                                    }
                                };
                                match op {
                                    crate::mir::IntBinOp::Shl => {
                                        writeln!(writer, "    shlq ${}, %{}", sv, dp)?
                                    }
                                    crate::mir::IntBinOp::AShr => {
                                        writeln!(writer, "    sarq ${}, %{}", sv, dp)?
                                    }
                                    crate::mir::IntBinOp::LShr => {
                                        writeln!(writer, "    shrq ${}, %{}", sv, dp)?
                                    }
                                    _ => unreachable!(),
                                }
                            }
                            crate::mir::Operand::Register(_) => {
                                // Need shift count in %cl; load rhs into rcx
                                load_operand_to_register(
                                    rhs,
                                    writer,
                                    reg_alloc,
                                    stack_slots,
                                    "rcx",
                                )?;
                                match op {
                                    crate::mir::IntBinOp::Shl => {
                                        writeln!(writer, "    shlq %cl, %{}", dp)?
                                    }
                                    crate::mir::IntBinOp::AShr => {
                                        writeln!(writer, "    sarq %cl, %{}", dp)?
                                    }
                                    crate::mir::IntBinOp::LShr => {
                                        writeln!(writer, "    shrq %cl, %{}", dp)?
                                    }
                                    _ => unreachable!(),
                                }
                            }
                        }
                    }
                    crate::mir::IntBinOp::SDiv
                    | crate::mir::IntBinOp::UDiv
                    | crate::mir::IntBinOp::SRem
                    | crate::mir::IntBinOp::URem => {
                        // Division always goes through rax/rdx; use rcx for divisor to avoid conflicts
                        load_operand_to_register(lhs, writer, reg_alloc, stack_slots, "rax")?;
                        load_operand_to_register(rhs, writer, reg_alloc, stack_slots, "rcx")?;
                        match op {
                            crate::mir::IntBinOp::SDiv => {
                                writeln!(writer, "    cqto")?;
                                writeln!(writer, "    idivq %rcx")?;
                            }
                            crate::mir::IntBinOp::UDiv => {
                                writeln!(writer, "    xorq %rdx, %rdx")?;
                                writeln!(writer, "    divq %rcx")?;
                            }
                            crate::mir::IntBinOp::SRem => {
                                writeln!(writer, "    cqto")?;
                                writeln!(writer, "    idivq %rcx")?;
                                writeln!(writer, "    movq %rdx, %rax")?;
                            }
                            crate::mir::IntBinOp::URem => {
                                writeln!(writer, "    xorq %rdx, %rdx")?;
                                writeln!(writer, "    divq %rcx")?;
                                writeln!(writer, "    movq %rdx, %rax")?;
                            }
                            _ => unreachable!(),
                        }
                        // Store result (rax) into dp
                        if dp != "rax" {
                            writeln!(writer, "    movq %rax, %{}", dp)?;
                        }
                    }
                    _ => {
                        // Arithmetic/bitwise: load lhs into dp, then apply op with rhs
                        load_operand_to_register(lhs, writer, reg_alloc, stack_slots, dp)?;

                        // Try to use rhs directly (register or small immediate)
                        match rhs {
                            crate::mir::Operand::Immediate(imm) => {
                                let v: i64 = match imm {
                                    crate::mir::instruction::Immediate::I8(x) => *x as i64,
                                    crate::mir::instruction::Immediate::I16(x) => *x as i64,
                                    crate::mir::instruction::Immediate::I32(x) => *x as i64,
                                    crate::mir::instruction::Immediate::I64(x) => *x,
                                    _ => {
                                        return Err(LaminaError::ValidationError(
                                            "Float immediate in integer op".to_string(),
                                        ));
                                    }
                                };
                                if v >= i32::MIN as i64 && v <= i32::MAX as i64 {
                                    // Fits in 32-bit sign-extended immediate
                                    match op {
                                        crate::mir::IntBinOp::Add => {
                                            writeln!(writer, "    addq ${}, %{}", v, dp)?
                                        }
                                        crate::mir::IntBinOp::Sub => {
                                            writeln!(writer, "    subq ${}, %{}", v, dp)?
                                        }
                                        crate::mir::IntBinOp::And => {
                                            writeln!(writer, "    andq ${}, %{}", v, dp)?
                                        }
                                        crate::mir::IntBinOp::Or => {
                                            writeln!(writer, "    orq  ${}, %{}", v, dp)?
                                        }
                                        crate::mir::IntBinOp::Xor => {
                                            writeln!(writer, "    xorq ${}, %{}", v, dp)?
                                        }
                                        crate::mir::IntBinOp::Mul => {
                                            writeln!(writer, "    imulq ${}, %{}, %{}", v, dp, dp)?
                                        }
                                        _ => unreachable!(),
                                    }
                                } else {
                                    // Large immediate: load into rax as temp, then op
                                    writeln!(writer, "    movq ${}, %rax", v)?;
                                    match op {
                                        crate::mir::IntBinOp::Add => {
                                            writeln!(writer, "    addq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Sub => {
                                            writeln!(writer, "    subq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::And => {
                                            writeln!(writer, "    andq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Or => {
                                            writeln!(writer, "    orq  %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Xor => {
                                            writeln!(writer, "    xorq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Mul => {
                                            writeln!(writer, "    imulq %rax, %{}", dp)?
                                        }
                                        _ => unreachable!(),
                                    }
                                }
                            }
                            crate::mir::Operand::Register(rhs_reg) => {
                                // Get rhs physical register if available for direct register op
                                let rhs_phys = match rhs_reg {
                                    Register::Virtual(v) => reg_alloc.get_mapping_for(v),
                                    Register::Physical(p) => Some(p.name),
                                };
                                if let Some(rp) = rhs_phys {
                                    // Both in registers: direct op, no memory access
                                    match op {
                                        crate::mir::IntBinOp::Add => {
                                            writeln!(writer, "    addq %{}, %{}", rp, dp)?
                                        }
                                        crate::mir::IntBinOp::Sub => {
                                            writeln!(writer, "    subq %{}, %{}", rp, dp)?
                                        }
                                        crate::mir::IntBinOp::Mul => {
                                            writeln!(writer, "    imulq %{}, %{}", rp, dp)?
                                        }
                                        crate::mir::IntBinOp::And => {
                                            writeln!(writer, "    andq %{}, %{}", rp, dp)?
                                        }
                                        crate::mir::IntBinOp::Or => {
                                            writeln!(writer, "    orq  %{}, %{}", rp, dp)?
                                        }
                                        crate::mir::IntBinOp::Xor => {
                                            writeln!(writer, "    xorq %{}, %{}", rp, dp)?
                                        }
                                        _ => unreachable!(),
                                    }
                                } else {
                                    // rhs in stack: load to rax as temp, then op
                                    load_operand_to_register(
                                        rhs,
                                        writer,
                                        reg_alloc,
                                        stack_slots,
                                        "rax",
                                    )?;
                                    match op {
                                        crate::mir::IntBinOp::Add => {
                                            writeln!(writer, "    addq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Sub => {
                                            writeln!(writer, "    subq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Mul => {
                                            writeln!(writer, "    imulq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::And => {
                                            writeln!(writer, "    andq %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Or => {
                                            writeln!(writer, "    orq  %rax, %{}", dp)?
                                        }
                                        crate::mir::IntBinOp::Xor => {
                                            writeln!(writer, "    xorq %rax, %{}", dp)?
                                        }
                                        _ => unreachable!(),
                                    }
                                }
                            }
                        }
                        // No store needed — result already in dp!
                    }
                }
            } else {
                // No physical register for dst — fall back to rax accumulator path
                load_operand_to_rax(lhs, writer, reg_alloc, stack_slots)?;

                match op {
                    crate::mir::IntBinOp::Shl
                    | crate::mir::IntBinOp::AShr
                    | crate::mir::IntBinOp::LShr => match rhs {
                        crate::mir::Operand::Immediate(imm) => {
                            let shift_val = match imm {
                                crate::mir::instruction::Immediate::I8(v) => *v as u64,
                                crate::mir::instruction::Immediate::I16(v) => *v as u64,
                                crate::mir::instruction::Immediate::I32(v) => *v as u64,
                                crate::mir::instruction::Immediate::I64(v) => *v as u64,
                                _ => {
                                    return Err(LaminaError::ValidationError(
                                        "Shift count must be an integer immediate".to_string(),
                                    ));
                                }
                            };
                            match op {
                                crate::mir::IntBinOp::Shl => {
                                    writeln!(writer, "    shlq ${}, %rax", shift_val)?
                                }
                                crate::mir::IntBinOp::AShr => {
                                    writeln!(writer, "    sarq ${}, %rax", shift_val)?
                                }
                                crate::mir::IntBinOp::LShr => {
                                    writeln!(writer, "    shrq ${}, %rax", shift_val)?
                                }
                                _ => unreachable!(),
                            }
                        }
                        crate::mir::Operand::Register(_) => {
                            let scratch = reg_alloc.alloc_scratch().unwrap_or("rbx");
                            load_operand_to_register(rhs, writer, reg_alloc, stack_slots, scratch)?;
                            writeln!(writer, "    movq %{}, %rcx", scratch)?;
                            match op {
                                crate::mir::IntBinOp::Shl => {
                                    writeln!(writer, "    shlq %cl, %rax")?
                                }
                                crate::mir::IntBinOp::AShr => {
                                    writeln!(writer, "    sarq %cl, %rax")?
                                }
                                crate::mir::IntBinOp::LShr => {
                                    writeln!(writer, "    shrq %cl, %rax")?
                                }
                                _ => unreachable!(),
                            }
                            if scratch != "rbx" {
                                reg_alloc.free_scratch(scratch);
                            }
                        }
                    },
                    crate::mir::IntBinOp::SDiv
                    | crate::mir::IntBinOp::UDiv
                    | crate::mir::IntBinOp::SRem
                    | crate::mir::IntBinOp::URem => {
                        load_operand_to_register(rhs, writer, reg_alloc, stack_slots, "rcx")?;
                        match op {
                            crate::mir::IntBinOp::SDiv => {
                                writeln!(writer, "    cqto")?;
                                writeln!(writer, "    idivq %rcx")?;
                            }
                            crate::mir::IntBinOp::UDiv => {
                                writeln!(writer, "    xorq %rdx, %rdx")?;
                                writeln!(writer, "    divq %rcx")?;
                            }
                            crate::mir::IntBinOp::SRem => {
                                writeln!(writer, "    cqto")?;
                                writeln!(writer, "    idivq %rcx")?;
                                writeln!(writer, "    movq %rdx, %rax")?;
                            }
                            crate::mir::IntBinOp::URem => {
                                writeln!(writer, "    xorq %rdx, %rdx")?;
                                writeln!(writer, "    divq %rcx")?;
                                writeln!(writer, "    movq %rdx, %rax")?;
                            }
                            _ => unreachable!(),
                        }
                    }
                    _ => {
                        let scratch = reg_alloc.alloc_scratch().unwrap_or("rbx");
                        load_operand_to_register(rhs, writer, reg_alloc, stack_slots, scratch)?;

                        match op {
                            crate::mir::IntBinOp::Add => {
                                writeln!(writer, "    addq %{}, %rax", scratch)?
                            }
                            crate::mir::IntBinOp::Sub => {
                                writeln!(writer, "    subq %{}, %rax", scratch)?
                            }
                            crate::mir::IntBinOp::Mul => {
                                writeln!(writer, "    imulq %{}, %rax", scratch)?
                            }
                            crate::mir::IntBinOp::And => {
                                writeln!(writer, "    andq %{}, %rax", scratch)?
                            }
                            crate::mir::IntBinOp::Or => {
                                writeln!(writer, "    orq  %{}, %rax", scratch)?
                            }
                            crate::mir::IntBinOp::Xor => {
                                writeln!(writer, "    xorq %{}, %rax", scratch)?
                            }
                            _ => unreachable!(),
                        }

                        if scratch != "rbx" {
                            reg_alloc.free_scratch(scratch);
                        }
                    }
                }

                if let Register::Virtual(vreg) = dst {
                    store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
                }
            }
        }
        MirInst::IntCmp {
            op,
            dst,
            lhs,
            rhs,
            ty: _,
        } => {
            load_operand_to_rax(lhs, writer, reg_alloc, stack_slots)?;
            let scratch = reg_alloc.alloc_scratch().unwrap_or("rbx");
            load_operand_to_register(rhs, writer, reg_alloc, stack_slots, scratch)?;

            writeln!(writer, "    cmpq %{}, %rax", scratch)?;
            match op {
                crate::mir::IntCmpOp::Eq => writeln!(writer, "    sete %al")?,
                crate::mir::IntCmpOp::Ne => writeln!(writer, "    setne %al")?,
                crate::mir::IntCmpOp::SLt => writeln!(writer, "    setl %al")?,
                crate::mir::IntCmpOp::SLe => writeln!(writer, "    setle %al")?,
                crate::mir::IntCmpOp::SGt => writeln!(writer, "    setg %al")?,
                crate::mir::IntCmpOp::SGe => writeln!(writer, "    setge %al")?,
                crate::mir::IntCmpOp::ULt => writeln!(writer, "    setb %al")?,
                crate::mir::IntCmpOp::ULe => writeln!(writer, "    setbe %al")?,
                crate::mir::IntCmpOp::UGt => writeln!(writer, "    seta %al")?,
                crate::mir::IntCmpOp::UGe => writeln!(writer, "    setae %al")?,
                #[allow(unreachable_patterns)]
                other => {
                    return Err(LaminaError::ValidationError(format!(
                        "x86_64 backend does not support integer comparison {:?}",
                        other
                    )));
                }
            }
            writeln!(writer, "    movzbq %al, %rax")?;

            if let Register::Virtual(vreg) = dst {
                store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
            }

            if scratch != "rbx" {
                reg_alloc.free_scratch(scratch);
            }
        }
        MirInst::Call { name, args, ret } => {
            if name == "print" {
                if let Some(arg) = args.first() {
                    load_operand_to_rax(arg, writer, reg_alloc, stack_slots)?;
                    match target_os {
                        TargetOperatingSystem::MacOS => {
                            writeln!(writer, "    leaq .L_mir_fmt_int(%rip), %rdi")?;
                            writeln!(writer, "    movq %rax, %rsi")?;
                            writeln!(writer, "    call _printf")?;
                            writeln!(writer, "    movq $0, %rdi")?;
                            writeln!(writer, "    call _fflush")?;
                        }
                        TargetOperatingSystem::Windows => {
                            writeln!(writer, "    subq ${}, %rsp", windows::SHADOW_SPACE_SIZE)?;
                            writeln!(writer, "    leaq .L_mir_fmt_int(%rip), %rcx")?;
                            writeln!(writer, "    movq %rax, %rdx")?;
                            writeln!(writer, "    call printf")?;
                            writeln!(writer, "    addq ${}, %rsp", windows::SHADOW_SPACE_SIZE)?;
                            writeln!(writer, "    subq ${}, %rsp", windows::SHADOW_SPACE_SIZE)?;
                            writeln!(writer, "    movq $0, %rcx")?;
                            writeln!(writer, "    call fflush")?;
                            writeln!(writer, "    addq ${}, %rsp", windows::SHADOW_SPACE_SIZE)?;
                        }
                        _ => {
                            writeln!(writer, "    leaq .L_mir_fmt_int(%rip), %rdi")?;
                            writeln!(writer, "    movq %rax, %rsi")?;
                            writeln!(writer, "    xorl %eax, %eax")?;
                            writeln!(writer, "    call printf")?;
                            writeln!(writer, "    movq $0, %rdi")?;
                            writeln!(writer, "    call fflush")?;
                        }
                    }
                }
            } else if name == "writebyte" && args.len() == 1 {
                let arg = args.first().ok_or_else(|| {
                    LaminaError::ValidationError("writebyte requires one argument".to_string())
                })?;
                writeln!(writer, "    subq ${}, %rsp", stack::ALIGNMENT)?;
                load_operand_to_rax(arg, writer, reg_alloc, stack_slots)?;
                writeln!(writer, "    movb %al, (%rsp)")?;

                match target_os {
                    TargetOperatingSystem::MacOS => {
                        writeln!(writer, "    movq ${}, %rax", macos::SYS_WRITE)?;
                        writeln!(writer, "    movq ${}, %rdi", fd::STDOUT)?;
                        writeln!(writer, "    movq %rsp, %rsi")?;
                        writeln!(writer, "    movq $1, %rdx")?;
                        writeln!(writer, "    syscall")?;
                    }
                    _ => {
                        writeln!(writer, "    movq ${}, %rax", linux::SYS_WRITE)?;
                        writeln!(writer, "    movq ${}, %rdi", fd::STDOUT)?;
                        writeln!(writer, "    movq %rsp, %rsi")?;
                        writeln!(writer, "    movq $1, %rdx")?;
                        writeln!(writer, "    syscall")?;
                    }
                }

                if let Some(ret_reg) = ret
                    && let Register::Virtual(vreg) = ret_reg
                {
                    store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
                }

                writeln!(writer, "    addq ${}, %rsp", stack::ALIGNMENT)?;
            } else {
                let abi = X86ABI::new(target_os);
                let arg_regs = abi.arg_registers();
                let num_reg_args = args.len().min(arg_regs.len());
                let num_stack_args = args.len().saturating_sub(arg_regs.len());

                if target_os == TargetOperatingSystem::Windows {
                    let shadow_space = if num_reg_args > 0 {
                        windows::SHADOW_SPACE_SIZE as usize
                    } else {
                        0
                    };
                    let total_stack = shadow_space + (num_stack_args * stack::SLOT_SIZE);
                    if total_stack > 0 {
                        writeln!(writer, "    subq ${}, %rsp", total_stack)?;
                    }
                    for i in 0..num_stack_args {
                        let arg_idx = num_reg_args + i;
                        let arg = &args[arg_idx];
                        let stack_offset = shadow_space + (i * stack::SLOT_SIZE);
                        load_operand_to_rax(arg, writer, reg_alloc, stack_slots)?;
                        writeln!(writer, "    movq %rax, {}(%rsp)", stack_offset)?;
                    }
                } else {
                    for i in (0..num_stack_args).rev() {
                        let arg_idx = num_reg_args + i;
                        let arg = &args[arg_idx];
                        load_operand_to_rax(arg, writer, reg_alloc, stack_slots)?;
                        writeln!(writer, "    pushq %rax")?;
                    }
                }

                for i in 0..num_reg_args {
                    let arg = &args[i];
                    let dest_reg = arg_regs[i];
                    load_operand_to_register(arg, writer, reg_alloc, stack_slots, dest_reg)?;
                }

                let mangled_name = abi.mangle_function_name(name);
                writeln!(writer, "    call {}", mangled_name)?;

                if target_os == TargetOperatingSystem::Windows {
                    let shadow_space = if num_reg_args > 0 {
                        windows::SHADOW_SPACE_SIZE as usize
                    } else {
                        0
                    };
                    let total_stack = shadow_space + (num_stack_args * stack::SLOT_SIZE);
                    if total_stack > 0 {
                        writeln!(writer, "    addq ${}, %rsp", total_stack)?;
                    }
                } else if num_stack_args > 0 {
                    writeln!(
                        writer,
                        "    addq ${}, %rsp",
                        num_stack_args * stack::SLOT_SIZE
                    )?;
                }

                if let Some(ret_reg) = ret
                    && let Register::Virtual(vreg) = ret_reg
                {
                    store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
                }
            }
        }
        MirInst::Load {
            dst,
            addr,
            ty: _,
            attrs: _,
        } => {
            if let crate::mir::AddressMode::BaseOffset { base, offset: 0 } = addr {
                match base {
                    Register::Virtual(vreg) => {
                        load_register_to_rax(vreg, writer, reg_alloc, stack_slots)?;
                    }
                    Register::Physical(phys) => {
                        writeln!(writer, "    movq %{}, %rax", phys.name)?;
                    }
                }
                writeln!(writer, "    movq (%rax), %rax")?;
                if let Register::Virtual(vreg) = dst {
                    store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
                }
            } else {
                return Err(LaminaError::ValidationError(format!(
                    "x86_64 backend does not support load address mode {:?}",
                    addr
                )));
            }
        }
        MirInst::Store {
            addr,
            src,
            ty: _,
            attrs: _,
        } => {
            // Simple direct store for now
            load_operand_to_rax(src, writer, reg_alloc, stack_slots)?;
            if let crate::mir::AddressMode::BaseOffset { base, offset: 0 } = addr {
                let scratch = reg_alloc.alloc_scratch().unwrap_or("rbx");
                match base {
                    Register::Virtual(vreg) => {
                        load_register_to_register(vreg, writer, reg_alloc, stack_slots, scratch)?;
                    }
                    Register::Physical(phys) => {
                        writeln!(writer, "    movq %{}, %{}", phys.name, scratch)?;
                    }
                }
                writeln!(writer, "    movq %rax, (%{})", scratch)?;
                if scratch != "rbx" {
                    reg_alloc.free_scratch(scratch);
                }
            } else {
                return Err(LaminaError::ValidationError(format!(
                    "x86_64 backend does not support store address mode {:?}",
                    addr
                )));
            }
        }
        MirInst::TailCall { name, args } => {
            let abi = X86ABI::new(target_os);
            let arg_regs = abi.arg_registers();
            let num_reg_args = args.len().min(arg_regs.len());
            let num_stack_args = args.len().saturating_sub(arg_regs.len());

            // 1. Handle Register Arguments
            for i in 0..num_reg_args {
                let arg = &args[i];
                let dest_reg = arg_regs[i];
                load_operand_to_register(arg, writer, reg_alloc, stack_slots, dest_reg)?;
            }

            // 2. Handle Stack Arguments (Overwrite incoming args)
            // Note: TailCallOptimization guarantees args.len() == current_func.args.len()
            // So we can strictly overwrite our own incoming stack slots.
            if num_stack_args > 0 {
                let shadow_space = if target_os == TargetOperatingSystem::Windows {
                    windows::SHADOW_SPACE_SIZE as usize
                } else {
                    0
                };

                for i in 0..num_stack_args {
                    let arg_idx = num_reg_args + i;
                    let arg = &args[arg_idx];

                    // Incoming args are at RBP + 16 + shadow + i*8
                    // (Return address is 8, saved RBP pushed, so RBP points to saved RBP)
                    // Wait:
                    // Standard Prologue: push rbp; mov rbp, rsp
                    // Stack:
                    //   [RBP + 16 + shadow + 8*i] -> Arg N (Stack Arg i)
                    //   [RBP + 8]  -> Return Address
                    //   [RBP + 0]  -> Saved RBP
                    //
                    // So first stack arg is at RBP + 16 (on Linux/Mac) or RBP + 16 + 32 (Windows? No shadow is allocated by caller?)
                    // Windows: Shadow space is 32 bytes allocated *by caller* right before return address?
                    // No, shadow space is allocated by caller *above* return address?
                    // Microsoft x64: "The caller allocates space for 4 register parameters..."
                    // Stack: [RetAddr] [Home P1] [Home P2] [Home P3] [Home P4] [Stack Arg 5] ...
                    // Wait, Home space is "Shadow Space". It's strictly for the first 4 args (which are in regs).
                    // Stack args start *after* shadow space.
                    // So RBP + 16 + 32 + i*8.

                    let offset = 16 + shadow_space + (i * stack::SLOT_SIZE);

                    // Load to RAX (scratch) first
                    load_operand_to_rax(arg, writer, reg_alloc, stack_slots)?;

                    // Store to incoming slot
                    writeln!(writer, "    movq %rax, {}(%rbp)", offset)?;
                }
            }

            // 3. Teardown Frame (Epilogue without ret)
            // Restore Stack Pointer
            writeln!(writer, "    movq %rbp, %rsp")?;
            // Restore Base Pointer
            writeln!(writer, "    popq %rbp")?;

            // 4. Jump to target
            let mangled_name = abi.mangle_function_name(name);
            writeln!(writer, "    jmp {}", mangled_name)?;
        }
        MirInst::Lea { dst, base, offset } => {
            match base {
                Register::Virtual(vreg) => {
                    let is_placeholder = !def_regs.contains(vreg);

                    if is_placeholder {
                        if let Some(slot_offset) = stack_slots.get(vreg) {
                            let total_offset = *slot_offset as i64 + (*offset as i64);
                            if total_offset == 0 {
                                writeln!(writer, "    leaq (%rbp), %rax")?;
                            } else {
                                writeln!(writer, "    leaq {}(%rbp), %rax", total_offset)?;
                            }
                        } else {
                            return Err(LaminaError::ValidationError(format!(
                                "LEA placeholder base vreg {:?} has no stack slot",
                                vreg
                            )));
                        }
                    } else if let Some(phys) = reg_alloc.get_mapping_for(vreg) {
                        if *offset == 0 {
                            writeln!(writer, "    movq %{}, %rax", phys)?;
                        } else {
                            writeln!(writer, "    leaq {}(%{}), %rax", offset, phys)?;
                        }
                    } else if let Some(slot_offset) = stack_slots.get(vreg) {
                        let scratch = reg_alloc.alloc_scratch().unwrap_or("rbx");
                        writeln!(writer, "    movq {}(%rbp), %{}", slot_offset, scratch)?;
                        if *offset == 0 {
                            writeln!(writer, "    movq %{}, %rax", scratch)?;
                        } else {
                            writeln!(writer, "    leaq {}(%{}), %rax", offset, scratch)?;
                        }
                        if scratch != "rbx" {
                            reg_alloc.free_scratch(scratch);
                        }
                    } else {
                        return Err(LaminaError::ValidationError(format!(
                            "x86_64 backend cannot lower LEA for base vreg {:?} (no mapping/slot)",
                            vreg
                        )));
                    }
                }
                Register::Physical(phys) => {
                    if *offset == 0 {
                        writeln!(writer, "    movq %{}, %rax", phys.name)?;
                    } else {
                        writeln!(writer, "    leaq {}(%{}), %rax", offset, phys.name)?;
                    }
                }
            }

            if let Register::Virtual(vreg) = dst {
                store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
            }
        }
        MirInst::FloatBinary {
            op,
            ty,
            dst,
            lhs,
            rhs,
        } => {
            let (add, sub, mul, div) = if is_f32(ty) {
                ("addss", "subss", "mulss", "divss")
            } else {
                ("addsd", "subsd", "mulsd", "divsd")
            };
            load_float_operand_to_xmm(lhs, writer, reg_alloc, stack_slots, "xmm0", ty)?;
            load_float_operand_to_xmm(rhs, writer, reg_alloc, stack_slots, "xmm1", ty)?;
            let sse_op = match op {
                crate::mir::FloatBinOp::FAdd => add,
                crate::mir::FloatBinOp::FSub => sub,
                crate::mir::FloatBinOp::FMul => mul,
                crate::mir::FloatBinOp::FDiv => div,
            };
            writeln!(writer, "    {} %xmm1, %xmm0", sse_op)?;
            if let Register::Virtual(vreg) = dst {
                store_xmm_to_register("xmm0", vreg, writer, reg_alloc, stack_slots, ty)?;
            }
        }
        MirInst::FloatUnary { op, ty, dst, src } => {
            load_float_operand_to_xmm(src, writer, reg_alloc, stack_slots, "xmm0", ty)?;
            match op {
                crate::mir::FloatUnOp::FNeg => {
                    if is_f32(ty) {
                        // XOR with the sign bit of f32
                        writeln!(writer, "    movq $0x80000000, %rax")?;
                        writeln!(writer, "    movd %rax, %xmm1")?;
                        writeln!(writer, "    xorps %xmm1, %xmm0")?;
                    } else {
                        // XOR with the sign bit of f64
                        writeln!(writer, "    movq $0x8000000000000000, %rax")?;
                        writeln!(writer, "    movq %rax, %xmm1")?;
                        writeln!(writer, "    xorpd %xmm1, %xmm0")?;
                    }
                }
                crate::mir::FloatUnOp::FSqrt => {
                    let sqrt = if is_f32(ty) { "sqrtss" } else { "sqrtsd" };
                    writeln!(writer, "    {} %xmm0, %xmm0", sqrt)?;
                }
            }
            if let Register::Virtual(vreg) = dst {
                store_xmm_to_register("xmm0", vreg, writer, reg_alloc, stack_slots, ty)?;
            }
        }
        MirInst::FloatCmp {
            op,
            ty,
            dst,
            lhs,
            rhs,
        } => {
            load_float_operand_to_xmm(lhs, writer, reg_alloc, stack_slots, "xmm0", ty)?;
            load_float_operand_to_xmm(rhs, writer, reg_alloc, stack_slots, "xmm1", ty)?;
            let ucomi = if is_f32(ty) { "ucomiss" } else { "ucomisd" };
            writeln!(writer, "    {} %xmm1, %xmm0", ucomi)?;
            match op {
                crate::mir::FloatCmpOp::Eq => writeln!(writer, "    sete %al")?,
                crate::mir::FloatCmpOp::Ne => writeln!(writer, "    setne %al")?,
                crate::mir::FloatCmpOp::Lt => writeln!(writer, "    setb %al")?,
                crate::mir::FloatCmpOp::Le => writeln!(writer, "    setbe %al")?,
                crate::mir::FloatCmpOp::Gt => writeln!(writer, "    seta %al")?,
                crate::mir::FloatCmpOp::Ge => writeln!(writer, "    setae %al")?,
            }
            writeln!(writer, "    movzbq %al, %rax")?;
            if let Register::Virtual(vreg) = dst {
                store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
            }
        }
        MirInst::Select {
            dst,
            cond,
            true_val,
            false_val,
            ty: _,
        } => {
            // Load false_val into a scratch register, true_val into rax.
            // Then test the condition and cmovnz true_val path.
            let scratch = reg_alloc.alloc_scratch().unwrap_or("rbx");
            load_operand_to_register(false_val, writer, reg_alloc, stack_slots, scratch)?;
            load_operand_to_rax(true_val, writer, reg_alloc, stack_slots)?;
            match cond {
                Register::Virtual(vreg) => {
                    if let Some(phys) = reg_alloc.get_mapping_for(vreg) {
                        writeln!(writer, "    testq %{}, %{}", phys, phys)?;
                    } else if let Some(offset) = stack_slots.get(vreg) {
                        writeln!(writer, "    cmpq $0, {}(%rbp)", offset)?;
                    }
                }
                Register::Physical(p) => {
                    writeln!(writer, "    testq %{}, %{}", p.name, p.name)?;
                }
            }
            // cmovz: if condition is zero (false), move scratch into rax
            writeln!(writer, "    cmovzq %{}, %rax", scratch)?;
            if scratch != "rbx" {
                reg_alloc.free_scratch(scratch);
            }
            if let Register::Virtual(vreg) = dst {
                store_rax_to_register(vreg, writer, reg_alloc, stack_slots)?;
            }
        }
        MirInst::Switch {
            value,
            cases,
            default,
        } => {
            // Load switch value into rax, then emit a linear cmp/je chain.
            match value {
                Register::Virtual(vreg) => {
                    load_register_to_rax(vreg, writer, reg_alloc, stack_slots)?;
                }
                Register::Physical(p) => {
                    writeln!(writer, "    movq %{}, %rax", p.name)?;
                }
            }
            for (case_val, case_label) in cases {
                writeln!(writer, "    cmpq ${}, %rax", case_val)?;
                writeln!(writer, "    je .L_{}_{}", func_name, case_label)?;
            }
            writeln!(writer, "    jmp .L_{}_{}", func_name, default)?;
        }
        MirInst::Comment { text } => {
            writeln!(writer, "    # {}", text)?;
        }
        MirInst::Ret { value } => {
            if let Some(val) = value {
                load_operand_to_rax(val, writer, reg_alloc, stack_slots)?;
            }
            // Epilogue
            X86Frame::generate_epilogue(writer, stack_size)?;
        }
        MirInst::Jmp { target } => {
            // Use function-scoped label to avoid collisions
            writeln!(writer, "    jmp .L_{}_{}", func_name, target)?;
        }
        MirInst::Br {
            cond,
            true_target,
            false_target,
        } => {
            if let Register::Virtual(vreg) = cond {
                load_register_to_rax(vreg, writer, reg_alloc, stack_slots)?;
            }
            writeln!(writer, "    testq %rax, %rax")?;
            // Use function-scoped labels to avoid collisions
            writeln!(writer, "    jnz .L_{}_{}", func_name, true_target)?;
            writeln!(writer, "    jmp .L_{}_{}", func_name, false_target)?;
        }
        other => {
            return Err(LaminaError::ValidationError(format!(
                "x86_64 backend does not support MIR instruction {:?}",
                other
            )));
        }
    }

    Ok(())
}