-
Notifications
You must be signed in to change notification settings - Fork 273
Expand file tree
/
Copy pathdebug_info.rs
More file actions
1759 lines (1625 loc) · 58.2 KB
/
Copy pathdebug_info.rs
File metadata and controls
1759 lines (1625 loc) · 58.2 KB
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
//! Debug symbols - `DebugInfoBuilder` interface
//!
//! # Example usage
//!
//! ## Setting up the module for holding debug info:
//! ```ignore
//! let context = Context::create();
//! let module = context.create_module("bin");
//!
//! let debug_metadata_version = context.i32_type().const_int(3, false);
//! module.add_basic_value_flag(
//! "Debug Info Version",
//! inkwell::module::FlagBehavior::Warning,
//! debug_metadata_version,
//! );
//! let builder = context.create_builder();
//! let (dibuilder, compile_unit) = module.create_debug_info_builder(
//! true,
//! /* language */ inkwell::debug_info::DWARFSourceLanguage::C,
//! /* filename */ "source_file",
//! /* directory */ ".",
//! /* producer */ "my llvm compiler frontend",
//! /* is_optimized */ false,
//! /* compiler command line flags */ "",
//! /* runtime_ver */ 0,
//! /* split_name */ "",
//! /* kind */ inkwell::debug_info::DWARFEmissionKind::Full,
//! /* dwo_id */ 0,
//! /* split_debug_inling */ false,
//! /* debug_info_for_profiling */ false,
//! );
//! ```
//! ## Creating function debug info
//! ```ignore
//! let ditype = dibuilder.create_basic_type(
//! "type_name",
//! 0_u64,
//! 0x00,
//! inkwell::debug_info::DIFlags::Public,
//! ).unwrap();
//! let subroutine_type = dibuilder.create_subroutine_type(
//! compile_unit.get_file(),
//! /* return type */ Some(ditype.as_type()),
//! /* parameter types */ &[],
//! inkwell::debug_info::DIFlags::Public,
//! );
//! let func_scope: DISubprogram<'_> = dibuilder.create_function(
//! /* scope */ compile_unit.as_debug_info_scope(),
//! /* func name */ "main",
//! /* linkage_name */ None,
//! /* file */ compile_unit.get_file(),
//! /* line_no */ 0,
//! /* DIType */ subroutine_type,
//! /* is_local_to_unit */ true,
//! /* is_definition */ true,
//! /* scope_line */ 0,
//! /* flags */ inkwell::debug_info::DIFlags::Public,
//! /* is_optimized */ false,
//! );
//! ```
//! The `DISubprogram` value must be attached to the generated `FunctionValue`:
//! ```ignore
//! /* after creating function: */
//! let fn_val = module.add_function(fn_name_str, fn_type, None);
//! fn_val.set_subprogram(func_scope);
//! ```
//!
//! ## Setting debug locations
//! ```ignore
//! let lexical_block = dibuilder.create_lexical_block(
//! /* scope */ func_scope.as_debug_info_scope(),
//! /* file */ compile_unit.get_file(),
//! /* line_no */ 0,
//! /* column_no */ 0);
//!
//! let loc = dibuilder
//! .create_debug_location(&context, /* line */ 0, /* column */ 0,
//! /* current_scope */ lexical_block.as_debug_info_scope(),
//! /* inlined_at */ None);
//! builder.set_current_debug_location(&context, loc);
//!
//! // Create global variable
//! let gv = module.add_global(context.i64_type(), Some(inkwell::AddressSpace::Global), "gv");
//!
//!
//! let const_v = di.create_constant_expression(10);
//!
//! let gv_debug = di.create_global_variable_expression(cu.get_file().as_debug_info_scope(), "gv", "", cu.get_file(), 1, ditype.as_type(), true, Some(const_v), None, 8);
//!
//! let meta_value: inkwell::values::BasicMetadataValueEnum = gv_debug.as_metadata_value(&context).into();
//! let metadata = context.metadata_node(&[meta_value]);
//! gv.set_metadata(metadata, 0);//dbg
//!
//! ```
//!
//! ## Finalize debug info
//! Before any kind of code generation (including verification passes; they generate code and
//! validate debug info), do:
//! ```ignore
//! dibuilder.finalize();
//! ```
use crate::basic_block::BasicBlock;
use crate::context::{AsContextRef, Context};
pub use crate::debug_info::flags::{DIFlags, DIFlagsConstants};
use crate::module::Module;
use crate::values::{AsValueRef, BasicValueEnum, InstructionValue, MetadataValue, PointerValue};
use crate::AddressSpace;
use llvm_sys::core::LLVMMetadataAsValue;
use llvm_sys::debuginfo::LLVMDIBuilderCreateTypedef;
pub use llvm_sys::debuginfo::LLVMDWARFTypeEncoding;
use llvm_sys::debuginfo::LLVMDebugMetadataVersion;
use llvm_sys::debuginfo::LLVMDisposeDIBuilder;
use llvm_sys::debuginfo::LLVMMetadataReplaceAllUsesWith;
use llvm_sys::debuginfo::LLVMTemporaryMDNode;
use llvm_sys::debuginfo::{LLVMCreateDIBuilder, LLVMCreateDIBuilderDisallowUnresolved};
use llvm_sys::debuginfo::{
LLVMDIBuilderCreateArrayType, LLVMDIBuilderCreateAutoVariable, LLVMDIBuilderCreateBasicType,
LLVMDIBuilderCreateCompileUnit, LLVMDIBuilderCreateDebugLocation, LLVMDIBuilderCreateExpression,
LLVMDIBuilderCreateFile, LLVMDIBuilderCreateFunction, LLVMDIBuilderCreateLexicalBlock,
LLVMDIBuilderCreateMemberType, LLVMDIBuilderCreateNameSpace, LLVMDIBuilderCreateParameterVariable,
LLVMDIBuilderCreatePointerType, LLVMDIBuilderCreateReferenceType, LLVMDIBuilderCreateStructType,
LLVMDIBuilderCreateSubroutineType, LLVMDIBuilderCreateUnionType, LLVMDIBuilderFinalize,
LLVMDIBuilderGetOrCreateSubrange, LLVMDILocationGetColumn, LLVMDILocationGetLine, LLVMDILocationGetScope,
LLVMDITypeGetAlignInBits, LLVMDITypeGetOffsetInBits, LLVMDITypeGetSizeInBits,
};
#[llvm_versions(..19.1)]
use llvm_sys::debuginfo::{
LLVMDIBuilderInsertDbgValueBefore, LLVMDIBuilderInsertDeclareAtEnd, LLVMDIBuilderInsertDeclareBefore,
};
#[llvm_versions(19.1..)]
use llvm_sys::debuginfo::{
LLVMDIBuilderInsertDbgValueRecordBefore as LLVMDIBuilderInsertDbgValueBefore,
LLVMDIBuilderInsertDeclareRecordAtEnd as LLVMDIBuilderInsertDeclareAtEnd,
LLVMDIBuilderInsertDeclareRecordBefore as LLVMDIBuilderInsertDeclareBefore,
};
#[llvm_versions(19.1..)]
use llvm_sys::prelude::LLVMValueRef;
use llvm_sys::debuginfo::{LLVMDIBuilderCreateConstantValueExpression, LLVMDIBuilderCreateGlobalVariableExpression};
use llvm_sys::prelude::{LLVMDIBuilderRef, LLVMMetadataRef};
use std::convert::TryInto;
use std::marker::PhantomData;
use std::ops::Range;
/// Gets the version of debug metadata produced by the current LLVM version.
pub fn debug_metadata_version() -> libc::c_uint {
unsafe { LLVMDebugMetadataVersion() }
}
/// A builder object to create debug info metadata. Used along with `Builder` while producing
/// IR. Created by `Module::create_debug_info_builder`. See `debug_info` module level
/// documentation for more.
#[derive(Debug, PartialEq, Eq)]
pub struct DebugInfoBuilder<'ctx> {
pub(crate) builder: LLVMDIBuilderRef,
_marker: PhantomData<&'ctx Context>,
}
/// Any kind of debug information scope (i.e. visibility of a source code symbol). Scopes are
/// created by special `DebugInfoBuilder` methods (eg `create_lexical_block`) and can be turned
/// into a `DIScope` with the `AsDIScope::as_debug_info_scope` trait method.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct DIScope<'ctx> {
metadata_ref: LLVMMetadataRef,
_marker: PhantomData<&'ctx Context>,
}
impl<'ctx> DIScope<'ctx> {
pub fn as_metadata_value(&self, context: impl AsContextRef<'ctx>) -> MetadataValue<'ctx> {
unsafe { MetadataValue::new(LLVMMetadataAsValue(context.as_ctx_ref(), self.metadata_ref)) }
}
/// Acquires the underlying raw pointer belonging to this `DIScope` type.
pub fn as_mut_ptr(&self) -> LLVMMetadataRef {
self.metadata_ref
}
}
/// Specific scopes (i.e. `DILexicalBlock`) can be turned into a `DIScope` with the
/// `AsDIScope::as_debug_info_scope` trait method.
pub trait AsDIScope<'ctx> {
#[allow(clippy::wrong_self_convention)]
fn as_debug_info_scope(self) -> DIScope<'ctx>;
}
impl<'ctx> DebugInfoBuilder<'ctx> {
pub(crate) fn new(
module: &Module,
allow_unresolved: bool,
language: DWARFSourceLanguage,
filename: &str,
directory: &str,
producer: &str,
is_optimized: bool,
flags: &str,
runtime_ver: libc::c_uint,
split_name: &str,
kind: DWARFEmissionKind,
dwo_id: libc::c_uint,
split_debug_inlining: bool,
debug_info_for_profiling: bool,
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
sysroot: &str,
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
sdk: &str,
) -> (Self, DICompileUnit<'ctx>) {
let builder = unsafe {
if allow_unresolved {
LLVMCreateDIBuilder(module.module.get())
} else {
LLVMCreateDIBuilderDisallowUnresolved(module.module.get())
}
};
let builder = DebugInfoBuilder {
builder,
_marker: PhantomData,
};
let file = builder.create_file(filename, directory);
let cu = builder.create_compile_unit(
language,
file,
producer,
is_optimized,
flags,
runtime_ver,
split_name,
kind,
dwo_id,
split_debug_inlining,
debug_info_for_profiling,
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
sysroot,
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
sdk,
);
(builder, cu)
}
/// Acquires the underlying raw pointer belonging to this `DebugInfoBuilder` type.
pub fn as_mut_ptr(&self) -> LLVMDIBuilderRef {
self.builder
}
/// A DICompileUnit provides an anchor for all debugging information generated during this instance of compilation.
///
/// * `language` - Source programming language
/// * `file` - File info
/// * `producer` - Identify the producer of debugging information and code. Usually this is a compiler version string.
/// * `is_optimized` - A boolean flag which indicates whether optimization is enabled or not.
/// * `flags` - This string lists command line options. This string is directly embedded in debug info output which may be used by a tool analyzing generated debugging information.
/// * `runtime_ver` - This indicates runtime version for languages like Objective-C.
/// * `split_name` - The name of the file that we'll split debug info out into.
/// * `kind` - The kind of debug information to generate.
/// * `dwo_id` - The DWOId if this is a split skeleton compile unit.
/// * `split_debug_inlining` - Whether to emit inline debug info.
/// * `debug_info_for_profiling` - Whether to emit extra debug info for profile collection.
fn create_compile_unit(
&self,
language: DWARFSourceLanguage,
file: DIFile<'ctx>,
producer: &str,
is_optimized: bool,
flags: &str,
runtime_ver: libc::c_uint,
split_name: &str,
kind: DWARFEmissionKind,
dwo_id: libc::c_uint,
split_debug_inlining: bool,
debug_info_for_profiling: bool,
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
sysroot: &str,
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
sdk: &str,
) -> DICompileUnit<'ctx> {
let metadata_ref = unsafe {
#[cfg(any(feature = "llvm8-0", feature = "llvm9-0", feature = "llvm10-0"))]
{
LLVMDIBuilderCreateCompileUnit(
self.builder,
language.into(),
file.metadata_ref,
producer.as_ptr() as _,
producer.len(),
is_optimized as _,
flags.as_ptr() as _,
flags.len(),
runtime_ver,
split_name.as_ptr() as _,
split_name.len(),
kind.into(),
dwo_id,
split_debug_inlining as _,
debug_info_for_profiling as _,
)
}
#[cfg(any(
feature = "llvm11-0",
feature = "llvm12-0",
feature = "llvm13-0",
feature = "llvm14-0",
feature = "llvm15-0",
feature = "llvm16-0",
feature = "llvm17-0",
feature = "llvm18-1",
feature = "llvm19-1",
feature = "llvm20-1"
))]
{
LLVMDIBuilderCreateCompileUnit(
self.builder,
language.into(),
file.metadata_ref,
producer.as_ptr() as _,
producer.len(),
is_optimized as _,
flags.as_ptr() as _,
flags.len(),
runtime_ver,
split_name.as_ptr() as _,
split_name.len(),
kind.into(),
dwo_id,
split_debug_inlining as _,
debug_info_for_profiling as _,
sysroot.as_ptr() as _,
sysroot.len(),
sdk.as_ptr() as _,
sdk.len(),
)
}
};
DICompileUnit {
file,
metadata_ref,
_marker: PhantomData,
}
}
/// A DIFunction provides an anchor for all debugging information generated for the specified subprogram.
///
/// * `scope` - Function scope.
/// * `name` - Function name.
/// * `linkage_name` - Mangled function name, if any.
/// * `file` - File where this variable is defined.
/// * `line_no` - Line number.
/// * `ty` - Function type.
/// * `is_local_to_unit` - True if this function is not externally visible.
/// * `is_definition` - True if this is a function definition ("When isDefinition: false,
/// subprograms describe a declaration in the type tree as opposed to a definition of a
/// function").
/// * `scope_line` - Set to the beginning of the scope this starts
/// * `flags` - E.g.: LLVMDIFlagLValueReference. These flags are used to emit dwarf attributes.
/// * `is_optimized` - True if optimization is ON.
pub fn create_function(
&self,
scope: DIScope<'ctx>,
name: &str,
linkage_name: Option<&str>,
file: DIFile<'ctx>,
line_no: u32,
ditype: DISubroutineType<'ctx>,
is_local_to_unit: bool,
is_definition: bool,
scope_line: u32,
flags: DIFlags,
is_optimized: bool,
) -> DISubprogram<'ctx> {
let linkage_name = linkage_name.unwrap_or(name);
let metadata_ref = unsafe {
LLVMDIBuilderCreateFunction(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
linkage_name.as_ptr() as _,
linkage_name.len(),
file.metadata_ref,
line_no,
ditype.metadata_ref,
is_local_to_unit as _,
is_definition as _,
scope_line as libc::c_uint,
flags,
is_optimized as _,
)
};
DISubprogram {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a lexical block scope.
pub fn create_lexical_block(
&self,
parent_scope: DIScope<'ctx>,
file: DIFile<'ctx>,
line: u32,
column: u32,
) -> DILexicalBlock<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateLexicalBlock(
self.builder,
parent_scope.metadata_ref,
file.metadata_ref,
line as libc::c_uint,
column as libc::c_uint,
)
};
DILexicalBlock {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a file scope.
pub fn create_file(&self, filename: &str, directory: &str) -> DIFile<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateFile(
self.builder,
filename.as_ptr() as _,
filename.len(),
directory.as_ptr() as _,
directory.len(),
)
};
DIFile {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a debug location.
pub fn create_debug_location(
&self,
context: impl AsContextRef<'ctx>,
line: u32,
column: u32,
scope: DIScope<'ctx>,
inlined_at: Option<DILocation<'ctx>>,
) -> DILocation<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateDebugLocation(
context.as_ctx_ref(),
line,
column,
scope.metadata_ref,
inlined_at.map(|l| l.metadata_ref).unwrap_or(std::ptr::null_mut()),
)
};
DILocation {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a primitive basic type. `encoding` is an unsigned int flag (`DW_ATE_*`
/// enum) defined by the chosen DWARF standard.
pub fn create_basic_type(
&self,
name: &str,
size_in_bits: u64,
encoding: LLVMDWARFTypeEncoding,
flags: DIFlags,
) -> Result<DIBasicType<'ctx>, crate::error::Error> {
if name.is_empty() {
// Also, LLVM returns the same type if you ask for the same
// (name, size_in_bits, encoding).
return Err(crate::error::Error::EmptyNameError);
}
let metadata_ref = unsafe {
LLVMDIBuilderCreateBasicType(
self.builder,
name.as_ptr() as _,
name.len(),
size_in_bits,
encoding,
flags,
)
};
Ok(DIBasicType {
metadata_ref,
_marker: PhantomData,
})
}
/// Create a typedef (alias) of `ditype`
pub fn create_typedef(
&self,
ditype: DIType<'ctx>,
name: &str,
file: DIFile<'ctx>,
line_no: u32,
scope: DIScope<'ctx>,
#[cfg(not(any(feature = "llvm8-0", feature = "llvm9-0")))] align_in_bits: u32,
) -> DIDerivedType<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateTypedef(
self.builder,
ditype.metadata_ref,
name.as_ptr() as _,
name.len(),
file.metadata_ref,
line_no,
scope.metadata_ref,
#[cfg(not(any(feature = "llvm8-0", feature = "llvm9-0")))]
align_in_bits,
)
};
DIDerivedType {
metadata_ref,
_marker: PhantomData,
}
}
/// Create union type of multiple types.
pub fn create_union_type(
&self,
scope: DIScope<'ctx>,
name: &str,
file: DIFile<'ctx>,
line_no: u32,
size_in_bits: u64,
align_in_bits: u32,
flags: DIFlags,
elements: &[DIType<'ctx>],
runtime_language: u32,
unique_id: &str,
) -> DICompositeType<'ctx> {
let mut elements: Vec<LLVMMetadataRef> = elements.iter().map(|dt| dt.metadata_ref).collect();
let metadata_ref = unsafe {
LLVMDIBuilderCreateUnionType(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
file.metadata_ref,
line_no,
size_in_bits,
align_in_bits,
flags,
elements.as_mut_ptr(),
elements.len().try_into().unwrap(),
runtime_language,
unique_id.as_ptr() as _,
unique_id.len(),
)
};
DICompositeType {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a type for a non-static member.
pub fn create_member_type(
&self,
scope: DIScope<'ctx>,
name: &str,
file: DIFile<'ctx>,
line_no: libc::c_uint,
size_in_bits: u64,
align_in_bits: u32,
offset_in_bits: u64,
flags: DIFlags,
ty: DIType<'ctx>,
) -> DIDerivedType<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateMemberType(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
file.metadata_ref,
line_no,
size_in_bits,
align_in_bits,
offset_in_bits,
flags,
ty.metadata_ref,
)
};
DIDerivedType {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a struct type.
pub fn create_struct_type(
&self,
scope: DIScope<'ctx>,
name: &str,
file: DIFile<'ctx>,
line_no: libc::c_uint,
size_in_bits: u64,
align_in_bits: u32,
flags: DIFlags,
derived_from: Option<DIType<'ctx>>,
elements: &[DIType<'ctx>],
runtime_language: libc::c_uint,
vtable_holder: Option<DIType<'ctx>>,
unique_id: &str,
) -> DICompositeType<'ctx> {
let mut elements: Vec<LLVMMetadataRef> = elements.iter().map(|dt| dt.metadata_ref).collect();
let derived_from = derived_from.map_or(std::ptr::null_mut(), |dt| dt.metadata_ref);
let vtable_holder = vtable_holder.map_or(std::ptr::null_mut(), |dt| dt.metadata_ref);
let metadata_ref = unsafe {
LLVMDIBuilderCreateStructType(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
file.metadata_ref,
line_no,
size_in_bits,
align_in_bits,
flags,
derived_from,
elements.as_mut_ptr(),
elements.len().try_into().unwrap(),
runtime_language,
vtable_holder,
unique_id.as_ptr() as _,
unique_id.len(),
)
};
DICompositeType {
metadata_ref,
_marker: PhantomData,
}
}
/// Create a function type
pub fn create_subroutine_type(
&self,
file: DIFile<'ctx>,
return_type: Option<DIType<'ctx>>,
parameter_types: &[DIType<'ctx>],
flags: DIFlags,
) -> DISubroutineType<'ctx> {
let mut p = vec![return_type.map_or(std::ptr::null_mut(), |t| t.metadata_ref)];
p.append(
&mut parameter_types
.iter()
.map(|t| t.metadata_ref)
.collect::<Vec<LLVMMetadataRef>>(),
);
let metadata_ref = unsafe {
LLVMDIBuilderCreateSubroutineType(
self.builder,
file.metadata_ref,
p.as_mut_ptr(),
p.len().try_into().unwrap(),
flags,
)
};
DISubroutineType {
metadata_ref,
_marker: PhantomData,
}
}
/// Creates a pointer type
pub fn create_pointer_type(
&self,
name: &str,
pointee: DIType<'ctx>,
size_in_bits: u64,
align_in_bits: u32,
address_space: AddressSpace,
) -> DIDerivedType<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreatePointerType(
self.builder,
pointee.metadata_ref,
size_in_bits,
align_in_bits,
address_space.0,
name.as_ptr() as _,
name.len(),
)
};
DIDerivedType {
metadata_ref,
_marker: PhantomData,
}
}
/// Creates a pointer type
pub fn create_reference_type(&self, pointee: DIType<'ctx>, tag: u32) -> DIDerivedType<'ctx> {
let metadata_ref = unsafe { LLVMDIBuilderCreateReferenceType(self.builder, tag, pointee.metadata_ref) };
DIDerivedType {
metadata_ref,
_marker: PhantomData,
}
}
/// Creates an array type
pub fn create_array_type(
&self,
inner_type: DIType<'ctx>,
size_in_bits: u64,
align_in_bits: u32,
subscripts: &[Range<i64>],
) -> DICompositeType<'ctx> {
//Create subranges
let mut subscripts = subscripts
.iter()
.map(|range| {
let lower = range.start;
let upper = range.end;
let subscript_size = upper - lower;
unsafe { LLVMDIBuilderGetOrCreateSubrange(self.builder, lower, subscript_size) }
})
.collect::<Vec<_>>();
let metadata_ref = unsafe {
LLVMDIBuilderCreateArrayType(
self.builder,
size_in_bits,
align_in_bits,
inner_type.metadata_ref,
subscripts.as_mut_ptr(),
subscripts.len().try_into().unwrap(),
)
};
DICompositeType {
metadata_ref,
_marker: PhantomData,
}
}
pub fn create_global_variable_expression(
&self,
scope: DIScope<'ctx>,
name: &str,
linkage: &str,
file: DIFile<'ctx>,
line_no: u32,
ty: DIType<'ctx>,
local_to_unit: bool,
expression: Option<DIExpression>,
declaration: Option<DIScope>,
align_in_bits: u32,
) -> DIGlobalVariableExpression<'ctx> {
let expression_ptr = expression.map_or(std::ptr::null_mut(), |dt| dt.metadata_ref);
let decl_ptr = declaration.map_or(std::ptr::null_mut(), |dt| dt.metadata_ref);
let metadata_ref = unsafe {
LLVMDIBuilderCreateGlobalVariableExpression(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
linkage.as_ptr() as _,
linkage.len(),
file.metadata_ref,
line_no,
ty.metadata_ref,
local_to_unit as _,
expression_ptr,
decl_ptr,
align_in_bits,
)
};
DIGlobalVariableExpression {
metadata_ref,
_marker: PhantomData,
}
}
pub fn create_constant_expression(&self, value: i64) -> DIExpression<'ctx> {
let metadata_ref = unsafe { LLVMDIBuilderCreateConstantValueExpression(self.builder, value as _) };
DIExpression {
metadata_ref,
_marker: PhantomData,
}
}
/// Create function parameter variable.
pub fn create_parameter_variable(
&self,
scope: DIScope<'ctx>,
name: &str,
arg_no: u32,
file: DIFile<'ctx>,
line_no: u32,
ty: DIType<'ctx>,
always_preserve: bool,
flags: DIFlags,
) -> DILocalVariable<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateParameterVariable(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
arg_no,
file.metadata_ref,
line_no,
ty.metadata_ref,
always_preserve as _,
flags,
)
};
DILocalVariable {
metadata_ref,
_marker: PhantomData,
}
}
/// Create local automatic storage variable.
pub fn create_auto_variable(
&self,
scope: DIScope<'ctx>,
name: &str,
file: DIFile<'ctx>,
line_no: u32,
ty: DIType<'ctx>,
always_preserve: bool,
flags: DIFlags,
align_in_bits: u32,
) -> DILocalVariable<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateAutoVariable(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
file.metadata_ref,
line_no,
ty.metadata_ref,
always_preserve as _,
flags,
align_in_bits,
)
};
DILocalVariable {
metadata_ref,
_marker: PhantomData,
}
}
pub fn create_namespace(&self, scope: DIScope<'ctx>, name: &str, export_symbols: bool) -> DINamespace<'ctx> {
let metadata_ref = unsafe {
LLVMDIBuilderCreateNameSpace(
self.builder,
scope.metadata_ref,
name.as_ptr() as _,
name.len(),
export_symbols as _,
)
};
DINamespace {
metadata_ref,
_marker: PhantomData,
}
}
/// Insert a variable declaration (`llvm.dbg.declare`) before a specified instruction.
pub fn insert_declare_before_instruction(
&self,
storage: PointerValue<'ctx>,
var_info: Option<DILocalVariable<'ctx>>,
expr: Option<DIExpression<'ctx>>,
debug_loc: DILocation<'ctx>,
instruction: InstructionValue<'ctx>,
) -> InstructionValue<'ctx> {
let value_ref = unsafe {
LLVMDIBuilderInsertDeclareBefore(
self.builder,
storage.as_value_ref(),
var_info.map(|v| v.metadata_ref).unwrap_or(std::ptr::null_mut()),
expr.unwrap_or_else(|| self.create_expression(vec![])).metadata_ref,
debug_loc.metadata_ref,
instruction.as_value_ref(),
)
};
#[cfg(any(feature = "llvm19-1", feature = "llvm20-1"))]
{
// In LLVM 19+, the insert... functions return a DbgRecord, not a Value.
// We need to cast it to a ValueRef to create an InstructionValue.
// This is unsafe, but it's the only way to do it.
unsafe { InstructionValue::new(value_ref as LLVMValueRef) }
}
#[cfg(not(any(feature = "llvm19-1", feature = "llvm20-1")))]
{
unsafe { InstructionValue::new(value_ref) }
}
}
/// Insert a variable declaration (`llvm.dbg.declare` intrinsic) at the end of `block`
pub fn insert_declare_at_end(
&self,
storage: PointerValue<'ctx>,
var_info: Option<DILocalVariable<'ctx>>,
expr: Option<DIExpression<'ctx>>,
debug_loc: DILocation<'ctx>,
block: BasicBlock<'ctx>,
) -> InstructionValue<'ctx> {
let value_ref = unsafe {
LLVMDIBuilderInsertDeclareAtEnd(
self.builder,
storage.as_value_ref(),
var_info.map(|v| v.metadata_ref).unwrap_or(std::ptr::null_mut()),
expr.unwrap_or_else(|| self.create_expression(vec![])).metadata_ref,
debug_loc.metadata_ref,
block.basic_block,
)
};
#[cfg(any(feature = "llvm19-1", feature = "llvm20-1"))]
{
// In LLVM 19+, the insert... functions return a DbgRecord, not a Value.
// We need to cast it to a ValueRef to create an InstructionValue.
// This is unsafe, but it's the only way to do it.