Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Provide LLVMTypeWrapper trait #223

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions src/llvm/di.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,14 @@ use gimli::{DW_TAG_pointer_type, DW_TAG_structure_type, DW_TAG_variant_part};
use llvm_sys::{core::*, debuginfo::*, prelude::*};
use tracing::{span, trace, warn, Level};

use super::types::{
di::DIType,
ir::{Function, MDNode, Metadata, Value},
use crate::llvm::{
iter::*,
types::{
di::{DISubprogram, DIType},
ir::{Function, MDNode, Metadata, Value},
LLVMTypeWrapper,
},
};
use crate::llvm::{iter::*, types::di::DISubprogram};

// KSYM_NAME_LEN from linux kernel intentionally set
// to lower value found accross kernel versions to ensure
Expand All @@ -26,7 +29,6 @@ pub struct DISanitizer {
module: LLVMModuleRef,
builder: LLVMDIBuilderRef,
visited_nodes: HashSet<u64>,
item_stack: Vec<Item>,
replace_operands: HashMap<u64, LLVMMetadataRef>,
skipped_types: Vec<String>,
}
Expand Down Expand Up @@ -66,7 +68,6 @@ impl DISanitizer {
module,
builder: unsafe { LLVMCreateDIBuilder(module) },
visited_nodes: HashSet::new(),
item_stack: Vec::new(),
replace_operands: HashMap::new(),
skipped_types: Vec::new(),
}
Expand Down Expand Up @@ -229,7 +230,7 @@ impl DISanitizer {
// An operand with no value is valid and means that the operand is
// not set
(v, Item::Operand { .. }) if v.is_null() => return,
(v, _) if !v.is_null() => Value::new(v),
(v, _) if !v.is_null() => unsafe { Value::from_ptr(v) },
// All other items should have values
(_, item) => panic!("{item:?} has no value"),
};
Expand All @@ -249,8 +250,6 @@ impl DISanitizer {
return;
}

self.item_stack.push(item.clone());

if let Value::MDNode(mdnode) = value.clone() {
self.visit_mdnode(mdnode)
}
Expand Down Expand Up @@ -285,8 +284,6 @@ impl DISanitizer {
}
}
}

let _ = self.item_stack.pop().unwrap();
}

pub fn run(mut self, exported_symbols: &HashSet<Cow<'static, str>>) {
Expand Down Expand Up @@ -337,7 +334,7 @@ impl DISanitizer {
for mut function in self
.module
.functions_iter()
.map(|value| unsafe { Function::from_value_ref(value) })
.map(|value| unsafe { Function::from_ptr(value) })
{
if export_symbols.contains(function.name()) {
continue;
Expand Down Expand Up @@ -376,7 +373,7 @@ impl DISanitizer {
// replace retained nodes manually below.
LLVMDIBuilderFinalizeSubprogram(self.builder, new_program);

DISubprogram::from_value_ref(LLVMMetadataAsValue(self.context, new_program))
DISubprogram::from_ptr(LLVMMetadataAsValue(self.context, new_program))
};

// Point the function to the new subprogram.
Expand All @@ -402,8 +399,8 @@ impl DISanitizer {
unsafe { LLVMMDNodeInContext2(self.context, core::ptr::null_mut(), 0) };
subprogram.set_retained_nodes(empty_node);

let ret = replace.insert(subprogram.value_ref as u64, unsafe {
LLVMValueAsMetadata(new_program.value_ref)
let ret = replace.insert(subprogram.as_ptr() as u64, unsafe {
LLVMValueAsMetadata(new_program.as_ptr())
});
assert!(ret.is_none());
}
Expand Down
79 changes: 61 additions & 18 deletions src/llvm/types/di.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,10 @@ use llvm_sys::{

use crate::llvm::{
mdstring_to_str,
types::ir::{MDNode, Metadata},
types::{
ir::{MDNode, Metadata},
LLVMTypeWrapper,
},
};

/// Returns a DWARF tag for the given debug info node.
Expand All @@ -41,11 +44,13 @@ unsafe fn di_node_tag(metadata_ref: LLVMMetadataRef) -> DwTag {
/// A `DIFile` debug info node, which represents a given file, is referenced by
/// other debug info nodes which belong to the file.
pub struct DIFile<'ctx> {
pub(super) metadata_ref: LLVMMetadataRef,
metadata_ref: LLVMMetadataRef,
_marker: PhantomData<&'ctx ()>,
}

impl<'ctx> DIFile<'ctx> {
impl<'ctx> LLVMTypeWrapper for DIFile<'ctx> {
type Target = LLVMMetadataRef;

/// Constructs a new [`DIFile`] from the given `metadata`.
///
/// # Safety
Expand All @@ -54,13 +59,19 @@ impl<'ctx> DIFile<'ctx> {
/// instance of [LLVM `DIFile`](https://llvm.org/doxygen/classllvm_1_1DIFile.html).
/// It's the caller's responsibility to ensure this invariant, as this
/// method doesn't perform any validation checks.
pub(crate) unsafe fn from_metadata_ref(metadata_ref: LLVMMetadataRef) -> Self {
unsafe fn from_ptr(metadata_ref: Self::Target) -> Self {
Self {
metadata_ref,
_marker: PhantomData,
}
}

fn as_ptr(&self) -> Self::Target {
self.metadata_ref
}
}

impl<'ctx> DIFile<'ctx> {
pub fn filename(&self) -> Option<&CStr> {
let mut len = 0;
// `LLVMDIFileGetName` doesn't allocate any memory, it just returns
Expand Down Expand Up @@ -109,12 +120,14 @@ unsafe fn di_type_name<'a>(metadata_ref: LLVMMetadataRef) -> Option<&'a CStr> {

/// Represents the debug information for a primitive type in LLVM IR.
pub struct DIType<'ctx> {
pub(super) metadata_ref: LLVMMetadataRef,
pub(super) value_ref: LLVMValueRef,
metadata_ref: LLVMMetadataRef,
value_ref: LLVMValueRef,
_marker: PhantomData<&'ctx ()>,
}

impl<'ctx> DIType<'ctx> {
impl<'ctx> LLVMTypeWrapper for DIType<'ctx> {
type Target = LLVMValueRef;

/// Constructs a new [`DIType`] from the given `value`.
///
/// # Safety
Expand All @@ -123,7 +136,7 @@ impl<'ctx> DIType<'ctx> {
/// instance of [LLVM `DIType`](https://llvm.org/doxygen/classllvm_1_1DIType.html).
/// It's the caller's responsibility to ensure this invariant, as this
/// method doesn't perform any validation checks.
pub unsafe fn from_value_ref(value_ref: LLVMValueRef) -> Self {
unsafe fn from_ptr(value_ref: Self::Target) -> Self {
let metadata_ref = unsafe { LLVMValueAsMetadata(value_ref) };
Self {
metadata_ref,
Expand All @@ -132,6 +145,12 @@ impl<'ctx> DIType<'ctx> {
}
}

fn as_ptr(&self) -> Self::Target {
self.value_ref
}
}

impl<'ctx> DIType<'ctx> {
/// Returns the offset of the type in bits. This offset is used in case the
/// type is a member of a composite type.
pub fn offset_in_bits(&self) -> usize {
Expand All @@ -141,7 +160,7 @@ impl<'ctx> DIType<'ctx> {

impl<'ctx> From<DIDerivedType<'ctx>> for DIType<'ctx> {
fn from(di_derived_type: DIDerivedType) -> Self {
unsafe { Self::from_value_ref(di_derived_type.value_ref) }
unsafe { Self::from_ptr(di_derived_type.value_ref) }
}
}

Expand All @@ -165,7 +184,9 @@ pub struct DIDerivedType<'ctx> {
_marker: PhantomData<&'ctx ()>,
}

impl<'ctx> DIDerivedType<'ctx> {
impl<'ctx> LLVMTypeWrapper for DIDerivedType<'ctx> {
type Target = LLVMValueRef;

/// Constructs a new [`DIDerivedType`] from the given `value`.
///
/// # Safety
Expand All @@ -174,7 +195,7 @@ impl<'ctx> DIDerivedType<'ctx> {
/// instance of [LLVM `DIDerivedType`](https://llvm.org/doxygen/classllvm_1_1DIDerivedType.html).
/// It's the caller's responsibility to ensure this invariant, as this
/// method doesn't perform any validation checks.
pub unsafe fn from_value_ref(value_ref: LLVMValueRef) -> Self {
unsafe fn from_ptr(value_ref: Self::Target) -> Self {
let metadata_ref = LLVMValueAsMetadata(value_ref);
Self {
metadata_ref,
Expand All @@ -183,6 +204,12 @@ impl<'ctx> DIDerivedType<'ctx> {
}
}

fn as_ptr(&self) -> Self::Target {
self.value_ref
}
}

impl<'ctx> DIDerivedType<'ctx> {
/// Returns the base type of this derived type.
pub fn base_type(&self) -> Metadata {
unsafe {
Expand Down Expand Up @@ -226,7 +253,9 @@ pub struct DICompositeType<'ctx> {
_marker: PhantomData<&'ctx ()>,
}

impl<'ctx> DICompositeType<'ctx> {
impl<'ctx> LLVMTypeWrapper for DICompositeType<'ctx> {
type Target = LLVMValueRef;

/// Constructs a new [`DICompositeType`] from the given `value`.
///
/// # Safety
Expand All @@ -235,7 +264,7 @@ impl<'ctx> DICompositeType<'ctx> {
/// instance of [LLVM `DICompositeType`](https://llvm.org/doxygen/classllvm_1_1DICompositeType.html).
/// It's the caller's responsibility to ensure this invariant, as this
/// method doesn't perform any validation checks.
pub unsafe fn from_value_ref(value_ref: LLVMValueRef) -> Self {
unsafe fn from_ptr(value_ref: Self::Target) -> Self {
let metadata_ref = LLVMValueAsMetadata(value_ref);
Self {
metadata_ref,
Expand All @@ -244,6 +273,12 @@ impl<'ctx> DICompositeType<'ctx> {
}
}

fn as_ptr(&self) -> Self::Target {
self.value_ref
}
}

impl<'ctx> DICompositeType<'ctx> {
/// Returns an iterator over elements (struct fields, enum variants, etc.)
/// of the composite type.
pub fn elements(&self) -> impl Iterator<Item = Metadata> {
Expand All @@ -266,7 +301,7 @@ impl<'ctx> DICompositeType<'ctx> {
pub fn file(&self) -> DIFile {
unsafe {
let metadata = LLVMDIScopeGetFile(self.metadata_ref);
DIFile::from_metadata_ref(metadata)
DIFile::from_ptr(metadata)
}
}

Expand All @@ -289,7 +324,7 @@ impl<'ctx> DICompositeType<'ctx> {
LLVMReplaceMDNodeOperandWith(
self.value_ref,
DICompositeTypeOperand::Elements as u32,
LLVMValueAsMetadata(mdnode.value_ref),
LLVMValueAsMetadata(mdnode.as_ptr()),
)
}
}
Expand Down Expand Up @@ -324,11 +359,13 @@ enum DISubprogramOperand {

/// Represents the debug information for a subprogram (function) in LLVM IR.
pub struct DISubprogram<'ctx> {
pub value_ref: LLVMValueRef,
value_ref: LLVMValueRef,
_marker: PhantomData<&'ctx ()>,
}

impl<'ctx> DISubprogram<'ctx> {
impl<'ctx> LLVMTypeWrapper for DISubprogram<'ctx> {
type Target = LLVMValueRef;

/// Constructs a new [`DISubprogram`] from the given `value`.
///
/// # Safety
Expand All @@ -337,13 +374,19 @@ impl<'ctx> DISubprogram<'ctx> {
/// instance of [LLVM `DISubprogram`](https://llvm.org/doxygen/classllvm_1_1DISubprogram.html).
/// It's the caller's responsibility to ensure this invariant, as this
/// method doesn't perform any validation checks.
pub(crate) unsafe fn from_value_ref(value_ref: LLVMValueRef) -> Self {
unsafe fn from_ptr(value_ref: Self::Target) -> Self {
DISubprogram {
value_ref,
_marker: PhantomData,
}
}

fn as_ptr(&self) -> Self::Target {
self.value_ref
}
}

impl<'ctx> DISubprogram<'ctx> {
/// Returns the name of the subprogram.
pub fn name(&self) -> Option<&str> {
let operand = unsafe { LLVMGetOperand(self.value_ref, DISubprogramOperand::Name as u32) };
Expand Down
Loading