diff --git a/sources/LLVMSharp/Extensions/LLVMTargetRef.cs b/sources/LLVMSharp/Extensions/LLVMTargetRef.cs index 2ee14560..a465dfa0 100644 --- a/sources/LLVMSharp/Extensions/LLVMTargetRef.cs +++ b/sources/LLVMSharp/Extensions/LLVMTargetRef.cs @@ -69,5 +69,15 @@ public string Name public override int GetHashCode() => Pointer.GetHashCode(); public LLVMTargetRef GetNext() => LLVM.GetNextTarget(this); + + public LLVMTargetMachineRef CreateTargetMachine(string triple, string cpu, string features, LLVMCodeGenOptLevel level, LLVMRelocMode reloc, LLVMCodeModel codeModel) + { + using (var marshaledTriple = new MarshaledString(triple)) + using (var marshaledCPU = new MarshaledString(cpu)) + using (var marshaledFeatures = new MarshaledString(features)) + { + return LLVM.CreateTargetMachine(this, marshaledTriple, marshaledCPU, marshaledFeatures, level, reloc, codeModel); + } + } } } diff --git a/sources/LLVMSharp/Wrappers/LLVMTargetMachineRef.cs b/sources/LLVMSharp/Wrappers/LLVMTargetMachineRef.cs index cbe56cf5..cceb2358 100644 --- a/sources/LLVMSharp/Wrappers/LLVMTargetMachineRef.cs +++ b/sources/LLVMSharp/Wrappers/LLVMTargetMachineRef.cs @@ -1,4 +1,5 @@ using System; +using System.Runtime.InteropServices; namespace LLVMSharp { @@ -20,5 +21,49 @@ public static implicit operator LLVMTargetMachineRef(LLVMOpaqueTargetMachine* va { return (LLVMOpaqueTargetMachine*)value.Pointer; } + + public string CreateTargetDataLayout() + { + var pDataLayout = LLVM.CreateTargetDataLayout(this); + + if (pDataLayout is null) + { + return string.Empty; + } + + var span = new ReadOnlySpan(pDataLayout, int.MaxValue); + return span.Slice(0, span.IndexOf((byte)'\0')).AsString(); + } + + public bool TryEmitToFile(LLVMModuleRef module, string fileName, LLVMCodeGenFileType codegen, out string message) + { + using (var marshaledFileName = new MarshaledString(fileName)) + { + sbyte* errorMessage; + + int result = LLVM.TargetMachineEmitToFile(this, module, marshaledFileName, codegen, &errorMessage); + + if (errorMessage is null) + { + message = string.Empty; + } + else + { + var span = new ReadOnlySpan(errorMessage, int.MaxValue); + message = span.Slice(0, span.IndexOf((byte)'\0')).AsString(); + LLVM.DisposeErrorMessage(errorMessage); + } + + return result == 0; + } + } + + public void EmitToFile(LLVMModuleRef module, string fileName, LLVMCodeGenFileType codegen) + { + if (!TryEmitToFile(module, fileName, codegen, out string Error)) + { + throw new ExternalException(Error); + } + } } }