llvm - 从 ExecutionEngine 调用 C/C++ 函数

标签 llvm

我正在学习 llvm 并想对我的想法进行概念证明。

基本上,我想拆分我的编译器和我的运行时。编译器会给出一个 .bc,运行时会通过 ParseBitcodeFile 加载它并使用 ExecutionEngine 来运行它。这部分正在工作。

现在,为了轻松进行系统调用,我希望能够在我的运行时 C/C++ 函数中实现所有系统调用(文件 io、stdout 打印等)。我的问题是,我怎么能从我的玩具编译器的代码中调用这些函数,它是由 llvm 在不同的步骤中编译的,并允许在执行时使用它。

最佳答案

好消息:使用 JIT 时 ExecutionEngine ,这将起作用。当 JIT-er 发现 IR 使用的外部符号在 IR 本身中找不到时,它会在 JIT-ing 进程本身中查找,因此可以调用主机程序中可见的任何符号。

这在 part 4 of the LLVM tutorial 中有直接解释:

Whoa, how does the JIT know about sin and cos? The answer is surprisingly simple: in this example, the JIT started execution of a function and got to a function call. It realized that the function was not yet JIT compiled and invoked the standard set of routines to resolve the function. In this case, there is no body defined for the function, so the JIT ended up calling “dlsym("sin")” on the Kaleidoscope process itself. Since “sin” is defined within the JIT’s address space, it simply patches up calls in the module to call the libm version of sin directly.



有关血腥细节,请查看 lib/ExecutionEngine/JIT/JIT.cpp - 特别是它对 DynamicLibrary 的使用.

关于llvm - 从 ExecutionEngine 调用 C/C++ 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17584752/

相关文章:

c++ - 链接到 Unix 上的 Clang 和 LLVM - 强制使用 LLVM 的编译器标志?

c++ - 是否有关于 std::move 的这种使用的编译警告?

c++ - LLVM 的位码对函数参数的错误检测

objective-c - 了解 gcov 文件中的分支

gcc - 如何在 Rust 中使用 -mlongcall GCcflags?

python - 在 OSX 上安装 llvmpy

iOS:-dynamic 未指定以下标志无效:-sectcreate

llvm - `ConstantInt::getTrue (LLVMContext &Context)` 和 `ConstantInt::getTrue (Type *Ty)` 有什么区别?

debugging - 在 lldb 中使用 `expr` 命令计算表达式时如何查看 printf 输出?

syntax-highlighting - 用于 LLVM 程序集的 Notepad++ 语法高亮器