Skip to content

Commit 8c7cf31

Browse files
authored
Support null metadata, represent as nothing. (#307)
1 parent a94adbf commit 8c7cf31

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/core/metadata.jl

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ function operands(md::MDNode)
108108
nops = API.LLVMExtraGetMDNodeNumOperands2(md)
109109
ops = Vector{API.LLVMMetadataRef}(undef, nops)
110110
API.LLVMExtraGetMDNodeOperands2(md, ops)
111-
return [Metadata(op) for op in ops]
111+
return [op == C_NULL ? nothing : Metadata(op) for op in ops]
112112
end
113113

114114
# TODO: setindex?
@@ -131,3 +131,10 @@ MDNode(mds::Vector{<:Metadata}; ctx::Context) =
131131
MDTuple(API.LLVMMDNodeInContext2(ctx, mds, length(mds)))
132132
MDNode(vals::Vector; ctx::Context) =
133133
MDNode(convert(Vector{Metadata}, vals); ctx)
134+
135+
# we support passing `nothing`, but convert it to a non-exported `MDNull` instance
136+
# so that we can keep everything as a subtype of `Metadata`
137+
struct MDNull <: Metadata end
138+
Base.convert(::Type{Metadata}, ::Nothing) = MDNull()
139+
Base.unsafe_convert(::Type{API.LLVMMetadataRef}, md::MDNull) =
140+
convert(API.LLVMMetadataRef, C_NULL)

test/core.jl

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -851,6 +851,23 @@ Context() do ctx
851851
@test ops[1] == str
852852
end
853853

854+
# null metadata, represented as null pointers in the API, by `nothing` in Julia
855+
Context() do ctx
856+
ir = """
857+
!0 = !{i32 42, null, !"string"}
858+
!foo = !{!0}
859+
"""
860+
mod = parse(LLVM.Module, ir; ctx)
861+
862+
foo_md = operands(metadata(mod)["foo"])[1]
863+
@test operands(foo_md)[1] !== nothing
864+
@test operands(foo_md)[2] === nothing
865+
@test operands(foo_md)[3] !== nothing
866+
867+
bar_md = MDNode([ConstantInt(Int32(42); ctx), nothing, MDString("string"; ctx)]; ctx)
868+
@test foo_md == bar_md
869+
end
870+
854871
@testset "debuginfo" begin
855872

856873
Context() do ctx

0 commit comments

Comments
 (0)