如何将生成的 llvm::Module 的 LLVM-IR 代码存储到字符串中?

How to store the generated LLVM-IR code of a llvm::Module to a string?

LLVM 的 Fibonacci 示例使用 errs() << *theModule 打印出 LLVM IR。

是否有任何函数能够将生成的 LLVM IR 存储到字符串(的向量)或任何其他变量中,而不仅仅是打印出来? (例如,std::string llvm_IR = theModule->getIR()

我一直在搜索 llvm::Module Class Reference 但没有得到任何帮助。

Fibonacci.cpp的一部分:

//前面定义了CreateFibFunction生成fibonacci函数

LLVMContext Context;

// Create some module to put our function into it.
std::unique_ptr<Module> Owner(new Module("test", Context));
Module *theModule = Owner.get();

// We are about to create the "fib" function:
Function *FibF = CreateFibFunction(M, Context);
errs() << "OK\n";
errs() << "We just constructed this LLVM module:\n\n---------\n";
errs() << *theModule;
errs() << "---------\nstarting fibonacci(" << n << ") with JIT...\n";

看起来将模块文本打印到流是模块外部的 class。 PrintModulePass 或类似版本,具体取决于您的版本

我会找到一个打印模块的工具,看看他们是怎么做的,也许 'opt'。

你可以用同样的方式来做——你可以使用 raw_string_ostream 而不是 errs(),它是 raw_ostream,像这样:

std::string Str;
raw_string_ostream OS(Str);
OS << *theModule;
OS.flush()
// Str now contains the module text