Add for loops
[kaleidoscope-hs-old.git] / Main.hs
diff --git a/Main.hs b/Main.hs
index f096ea6fa5177b8deb5671c570cb97ba79f37192..7fa4499024c94db07b3264d0a08964af7b194c67 100644 (file)
--- a/Main.hs
+++ b/Main.hs
@@ -44,14 +44,14 @@ main = do
     Left err -> die err
     Right mdl' -> withContext $ \ctx ->
       withHostTargetMachine $ \tm -> do
-        -- hPutStrLn stderr "Before optimisation:"
-        -- Text.hPutStrLn stderr (ppllvm mdl')
+        hPutStrLn stderr "Before optimisation:"
+        Text.hPutStrLn stderr (ppllvm mdl')
 
         withModuleFromAST ctx mdl' $ \mdl -> do
           let spec = defaultCuratedPassSetSpec { optLevel = Just 3 }
           withPassManager spec $ flip runPassManager mdl
-          -- hPutStrLn stderr "After optimisation:"
-          -- Text.hPutStrLn stderr . ppllvm =<< moduleAST mdl
+          hPutStrLn stderr "After optimisation:"
+          Text.hPutStrLn stderr . ppllvm =<< moduleAST mdl
           jit tm mdl >>= print
 
 jit :: TargetMachine -> Module -> IO Double
@@ -153,3 +153,33 @@ buildExpr binds (AST.If cond thenE elseE) = mdo
 
   mergeB <- block `named` "ifcont"
   phi [(thenOp, thenB), (elseOp, elseB)]
+
+buildExpr binds (AST.For ident start cond mStep body) = mdo
+  startV <- buildExpr binds start
+
+  preheaderB <- block `named` "preheader"
+
+  br loopB
+
+  loopB <- block `named` "loop"
+
+  i <- phi [(startV, preheaderB), (nextVar, loopB)] `named` "i"
+
+  let newBinds = Map.insert ident i binds
+
+  buildExpr newBinds body `named` "body"
+
+  stepV <- case mStep of
+    Just step -> buildExpr newBinds step
+    Nothing -> pure $ ConstantOperand (Float (Double 1))
+
+  nextVar <- fadd i stepV `named` "nextvar"
+
+  condV <- buildExpr newBinds cond `named` "cond"
+
+  condBr condV loopB afterB
+
+  afterB <- block `named` "after"
+
+  return (ConstantOperand (Float (Double 0)))
+