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

SCM Repository

[diderot] Annotation of /branches/vis15/src/compiler/translate/translate.sml
ViewVC logotype

Annotation of /branches/vis15/src/compiler/translate/translate.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 5286 - (view) (download)

1 : jhr 3471 (* translate.sml
2 :     *
3 :     * This code is part of the Diderot Project (http://diderot-language.cs.uchicago.edu)
4 :     *
5 :     * COPYRIGHT (c) 2015 The University of Chicago
6 :     * All rights reserved.
7 :     *
8 : jhr 3476 * Translate Simple-AST code into the HighIR representation. This translation is based on the
9 : jhr 3471 * algorithm described in
10 :     *
11 :     * Single-pass generation of static single assignment form for structured languages
12 :     * ACM TOPLAS, Nov. 1994
13 :     * by Brandis and MossenBock.
14 :     *)
15 :    
16 :     structure Translate : sig
17 :    
18 : jhr 3476 val translate : Simple.program -> HighIR.program
19 : jhr 3471
20 :     end = struct
21 :    
22 :     structure S = Simple
23 :     structure Ty = SimpleTypes
24 : jhr 3485 structure SV = SimpleVar
25 :     structure VMap = SV.Map
26 :     structure VSet = SV.Set
27 : jhr 3476 structure IR = HighIR
28 : jhr 3471 structure Op = HighOps
29 : jhr 3476 structure DstTy = HighTypes
30 :     structure Census = HighCensus
31 : jhr 3493 structure Inp = Inputs
32 : jhr 3471
33 :     val cvtTy = TranslateTy.tr
34 :    
35 : jhr 5286 (* code contexts *)
36 :     datatype context = Method | GlobalUpdate | Other
37 :    
38 : jhr 3471 (* maps from SimpleAST variables to the current corresponding SSA variable *)
39 : jhr 5286 datatype env = E of context * IR.var VMap.map
40 : jhr 3471
41 :     (* +DEBUG *)
42 : jhr 5286 fun prEnv (prefix, E(_, env)) = let
43 : jhr 3471 val wid = ref 0
44 :     fun pr s = (print s; wid := !wid + size s)
45 :     fun nl () = if (!wid > 0) then (print "\n"; wid := 0) else ()
46 :     fun prElem (src, dst) = let
47 :     val s = String.concat [
48 : jhr 3485 " ", SV.uniqueNameOf src, "->", IR.Var.toString dst
49 : jhr 3471 ]
50 :     in
51 :     pr s;
52 :     if (!wid >= 100) then (nl(); pr " ") else ()
53 :     end
54 :     in
55 :     pr prefix; pr " ENV: {"; nl(); pr " ";
56 :     VMap.appi prElem env;
57 :     nl(); pr "}"; nl()
58 :     end
59 :     (* -DEBUG *)
60 :    
61 : jhr 3846 (* a property to map Simple variables to High IR state variables. We need this to support
62 :     * reading the state of other strands.
63 :     *)
64 :     val {getFn=getStateVar, ...} = let
65 : jhr 4317 fun newSVar x = IR.StateVar.new (
66 :     SV.kindOf x = SV.StrandOutputVar,
67 :     SV.nameOf x, cvtTy(SV.typeOf x),
68 :     AnalyzeSimple.varyingStateVar x,
69 :     AnalyzeSimple.sharedStateVar x)
70 :     in
71 :     SV.newProp newSVar
72 :     end
73 : jhr 3846
74 : jhr 5286 fun emptyEnv cxt = E(cxt, VMap.empty)
75 :    
76 :     fun lookup (E(_, vMap)) x = (case VMap.find (vMap, x)
77 : jhr 3471 of SOME x' => x'
78 :     | NONE => raise Fail(concat[
79 : jhr 4505 "no binding for ", SV.kindToString(SV.kindOf x), " ",
80 : jhr 4628 SV.uniqueNameOf x, " in environment"
81 : jhr 3471 ])
82 :     (* end case *))
83 :    
84 : jhr 5286 fun find (E(_, vMap), x) = VMap.find(vMap, x)
85 :    
86 :     fun insert (E(cxt, vMap), x, x') = E(cxt, VMap.insert(vMap, x, x'))
87 :    
88 :     fun context (E(_, vMap), cxt) = E(cxt, vMap)
89 :    
90 :     fun inMethod (E(Method, _)) = true
91 :     | inMethod _ = false
92 :    
93 :     fun inGlobalUpdate (E(GlobalUpdate, _)) = true
94 :     | inGlobalUpdate _ = false
95 :    
96 : jhr 3471 (* create a new instance of a variable *)
97 : jhr 3485 fun newVar x = IR.Var.new (SV.nameOf x, cvtTy(SV.typeOf x))
98 : jhr 3471
99 : jhr 3506 (* is a Simple AST variable mapped to an IR.global_var? *)
100 :     fun isGlobalVar x = (case SV.kindOf x
101 : jhr 4317 of SV.ConstVar => true
102 :     | SV.InputVar => true
103 :     | SV.GlobalVar => true
104 :     | _ => false
105 :     (* end case *))
106 : jhr 3506
107 :     (* convert a global and cache the result in a property *)
108 :     local
109 :     fun new x = let
110 : jhr 4317 val kind = (case SV.kindOf x
111 :     of SV.ConstVar => IR.ConstVar
112 :     | SV.InputVar => IR.InputVar
113 :     | SV.GlobalVar => IR.GlobalVar
114 :     | k => raise Fail(concat[
115 :     "global variable ", SV.uniqueNameOf x,
116 :     " has kind ", SV.kindToString k
117 :     ])
118 :     (* end case *))
119 :     in
120 :     IR.GlobalVar.new(
121 :     kind, AnalyzeSimple.updatedGlobal x, SV.nameOf x, cvtTy(SV.typeOf x))
122 :     end
123 : jhr 3506 in
124 :     val {getFn = cvtGlobalVar, ...} = SV.newProp new
125 : jhr 4163 end (* local *)
126 : jhr 3506
127 : jhr 4163 (* convert a function variable and cache the result in a property *)
128 :     local
129 :     fun new f = let
130 : jhr 4317 val (resTy, paramTys) = SimpleFunc.typeOf f
131 :     in
132 :     IR.Func.new(SimpleFunc.nameOf f, cvtTy resTy, List.map cvtTy paramTys)
133 :     end
134 : jhr 4163 in
135 :     val {getFn = cvtFuncVar, ...} = SimpleFunc.newProp new
136 :     end (* local *)
137 :    
138 : jhr 3471 (* generate fresh SSA variables and add them to the environment *)
139 :     fun freshVars (env, xs) = let
140 :     fun cvtVar (x, (env, xs)) = let
141 :     val x' = newVar x
142 :     in
143 : jhr 5286 (insert(env, x, x'), x'::xs)
144 : jhr 3471 end
145 :     val (env, xs) = List.foldl cvtVar (env, []) xs
146 :     in
147 :     (env, List.rev xs)
148 :     end
149 :    
150 :     (* a pending-join node tracks the phi nodes needed to join the assignments
151 :     * that flow into the join node.
152 :     *)
153 :     datatype join = JOIN of {
154 :     env : env, (* the environment that was current at the conditional *)
155 :     (* associated with this node. *)
156 :     arity : int ref, (* actual number of predecessors *)
157 : jhr 3476 nd : IR.node, (* the CFG node for this pending join *)
158 :     phiMap : (IR.var * IR.var list) VMap.map ref,
159 : jhr 3471 (* a mapping from Simple AST variables that are assigned *)
160 :     (* to their phi nodes. *)
161 :     predKill : bool array (* killed predecessor edges (because of DIE or STABILIZE *)
162 :     }
163 :    
164 :     (* a stack of pending joins. The first component specifies the path index of the current
165 :     * path to the join.
166 :     *)
167 :     type pending_joins = (int * join) list
168 :    
169 : jhr 3504 (* create a new pending-join node for a conditional *)
170 : jhr 3471 fun newJoin (env, arity) = JOIN{
171 : jhr 3476 env = env, arity = ref arity, nd = IR.Node.mkJOIN [], phiMap = ref VMap.empty,
172 : jhr 3471 predKill = Array.array(arity, false)
173 :     }
174 :    
175 : jhr 3504 (* create a new pending-join node for a loop *)
176 : jhr 3502 fun newForeach (env, x, xs, phiVars) = let
177 : jhr 4368 (* for each assigned variable y in the body of the loop, we will need a phi node
178 :     * y'' = PHI(y', y''')
179 :     * where y' is the binding of y coming into the loop and y''' is the binding of y
180 :     * at the end of the loop body. Since we don't know what y''' is at this point, we
181 :     * just use y''.
182 :     *)
183 : jhr 5286 fun doVar (y, (env', phiMap)) = let
184 :     val y' = lookup env y
185 :     val y'' = newVar y
186 :     in
187 :     (insert(env', y, y''), VMap.insert(phiMap, y, (y'', [y', y''])))
188 :     end
189 : jhr 4317 val (env', phiMap) = List.foldl doVar (env, VMap.empty) phiVars
190 :     in
191 :     JOIN{
192 :     env = env',
193 :     arity = ref 2,
194 :     nd = IR.Node.mkFOREACH(x, xs),
195 :     phiMap = ref phiMap,
196 :     predKill = Array.array(2, false)
197 :     }
198 :     end
199 : jhr 3500
200 : jhr 4168 (* record that a path to the top join in the stack has been killed because of RETURN,
201 :     * DIE or STABILIZE
202 :     *)
203 : jhr 3471 fun killPath ((i, JOIN{arity, predKill, ...}) :: _) = (
204 :     arity := !arity - 1;
205 :     Array.update (predKill, i, true))
206 :     | killPath _ = ()
207 :    
208 : jhr 3476 (* record an assignment to the IR variable dstVar (corresponding to the Simple AST variable
209 : jhr 3471 * srcVar) in the current pending-join node. The predIndex specifies which path into the
210 :     * JOIN node this assignment occurs on.
211 :     *)
212 : jhr 4505 fun recordAssign ((predIndex, JOIN{env, phiMap, predKill, nd, ...})::_, srcVar, dstVar) = let
213 : jhr 3471 val arity = Array.length predKill (* the original arity before any killPath calls *)
214 :     val m = !phiMap
215 :     in
216 : jhr 5286 case find (env, srcVar)
217 : jhr 3471 of NONE => () (* local temporary *)
218 :     | SOME dstVar' => (case VMap.find (m, srcVar)
219 :     of NONE => let
220 :     val lhs = newVar srcVar
221 :     val rhs = List.tabulate (arity, fn i => if (i = predIndex) then dstVar else dstVar')
222 :     in
223 : jhr 4391 (**
224 : jhr 3485 print(concat["recordAssign: ", SV.uniqueNameOf srcVar, " --> ", IR.Var.toString lhs,
225 : jhr 3476 " @ ", IR.Node.toString nd, "\n"]);
226 : jhr 4391 **)
227 : jhr 3471 phiMap := VMap.insert (m, srcVar, (lhs, rhs))
228 :     end
229 :     | SOME(lhs, rhs) => let
230 :     fun update (i, l as x::r) = if (i = predIndex)
231 :     then dstVar::r
232 :     else x::update(i+1, r)
233 :     | update _ = raise Fail "invalid predecessor index"
234 :     in
235 :     phiMap := VMap.insert (m, srcVar, (lhs, update(0, rhs)))
236 :     end
237 :     (* end case *))
238 :     (* end case *)
239 :     end
240 : jhr 4505 | recordAssign ([], _, _) = ()
241 : jhr 3471
242 :     (* complete a pending join operation by filling in the phi nodes from the phi map and
243 :     * updating the environment.
244 :     *)
245 :     fun commitJoin (joinStk, JOIN{env, arity, nd, phiMap, predKill}) = let
246 : jhr 4317 val (preds, phis, mask) = (case IR.Node.kind nd
247 :     of IR.JOIN{preds, phis, mask, ...} => (!preds, phis, mask)
248 :     | IR.FOREACH{pred, bodyExit, phis, mask, ...} => ([!pred, !bodyExit], phis, mask)
249 :     | _ => raise Fail "invalid JOIN node"
250 :     (* end case *))
251 : jhr 3471 (* update the predKill array based on reachability *)
252 :     val _ = let
253 :     fun update (_, []) = ()
254 :     | update (i, nd::nds) = (
255 : jhr 3476 if IR.Node.isReachable nd then ()
256 : jhr 3471 else if Array.sub(predKill, i) then ()
257 :     else (arity := !arity-1; Array.update(predKill, i, true));
258 :     update (i+1, nds))
259 :     in
260 : jhr 3509 update (0, preds)
261 : jhr 3471 end
262 :     (* compute the predecessor mask *)
263 :     val mask' = Array.foldr (op ::) [] predKill
264 :     in
265 :     mask := mask';
266 : jhr 4628 if (!arity = 0)
267 :     then env (* all incoming edges are fake *)
268 :     else if (!arity < Array.length predKill)
269 : jhr 4387 then let
270 : jhr 4628 (* filter out variables that correspond to fake preds from the RHS of a phi *)
271 :     fun filterPhiRHS xs = let
272 :     fun f ([], _, xs') = List.rev xs'
273 :     | f (x::xs, i, xs') = if Array.sub(predKill, i)
274 :     then f (xs, i+1, NONE :: xs')
275 :     else f (xs, i+1, (SOME x) :: xs')
276 :     in
277 :     f (xs, 0, [])
278 :     end
279 :     fun doVar (srcVar, phi as (dstVar, srcVars), (env, phis)) = (
280 : jhr 3471 (*
281 : jhr 3485 print(concat["doVar (", SV.uniqueNameOf srcVar, ", ", IR.phiToString phi, ", _) @ ", IR.Node.toString nd, "\n"]);
282 : jhr 3471 *)
283 : jhr 4628 recordAssign (joinStk, srcVar, dstVar);
284 : jhr 5286 (insert (env, srcVar, dstVar), (dstVar, filterPhiRHS srcVars)::phis))
285 : jhr 4628 val (env, phis') = VMap.foldli doVar (env, []) (!phiMap)
286 :     in
287 :     phis := phis';
288 :     env
289 :     end
290 :     else let
291 :     fun doVar (srcVar, phi as (dstVar, xs), (env, phis)) = let
292 :     val xs = List.map SOME xs
293 :     in
294 : jhr 3471 (*
295 : jhr 3485 print(concat["doVar (", SV.uniqueNameOf srcVar, ", ", IR.phiToString phi, ", _) @ ", IR.Node.toString nd, "\n"]);
296 : jhr 3471 *)
297 : jhr 4628 recordAssign (joinStk, srcVar, dstVar);
298 :     IR.Var.setBinding (dstVar, IR.VB_PHI xs);
299 : jhr 5286 (insert (env, srcVar, dstVar), (dstVar, xs)::phis)
300 : jhr 4628 end
301 :     val (env, phis') = VMap.foldli doVar (env, []) (!phiMap)
302 :     in
303 :     phis := phis';
304 :     env
305 :     end
306 : jhr 3471 end
307 :    
308 :     (* expression translation *)
309 :     fun cvtExp (env : env, lhs, exp) = (case exp
310 : jhr 3476 of S.E_Var x => [IR.ASSGN(lhs, IR.VAR(lookup env x))]
311 :     | S.E_Lit lit => [IR.ASSGN(lhs, IR.LIT lit)]
312 : jhr 4317 | S.E_Kernel h => [IR.ASSGN(lhs, IR.OP(Op.Kernel(h, 0), []))]
313 :     | S.E_Select(x, fld) => [IR.ASSGN(lhs, IR.STATE(SOME(lookup env x), getStateVar fld))]
314 : jhr 4163 | S.E_Apply(f, args) =>
315 : jhr 4317 [IR.ASSGN(lhs, IR.APPLY(cvtFuncVar f, List.map (lookup env) args))]
316 : jhr 3471 | S.E_Prim(f, tyArgs, args, ty) => let
317 :     val args' = List.map (lookup env) args
318 :     in
319 :     TranslateBasis.translate (lhs, f, tyArgs, args')
320 :     end
321 : jhr 4163 | S.E_Tensor(args, _) =>
322 : jhr 4317 [IR.ASSGN(lhs, IR.CONS(List.map (lookup env) args, IR.Var.ty lhs))]
323 : jhr 3476 | S.E_Seq(args, _) => [IR.ASSGN(lhs, IR.SEQ(List.map (lookup env) args, IR.Var.ty lhs))]
324 : jhr 4317 | S.E_Tuple xs => raise Fail "FIXME: E_Tuple"
325 :     | S.E_Project(x, i) => raise Fail "FIXME: E_Project"
326 : cchiw 4155 | S.E_Slice(x, indices, ty as Ty.T_Field{diff, dim, shape}) => let
327 :     val x = lookup env x
328 :     (* extract the integer indices from the mask *)
329 :     val args' = List.mapPartial Fn.id indices
330 :     val mask' = List.map Option.isSome indices
331 :     val rator = MkOperators.sliceF(mask', args', shape, dim)
332 :     val ein = IR.EINAPP(rator, [x])
333 :     in
334 :     [IR.ASSGN(lhs, ein)]
335 :     end
336 : jhr 3471 | S.E_Slice(x, indices, ty) => let
337 :     val x = lookup env x
338 : jhr 4317 (* check the indices to the slice. There are two special cases: if all of the indices
339 :     * are NONE, then the result is just the original tensor; and if all of the indices
340 :     * are SOME ix, then the result is scalar so we use TensorIndex.
341 :     *)
342 : cchiw 3991 fun chkIndices ([], _, true, idxs) = IR.OP(Op.TensorIndex(IR.Var.ty x, rev idxs), [x])
343 : jhr 4317 | chkIndices ([], true, _, _) = IR.VAR x (* all axes *)
344 :     | chkIndices (NONE :: r, true, _, _) = chkIndices (r, true, false, [])
345 :     | chkIndices (SOME ix :: r, _, true, idxs) = chkIndices (r, false, true, ix::idxs)
346 :     | chkIndices _ = let
347 :     (* extract the integer indices from the mask *)
348 :     val args' = List.mapPartial Fn.id indices
349 :     val mask' = List.map Option.isSome indices
350 :     val rator = (case (IR.Var.ty lhs, IR.Var.ty x, ty)
351 :     of (DstTy.TensorTy rstTy, DstTy.TensorTy argTy, _) =>
352 :     MkOperators.sliceT (mask', args', rstTy, argTy)
353 :     | (_, _, Ty.T_Field{diff, dim, shape}) =>
354 :     MkOperators.sliceF(mask', args', shape, dim)
355 :     | (_, _, _ ) => raise Fail "unsupported type"
356 :     (* end case *))
357 :     in
358 :     IR.EINAPP(rator, [x])
359 :     end
360 : jhr 3471 in
361 : jhr 4317 [IR.ASSGN(lhs, chkIndices (indices, true, true, []))]
362 : jhr 3471 end
363 :     | S.E_Coerce{srcTy, dstTy, x} => (case (srcTy, dstTy)
364 :     of (Ty.T_Int, Ty.T_Tensor _) =>
365 : jhr 3476 [IR.ASSGN(lhs, IR.OP(Op.IntToReal, [lookup env x]))]
366 : jhr 3485 | (Ty.T_Sequence(ty, SOME n), Ty.T_Sequence(_, NONE)) =>
367 : jhr 3476 [IR.ASSGN(lhs, IR.OP(Op.MkDynamic(cvtTy ty, n), [lookup env x]))]
368 : jhr 3471 | (Ty.T_Field _, Ty.T_Field _) =>
369 :     (* change in continuity is a no-op *)
370 : jhr 3476 [IR.ASSGN(lhs, IR.VAR(lookup env x))]
371 : jhr 4317 | (Ty.T_Kernel, Ty.T_Kernel) =>
372 : jhr 4207 (* change in continuity is a no-op *)
373 :     [IR.ASSGN(lhs, IR.VAR(lookup env x))]
374 : jhr 3471 | _ => raise Fail(concat[
375 :     "unsupported type coercion: ", Ty.toString srcTy,
376 :     " ==> ", Ty.toString dstTy
377 :     ])
378 :     (* end case *))
379 : jhr 4317 | S.E_BorderCtl(ctl, img) => let
380 :     val img = lookup env img
381 :     val DstTy.ImageTy info = IR.Var.ty img
382 :     val (rator, args) = (case ctl
383 :     of BorderCtl.Default x => (Op.BorderCtlDefault info, [lookup env x, img])
384 :     | BorderCtl.Clamp => (Op.BorderCtlClamp info, [img])
385 :     | BorderCtl.Mirror => (Op.BorderCtlMirror info, [img])
386 :     | BorderCtl.Wrap => (Op.BorderCtlWrap info, [img])
387 :     (* end case *))
388 :     in
389 :     [IR.ASSGN(lhs, IR.OP(rator, args))]
390 :     end
391 : jhr 3476 | S.E_LoadSeq(ty, nrrd) => [IR.ASSGN(lhs, IR.OP(Op.LoadSeq(cvtTy ty, nrrd), []))]
392 : jhr 4043 | S.E_LoadImage(_, nrrd, info) =>
393 : jhr 4317 [IR.ASSGN(lhs, IR.OP(Op.LoadImage(DstTy.ImageTy info, nrrd), []))]
394 :     | S.E_InsideImage(pos, img, s) => let
395 :     val Ty.T_Image info = SV.typeOf img
396 :     in
397 :     [IR.ASSGN(lhs, IR.OP(Op.Inside(info, s), [lookup env pos, lookup env img]))]
398 :     end
399 : jhr 3471 (* end case *))
400 :    
401 : jhr 4894 (* add nodes to save the varying strand state, followed by an exit node *)
402 : jhr 3471 fun saveStrandState (env, (srcState, dstState), exit) = let
403 : jhr 4894 val lookup = lookup env
404 :     fun save (x, x', cfg) = if AnalyzeSimple.varyingStateVar x'
405 :     then IR.CFG.appendNode (cfg, IR.Node.mkSAVE(x, lookup x'))
406 :     else cfg (* no need to save invariant variables! *)
407 : jhr 3471 in
408 : jhr 3476 IR.CFG.appendNode (
409 : jhr 4894 ListPair.foldlEq save IR.CFG.empty (dstState, srcState),
410 : jhr 3471 exit)
411 :     end
412 :     (*DEBUG*)handle ex => raise ex
413 :    
414 : jhr 4163 (* convert a block to a CFG. The parameters are:
415 : jhr 4317 * state -- a pair of the src/dst state variables for saving the state of a strand.
416 :     * These are empty if the block is not in a strand.
417 : jhr 4163 * env -- environment for mapping SimpleIR variables to HighIR locals
418 :     * joinStk -- a stack of pending joins
419 : jhr 4317 * blk -- the block to translate
420 : jhr 4163 *)
421 : jhr 3501 fun cvtBlock (state, env : env, joinStk, blk as S.Block{code, ...}) = let
422 : jhr 3471 fun cvt (env : env, cfg, []) = (cfg, env)
423 :     | cvt (env, cfg, stm::stms) = (case stm
424 : jhr 3485 of S.S_Var(x, NONE) => let
425 : jhr 3471 val x' = newVar x
426 :     in
427 : jhr 5286 cvt (insert (env, x, x'), cfg, stms)
428 : jhr 3471 end
429 : jhr 4317 | S.S_Var(x, SOME e) => let
430 : jhr 3485 val x' = newVar x
431 :     val assigns = cvtExp (env, x', e)
432 : jhr 4317 in
433 : jhr 3485 recordAssign (joinStk, x, x');
434 :     cvt (
435 : jhr 5286 insert(env, x, x'),
436 : jhr 3485 IR.CFG.concat(cfg, IR.CFG.mkBlock assigns),
437 :     stms)
438 : jhr 4317 end
439 : jhr 3471 | S.S_Assign(lhs, rhs) => let
440 : jhr 4317 val lhs' = newVar lhs
441 :     val assigns = cvtExp (env, lhs', rhs)
442 :     in
443 :     (* check for assignment to global (i.e., constant, input, or other global) *)
444 : jhr 3550 (* FIXME: for the global initialization block, we should batch up the saving of globals until
445 :     * the end so that we can properly set the bindings (i.e., so that we avoid conflicts between
446 :     * branches of an if statement).
447 :     *)
448 : jhr 4317 if isGlobalVar lhs
449 :     then cvt (
450 : jhr 5286 insert(env, lhs, lhs'),
451 : jhr 4317 IR.CFG.concat(
452 :     cfg,
453 :     IR.CFG.mkBlock(assigns @ [IR.GASSGN(cvtGlobalVar lhs, lhs')])),
454 :     stms)
455 :     else (
456 :     recordAssign (joinStk, lhs, lhs');
457 :     cvt (
458 : jhr 5286 insert(env, lhs, lhs'),
459 : jhr 4317 IR.CFG.concat(cfg, IR.CFG.mkBlock assigns),
460 :     stms))
461 :     end
462 : jhr 3471 | S.S_IfThenElse(x, b0, b1) => let
463 :     val x' = lookup env x
464 :     val join as JOIN{nd=joinNd, ...} = newJoin (env, 2)
465 :     val (cfg0, _) = cvtBlock (state, env, (0, join)::joinStk, b0)
466 :     val (cfg1, _) = cvtBlock (state, env, (1, join)::joinStk, b1)
467 : jhr 3476 val cond = IR.Node.mkCOND x'
468 :     fun addEdgeToJoin nd = (case IR.Node.kind nd
469 :     of IR.EXIT{succ, ...} => (
470 : jhr 3471 succ := SOME joinNd;
471 : jhr 3476 IR.Node.setPred (joinNd, nd)) (* will be converted to fake later *)
472 :     | _ => IR.Node.addEdge(nd, joinNd)
473 : jhr 3471 (* end case *))
474 :     (* package the CFG the represents the conditional (cond, two blocks, and join) *)
475 :     val condCFG = (
476 : jhr 3476 if IR.CFG.isEmpty cfg0
477 : jhr 3471 then (
478 : jhr 3476 IR.Node.setTrueBranch (cond, joinNd);
479 :     IR.Node.setPred (joinNd, cond))
480 : jhr 3471 else (
481 : jhr 3476 IR.Node.setTrueBranch (cond, IR.CFG.entry cfg0);
482 :     IR.Node.setPred (IR.CFG.entry cfg0, cond);
483 :     addEdgeToJoin (IR.CFG.exit cfg0));
484 :     if IR.CFG.isEmpty cfg1
485 : jhr 3471 then (
486 : jhr 3476 IR.Node.setFalseBranch (cond, joinNd);
487 :     IR.Node.setPred (joinNd, cond))
488 : jhr 3471 else (
489 : jhr 3476 IR.Node.setFalseBranch (cond, IR.CFG.entry cfg1);
490 :     IR.Node.setPred (IR.CFG.entry cfg1, cond);
491 :     addEdgeToJoin (IR.CFG.exit cfg1));
492 :     IR.CFG{entry = cond, exit = joinNd})
493 : jhr 3471 val env = commitJoin (joinStk, join)
494 : jhr 4317 val cfg = IR.CFG.concat (cfg, condCFG)
495 : jhr 3471 in
496 : jhr 4317 (* add an UNREACHABLE exit node when the join is the final node in the
497 :     * graph and it is unreachable.
498 :     *)
499 :     if List.null joinStk andalso not(IR.Node.isReachable joinNd)
500 :     then (* NOTE: this case implies that stms is empty! *)
501 :     (IR.CFG.appendNode(cfg, IR.Node.mkUNREACHABLE()), env)
502 :     else cvt (env, cfg, stms)
503 : jhr 3471 end
504 : jhr 4317 | S.S_Foreach(x, xs, b) => let
505 :     val x' = newVar x
506 : jhr 3500 val xs' = lookup env xs
507 : jhr 4317 (* For any local variable y that is both live on exit of the block b and
508 :     * assigned to in b, we will need a phi node for y.
509 :     *)
510 :     val phiVars = VSet.listItems(
511 :     VSet.intersection(AnalyzeSimple.assignedVars b, AnalyzeSimple.liveOut b))
512 : jhr 3502 val join as JOIN{env, nd=foreachNd, ...} = newForeach (env, x', xs', phiVars)
513 : jhr 5286 val (body, _) = cvtBlock (state, insert(env, x, x'), (1, join)::joinStk, b)
514 : jhr 4317 val body = IR.CFG.appendNode (body, IR.Node.mkNEXT())
515 : jhr 3502 val env = commitJoin (joinStk, join)
516 : jhr 4317 in
517 :     (* link in CFG edges *)
518 :     IR.Node.setBodyEntry (foreachNd, IR.CFG.entry body); (* loop header to body *)
519 :     IR.Node.setPred (IR.CFG.entry body, foreachNd); (* back edge *)
520 :     IR.Node.setSucc (IR.CFG.exit body, foreachNd);
521 :     IR.Node.setBodyExit (foreachNd, IR.CFG.exit body);
522 :     (* process the rest of the block *)
523 :     cvt (env, IR.CFG.concat (cfg, IR.CFG{entry=foreachNd, exit=foreachNd}), stms)
524 :     end
525 : jhr 3471 | S.S_New(strandId, args) => let
526 : jhr 4339 val nd = IR.Node.mkNEW(strandId, List.map (lookup env) args)
527 : jhr 3471 in
528 : jhr 3476 cvt (env, IR.CFG.appendNode (cfg, nd), stms)
529 : jhr 3471 end
530 : jhr 4628 | S.S_KillAll => let
531 :     val nd = IR.Node.mkMASSIGN([], IR.OP(Op.KillAll, []))
532 :     in
533 :     cvt (env, IR.CFG.appendNode (cfg, nd), stms)
534 :     end
535 :     | S.S_StabilizeAll => let
536 : jhr 4480 val nd = IR.Node.mkMASSIGN([], IR.OP(Op.StabilizeAll, []))
537 :     in
538 :     cvt (env, IR.CFG.appendNode (cfg, nd), stms)
539 :     end
540 : jhr 3471 | S.S_Continue => (
541 : jhr 4628 killPath joinStk;
542 : jhr 5286 if inMethod env
543 : jhr 4628 then (
544 :     IR.CFG.concat (cfg, saveStrandState (env, state, IR.Node.mkACTIVE())),
545 :     env
546 :     )
547 : jhr 5286 else if inGlobalUpdate env
548 :     then (IR.CFG.appendNode (cfg, IR.Node.mkNEXTSTEP()), env)
549 : jhr 4628 else (IR.CFG.appendNode (cfg, IR.Node.mkRETURN NONE), env))
550 : jhr 3471 | S.S_Die => (
551 :     killPath joinStk;
552 : jhr 3476 (IR.CFG.appendNode (cfg, IR.Node.mkDIE ()), env))
553 : jhr 3471 | S.S_Stabilize => (
554 :     killPath joinStk;
555 : jhr 3476 (IR.CFG.concat (cfg, saveStrandState (env, state, IR.Node.mkSTABILIZE())), env))
556 : jhr 4164 | S.S_Return x => (
557 : jhr 4317 killPath joinStk;
558 :     (IR.CFG.appendNode (cfg, IR.Node.mkRETURN(SOME(lookup env x))), env))
559 : jhr 3471 | S.S_Print args => let
560 :     val args = List.map (lookup env) args
561 : jhr 4362 val nd = IR.Node.mkMASSIGN([], IR.OP(Op.Print(List.map IR.Var.ty args), args))
562 : jhr 3471 in
563 : jhr 3476 cvt (env, IR.CFG.appendNode (cfg, nd), stms)
564 : jhr 3471 end
565 : jhr 4378 | S.S_MapReduce mrs => let
566 :     fun cvtMR (mr, (env, assigns, lhs, mrs')) = let
567 :     val (S.MapReduce{
568 :     result, reduction, mapf=S.Func{f, ...}, args, source, domain
569 :     }) = mr
570 :     (* note that we are making the source of strands explicit and changing the
571 :     * type of the first argument to the map function.
572 :     *)
573 :     val strandTy = cvtTy(SV.typeOf source)
574 :     val src = IR.Var.new (SV.nameOf source, DstTy.SeqTy(strandTy, NONE))
575 : jhr 5286 val env' = insert (env, source, src)
576 : jhr 4378 val srcAssign = IR.ASSGN(src, IR.OP(Op.Strands(strandTy, domain), []))
577 :     val result' = newVar result
578 : jhr 5286 val env = insert(env, result, result')
579 : jhr 4378 val mr' = (reduction, cvtFuncVar f, List.map (lookup env') args)
580 : jhr 4368 in
581 : jhr 4378 (env, srcAssign :: assigns, result'::lhs, mr'::mrs')
582 : jhr 4368 end
583 : jhr 4378 val (env, assigns, lhs, mrs) = List.foldl cvtMR (env, [], [], []) mrs
584 :     val assigns = IR.MASSGN(List.rev lhs, IR.MAPREDUCE(List.rev mrs)) :: assigns
585 : jhr 4368 in
586 : jhr 4378 cvt (env, IR.CFG.appendBlock (cfg, List.rev assigns), stms)
587 : jhr 4368 end
588 : jhr 3471 (* end case *))
589 :     in
590 : jhr 3505 cvt (env, IR.CFG.empty, code)
591 : jhr 3471 end
592 :     (*DEBUG*)handle ex => raise ex
593 :    
594 : jhr 4164 (* a function for generating a block of assignments to load the globals that
595 :     * are referenced in a SimpleIR block.
596 :     *)
597 :     fun loadGlobals (env, blk) = let
598 : jhr 4317 fun load (x, (env, stms)) = let
599 : jhr 3506 val x' = newVar x
600 :     val stm = IR.ASSGN(x', IR.GLOBAL(cvtGlobalVar x))
601 : jhr 5286 val env = insert (env, x, x')
602 : jhr 3506 in
603 : jhr 4164 (env, stm::stms)
604 : jhr 3506 end
605 : jhr 4628 val globs = AnalyzeSimple.globalsOfBlock blk
606 : jhr 4570 val (env, stms) = VSet.foldr load (env, []) globs
607 : jhr 3506 in
608 : jhr 4164 (IR.CFG.mkBlock stms, env)
609 : jhr 3506 end
610 :    
611 : jhr 4164 fun cvtMethod (env, isStabilize, state, svars, blk) = let
612 : jhr 3471 (* load the globals into fresh variables *)
613 : jhr 4164 val (loadGlobsCFG, env) = loadGlobals (env, blk)
614 : jhr 3471 (* load the state into fresh variables *)
615 :     val (env, loadCFG) = let
616 :     (* allocate shadow variables for the state variables *)
617 :     val (env, stateIn) = freshVars (env, state)
618 : jhr 3846 fun load (x, x') = IR.ASSGN(x, IR.STATE(NONE, x'))
619 : jhr 3476 val cfg = IR.CFG.mkBlock (ListPair.map load (stateIn, svars))
620 : jhr 3471 in
621 : jhr 3476 (env, IR.CFG.concat(loadGlobsCFG, cfg))
622 : jhr 3471 end
623 :     (* convert the body of the method *)
624 :     val (cfg, env) = cvtBlock ((state, svars), env, [], blk)
625 :     (* add the entry/exit nodes *)
626 : jhr 3476 val entry = IR.Node.mkENTRY ()
627 :     val loadCFG = IR.CFG.prependNode (entry, loadCFG)
628 : jhr 3505 val exit = if isStabilize
629 : jhr 4317 then IR.Node.mkRETURN NONE
630 :     else IR.Node.mkACTIVE()
631 : jhr 3476 val body = IR.CFG.concat (loadCFG, cfg)
632 :     val body = if IR.Node.hasSucc(IR.CFG.exit body)
633 :     then IR.CFG.concat (body, saveStrandState (env, (state, svars), exit))
634 :     else IR.CFG{entry = IR.CFG.entry body, exit = exit}
635 : jhr 3471 in
636 : jhr 3505 body
637 : jhr 3471 end
638 : jhr 3505 (*DEBUG*)handle ex => (print "error in cvtMethod\n"; raise ex)
639 : jhr 3471
640 : jhr 3506 (* convert global code *)
641 : jhr 5286 fun cvtGlobalBlock cxt block = let
642 : jhr 3506 (* load the globals into fresh variables *)
643 : jhr 5286 val (loadCFG, env) = loadGlobals (emptyEnv cxt, block)
644 : jhr 4317 (* convert the code *)
645 :     val (cfg, _) = cvtBlock (([], []), env, [], block)
646 :     val cfg = IR.CFG.concat (loadCFG, cfg)
647 :     val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), cfg)
648 : jhr 5286 val cfg = if inGlobalUpdate env
649 :     then IR.CFG.appendNode (cfg, IR.Node.mkNEXTSTEP())
650 :     else IR.CFG.appendNode (cfg, IR.Node.mkRETURN NONE)
651 : jhr 4317 in
652 :     cfg
653 :     end
654 : jhr 4570 (*DEBUG*)handle ex => raise ex
655 : jhr 3471
656 : jhr 4163 (* extend the global environment with the strand's parameters *)
657 :     fun initEnvFromParams params = let
658 : jhr 4317 fun cvtParam (x, (env, xs)) = let
659 :     val x' = newVar x
660 :     in
661 : jhr 5286 (insert(env, x, x'), x'::xs)
662 : jhr 4317 end
663 : jhr 5286 val (env, params) = List.foldl cvtParam (emptyEnv Other, []) params
664 : jhr 4317 in
665 :     (env, List.rev params)
666 :     end
667 : jhr 4163
668 : jhr 4359 (* convert a function definition to a HighIR function *)
669 :     fun cvtFunc (S.Func{f, params, body}) = let
670 : jhr 4368 (* initialize the environment with the function's parameters *)
671 :     val (env, params) = initEnvFromParams params
672 :     val (loadBlk, env) = loadGlobals (env, body)
673 :     val (bodyCFG, _) = cvtBlock (([], []), env, [], body)
674 :     val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), loadBlk)
675 :     val cfg = IR.CFG.concat(cfg, bodyCFG)
676 :     in
677 :     IR.Func{name = cvtFuncVar f, params = params, body = cfg}
678 :     end
679 : jhr 4359
680 :     (* lift functions used in map-reduce expressions *)
681 :     fun liftFuncs NONE = []
682 :     | liftFuncs (SOME blk) = let
683 : jhr 4368 fun liftBlk (S.Block{code, ...}, fns) = List.foldl liftStm fns code
684 :     and liftStm (S.S_IfThenElse(_, b1, b2), fns) = liftBlk(b2, liftBlk(b1, fns))
685 :     | liftStm (S.S_Foreach(_, _, b), fns) = liftBlk(b, fns)
686 : jhr 4378 | liftStm (S.S_MapReduce mrs, fns) =
687 :     List.foldl (fn (S.MapReduce{mapf, ...}, fns) => cvtFunc mapf :: fns) fns mrs
688 : jhr 4368 | liftStm (_, fns) = fns
689 :     in
690 :     liftBlk (blk, [])
691 :     end
692 : jhr 4359
693 : jhr 3485 fun translate prog = let
694 : jhr 4317 val S.Program{
695 :     props, consts, inputs, constInit, globals, funcs,
696 : jhr 4491 globInit, strand, create, start, update
697 : jhr 4317 } = prog
698 :     val _ = AnalyzeSimple.analyze prog
699 :     val consts' = List.map cvtGlobalVar consts
700 :     val inputs' = List.map (Inputs.map cvtGlobalVar) inputs
701 :     val inputs = List.map Inputs.varOf inputs
702 :     val constInit = let
703 : jhr 5286 val (cfg, _) = cvtBlock (([], []), emptyEnv Other, [], constInit)
704 : jhr 4317 val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), cfg)
705 :     val cfg = IR.CFG.appendNode (cfg, IR.Node.mkRETURN NONE)
706 :     in
707 :     cfg
708 :     end
709 : jhr 3506 val globals' = List.map cvtGlobalVar globals
710 : jhr 4359 val funcs' = List.map cvtFunc funcs
711 : jhr 4368 (* if the program has global reductions, then lift those functions *)
712 :     val funcs' = if Properties.hasProp Properties.GlobalReduce props
713 : jhr 4491 then liftFuncs start @ liftFuncs update @ funcs'
714 : jhr 4368 else funcs'
715 : jhr 3471 (* create the global initialization code *)
716 : jhr 3995 val globInit = let
717 : jhr 3471 (* we start by loading the input globals, since they may be needed to compute the
718 :     * other globals
719 :     *)
720 : jhr 5286 val (loadBlk, env) = loadGlobals (emptyEnv Other, globInit)
721 : jhr 3995 val (globBlk, env) = cvtBlock (([], []), env, [], globInit)
722 : jhr 3506 val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), loadBlk)
723 : jhr 3476 val cfg = IR.CFG.concat(cfg, globBlk)
724 : jhr 4164 val cfg = IR.CFG.appendNode (cfg, IR.Node.mkRETURN NONE)
725 : jhr 3471 in
726 :     cfg
727 :     end
728 : jhr 4570 (*DEBUG*)handle ex => raise ex
729 : jhr 4368 fun cvtStrand strand = let
730 :     val S.Strand{
731 : jhr 4491 name, params, spatialDim, state, stateInit, startM, updateM, stabilizeM
732 : jhr 4368 } = strand
733 : jhr 4163 (* initialize the environment with the strand's parameters *)
734 :     val (env, params) = initEnvFromParams params
735 : jhr 3471 (* create the state variables *)
736 : jhr 3846 val svars = List.map getStateVar state
737 : jhr 3471 (* convert the state initialization code *)
738 :     val (stateInit, env) = let
739 :     (* load globals into local variables *)
740 : jhr 4164 val (loadGlobsCFG, env) = loadGlobals (env, stateInit)
741 : jhr 5286 val env = List.foldl (fn (x, env) => insert(env, x, newVar x)) env state
742 : jhr 3471 val (cfg, env) = cvtBlock (([], []), env, [], stateInit)
743 : jhr 3476 val cfg = IR.CFG.concat(loadGlobsCFG, cfg)
744 :     val cfg = IR.CFG.prependNode (IR.Node.mkENTRY(), cfg)
745 : jhr 4894 (* add nodes to initialize the strand state *)
746 :     val cfg = let
747 :     val lookup = lookup env
748 :     fun save (x, x', cfg) =
749 :     IR.CFG.appendNode (cfg, IR.Node.mkSAVE(x, lookup x'))
750 :     in
751 :     IR.CFG.appendNode (
752 :     ListPair.foldlEq save cfg (svars, state),
753 :     IR.Node.mkRETURN NONE)
754 :     end
755 : jhr 3471 in
756 :     (cfg, env)
757 :     end
758 : jhr 3505 fun cvtMeth isStabilize blk =
759 : jhr 5286 cvtMethod (context(env, Method), isStabilize, state, svars, blk)
760 : jhr 3471 in
761 : jhr 3476 IR.Strand{
762 : jhr 3471 name = name,
763 :     params = params,
764 : jhr 4369 spatialDim = spatialDim,
765 : jhr 3471 state = svars,
766 :     stateInit = stateInit,
767 : jhr 4491 startM = Option.map (cvtMeth false) startM,
768 : jhr 4317 updateM = cvtMeth false updateM,
769 :     stabilizeM = Option.map (cvtMeth true) stabilizeM
770 : jhr 3471 }
771 :     end
772 : jhr 4570 (*DEBUG*)handle ex => raise ex
773 : jhr 5286 val create = Create.map (cvtGlobalBlock Other) create
774 : jhr 3476 val prog = IR.Program{
775 : jhr 3471 props = props,
776 : jhr 4317 consts = consts',
777 :     inputs = inputs',
778 :     globals = globals',
779 :     funcs = funcs',
780 :     constInit = constInit,
781 : jhr 3995 globInit = globInit,
782 : jhr 3505 strand = cvtStrand strand,
783 :     create = create,
784 : jhr 5286 start = Option.map (cvtGlobalBlock Other) start,
785 :     update = Option.map (cvtGlobalBlock GlobalUpdate) update
786 : jhr 4317 }
787 : jhr 3471 in
788 :     Census.init prog;
789 :     prog
790 :     end
791 :    
792 :     end

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