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 3886 - (download) (annotate)
Fri May 20 15:10:11 2016 UTC (3 years ago) by jhr
File size: 23834 byte(s)
working on 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 * TreeIR.target_info -> 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

  (* for variables that are in an equivalence class (see UnifyVars), we use a single
   * TreeIR variable (or vector of variables) to represent them.
   *)
    datatype eq_var_rep = NOEQ | VAR of TV.t | VEC of TV.t list
    local
      val {peekFn : IR.var -> eq_var_rep option, setFn, ...} =
	    V.newProp (fn x => raise Fail(V.toString x))

      fun repOf (env, x, x') = (case peekFn x'
	     of SOME b => b
	      | NONE => let
		  val rep = (case V.ty x
			 of Ty.TensorTy[d] => VEC(Util.newVectorVars(Env.layoutVec env d))
			  | ty => VAR(Util.newLocalVar x)
			(* end case *))
		  in
		    setFn (x, rep);
		    rep
		  end
	    (* end case *))
    in

    fun eqClassRepOf (env, x) = (case UnifyVars.eqClassOf x
	   of SOME x' => repOf (env, x, x')
	    | NONE => NOEQ
	  (* end case *))

    fun useVar env = let
	  val useV = Env.useVar env
	  in
	    fn x => (case UnifyVars.eqClassOf x
		  of SOME x' => (case repOf (env, x, x')
		       of VAR x => Env.TREE(T.E_Var x)
			| VEC xs => let
			    val Ty.TensorTy[d] = V.ty x
			    in
			      Env.VEC(Env.layoutVec env d, List.map T.E_Var xs)
			    end
			| NOEQ => raise Fail "impossible"
		      (* end case *))
		   | NONE => useV x
		 (* end case *))
	  end
    end

    fun mkBlock stms = T.Block{locals = ref [], 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 mkAssign (x, e) = T.S_Assign(false, x, e)
    fun mkDefn (x, e) = T.S_Assign(true, x, e)

    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, ")"])

  (* define a new local variable and bind x to it. *)
    fun newLocal (env, x) = let
	  val x' = Util.newLocalVar x
	  in
	    Env.bindSimple (env, x, Env.TREE(T.E_Var x'));
	    x'
	  end

  (* get a variable's binding as a single argument expression.  This means that
   * if x is bound to a vector of expressions, then we need to pack it.
   *)
    fun singleArg env x = (case useVar env x
	   of Env.TREE e => e
	    | Env.VEC(layout, es) => T.E_Pack(layout, es)
	  (* end case *))

    fun scalarArg env x = (case useVar env x
	   of Env.TREE e => e
	    | _ => raise Fail("expected scalar binding for " ^ IR.Var.toString x)
	  (* end case *))

    fun vectorArg (env, x) = (case useVar env x
	   of Env.TREE e => (case V.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(concat[
			"expected ", V.toString x, " : 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, srcRator, args) = let
	  fun bindOp rator = Env.TREE(T.E_Op(rator, List.map (scalarArg env) args))
	  fun bindVOp rator = let
		val (layout, argss) = vectorArgs (env, args)
		fun mkArgs (_, [], []) = []
		  | mkArgs (w, p::ps, args::argss) =
		      T.E_Op(rator(w, p), args) :: mkArgs (w-p, ps, argss)
		val exps = mkArgs (#wid layout, #pieces layout, argss)
		in
		  Env.VEC(layout, exps)
		end
	  fun mkArgs f ({wid, pieces, ...} : TTy.vec_layout, args) = let
		fun mk (w, [p], [x]) = [T.E_Op(f(w, p, x))]
		  | mk (w, p::ps, x::xs) = T.E_Op(f(p, p, x)) :: mk (w-p, ps, xs)
		  | mk _ = raise Fail "mkArgs: arity mismatch"
		in
		  mk (wid, pieces, args)
		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 _ => let
		  val [s, v] = args
		  val s = scalarArg env s
		  val (layout, vs) = vectorArg (env, v)
		  val exps = mkArgs (fn (w, p, x) => (TOp.VScale(w, p), [s, x])) (layout, vs)
		  in
		    Env.VEC(layout, exps)
		  end
	      | Op.VMul _ => bindVOp TOp.VMul
	      | Op.VNeg _ => bindVOp TOp.VNeg
	      | Op.VSum _ => let
		  val [v] = args
		  val e::es = mkArgs (fn (w, p, x) => (TOp.VSum(w, p), [x])) (vectorArg (env, v))
		  in
		    Env.TREE(List.foldr (fn (e, es) => T.E_Op(TOp.RAdd, [e, es])) e es)
		  end
	      | Op.VIndex(_, i) => let
		  val [v] = args
(* FIXME: more efficient to lookup the variable and avoid expanding TREE args *)
		  val ({wid, pieces, ...}, es) = vectorArg (env, v)
		  fun select (_, wid, [w], [e]) = Env.TREE(T.E_Op(TOp.VIndex(wid, w, i), [e]))
		    | select (i, wid, w::ws, e::es) =
			if (i < w)
			  then Env.TREE(T.E_Op(TOp.VIndex(w, w, i), [e]))
			  else select (i-w, wid-w, ws, es)
		    | select _ = raise Fail("bogus " ^ Op.toString srcRator)
		  in
		    select (i, wid, pieces, es)
		  end
	      | Op.VClamp n => let
		  val [v, lo, hi] = args
		  val (layout, vs) = vectorArg (env, v)
		  val lo = scalarArg env lo
		  val hi = scalarArg env hi
		  val exps = mkArgs
			(fn (w, p, x) => (TOp.VClamp(w, p), [x, lo, hi]))
			  (layout, vs)
		  in
		    Env.VEC(layout, exps)
		  end
	      | Op.VMapClamp n => bindVOp TOp.VMapClamp
	      | Op.VLerp n => bindVOp TOp.VLerp
	      | Op.TensorIndex(ty, idxs) => bindOp(TOp.TensorIndex(Util.trType ty, idxs))
	      | Op.ProjectLast(ty, idxs) => bindOp(TOp.ProjectLast(Util.trType ty, idxs))
	      | Op.Zero ty => bindOp (TOp.Zero(Util.trType ty))
	      | Op.Select(ty, i) => bindOp (TOp.Select(Util.trType ty, i))
	      | Op.Subscript ty => bindOp (TOp.Subscript(Util.trType ty))
	      | Op.MkDynamic(ty, n) => bindOp (TOp.MkDynamic(Util.trType ty, n))
	      | Op.Append ty => bindOp (TOp.Append(Util.trType ty))
	      | Op.Prepend ty => bindOp (TOp.Prepend(Util.trType ty))
	      | Op.Concat ty => bindOp (TOp.Concat(Util.trType ty))
	      | Op.Range => bindOp TOp.Range
	      | Op.Length ty => bindOp (TOp.Length(Util.trType ty))
	      | Op.SphereQuery(ty1, ty2) => raise Fail "FIXME: SphereQuery"
	      | 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.RCeiling
	      | Op.Ceiling d => bindVOp TOp.VCeiling
	      | Op.Floor 1 => bindOp TOp.RFloor
	      | Op.Floor d => bindVOp TOp.VFloor
	      | Op.Round 1 => bindOp TOp.RRound
	      | Op.Round d => bindVOp TOp.VRound
	      | Op.Trunc 1 => bindOp TOp.RTrunc
	      | Op.Trunc d => bindVOp TOp.VTrunc
	      | Op.IntToReal => bindOp TOp.IntToReal
	      | Op.RealToInt 1 => bindOp TOp.RealToInt
	      | Op.RealToInt d => let
		  val layout = Env.layoutVec env d
		  val (_, args) = vectorArg (env, hd args)
		  in
		    case #pieces layout
		     of [w] => Env.TREE(T.E_Op(TOp.VToInt(d, w), args))
		      | _ => raise Fail(concat["FIXME: RealToInt<", Int.toString d, ">"])
		    (* end case *)
		  end
(* 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 => bindOp (TOp.Transform info)
	      | Op.Translate info => bindOp (TOp.Translate info)
	      | Op.ControlIndex(info, ctl, d) => bindOp (TOp.ControlIndex(info, ctl, d))
	      | Op.LoadVoxel info => bindOp (TOp.LoadVoxel info)
	      | Op.Inside(info, s) => bindOp (TOp.Inside(info, s))
	      | Op.ImageDim(info, d) => bindOp(TOp.ImageDim(info, d))
	      | Op.MathFn f => bindOp (TOp.MathFn f)
	      | rator => raise Fail("bogus operator " ^ Op.toString srcRator)
	    (* end case *)
	  end

(* cases:
	x in EqClass
		issue assignment; lhs is binding of representative (could be multiple vars)
	useCount(x) > 1 and rhs is not simple
	rhs is simple
	rhs is vector
*)
    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 eqClassRepOf(env, lhs)
		 of NOEQ => (Env.bindSimple (env, lhs, Env.TREE rhs); [])
		  | VAR x' => [mkAssign(x', rhs)]
		  | VEC _ => raise Fail "unexpected VEC"
		(* end case *))
	  fun assignOp (rator, args) = (case eqClassRepOf(env, lhs)
		 of NOEQ =>
		      [mkDefn(newLocal (env, lhs), T.E_Op(rator, List.map (scalarArg env) args))]
		  | VAR x' => [mkAssign(x', T.E_Op(rator, List.map (scalarArg env) args))]
		  | VEC _ => raise Fail "unexpected VEC"
		(* end case *))
	  in
	    case rhs
	     of IR.GLOBAL x => bindSimple (T.E_Global(mkGlobalVar x))
	      | IR.STATE(NONE, fld) =>
		  bindSimple (T.E_State(NONE, getStateVar fld))
	      | IR.STATE(SOME x, fld) =>
		  bindSimple (T.E_State(SOME(scalarArg env x), getStateVar fld))
	      | IR.VAR x => raise Fail "FIXME: VAR"
	      | IR.LIT lit => bindSimple (T.E_Lit lit)
	      | IR.OP(Op.EigenVecs2x2, args) => assignOp (TOp.EigenVecs2x2, args)
	      | IR.OP(Op.EigenVecs3x3, args) => assignOp (TOp.EigenVecs3x3, args)
	      | IR.OP(Op.EigenVals2x2, args) => assignOp (TOp.EigenVals2x2, args)
	      | IR.OP(Op.EigenVals3x3, args) => assignOp (TOp.EigenVals3x3, args)
	      | IR.OP(Op.Zero(ty as Ty.TensorTy dd), []) => let
		  val z = T.E_Lit(Literal.Real(RealLit.zero))
		  val sz = List.foldl Int.* 1 dd
		  in [
		    mkDefn (
		      newLocal(env, lhs),
		      T.E_Cons(List.tabulate(sz, z), Util.trType ty))
		  ] end
	      | IR.OP(Op.LoadSeq(ty, file), []) => let
		  val lhs = newLocal (env, lhs)
		  in
		    [T.S_LoadNrrd(lhs, file)]
		  end
	      | IR.OP(Op.LoadImage(ty, file), []) => let
		  val lhs = newLocal (env, lhs)
		  in
		    [T.S_LoadNrrd(lhs, file)]
		  end
	      | IR.OP(rator, args) => let
		  val rhs = trOp (env, rator, args)
		  val needAssignment = (V.useCount lhs > 1) orelse (Env.isInlineOp env rator)
		  in
		    case (rhs, eqClassRepOf(env, lhs), needAssignment)
		     of (_, NOEQ, false) => (Env.bindSimple (env, lhs, rhs); [])
		      | (Env.TREE e, NOEQ, true) => [mkDefn(newLocal(env, lhs), e)]
		      | (Env.TREE e, VAR x', _) => [mkAssign(x', e)]
		      | (Env.VEC(layout, es), NOEQ, true) => let
			  val vs = Util.newVectorVars layout
			  in
			    Env.bindSimple (env, lhs, Env.VEC(layout, List.map T.E_Var vs));
			    ListPair.mapEq mkDefn (vs, es)
			  end
		      | (Env.VEC(layout, es), VEC xs, _) => ListPair.mapEq mkAssign (xs, es)
		      | _ => raise Fail "inconsistent"
		    (* end case *)
		  end
	      | IR.CONS(args, Ty.TensorTy[d]) => let
		  val layout = Env.layoutVec env d
		  fun mkVecs (args, w::ws) = let
		      (* take arguments from args to build a vector value of width w; pad as
		       * necessary.
		       *)
			fun take (0, args, es) = T.E_Vec(w, List.rev es) :: mkVecs (args, ws)
			  | take (i, [], es) = if #padded layout andalso null ws
			      then [T.E_Vec(w, List.rev es)]
			      else raise Fail "too few arguments for CONS"
			  | take (i, arg::args, es) = take (i-1, args, scalarArg env arg :: es)
			in
			  take (w, args, [])
			end
		    | mkVecs ([], []) = []
		    | mkVecs (_, []) = raise Fail "too many arguments for CONS"
		  val es = mkVecs (args, #pieces layout)
		  in
		    case (eqClassRepOf(env, lhs), V.useCount lhs > 1)
		     of (NOEQ, false) => (Env.bindVar(env, lhs, Env.VEC(layout, es)); [])
		      | (NOEQ, true) => let
			  val vs = Util.newVectorVars layout
			  in
			    Env.bindSimple (env, lhs, Env.VEC(layout, List.map T.E_Var vs));
			    ListPair.mapEq mkDefn (vs, es)
			  end
		      | (VEC xs, _) => ListPair.mapEq mkAssign (xs, es)
		      | _ => raise Fail "inconsistent"
		    (* end case *)
		  end
	      | IR.CONS(args, ty) => [
		    mkDefn (
		      newLocal(env, lhs),
		      T.E_Cons(List.map (singleArg env) args, Util.trType ty))
		  ]
	      | IR.SEQ(args, ty) => [
		    mkDefn (
		      newLocal(env, lhs),
		      T.E_Seq(List.map (singleArg env) args, Util.trType ty))
		  ]
	      | rhs => raise Fail(concat["unexpected ", IR.RHS.toString rhs, " in LowIR code"])
	    (* end case *)
	  end
handle ex => (
print(concat["trAssign: ", V.toString lhs, " = ", IR.RHS.toString rhs, "\n"]);
raise ex)

  (* 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, cfg) = let
	  fun useScalar x = (case useVar env x
		 of Env.TREE e => e
		  | _ => raise Fail("expected scalar binding for " ^ V.toString x)
		(* end case *))
	  val _ = UnifyVars.analyze cfg
        (* join (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 ([], _, IR.JOIN _) = raise Fail "JOIN with no open if"
            | join ([], stms, _) = mkBlock (List.rev stms)
            | join (THEN_BR(stms1, cond, elseBr)::stk, thenBlk, k) = let
                val thenBlk = Env.flushPending (env, thenBlk)
                in
                  doNode (elseBr, ELSE_BR(stms1, cond, thenBlk, k)::stk, [])
                end
            | join (ELSE_BR(stms, cond, thenBlk, k1)::stk, elseBlk, k2) = let
                val elseBlk = Env.flushPending (env, elseBlk)
                in
                  case (k1, k2)
                   of (IR.JOIN{succ, ...}, IR.JOIN _) => let
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          doNode (!succ, stk, stm::stms)
                        end
                    | (IR.JOIN{succ, ...}, _) => let
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          doNode (!succ, stk, stm::stms)
                        end
                    | (_, IR.JOIN{succ, ...}) => let
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          doNode (!succ, stk, stm::stms)
                        end
                    | (_, _) => let
                        val stm = mkIf(cond, List.rev thenBlk, List.rev elseBlk)
                        in
                          mkBlock (List.rev(stm::stms))
                        end
                  (* end case *)
                end
	  and doNode (nd : IR.node, ifStk : open_if list, stms) = (case IR.Node.kind nd
                 of IR.NULL => raise Fail "unexpected NULL"
                  | IR.ENTRY{succ} => doNode (!succ, ifStk, stms)
                  | k as IR.JOIN _ => join (ifStk, stms, k)
                  | IR.COND{cond, trueBranch, falseBranch, ...} => let
                      val cond = useScalar (!cond)
                      val stms = Env.flushPending (env, stms)
                      in
                        doNode (!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 stms = Env.flushPending (env, stms)
		      val _ = Env.bindSimple (env, var, Env.TREE(T.E_Var var'))
		      val body = doNode (!bodyEntry, [], [])
		      val stm = T.S_Foreach(var', src, body)
		      in
			doNode (!succ, ifStk, stm::stms)
		      end
		  | IR.NEXT _ => mkBlock (List.rev stms)
                  | IR.COM {text, succ, ...} =>
                      doNode (!succ, ifStk, T.S_Comment text :: stms)
                  | IR.ASSIGN{stm=(lhs, rhs), succ, ...} => let
                      val stms' = trAssign (env, lhs, rhs)
                      in
                        doNode (!succ, ifStk, stms' @ stms)
                      end
                  | IR.MASSIGN{stm=([], Op.Print tys, xs), succ, ...} => let
		      val stm = T.S_Print(List.map Util.trType tys, List.map (singleArg env) xs)
		      in
			doNode (!succ, ifStk, stm :: stms)
		      end
                  | IR.MASSIGN{stm=(ys, rator, xs), succ, ...} => raise Fail(concat[
			"unexepected operator ", Op.toString rator, " for MASSIGN"
		      ])
                  | IR.GASSIGN{lhs, rhs, succ, ...} => let
                      val stm = T.S_GAssign(mkGlobalVar lhs, singleArg env rhs)
                      in
                        doNode (!succ, ifStk, stm::stms)
                      end
                  | IR.NEW{strand, args, succ, ...} => let
		      val stm = T.S_New(strand, List.map (singleArg env) args)
		      in
			doNode (!succ, ifStk, stm::stms)
		      end
                  | IR.SAVE{lhs, rhs, succ, ...} => let
                      val stm = T.S_Save(getStateVar lhs, singleArg env rhs)
                      in
                        doNode (!succ, ifStk, stm::stms)
                      end
                  | k as IR.EXIT{kind, succ, ...} => (case (!succ, kind)
                       of (NONE, ExitKind.RETURN) => mkBlock (List.rev(T.S_Exit :: stms))
                        | (NONE, ExitKind.ACTIVE) => mkBlock (List.rev(T.S_Active :: stms))
                        | (NONE, ExitKind.STABILIZE) => let
                            val stms = T.S_Stabilize :: stms
                            in
                              join (ifStk, stms, k)
                            end
                        | (NONE, ExitKind.DIE) => join (ifStk, T.S_Die :: stms, k)
                        | (NONE, ExitKind.UNREACHABLE) => join (ifStk, stms, k)
                        | (SOME nd, ExitKind.ACTIVE) => doNode (nd, ifStk, T.S_Active :: stms)
                        | (SOME nd, ExitKind.STABILIZE) => doNode (nd, ifStk, T.S_Stabilize :: stms)
                        | (SOME nd, ExitKind.DIE) => doNode (nd, ifStk, T.S_Die :: stms)
                        | (SOME nd, ExitKind.UNREACHABLE) => doNode (nd, ifStk, stms)
                        | _ => raise Fail("unexpected continuation edge from "^IR.Node.toString nd)
                      (* end case *))
                (* end case *))
	  in
	    doNode (IR.CFG.entry cfg, [], [])
	  end

    fun trCFG info cfg = ScopeVars.assignScopes ([], trCFGWithEnv (Env.new info, cfg))

    fun trStrand info strand = let
	  val trCFG = trCFG info
	  val IR.Strand{name, params, state, stateInit, initM, updateM, stabilizeM} = strand
          val params' = List.map Util.newParamVar params
	  val state' = List.map getStateVar state
	  val stateInit' = let
		val env = Env.new info
		in
          	  ListPair.appEq
		    (fn (x, x') => Env.bindSimple (env, x, Env.TREE(T.E_Var x')))
		      (params, params');
		  ScopeVars.assignScopes (params', trCFGWithEnv (env, stateInit))
		end
	  in
	    T.Strand{
		name = name,
		params = params',
		state = state',
		stateInit = stateInit',
		initM = Option.map trCFG initM,
		updateM = trCFG updateM,
		stabilizeM = Option.map trCFG stabilizeM
	      }
	  end

    fun translate (prog, info) = let
	(* first step is to flatten any nested CONS nodes *)
	  val prog = Flatten.transform prog
	  val LowIR.Program{
		  props, consts, inputs, constInit, globals, globalInit, strand, create, update
		} = prog
	  val trCFG = trCFG info
	  in
	    TreeIR.Program{
		props = props,
		target = info,
		consts = List.map mkGlobalVar consts,
		inputs = List.map (Inputs.map mkGlobalVar) inputs,
		constInit = trCFG constInit,
		globals = List.map mkGlobalVar globals,
		globalInit = trCFG globalInit,
		strand = trStrand info strand,
		create = let
		  val IR.Create{dim, code} = create
		  in
		    T.Create{dim = dim, code = trCFG code}
		  end,
		update = Option.map trCFG update
	      }
	  end

  end

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