57 lines
1.4 KiB
Haskell
57 lines
1.4 KiB
Haskell
{-# LANGUAGE ImportQualifiedPost #-}
|
|
{-# LANGUAGE OverloadedStrings #-}
|
|
|
|
-- see https://gh.sudoer.ch/danieljharvey/mimsa/blob/trunk/llvm-calc/src/Calc/Compile/ToLLVM.hs
|
|
|
|
module LLVMGen.Expr (getLLVMStr) where
|
|
|
|
import Data.Text.Lazy
|
|
import LLVM.AST hiding (function)
|
|
import LLVM.AST.Type
|
|
import LLVM.IRBuilder.Constant
|
|
import LLVM.IRBuilder.Instruction
|
|
import LLVM.IRBuilder.Module
|
|
import LLVM.IRBuilder.Monad
|
|
import LLVM.Pretty
|
|
import Types.Expr as Expr
|
|
|
|
-- charStar :: LLVM.Type
|
|
-- charStar = LLVM.ptr LLVM.i8
|
|
|
|
getLLVM :: Expr -> Module
|
|
getLLVM expr =
|
|
buildModule "program" $ do
|
|
-- TODO: better naming
|
|
printf <- externVarArgs "printf" [ptr] i32 -- or LLVM.ptr LLVM.i8
|
|
let numFormatStr = globalStringPtr "%d\n" (mkName "str")
|
|
function "main" [] i32 $ \_ -> do
|
|
ourExpression <- exprToLLVM expr
|
|
nfs <- numFormatStr
|
|
_ <- call i32 printf [(ConstantOperand nfs, []), (ourExpression, [])]
|
|
ret (int32 0)
|
|
|
|
exprToLLVM ::
|
|
( MonadIRBuilder m,
|
|
MonadModuleBuilder m
|
|
) =>
|
|
Expr ->
|
|
m Operand
|
|
exprToLLVM (Lit prim) = pure $ primToLLVM prim
|
|
exprToLLVM (Expr.Add a b) = do
|
|
lhs <- exprToLLVM a
|
|
rhs <- exprToLLVM b
|
|
add lhs rhs
|
|
exprToLLVM (Expr.Sub a b) = do
|
|
lhs <- exprToLLVM a
|
|
rhs <- exprToLLVM b
|
|
sub lhs rhs
|
|
exprToLLVM (Expr.Mul a b) = do
|
|
lhs <- exprToLLVM a
|
|
rhs <- exprToLLVM b
|
|
mul lhs rhs
|
|
|
|
primToLLVM :: Int -> Operand
|
|
primToLLVM i = int32 (fromIntegral i)
|
|
|
|
getLLVMStr :: Expr -> Text
|
|
getLLVMStr expr = ppllvm (getLLVM expr) |