llvm-native-core-ext 0.1.0

Extended modules for llvm-native-core: analysis passes, transforms, codegen extras, bitcode, linker, JIT, utilities. Part of the llvm-native workspace (https://crates.io/crates/llvm-native).
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
// debug_info_v2.rs — World-Class Debug Information Extension
//
// Clean-room forensic-parity expansion:
//   - LLVM's DebugInfoMetadata hierarchy (DICompileUnit, DIFile, DISubprogram, etc.)
//   - DILocation with inlined-at scope chains
//   - DILocalVariable, DIGlobalVariable, DIType full hierarchy
//   - DIExpression with fragment support
//   - DIMacro, DIMacroFile (DWARF 5 macro support)
//   - Debug info stripping / merging
//   - Debug info for optimized code (salvage debug info)
//   - DIVariable debug value tracking
//   - LLVM debug intrinsic handling (llvm.dbg.declare, llvm.dbg.value)
//   - DebugLoc → DILocation mapping

use llvm_native_core::debug_info::{
    DW_AT_location, DW_AT_name, DW_AT_type, DW_LANG_C_plus_plus, DW_TAG_compile_unit,
    DW_TAG_lexical_block, DebugInfoBuilder, ExpressionBuilder, DW_LANG_C,
};
use std::collections::{BTreeMap, HashMap, HashSet};
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};

// ============================================================================
// Section 1: DILocation — Source Location Metadata
// ============================================================================

/// Debug location node (mirrors LLVM's DILocation)
#[derive(Debug, Clone)]
pub struct DILocation {
    /// Line number
    pub line: u32,
    /// Column number
    pub column: u32,
    /// Scope (DIScope reference)
    pub scope: Option<Box<DIScope>>,
    /// Inlined-at location (for inlined call sites)
    pub inlined_at: Option<Box<DILocation>>,
    /// Is this an implicit location (auto-generated code)?
    pub is_implicit_code: bool,
}

impl DILocation {
    pub fn new(line: u32, column: u32, scope: DIScope) -> Self {
        DILocation {
            line,
            column,
            scope: Some(Box::new(scope)),
            inlined_at: None,
            is_implicit_code: false,
        }
    }

    pub fn with_inlined_at(mut self, loc: DILocation) -> Self {
        self.inlined_at = Some(Box::new(loc));
        self
    }

    pub fn get_scope(&self) -> Option<&DIScope> {
        self.scope.as_ref().map(|s| s.as_ref())
    }

    pub fn get_inlined_at(&self) -> Option<&DILocation> {
        self.inlined_at.as_ref().map(|l| l.as_ref())
    }

    pub fn get_line(&self) -> u32 {
        self.line
    }
    pub fn get_column(&self) -> u32 {
        self.column
    }
}

impl fmt::Display for DILocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "line {} col {}", self.line, self.column)?;
        if let Some(ref inlined) = self.inlined_at {
            write!(f, " inlined from {}", inlined)?;
        }
        Ok(())
    }
}

// ============================================================================
// Section 2: DIScope Hierarchy
// ============================================================================

/// Debug info scope (base class)
#[derive(Debug, Clone)]
pub enum DIScope {
    CompileUnit(DICompileUnit),
    File(DIFile),
    Subprogram(DISubprogram),
    LexicalBlock(DILexicalBlock),
    LexicalBlockFile(DILexicalBlockFile),
    Namespace(DINamespace),
    Module(DIModule),
    Type(DIType),
}

impl DIScope {
    pub fn get_name(&self) -> Option<&str> {
        match self {
            DIScope::CompileUnit(cu) => cu.file.as_ref().map(|f| f.name.as_str()),
            DIScope::File(f) => Some(&f.name),
            DIScope::Subprogram(sp) => Some(&sp.name),
            DIScope::LexicalBlock(lb) => lb.name.as_deref(),
            DIScope::Namespace(ns) => Some(&ns.name),
            DIScope::Module(m) => Some(&m.name),
            _ => None,
        }
    }

    pub fn is_subprogram(&self) -> bool {
        matches!(self, DIScope::Subprogram(_))
    }
    pub fn is_compile_unit(&self) -> bool {
        matches!(self, DIScope::CompileUnit(_))
    }
    pub fn is_lexical_block(&self) -> bool {
        matches!(self, DIScope::LexicalBlock(_))
    }
}

/// Compile unit descriptor
#[derive(Debug, Clone)]
pub struct DICompileUnit {
    /// Unique identifier
    pub id: u64,
    /// Source language
    pub language: u16,
    /// Source file
    pub file: Option<DIFile>,
    /// Producer string
    pub producer: String,
    /// Is optimized?
    pub is_optimized: bool,
    /// Compilation flags
    pub flags: String,
    /// Runtime version
    pub runtime_version: u32,
    /// Enum types
    pub enum_types: Vec<u64>,
    /// Retained types
    pub retained_types: Vec<u64>,
    /// Global variables
    pub global_variables: Vec<u64>,
    /// Imported entities
    pub imported_entities: Vec<u64>,
    /// Macros
    pub macros: Vec<u64>,
    /// Split debug inlining?
    pub split_debug_inlining: bool,
    /// Debug info for profiling?
    pub debug_info_for_profiling: bool,
    /// Name table kind
    pub name_table_kind: NameTableKind,
    /// Sysroot
    pub sysroot: String,
    /// SDK
    pub sdk: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NameTableKind {
    None,
    GNU,
    Apple,
    AppleAccel,
}

impl Default for DICompileUnit {
    fn default() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1);
        DICompileUnit {
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
            language: 0,
            file: None,
            producer: String::new(),
            is_optimized: false,
            flags: String::new(),
            runtime_version: 0,
            enum_types: Vec::new(),
            retained_types: Vec::new(),
            global_variables: Vec::new(),
            imported_entities: Vec::new(),
            macros: Vec::new(),
            split_debug_inlining: false,
            debug_info_for_profiling: false,
            name_table_kind: NameTableKind::None,
            sysroot: String::new(),
            sdk: String::new(),
        }
    }
}

/// Source file descriptor
#[derive(Debug, Clone)]
pub struct DIFile {
    /// File name (without path)
    pub name: String,
    /// Directory path
    pub directory: String,
    /// Optional checksum
    pub checksum: Option<DIFileChecksum>,
    /// Source text (for inlined source)
    pub source: Option<String>,
    /// Unique source kind
    pub source_kind: SourceKind,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SourceKind {
    Text,
    Preprocessed,
    Assembly,
    Other,
}

#[derive(Debug, Clone)]
pub struct DIFileChecksum {
    pub kind: ChecksumKind,
    pub value: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChecksumKind {
    MD5,
    SHA1,
    SHA256,
}

impl DIFile {
    pub fn new(name: String, directory: String) -> Self {
        DIFile {
            name,
            directory,
            checksum: None,
            source: None,
            source_kind: SourceKind::Text,
        }
    }

    pub fn get_filename(&self) -> String {
        if self.directory.is_empty() {
            self.name.clone()
        } else {
            format!("{}/{}", self.directory, self.name)
        }
    }
}

/// Subprogram descriptor
#[derive(Debug, Clone)]
pub struct DISubprogram {
    /// Unique identifier
    pub id: u64,
    /// Subprogram name
    pub name: String,
    /// Linkage name (mangled)
    pub linkage_name: String,
    /// Source file
    pub file: Option<DIFile>,
    /// Line number
    pub line: u32,
    /// Type (signature)
    pub ty: Option<DIType>,
    /// Scope (parent)
    pub scope: Option<Box<DIScope>>,
    /// Containing type (for methods)
    pub containing_type: Option<DIType>,
    /// Is this a local function?
    pub is_local: bool,
    /// Is this a definition?
    pub is_definition: bool,
    /// Virtual index (for virtual functions)
    pub virtual_index: u32,
    /// This adjustment
    pub this_adjustment: i32,
    /// Flags
    pub flags: DIFlags,
    /// Is optimized?
    pub is_optimized: bool,
    /// Unit (owning compile unit)
    pub unit: Option<u64>,
    /// Template parameters
    pub template_params: Vec<u64>,
    /// Declaration (for definitions pointing to declarations)
    pub declaration: Option<u64>,
    /// Retained nodes
    pub retained_nodes: Vec<u64>,
    /// Thrown types
    pub thrown_types: Vec<u64>,
}

impl Default for DISubprogram {
    fn default() -> Self {
        static NEXT_ID: AtomicU64 = AtomicU64::new(1000);
        DISubprogram {
            id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
            name: String::new(),
            linkage_name: String::new(),
            file: None,
            line: 0,
            ty: None,
            scope: None,
            containing_type: None,
            is_local: false,
            is_definition: false,
            virtual_index: 0,
            this_adjustment: 0,
            flags: DIFlags::default(),
            is_optimized: false,
            unit: None,
            template_params: Vec::new(),
            declaration: None,
            retained_nodes: Vec::new(),
            thrown_types: Vec::new(),
        }
    }
}

/// Lexical block descriptor
#[derive(Debug, Clone)]
pub struct DILexicalBlock {
    pub scope: Option<Box<DIScope>>,
    pub file: Option<DIFile>,
    pub line: u32,
    pub column: u32,
    pub name: Option<String>,
    pub discriminator: u32,
}

/// Lexical block file (for #line directives)
#[derive(Debug, Clone)]
pub struct DILexicalBlockFile {
    pub scope: Option<Box<DIScope>>,
    pub file: DIFile,
    pub discriminator: u32,
}

/// Namespace descriptor
#[derive(Debug, Clone)]
pub struct DINamespace {
    pub name: String,
    pub scope: Option<Box<DIScope>>,
    pub export_symbols: bool,
}

/// Module descriptor (for Clang modules)
#[derive(Debug, Clone)]
pub struct DIModule {
    pub name: String,
    pub scope: Option<Box<DIScope>>,
    pub configuration_macros: String,
    pub include_path: String,
    pub api_notes_file: String,
}

// ============================================================================
// Section 3: DIType Hierarchy
// ============================================================================

/// Debug info type (mirrors LLVM's DIType hierarchy)
#[derive(Debug, Clone)]
pub enum DIType {
    Basic(DIBasicType),
    Derived(DIDerivedType),
    Composite(DICompositeType),
    Subroutine(DISubroutineType),
    ForwardDeclaration(DIForwardDecl),
    Unspecified,
}

/// Basic type (int, float, char, etc.)
#[derive(Debug, Clone)]
pub struct DIBasicType {
    pub name: String,
    pub size_in_bits: u64,
    pub encoding: u32,
    pub flags: DIFlags,
}

/// Derived type (pointer, reference, typedef, const, volatile, etc.)
#[derive(Debug, Clone)]
pub struct DIDerivedType {
    pub tag: u16,
    pub name: String,
    pub base_type: Option<Box<DIType>>,
    pub size_in_bits: u64,
    pub align_in_bits: u64,
    pub offset_in_bits: u64,
    pub flags: DIFlags,
    pub extra_data: Option<u64>,
    pub dwarf_address_space: Option<u32>,
}

/// Composite type (struct, class, union, array, enum, vector)
#[derive(Debug, Clone)]
pub struct DICompositeType {
    pub tag: u16,
    pub name: String,
    pub file: Option<DIFile>,
    pub line: u32,
    pub scope: Option<Box<DIScope>>,
    pub base_type: Option<Box<DIType>>,
    pub size_in_bits: u64,
    pub align_in_bits: u64,
    pub offset_in_bits: u64,
    pub flags: DIFlags,
    pub elements: Vec<u64>,
    pub runtime_lang: u32,
    pub vtable_holder: Option<Box<DIType>>,
    pub template_params: Vec<u64>,
    pub identifier: String,
    pub discriminator: Option<u64>,
    pub data_location: Option<Box<DIExpression>>,
    pub associated: Option<Box<DIExpression>>,
    pub allocated: Option<Box<DIExpression>>,
    pub rank: Option<u32>,
}

/// Subroutine type (function signature)
#[derive(Debug, Clone)]
pub struct DISubroutineType {
    pub flags: DIFlags,
    pub cc: u32,
    pub types: Vec<DIType>,
}

/// Forward declaration
#[derive(Debug, Clone)]
pub struct DIForwardDecl {
    pub tag: u16,
    pub name: String,
    pub file: Option<DIFile>,
    pub line: u32,
    pub scope: Option<Box<DIScope>>,
    pub identifier: String,
    pub flags: DIFlags,
}

/// Debug info flags (AccessFlag, etc.)
#[derive(Debug, Clone, Copy, Default)]
pub struct DIFlags {
    pub is_private: bool,
    pub is_protected: bool,
    pub is_public: bool,
    pub is_explicit: bool,
    pub is_prototyped: bool,
    pub is_artificial: bool,
    pub is_virtual: bool,
    pub is_pure_virtual: bool,
    pub is_optimized: bool,
    pub is_main_subprogram: bool,
    pub is_definition: bool,
    pub is_export_symbols: bool,
    pub is_imported: bool,
    pub is_rvalue_reference: bool,
    pub is_big_endian: bool,
    pub is_little_endian: bool,
    pub is_trivial: bool,
    pub is_pass_by_value: bool,
    pub is_noderef: bool,
    pub is_object_pointer: bool,
    pub is_static_data_member: bool,
    pub is_indirect_virtual_base: bool,
    pub is_fixed_enum: bool,
}

impl DIFlags {
    pub fn apply(&self, _tag: u16) {}
}

// ============================================================================
// Section 4: DILocalVariable / DIGlobalVariable
// ============================================================================

/// Local variable descriptor
#[derive(Debug, Clone)]
pub struct DILocalVariable {
    pub name: String,
    pub scope: Option<Box<DIScope>>,
    pub file: Option<DIFile>,
    pub line: u32,
    pub ty: Option<DIType>,
    pub arg: u32, // Argument number (1-based), 0 if not an argument
    pub flags: DIFlags,
    pub align_in_bits: u32,
}

impl DILocalVariable {
    pub fn new(name: String, ty: DIType, arg: u32) -> Self {
        DILocalVariable {
            name,
            scope: None,
            file: None,
            line: 0,
            ty: Some(ty),
            arg,
            flags: DIFlags::default(),
            align_in_bits: 0,
        }
    }

    pub fn with_scope(mut self, scope: DIScope) -> Self {
        self.scope = Some(Box::new(scope));
        self
    }

    pub fn with_file(mut self, file: DIFile) -> Self {
        self.file = Some(file);
        self
    }

    pub fn with_line(mut self, line: u32) -> Self {
        self.line = line;
        self
    }

    pub fn is_parameter(&self) -> bool {
        self.arg > 0
    }
}

/// Global variable descriptor
#[derive(Debug, Clone)]
pub struct DIGlobalVariable {
    pub name: String,
    pub linkage_name: String,
    pub scope: Option<Box<DIScope>>,
    pub file: Option<DIFile>,
    pub line: u32,
    pub ty: Option<DIType>,
    pub is_local: bool,
    pub is_definition: bool,
    pub declaration: Option<u64>,
    pub align_in_bits: u32,
}

/// Global variable expression
#[derive(Debug, Clone)]
pub struct DIGlobalVariableExpression {
    pub variable: u64,
    pub expression: Option<Box<DIExpression>>,
}

// ============================================================================
// Section 5: DIExpression — DWARF Expression
// ============================================================================

/// DWARF expression with fragment support
#[derive(Debug, Clone)]
pub struct DIExpression {
    /// Encoded operations
    pub operations: Vec<DIExpressionOp>,
    /// Number of elements
    pub num_elements: usize,
}

#[derive(Debug, Clone)]
pub enum DIExpressionOp {
    /// Simple DW_OP code
    Simple(u8),
    /// Operation with single unsigned argument
    UnsignedArg(u8, u64),
    /// Operation with single signed argument
    SignedArg(u8, i64),
    /// LLVM fragment (offset_in_bits, size_in_bits)
    Fragment(u64, u64),
}

impl DIExpression {
    pub fn new() -> Self {
        DIExpression {
            operations: Vec::new(),
            num_elements: 0,
        }
    }

    pub fn from_opcodes(ops: &[u8]) -> Self {
        let mut expr = DIExpression::new();
        for &op in ops {
            expr.operations.push(DIExpressionOp::Simple(op));
            expr.num_elements += 1;
        }
        expr
    }

    pub fn append_op(&mut self, op: DIExpressionOp) {
        self.num_elements += 1;
        self.operations.push(op);
    }

    pub fn append_fragment(&mut self, offset_in_bits: u64, size_in_bits: u64) {
        self.operations
            .push(DIExpressionOp::Fragment(offset_in_bits, size_in_bits));
        self.num_elements += 1;
    }

    pub fn is_empty(&self) -> bool {
        self.operations.is_empty()
    }

    pub fn is_complex(&self) -> bool {
        self.operations.len() > 1
    }

    pub fn get_fragment_info(&self) -> Option<(u64, u64)> {
        for op in &self.operations {
            if let DIExpressionOp::Fragment(off, size) = op {
                return Some((*off, *size));
            }
        }
        None
    }

    /// Create a fragment expression covering bits
    pub fn create_fragment(offset_in_bits: u64, size_in_bits: u64) -> Self {
        let mut expr = DIExpression::new();
        expr.append_fragment(offset_in_bits, size_in_bits);
        expr
    }

    /// Salvage debug info: adjust expression for optimization
    pub fn prepend(&mut self, other: &DIExpression) {
        let mut new_ops = other.operations.clone();
        new_ops.extend(self.operations.clone());
        self.operations = new_ops;
        self.num_elements = self.operations.len();
    }

    pub fn append(&mut self, other: &DIExpression) {
        self.operations.extend(other.operations.clone());
        self.num_elements = self.operations.len();
    }
}

impl Default for DIExpression {
    fn default() -> Self {
        DIExpression::new()
    }
}

// ============================================================================
// Section 6: DIMacro / DIMacroFile (DWARF 5)
// ============================================================================

/// Macro descriptor
#[derive(Debug, Clone)]
pub struct DIMacro {
    pub ty: MacroType,
    pub line: u32,
    pub name: String,
    pub value: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MacroType {
    Define = 0x01,
    Undef = 0x02,
    StartFile = 0x03,
    EndFile = 0x04,
    DefineStmt = 0x05,
    UndefStmt = 0x06,
    DefineIndirect = 0x07,
    UndefIndirect = 0x08,
    TransparentInclude = 0x09,
}

/// Macro file descriptor
#[derive(Debug, Clone)]
pub struct DIMacroFile {
    pub file: Option<DIFile>,
    pub line: u32,
    pub macros: Vec<u64>,
}

// ============================================================================
// Section 7: DIImportedEntity and DITemplateParameter
// ============================================================================

/// Imported entity (using declaration/directive)
#[derive(Debug, Clone)]
pub struct DIImportedEntity {
    pub tag: u16,
    pub scope: Option<Box<DIScope>>,
    pub entity: Option<u64>,
    pub file: Option<DIFile>,
    pub line: u32,
    pub name: String,
}

/// Template type parameter
#[derive(Debug, Clone)]
pub struct DITemplateTypeParameter {
    pub name: String,
    pub ty: Option<DIType>,
}

/// Template value parameter
#[derive(Debug, Clone)]
pub struct DITemplateValueParameter {
    pub name: String,
    pub ty: Option<DIType>,
    pub value: Option<u64>,
}

// ============================================================================
// Section 8: Debug Info Stripping
// ============================================================================

/// Debug info stripper configuration
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DebugInfoKind {
    /// No debug info
    None,
    /// Line tables only
    LineTablesOnly,
    /// Full debug info
    Full,
    /// Limited debug info (for optimized builds)
    Limited,
    /// Constructor homing (type info stays in module with constructor)
    ConstructorHoming,
}

/// Strips debug info from modules
pub struct DebugInfoStripper {
    pub keep_kind: DebugInfoKind,
    pub keep_functions: HashSet<String>,
}

impl DebugInfoStripper {
    pub fn new(kind: DebugInfoKind) -> Self {
        DebugInfoStripper {
            keep_kind: kind,
            keep_functions: HashSet::new(),
        }
    }

    /// Determine what debug info to keep for a function
    pub fn keep_for_function(&self, name: &str, _subprogram: &DISubprogram) -> DebugInfoKind {
        if self.keep_functions.contains(name) {
            return DebugInfoKind::Full;
        }
        self.keep_kind
    }

    /// Strip debug info from a subprogram
    pub fn strip_subprogram(&self, sub: &mut DISubprogram, kind: DebugInfoKind) {
        match kind {
            DebugInfoKind::None => {
                sub.name.clear();
                sub.linkage_name.clear();
                sub.file = None;
            }
            DebugInfoKind::LineTablesOnly => {
                // Keep line info but drop everything else
                sub.linkage_name.clear();
                sub.ty = None;
            }
            DebugInfoKind::Limited => {
                sub.linkage_name.clear();
            }
            DebugInfoKind::Full | DebugInfoKind::ConstructorHoming => {
                // Keep everything
            }
        }
    }
}

// ============================================================================
// Section 9: Debug Value Tracking
// ============================================================================

/// Track debug value assignments across optimization
#[derive(Debug, Clone)]
pub struct DebugValue {
    pub variable: DILocalVariable,
    pub expression: DIExpression,
    pub location: DILocation,
    pub value: DebugValueKind,
}

#[derive(Debug, Clone)]
pub enum DebugValueKind {
    /// Variable is in a register
    Register(u32),
    /// Variable is at a memory address
    Memory(u64),
    /// Variable is a constant
    Constant(i64),
    /// Variable is undefined
    Undef,
    /// Variable location is unknown
    Unknown,
}

/// Maintains debug variable -> value mappings
pub struct DebugValueTracker {
    pub values: HashMap<String, Vec<DebugValue>>,
}

impl DebugValueTracker {
    pub fn new() -> Self {
        DebugValueTracker {
            values: HashMap::new(),
        }
    }

    pub fn record_declare(
        &mut self,
        variable: DILocalVariable,
        expression: DIExpression,
        location: DILocation,
        reg: u32,
    ) {
        let key = variable.name.clone();
        self.values.entry(key).or_default().push(DebugValue {
            variable,
            expression,
            location,
            value: DebugValueKind::Register(reg),
        });
    }

    pub fn record_value(
        &mut self,
        variable: DILocalVariable,
        expression: DIExpression,
        location: DILocation,
        value: DebugValueKind,
    ) {
        let key = variable.name.clone();
        self.values.entry(key).or_default().push(DebugValue {
            variable,
            expression,
            location,
            value,
        });
    }

    pub fn get_values(&self, var_name: &str) -> Option<&Vec<DebugValue>> {
        self.values.get(var_name)
    }

    pub fn clear(&mut self) {
        self.values.clear();
    }
}

impl Default for DebugValueTracker {
    fn default() -> Self {
        DebugValueTracker::new()
    }
}

// ============================================================================
// Section 10: Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_di_location() {
        let file = DIFile::new("test.c".to_string(), "/src".to_string());
        let scope = DIScope::File(file);
        let loc = DILocation::new(10, 5, scope);
        assert_eq!(loc.get_line(), 10);
        assert_eq!(loc.get_column(), 5);
    }

    #[test]
    fn test_di_compile_unit() {
        let mut cu = DICompileUnit::default();
        cu.language = 12; // DW_LANG_C99
        cu.producer = "llvm-native 1.0".to_string();
        assert_eq!(cu.language, 12);
    }

    #[test]
    fn test_di_expression_fragment() {
        let expr = DIExpression::create_fragment(0, 32);
        assert!(expr.is_complex());
        let (off, size) = expr.get_fragment_info().unwrap();
        assert_eq!(off, 0);
        assert_eq!(size, 32);
    }

    #[test]
    fn test_di_expression_prepend() {
        let mut expr = DIExpression::create_fragment(32, 32);
        let prefix = DIExpression::from_opcodes(&[0x70]); // DW_OP_piece
        expr.prepend(&prefix);
        assert!(expr.is_complex());
    }

    #[test]
    fn test_difile_get_filename() {
        let file = DIFile::new("main.c".to_string(), "/home/user".to_string());
        assert_eq!(file.get_filename(), "/home/user/main.c");
    }

    #[test]
    fn test_di_local_variable() {
        let basic = DIType::Basic(DIBasicType {
            name: "int".to_string(),
            size_in_bits: 32,
            encoding: 5, // DW_ATE_signed
            flags: DIFlags::default(),
        });
        let var = DILocalVariable::new("x".to_string(), basic, 1);
        assert!(var.is_parameter());
        assert_eq!(var.name, "x");
    }

    #[test]
    fn test_debug_value_tracker() {
        let mut tracker = DebugValueTracker::new();
        let var = DILocalVariable::new("count".to_string(), DIType::Unspecified, 0);
        let expr = DIExpression::new();
        let loc = DILocation::new(
            42,
            1,
            DIScope::File(DIFile::new("f.c".to_string(), ".".to_string())),
        );
        tracker.record_declare(var, expr, loc, 5);
        assert!(tracker.get_values("count").is_some());
    }

    #[test]
    fn test_debug_info_stripper() {
        let mut stripper = DebugInfoStripper::new(DebugInfoKind::LineTablesOnly);
        stripper.keep_functions.insert("important_fn".to_string());
        assert_eq!(
            stripper.keep_for_function("important_fn", &DISubprogram::default()),
            DebugInfoKind::Full
        );
        assert_eq!(
            stripper.keep_for_function("boring_fn", &DISubprogram::default()),
            DebugInfoKind::LineTablesOnly
        );
    }

    #[test]
    fn test_di_scope_name() {
        let ns = DIScope::Namespace(DINamespace {
            name: "std".to_string(),
            scope: None,
            export_symbols: true,
        });
        assert_eq!(ns.get_name(), Some("std"));
    }

    #[test]
    fn test_di_flags() {
        let mut flags = DIFlags::default();
        flags.is_private = true;
        flags.is_virtual = true;
        assert!(flags.is_private);
        assert!(flags.is_virtual);
        assert!(!flags.is_protected);
    }
}