X-Git-Url: https://git.lukelau.me/?p=kaleidoscope-hs-old.git;a=blobdiff_plain;f=Main.hs;h=8f4610af8b249920f0b03e67091804ad70c34faa;hp=7a26601b60ab6ca070c604d893332a1bbd1a62ab;hb=98897ccc44795260735bafc5124e0e14052247f2;hpb=3b388fc2dfc375b25dc2d263237d2c895e433a6e diff --git a/Main.hs b/Main.hs index 7a26601..8f4610a 100644 --- a/Main.hs +++ b/Main.hs @@ -4,6 +4,12 @@ module Main where import qualified AST import qualified Data.Text.Lazy.IO as Text +import Foreign.Ptr +import System.IO +import LLVM.Context +import LLVM.CodeModel +import LLVM.ExecutionEngine +import LLVM.Module import LLVM.IRBuilder import LLVM.AST.Constant import LLVM.AST.Float @@ -11,18 +17,29 @@ import LLVM.AST.Operand import LLVM.AST.Type import LLVM.Pretty +foreign import ccall "dynamic" exprFun :: FunPtr (IO Float) -> IO Float + main :: IO () main = do ast <- read <$> getContents let mdl = buildModule "main" $ - function "expr" [] float $ \_ -> do - build ast - return () - Text.putStrLn (ppllvm mdl) + function "expr" [] float $ \_ -> build ast >>= ret + Text.hPutStrLn stderr (ppllvm mdl) + withContext $ \ctx -> + withMCJIT ctx Nothing Nothing Nothing Nothing $ \mcjit -> + withModuleFromAST ctx mdl $ \mdl' -> + withModuleInEngine mcjit mdl' $ \emdl -> do + Just f <- getFunction emdl "expr" + let f' = castFunPtr f :: FunPtr (IO Float) + exprFun f' >>= print build :: AST.Expr -> IRBuilderT ModuleBuilder Operand build (AST.Num a) = pure $ ConstantOperand (Float (Single a)) -build (AST.Add a b) = do +build (AST.BinOp op a b) = do va <- build a vb <- build b - fadd va vb + let instr = case op of + AST.Add -> fadd + AST.Sub -> fsub + AST.Mul -> fmul + instr va vb