progs/fun_llvm.scala
author Christian Urban <urbanc@in.tum.de>
Tue, 08 Oct 2019 21:12:52 +0100
changeset 649 e83afb44f276
parent 648 36379b038438
child 650 3031e3379ea3
permissions -rw-r--r--
updated

// A Small Compiler for a Simple Functional Language
// (includes an external lexer and parser)
//
// call with 
//
//     scala fun.scala fact
//
//     scala fun.scala defs
//
// this will generate a .j file and run the jasmin
// assembler (installed at jvm/jasmin-2.4/jasmin.jar)
// it runs the resulting JVM file twice for timing 
// purposes.




object Compiler {

import java.io._  
import scala.util._
import scala.sys.process._

// Abstract syntax trees for the Fun language
abstract class Exp extends Serializable 
abstract class BExp extends Serializable 
abstract class Decl extends Serializable 

case class Def(name: String, args: List[String], body: Exp) extends Decl
case class Main(e: Exp) extends Decl

case class Call(name: String, args: List[Exp]) extends Exp
case class If(a: BExp, e1: Exp, e2: Exp) extends Exp
case class Write(e: Exp) extends Exp
case class Var(s: String) extends Exp
case class Num(i: Int) extends Exp
case class Aop(o: String, a1: Exp, a2: Exp) extends Exp
case class Sequence(e1: Exp, e2: Exp) extends Exp
case class Bop(o: String, a1: Exp, a2: Exp) extends BExp


// compiler - built-in functions 
// copied from http://www.ceng.metu.edu.tr/courses/ceng444/link/jvm-cpm.html
//


// for generating new labels
var counter = -1

def Fresh(x: String) = {
  counter += 1
  x ++ "_" ++ counter.toString()
}



// Abstract syntax trees for the Fun language
abstract class KExp

case class KVar(s: String) extends KExp
case class KNum(i: Int) extends KExp
case class KAop(o: String, x1: String, x2: String) extends KExp
case class KIfeq(x1: String, x2: String, e1: KExp, e2: KExp) extends KExp {
  override def toString = s"KIf $x1 == $x2 \nIF\n$e1\nELSE\n$e2"

}
case class KCall(o: String, vrs: List[String]) extends KExp
case class KLet(x: String, e1: KExp, e2: KExp) extends KExp {
  override def toString = s"let $x = $e1 in \n$e2" 
}

def K(e: Exp) : KExp = e match {
  case Var(s) => KVar(s) 
  case Num(i) => KNum(i)
  case Aop(o, a1, a2) => {
    val x1 = Fresh("tmp")
    val x2 = Fresh("tmp") 
    KLet(x1, K(a1), KLet(x2, K(a2), KAop(o, x1, x2)))
  } 
  case Call(name: String, args: List[Exp]) => {
    val args_new = args.map{a => (Fresh("tmp"), K(a))}
    def aux(as: List[(String, KExp)]) : KExp = as match {
      case Nil => KCall(name, args_new.map(_._1))
      case (x, a)::rest => KLet(x, a, aux(rest))
    }
    aux(args_new)
  }
  case If(Bop("==", b1, b2), e1, e2) => {
    val x1 = Fresh("tmp")
    val x2 = Fresh("tmp") 
    KLet(x1, K(b1), KLet(x2, K(b2), KIfeq(x1, x2, K(e1), K(e2))))
  }
}

def Denest(e: KExp) : KExp = e match {
  case KLet(xt, e1, e2) => {
    def insert(e: KExp) : KExp = e match {
      case KLet(yt, e3, e4) => KLet(yt, e3, insert(e4))
      case e => KLet(xt, e, Denest(e2))
    }
    insert(Denest(e1))  
  }
  case KIfeq(x1, x2, e1, e2) =>  KIfeq(x1, x2, Denest(e1), Denest(e2))
  case _ => e
}


val e = Aop("*", Aop("+", Num(1), Call("foo", List(Var("a"), Num(3)))), Num(4))
println(K(e))
println()
println(Denest(K(e)))
println()



// convenient string interpolations 
// for instructions, labels and methods
import scala.language.implicitConversions
import scala.language.reflectiveCalls

implicit def sring_inters(sc: StringContext) = new {
    def i(args: Any*): String = "   " ++ sc.s(args:_*) ++ "\n"
    def l(args: Any*): String = sc.s(args:_*) ++ ":\n"
    def m(args: Any*): String = sc.s(args:_*) ++ "\n"
}


type Env = Map[String, Int]



// compile K expressions
def compile_exp(a: KExp) : String = a match {
  case KNum(i) => s"?$i?"
  case KVar(s) => s"?$s?"
  case KAop("+", x1, x2) => s"add i32 %$x1, i32 %$x2"
  case KAop("-", x1, x2) => s"sub i32 %$x1, i32 %$x2"
  case KAop("*", x1, x2) => s"mul i32 %$x1, i32 %$x2"
  case KLet(x: String, e1: KExp, e2: KExp) => {
    val is1 = compile_exp(e1)
    val is2 = compile_exp(e2)
    i"%$x = $is1" ++ is2
  }
  case KIfeq(x1, x2, a1, a2) => {
    val if_br = Fresh("if_br")
    val else_br = Fresh("else_br")
    val x = Fresh("tmp")
    i"%$x = icmp eq i32 %$x1, i32 %$x2" ++
    i"br i1 %$x, label %$if_br, label %$else_br" ++
    l"\n$if_br" ++
    compile_exp(a1) ++
    l"\n$else_br" ++ 
    compile_exp(a2)
  }
  case KCall(x1, args) => {
    s"Call $x1 ($args)"
  }
/*
  case Call(name, args) => {
    val is = "I" * args.length
    args.map(a => compile_exp(a, env)).mkString ++
    i"invokestatic XXX/XXX/$name($is)I"
  }
  case Sequence(a1, a2) => {
    compile_exp(a1, env) ++ i"pop" ++ compile_exp(a2, env)
  }
  case Write(a1) => {
    compile_exp(a1, env) ++
    i"dup" ++
    i"invokestatic XXX/XXX/write(I)V"
  }
  */
}

/*
// compile boolean expressions
def compile_bexp(b: BExp, env : Env, jmp: String) : String = b match {
  case Bop("==", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpne $jmp"
  case Bop("!=", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpeq $jmp"
  case Bop("<", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpge $jmp"
  case Bop("<=", a1, a2) => 
    compile_exp(a1, env) ++ compile_exp(a2, env) ++ i"if_icmpgt $jmp"
}
*/

// compile function for declarations and main
def compile_decl(d: Decl) : String = d match {
  case Def(name, args, body) => { 
    println(s"DEF\n $name ($args) = \nBODY:")
    println(Denest(K(body)))
    println()
    counter = -1
    m"define i32 @$name (${args.mkString("i32 %", ", i32 %", "")}) {" ++
    compile_exp(Denest(K(body))) ++
    m"}\n"
  }
  case Main(body) => {
    m"define i32 @main() {" ++
    compile_exp(Denest(K(body))) ++
    i"ret i32 0" ++
    m"}\n"
  }
}

// main compiler functions

def time_needed[T](i: Int, code: => T) = {
  val start = System.nanoTime()
  for (j <- 1 to i) code
  val end = System.nanoTime()
  (end - start)/(i * 1.0e9)
}

def deserialise[T](fname: String) : Try[T] = {
  import scala.util.Using
  Using(new ObjectInputStream(new FileInputStream(fname))) {
    in => in.readObject.asInstanceOf[T]
  }
}

def compile(class_name: String) : String = {
  val ast = deserialise[List[Decl]](class_name ++ ".prs").getOrElse(Nil) 
  println(ast(0).toString ++ "\n")
  val instructions = List(ast(0), ast(2)).map(compile_decl).mkString
  instructions
}

/*
def compile_to_file(class_name: String) = {
  val output = compile(class_name)
  scala.tools.nsc.io.File(s"${class_name}.j").writeAll(output)
}

def compile_and_run(class_name: String) : Unit = {
  compile_to_file(class_name)
  (s"java -jar jvm/jasmin-2.4/jasmin.jar ${class_name}.j").!!
  println("Time: " + time_needed(2, (s"java ${class_name}/${class_name}").!))
}
*/

// some examples of .fun files
//compile_to_file("fact")
//compile_and_run("fact")
//compile_and_run("defs")


def main(args: Array[String]) : Unit = 
   println(compile(args(0)))


}