Home My Page Projects Code Snippets Project Openings diderot
Summary Activity Tracker Tasks SCM

SCM Repository

[diderot] View of /branches/vis15/src/compiler/low-to-tree/low-to-tree.sml
ViewVC logotype

View of /branches/vis15/src/compiler/low-to-tree/low-to-tree.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3844 - (download) (annotate)
Tue May 10 19:15:03 2016 UTC (3 years, 1 month ago) by jhr
File size: 17881 byte(s)
  working in merge
(* low-to-tree.sml
 *
 * This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
 *
 * COPYRIGHT (c) 2016 The University of Chicago
 * All rights reserved.
 *)

structure LowToTree : sig

    val translate : LowIR.program * (int -> TreeTypes.vec_layout) -> TreeIR.program

  end = struct

    structure IR = LowIR
    structure V = LowIR.Var
    structure Ty = LowTypes
    structure Op = LowOps
    structure GV = IR.GlobalVar
    structure SV = IR.StateVar
    structure T = TreeIR
    structure TTy = TreeTypes
    structure TOp = TreeOps
    structure TV = TreeVar
    structure TGV = TreeGlobalVar
    structure TSV = TreeStateVar

  (* associate Tree IL globals variables with Low IL variables using properties *)
    local
      val {setFn, peekFn, ...} =
	    GV.newProp (fn x => raise Fail(concat["getGlobalVar(", GV.uniqueName x, ")"]))
    in
      fun mkGlobalVar x = (case peekFn x
	     of NONE => let
		    val x' = TGV.new {
			    name = GV.name x,
			    ty = Util.trType (GV.ty x),
			    input = GV.isInput x,
			    output = false, (* FIXME: change once we support output globals *)
			    varying = GV.isVarying x,
			    apiTy = if GV.isInput x
			      then SOME(Util.toAPIType (GV.ty x))
			      else NONE
			  }
		    in
		      setFn (x, x');
		      x'
		    end
	      | SOME x' => x'
	    (* end case *))
    end

  (* associate Tree IL state variables with Low IL variables using properties *)
    local
      fun mkStateVar x = TSV.new {
              name = SV.name x,
              ty = Util.trType (SV.ty x),
              varying = SV.isVarying x,
              apiTy = if (SV.isOutput x)
		then SOME(Util.toAPIType (SV.ty x))
		else NONE
            }
    in
    val {getFn = getStateVar, ...} = SV.newProp mkStateVar
    end

    fun mkBlock stms = T.Block{locals=[], body=stms}
    fun mkIf (x, stms, []) = T.S_IfThen(x, mkBlock stms)
      | mkIf (x, stms1, stms2) = T.S_IfThenElse(x, mkBlock stms1, mkBlock stms2)

    fun cvtScalarTy Ty.BoolTy = TTy.BoolTy
      | cvtScalarTy Ty.IntTy = TTy.IntTy
      | cvtScalarTy (Ty.TensorTy[]) = TTy.realTy
      | cvtScalarTy ty = raise Fail(concat["cvtScalarTy(", Ty.toString ty, ")"])

    fun vectorArg (env, x) = (case Env.useVar env x
	   of Env.TREE e => (case IR.Var.ty x
		 of Ty.TensorTy[d] => let
		      val layout = Env.layoutVec env d
(* QUESTION: can "e" be a complicated expression or are we guaranteed that it will just
 * be a memory reference?
 *)
		      val es = List.tabulate (
			    List.length(#pieces layout),
			    fn i => T.E_VLoad(layout, e, i))
		      in
			(layout, es)
		      end
		  | ty => raise Fail("expected TensorTy[_], but found " ^ Ty.toString ty)
		(* end case *))
	    | Env.VEC(layout, es) => (layout, es)
	  (* end case *))

  (* convert a list of LowIR variables, each of which are mapped
   * to lists of of vector expressions, to a list of list of expressions
   *)
    fun vectorArgs (env, []) = raise Fail "unexpected empty argument list"
      | vectorArgs (env, x::xs) = let
	  val (layout, exps) = vectorArg (env, x)
	  fun doArg (x, argLists) = let
		val (_, exps) = vectorArg (env, x)
		in
		  ListPair.mapEq (op ::) (exps, argLists)
		end
	  val argLists = List.foldl doArg [exps] xs
	  in
	    (layout, List.map List.rev argLists)
	  end

    fun trOp (env, lhs, srcRator, args) = let
	  fun bindOp rator = let
		fun getBinding x = (case Env.useVar env x
		       of Env.TREE e => e
			| _ => raise Fail("expected single binding for " ^ IR.Var.toString x)
		      (* end case *))
		in
		  Env.TREE(T.E_Op(rator, List.map getBinding args))
		end
	  fun bindVOp rator = let
		val (layout, argss) = vectorArgs (env, args)
		val exps = ListPair.map
		      (fn (w, args) => T.E_Op(rator w, args))
			(#pieces layout, argss)
		in
		  Env.VEC(layout, exps)
		end
	  in
	    case srcRator
	     of Op.IAdd => bindOp TOp.IAdd
	      | Op.ISub => bindOp TOp.ISub
	      | Op.IMul => bindOp TOp.IMul
	      | Op.IDiv => bindOp TOp.IDiv
	      | Op.IMod => bindOp TOp.IMod
	      | Op.INeg => bindOp TOp.INeg
(* QUESTION: should we just use VAdd 1, etc ?*)
	      | Op.RAdd => bindOp TOp.RAdd
	      | Op.RSub => bindOp TOp.RSub
	      | Op.RMul => bindOp TOp.RMul
	      | Op.RDiv => bindOp TOp.RDiv
	      | Op.RNeg => bindOp TOp.RNeg
	      | Op.LT ty => bindOp (TOp.LT (cvtScalarTy ty))
	      | Op.LTE ty => bindOp (TOp.LTE (cvtScalarTy ty))
	      | Op.EQ ty => bindOp (TOp.EQ (cvtScalarTy ty))
	      | Op.NEQ ty => bindOp (TOp.NEQ (cvtScalarTy ty))
	      | Op.GT ty => bindOp (TOp.GT (cvtScalarTy ty))
	      | Op.GTE ty => bindOp (TOp.GTE (cvtScalarTy ty))
	      | Op.Not => bindOp TOp.Not
	      | Op.Abs ty => bindOp (TOp.Abs (cvtScalarTy ty))
	      | Op.Max ty => bindOp (TOp.Max (cvtScalarTy ty))
	      | Op.Min ty => bindOp (TOp.Min (cvtScalarTy ty))
	      | Op.RClamp => bindOp TOp.RClamp
	      | Op.RLerp => bindOp TOp.RLerp
	      | Op.VAdd _ => bindVOp TOp.VAdd
	      | Op.VSub _ => bindVOp TOp.VSub
	      | Op.VScale _ => bindVOp TOp.VScale
	      | Op.VMul _ => bindVOp TOp.VMul
	      | Op.VNeg _ => bindVOp TOp.VNeg
	      | Op.VSum _ => ??
	      | Op.VIndex(_, i) => let
(* FIXME: more efficient to lookup the variable and avoid expanding TREE args *)
		  val ({pieces, ...}, es) = vectorArg (env, hd args)
		  fun select (i, w::ws, e::es) =
			if (i < w)
			  then Env.TREE(T.E_Op(TOp.VIndex(w, i), [e]))
			  else select (i-w, ws, es)
		    | select _ = raise Fail("bogus " ^ Op.toString srcRator)
		  in
		    select (i, pieces, es)
		  end
	      | Op.VClamp n => bindVOp TOp.VClamp
	      | Op.VMapClamp n => bindVOp TOp.VMapClamp
	      | Op.VLerp n => bindVOp TOp.VLerp
	      | Op.TensorIndex(ty, idxs) => ??
	      | Op.ProjectLast(ty, idxs) => ??
	      | Op.EigenVecs2x2 => ??
	      | Op.EigenVecs3x3 => ??
	      | Op.EigenVals2x2 => ??
	      | Op.EigenVals3x3 => ??
	      | Op.Zero ty => ??
	      | Op.Select(Ty.TupleTy tys, i) => ??
	      | Op.Subscript(Ty.SeqTy(ty, NONE)) => ??
	      | Op.Subscript(Ty.SeqTy(ty, SOME _)) => ??
	      | Op.MkDynamic(ty, n) => ??
	      | Op.Append ty => ??
	      | Op.Prepend ty => ??
	      | Op.Concat ty => ??
	      | Op.Range => ??
	      | Op.Length ty => ??
	      | Op.SphereQuery(ty1, ty2) => ??
	      | Op.Sqrt => bindOp TOp.Sqrt
	      | Op.Cos => bindOp TOp.Cos
	      | Op.ArcCos => bindOp TOp.ArcCos
	      | Op.Sin => bindOp TOp.Sin
	      | Op.ArcSin => bindOp TOp.ArcSin
	      | Op.Tan => bindOp TOp.Tan
	      | Op.ArcTan => bindOp TOp.ArcTan
	      | Op.Ceiling 1 => bindOp (TOp.Ceiling 1)
	      | Op.Ceiling d => ??
	      | Op.Floor 1 => bindOp (TOp.Floor 1)
	      | Op.Floor d => ??
	      | Op.Round 1 => bindOp (TOp.Floor 1)
	      | Op.Round d => ??
	      | Op.Trunc 1 => bindOp (TOp.Trunc 1)
	      | Op.Trunc d => ??
	      | Op.IntToReal => bindOp TOp.IntToReal
	      | Op.RealToInt 1 => ??
	      | Op.RealToInt d => ??
(* FIXME
	      | Op.R_All ty => ??
	      | Op.R_Exists ty => ??
	      | Op.R_Max ty => ??
	      | Op.R_Min ty => ??
	      | Op.R_Sum ty => ??
	      | Op.R_Product ty => ??
	      | Op.R_Mean ty => ??
	      | Op.R_Variance ty => ??
*)
	      | Op.Transform info => ??
	      | Op.Translate info => ??
	      | Op.ControlIndex(info, ctl, d) => ??
	      | Op.LoadVoxel info => ??
	      | Op.Inside(info, s) => ??
	      | Op.ImageDim(info, d) => bindOp(TOp.ImageDim(info, d))
	      | Op.LoadSeq(ty, file) => ??
	      | Op.LoadImage(ty, file) => ??
	      | Op.MathFn f => bindOp (TOp.MathFn f)
	      | rator => raise Fail("bogus operator " ^ Op.toString srcRator)
	    (* end case *)
	  end

    fun trAssign (env, lhs, rhs) = let
	(* simple binding for lhs variable; we check to see if it is part of an merged
	 * equivalence class, in which case we need to generate the assigment.
	 *)
	  fun bindSimple rhs = (case UnifyVars.eqClassOf lhs
		 of SOME x => ??
		  | NONE => (Env.bindSimple (env, lhs, rhs); (env, []))
		(* end case *))
	  in
	    case rhs
	     of IR.GLOBAL x => bindSimple (T.E_Global(mkGlobalVar x))
	      | IR.STATE x => bindSimple (T.E_State(getStateVar x))
	      | IR.VAR x => (case Env.useVar env x
		   of Env.TREE e => ??
		    | Env.VEC(layout, es) => ??
		  (* end case *))
	      | IR.LIT lit => bindSimple (env, lhs, T.E_Lit lit)
	      | IR.OP(rator, args) => ??
	      | IR.CONS(args, ty) => ??
	      | IR.SEQ(args, ty) => ??
	      | IR.EINAPP _ => raise Fail "unexpected EINAPP in LowIR code"
	    (* end case *)
	  end

  (* In order to reconstruct the block-structure from the CFG, we keep a stack of open ifs.
   * the items on this stack distinguish between when we are processing the then and else
   * branches of the if.
   *)
    datatype open_if
    (* working on the "then" branch.  The fields are statments that preceed the if, the condition,
     * and the else-branch node.
     *)
      = THEN_BR of T.stm list * T.exp * IR.node
    (* working on the "else" branch.  The fields are statments that preceed the if, the condition,
     * the "then" branch statements, and the node kind that terminated the "then" branch (will be
     * a JOIN or EXIT(DIE, STABILIZE, or UNREACHABLE)).
     *)
      | ELSE_BR of T.stm list * T.exp * T.stm list * IR.node_kind

    fun trCFGWithEnv (env, prefix, cfg) = let
	  fun useScalar x = (case Env.useVar env x
		 of Env.TREE e => e
		  | _ => raise Fail("expected scalar binding for " ^ V.toString x)
		(* end case *))
	  val _ = UnifyVars.analyze cfg
        (* join (env, stk, stms, k): handle a control-flow join, where env is the
         * current environment, stk is the stack of open ifs (the top of stk specifies
         * which branch we are in), stms are the TreeIL statements preceding the join
         * on the current path, and k is the kind of the join node (either JOIN or EXIT).
         *)
          fun join (env, [], _, IR.JOIN _) = raise Fail "JOIN with no open if"
            | join (env, [], stms, _) = Env.endScope (env, prefix @ List.rev stms)
            | join (env, THEN_BR(stms1, cond, elseBr)::stk, thenBlk, k) = let
                val (env, thenBlk) = Env.flushPending (env, thenBlk)
                in
                  doNode (env, elseBr, ELSE_BR(stms1, cond, thenBlk, k)::stk, [])
                end
            | join (env, ELSE_BR(stms, cond, thenBlk, k1)::stk, elseBlk, k2) = let
                val (env, elseBlk) = Env.flushPending (env, elseBlk)
                in
                  case (k1, k2)
                   of (IR.JOIN{phis, succ, ...}, IR.JOIN _) => let
                        val (env, [thenBlk, elseBlk]) =
                              List.foldl doPhi (env, [thenBlk, elseBlk]) (!phis)
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          doNode (env, !succ, stk, stm::stms)
                        end
                    | (IR.JOIN{phis, succ, ...}, _) => let
                        val (env, [thenBlk]) = List.foldl doPhi (env, [thenBlk]) (!phis)
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          doNode (env, !succ, stk, stm::stms)
                        end
                    | (_, IR.JOIN{phis, succ, ...}) => let
                        val (env, [elseBlk]) = List.foldl doPhi (env, [elseBlk]) (!phis)
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          doNode (env, !succ, stk, stm::stms)
                        end
                    | (_, _) => let
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          Env.endScope (env, prefix @ List.rev(stm::stms))
                        end
                  (* end case *)
                end
	  and doNode (env, nd : IR.node, ifStk : open_if list, stms) = (case IR.Node.kind nd
                 of IR.NULL => raise Fail "unexpected NULL"
                  | IR.ENTRY{succ} => doNode (env, !succ, ifStk, stms)
                  | k as IR.JOIN _ => join (env, ifStk, stms, k)
                  | IR.COND{cond, trueBranch, falseBranch, ...} => let
                      val cond = useScalar (!cond)
                      val (env, stms) = Env.flushPending (env, stms)
                      in
                        doNode (env, !trueBranch, THEN_BR(stms, cond, !falseBranch)::ifStk, [])
                      end
		  | IR.FOREACH{var, src, bodyEntry, succ, ...} => let
		      val src = useScalar (!src)
		      val var = Util.newIterVar var
                      val (env, stms) = Env.flushPending (env, stms)
		      val body = doNode (env, !bodyEntry, [], [])
		      val stm = T.S_Foreach(var, src, body)
		      in
			doNode (env, !succ, ifStk, stm::stms)
		      end
		  | IR.NEXT _ => Env.endScope (env, List.rev stms)
                  | IR.COM {text, succ, ...} =>
                      doNode (env, !succ, ifStk, T.S_Comment text :: stms)
                  | IR.ASSIGN{stm=(lhs, rhs), succ, ...} => let
                      val (env, stms') = doAssign (env, lhs, rhs)
                      in
                        doNode (env, !succ, ifStk, stms' @ stms)
                      end
                  | IR.MASSIGN{stm=(ys, rator, xs), succ, ...} => let
                      fun doit () = let
                            fun doLHSVar (y, (env, ys)) = let
                                  val t = Util.newLocalVar y
                                  in
                                    (rename (Util.addLocalVar(env, t), y, t), t::ys)
                                  end
                            val (env, ys) = List.foldr doLHSVar (env, []) ys
(* FIXME: need to translate the operator *)
                            val exp = T.E_Op(??, List.map (Env.useVar env) xs)
                            val stm = T.S_MAssign(ys, exp)
                            in
                              doNode (env, !succ, ifStk, stm :: stms)
                            end
                      in
                        case rator
                         of Op.Print _ => if Target.supportsPrinting()
                              then doit ()
                              else doNode (env, !succ, ifStk, stms)
                          | _ => doit()
                        (* end case *)
                      end
                  | IR.GASSIGN{lhs, rhs, succ, ...} => let
                      val stm = (case useAsInput(env, rhs)
                             of NONE => T.S_GAssign(mkGlobalVar lhs, Env.useVar env rhs)
                              | SOME mkStm => mkStm(mkGlobalVar lhs)
                            (* end case *))
                      in
                        doNode (env, !succ, ifStk, stm::stms)
                      end
                  | IR.NEW{strand, args, succ, ...} => raise Fail "NEW unimplemented"
                  | IR.SAVE{lhs, rhs, succ, ...} => let
                      val stm = T.S_Save([getStateVar lhs], Env.useVar env rhs)
                      in
                        doNode (env, !succ, ifStk, stm::stms)
                      end
                  | k as IR.EXIT{kind, succ, ...} => (case (!succ, kind)
                       of (NONE, ExitKind.RETURN) => let
                            val suffix = [T.S_Exit]
                            in
                              Env.endScope (env, prefix @ List.revAppend(stms, suffix))
                            end
                        | (NONE, ExitKind.ACTIVE) => let
                            val suffix = [T.S_Active]
                            in
                              Env.endScope  (env, prefix @ List.revAppend(stms, suffix))
                            end
                        | (NONE, ExitKind.STABILIZE) => let
                            val stms = T.S_Stabilize :: stms
                            in
                              join (env, ifStk, stms, k)
                            end
                        | (NONE, ExitKind.DIE) => join (env, ifStk, T.S_Die :: stms, k)
                        | (NONE, ExitKind.UNREACHABLE) => join (env, ifStk, stms, k)
                        | (SOME nd, ExitKind.ACTIVE) => doNode (env, nd, ifStk, T.S_Active :: stms)
                        | (SOME nd, ExitKind.STABILIZE) => doNode (env, nd, ifStk, T.S_Stabilize :: stms)
                        | (SOME nd, ExitKind.DIE) => doNode (env, nd, ifStk, T.S_Die :: stms)
                        | (SOME nd, ExitKind.UNREACHABLE) => doNode (env, nd, ifStk, stms)
                        | _ => raise Fail("unexpected continuation edge from "^IR.Node.toString nd)
                      (* end case *))
                (* end case *))
	  in
	    doNode (env, IR.CFG.entry cfg, [], [])
	  end

    fun trCFG vecLayout (prefix, cfg) = trCFGWithEnv (Env.new vecLayout, prefix, cfg)

    fun trStrand layout strand = let
	  val trCFG = trCFG layout
	  val IR.Strand{name, params, state, stateInit, initM, updateM, stabilizeM} = strand
          val params' = List.map Util.newParamVar params
          val env = ListPair.foldlEq
		(fn (x, x', env) => rename(env, x, x')) (Env.new layout) (params, params')
	  val state' = List.map getStateVar state
	  in
	    T.Strand{
		name = name,
		params = params',
		state = state',
		stateInit = trCFGWithEnv (env, stateInit),
		initM = Option.map (fn cfg => trCFG ([], cfg)) initM,
		updateM = trCFG ([], updateM),
		stabilizeM = Option.map (fn cfg => trCFG ([], cfg)) stabilizeM
	      }
	  end

    fun translate (prog, vecLayout) = let
	  val LowIR.Program{
		  props, consts, inputs, constInit, globals, globalInit, strand, create, update
		} = prog
	  in
	    TreeIR.Program{
		props = props,
		consts = ??,
		inputs = ??,
		constInit = ??,
		globals = ??,
		globalInit = ??,
		strand = trStrand vecLayout strand,
		create = ??,
		update = ??
	      }
	  end

  end

root@smlnj-gforge.cs.uchicago.edu
ViewVC Help
Powered by ViewVC 1.0.0