将 llvm-general-pure AST 漂亮地打印为 llvm-ir?

Pretty print llvm-general-pure ASTs as llvm-ir?

我用了llvm-general-pure to build an abstract syntax trees for a program in the LLVM language.

使用 provided pretty printer,我得到的输出看起来像

A.Module {
  A.moduleName = "main",
  A.moduleDataLayout = Nothing,
  A.moduleTargetTriple = Nothing,
  A.moduleDefinitions = [
    ...
    A.GlobalDefinition A.G.Function {
      A.G.linkage = A.L.External,
      A.G.visibility = A.V.Default,
      A.G.callingConvention = A.CC.C,
      A.G.returnAttributes = [],
      A.G.returnType = A.IntegerType {A.typeBits = 32},
      A.G.name = A.Name "Main",
      A.G.parameters = ([], False),
      A.G.functionAttributes = [],
      A.G.section = Nothing,
      A.G.alignment = 0,
      A.G.garbageCollectorName = Nothing,
      A.G.basicBlocks = [
        A.G.BasicBlock (A.Name "mainBlock") [
          A.Name "n57" A.:= A.Alloca {
            A.allocatedType = A.IntegerType {A.typeBits = 64},
            A.numElements = Nothing,
            A.alignment = 0,
            A.metadata = []
          },
...

我想要看起来像

的输出
define i32 @main() {
mainBlock:
    %n57 = alloca i64
    ...
}
...

在 llvm-general-quote 包中似乎有一个 LLVM 语言的 automatically generated parser,但没有相应的漂亮打印机。

Stephen Diehl's excellent article 暗示了一个叫做 moduleString.

的东西

llvm-general-pure 没有纯漂亮的打印机,我们必须通过 llvm-general 才能做到这一点。它可以通过 Haskell AST 上的 withModuleFromAST 打印出 IR,以显示 IR 的模块表示(即 C++ 模块),然后调用 moduleLLVMAssembly 调用漂亮的打印机。

moduleLLVMAssembly :: Mod.Module -> IO String
withModuleFromAST :: Context -> AST.Module -> (Mod.Module -> IO a) -> ErrorT String IO a

虽然这不是纯粹的Haskell,它都是通过 FFI 调用 LLVM 的内部函数。

import LLVM.General.Module as Mod
import qualified LLVM.General.AST as AST

ppModule :: AST.Module -> IO ()
ppModule ast = withContext $ \ctx ->
  runExceptT $ withModuleFromAST ctx ast $ \m -> do
    llstr <- moduleLLVMAssembly m
    putStrLn llstr

虽然我们没有理由不能拥有一台纯粹漂亮的打印机,事实上我开始了一个项目来做这个叫做 llvm-pp,但这只是大量令人麻木的无聊工作要写一个适合整个 LLVM 规范的漂亮打印机。