progs/fun_llvm.scala
changeset 656 cfc0e730bcda
parent 655 3d04ee04966d
child 657 732cb155d806
--- a/progs/fun_llvm.scala	Mon Oct 14 00:02:24 2019 +0100
+++ b/progs/fun_llvm.scala	Mon Oct 14 00:48:01 2019 +0100
@@ -66,8 +66,7 @@
 
 case class KVar(s: String) extends KVal
 case class KNum(i: Int) extends KVal
-case class KAop(o: String, v1: KVal, v2: KVal) extends KVal
-case class KBop(o: String, v1: KVal, v2: KVal) extends KVal
+case class Kop(o: String, v1: KVal, v2: KVal) extends KVal
 case class KCall(o: String, vrs: List[KVal]) extends KVal
 case class KWrite(v: KVal) extends KVal
 
@@ -88,13 +87,13 @@
   case Aop(o, e1, e2) => {
     val z = Fresh("tmp")
     CPS(e1)(y1 => 
-      CPS(e2)(y2 => KLet(z, KAop(o, y1, y2), k(KVar(z)))))
+      CPS(e2)(y2 => KLet(z, Kop(o, y1, y2), k(KVar(z)))))
   }
   case If(Bop(o, b1, b2), e1, e2) => {
     val z = Fresh("tmp")
     CPS(b1)(y1 => 
       CPS(b2)(y2 => 
-        KLet(z, KBop(o, y1, y2), KIf(z, CPS(e1)(k), CPS(e2)(k)))))
+        KLet(z, Kop(o, y1, y2), KIf(z, CPS(e1)(k), CPS(e2)(k)))))
   }
   case Call(name, args) => {
     def aux(args: List[Exp], vs: List[KVal]) : KExp = args match {
@@ -106,11 +105,8 @@
     }
     aux(args, Nil)
   }
-  case Sequence(e1, e2) => {
-    val z = Fresh("tmp")
-    CPS(e1)(y1 => 
-      CPS(e2)(y2 => KLet("_", y1, KLet(z, y2, k(KVar(z))))))
-  }
+  case Sequence(e1, e2) => 
+    CPS(e1)(y1 => CPS(e2)(y2 => k(y2)))
   case Write(e) => {
     val z = Fresh("tmp")
     CPS(e)(y => KLet(z, KWrite(y), k(KVar(z))))
@@ -164,19 +160,22 @@
     def m(args: Any*): String = sc.s(args:_*) ++ "\n"
 }
 
+// mathematical and boolean operations
 def compile_op(op: String) = op match {
   case "+" => "add i32 "
   case "*" => "mul i32 "
   case "-" => "sub i32 "
+  case "/" => "sdiv i32 "
+  case "%" => "srem i32 "
   case "==" => "icmp eq i32 "
+  case "<=" => "icmp sle i32 "    // signed less or equal
+  case "<" => "icmp slt i32 "     // signed less than
 }
 
 def compile_val(v: KVal) : String = v match {
   case KNum(i) => s"$i"
   case KVar(s) => s"%$s"
-  case KAop(op, x1, x2) => 
-    s"${compile_op(op)} ${compile_val(x1)}, ${compile_val(x2)}"
-  case KBop(op, x1, x2) => 
+  case Kop(op, x1, x2) => 
     s"${compile_op(op)} ${compile_val(x1)}, ${compile_val(x2)}"
   case KCall(x1, args) => 
     s"call i32 @$x1 (${args.map(compile_val).mkString("i32 ", ", i32 ", "")})"