TPDE
Loading...
Searching...
No Matches
LLVMCompiler.hpp
1// SPDX-FileCopyrightText: 2025 Contributors to TPDE <https://tpde.org>
2// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
3#pragma once
4
5#include <cstdint>
6#include <functional>
7#include <memory>
8#include <string_view>
9#include <vector>
10
11namespace llvm {
12class GlobalValue;
13class Module;
14class Triple;
15} // namespace llvm
16
17namespace tpde_llvm {
18
19class JITMapperImpl;
20
21/// In-memory mapper for JIT execution. Memory and registered unwind info will
22/// be released on destruction.
23class JITMapper {
24private:
25 friend class JITMapperImpl;
26
27 std::unique_ptr<JITMapperImpl> impl;
28
29public:
30 explicit JITMapper(std::unique_ptr<JITMapperImpl> impl) noexcept;
31 ~JITMapper();
32
33 JITMapper(const JITMapper &) = delete;
34 JITMapper(JITMapper &&other) noexcept;
35
36 JITMapper &operator=(const JITMapper &) = delete;
37 JITMapper &operator=(JITMapper &&other) noexcept;
38
39 /// Get the address for a global, which must be contained in the compiled
40 /// module.
41 void *lookup_global(llvm::GlobalValue *) noexcept;
42
43 /// Indicate whether compilation and in-memory mapping was successful.
44 operator bool() const noexcept { return impl != nullptr; }
45};
46
47/// Compiler for LLVM modules
48class LLVMCompiler {
49protected:
50 LLVMCompiler() = default;
51
52public:
53 virtual ~LLVMCompiler();
54
55 LLVMCompiler(const LLVMCompiler &) = delete;
56 LLVMCompiler &operator=(const LLVMCompiler &) = delete;
57
58 /// Create a compiler for the specified target triple; returns null if the
59 /// triple is not supported. The only supported code model is small, the only
60 /// supported relocation model is PIC.
61 static std::unique_ptr<LLVMCompiler>
62 create(const llvm::Triple &triple) noexcept;
63
64 /// Compile the module to an object file and emit it into the buffer. The
65 /// module might be modified during compilation.
66 /// \returns true on success.
67 virtual bool compile_to_elf(llvm::Module &mod,
68 std::vector<uint8_t> &buf) noexcept = 0;
69
70 /// Compile the module and map it into memory, calling resolver to resolve
71 /// references to external symbols. This function will also register unwind
72 /// information. The module might be modified during compilation.
74 llvm::Module &mod,
75 std::function<void *(std::string_view)> resolver) noexcept = 0;
76};
77
78} // namespace tpde_llvm
void * lookup_global(llvm::GlobalValue *) noexcept
virtual JITMapper compile_and_map(llvm::Module &mod, std::function< void *(std::string_view)> resolver) noexcept=0
static std::unique_ptr< LLVMCompiler > create(const llvm::Triple &triple) noexcept
virtual bool compile_to_elf(llvm::Module &mod, std::vector< uint8_t > &buf) noexcept=0