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

SCM Repository

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

Annotation of /trunk/src/compiler/translate/translate.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1766 - (view) (download)

1 : jhr 137 (* translate.sml
2 :     *
3 : jhr 435 * COPYRIGHT (c) 2010 The Diderot Project (http://diderot-language.cs.uchicago.edu)
4 : jhr 137 * All rights reserved.
5 :     *
6 : jhr 1116 * Translate Simple-AST code into the IL representation. This translation is based on the
7 :     * algorithm described in
8 :     *
9 :     * Single-pass generation of static single assignment form for structured languages
10 :     * ACM TOPLAS, Nov. 1994
11 :     * by Brandis and MossenBock.
12 : jhr 137 *)
13 :    
14 :     structure Translate : sig
15 :    
16 : jhr 176 val translate : Simple.program -> HighIL.program
17 : jhr 137
18 :     end = struct
19 :    
20 : jhr 176 structure S = Simple
21 : jhr 394 structure Ty = Types
22 : jhr 137 structure VMap = Var.Map
23 : jhr 189 structure VSet = Var.Set
24 : jhr 168 structure IL = HighIL
25 : jhr 1640 structure Op = HighOps
26 : jhr 394 structure DstTy = HighILTypes
27 : jhr 1116 structure Census = HighILCensus
28 : jhr 137
29 : jhr 1640 val cvtTy = TranslateTy.tr
30 :    
31 : jhr 1116 (* maps from SimpleAST variables to the current corresponding SSA variable *)
32 : jhr 511 type env = IL.var VMap.map
33 :    
34 : jhr 1640 (* +DEBUG *)
35 :     fun prEnv (prefix, env) = let
36 :     val wid = ref 0
37 :     fun pr s = (print s; wid := !wid + size s)
38 :     fun nl () = if (!wid > 0) then (print "\n"; wid := 0) else ()
39 :     fun prElem (src, dst) = let
40 :     val s = String.concat [
41 :     " ", Var.uniqueNameOf src, "->", IL.Var.toString dst
42 :     ]
43 :     in
44 :     pr s;
45 :     if (!wid >= 100) then (nl(); pr " ") else ()
46 :     end
47 :     in
48 :     pr prefix; pr " ENV: {"; nl(); pr " ";
49 :     VMap.appi prElem env;
50 :     nl(); pr "}"; nl()
51 :     end
52 :     (* -DEBUG *)
53 :    
54 : jhr 197 fun lookup env x = (case VMap.find (env, x)
55 : jhr 176 of SOME x' => x'
56 :     | NONE => raise Fail(concat[
57 : jhr 197 "no binding for ", Var.uniqueNameOf x, " in environment"
58 : jhr 176 ])
59 :     (* end case *))
60 :    
61 : jhr 189 (* create a new instance of a variable *)
62 : jhr 394 fun newVar x = IL.Var.new (Var.nameOf x, cvtTy(Var.monoTypeOf x))
63 : jhr 189
64 : jhr 1116 (* generate fresh SSA variables and add them to the environment *)
65 :     fun freshVars (env, xs) = let
66 :     fun cvtVar (x, (env, xs)) = let
67 :     val x' = newVar x
68 :     in
69 :     (VMap.insert(env, x, x'), x'::xs)
70 :     end
71 :     val (env, xs) = List.foldl cvtVar (env, []) xs
72 :     in
73 :     (env, List.rev xs)
74 :     end
75 :    
76 :     (* a pending-join node tracks the phi nodes needed to join the assignments
77 :     * that flow into the join node.
78 :     *)
79 :     datatype join = JOIN of {
80 : jhr 1232 env : env, (* the environment that was current at the conditional *)
81 :     (* associated with this node. *)
82 : jhr 1116 arity : int ref, (* actual number of predecessors *)
83 :     nd : IL.node, (* the CFG node for this pending join *)
84 :     phiMap : IL.phi VMap.map ref, (* a mapping from Simple AST variables that are assigned *)
85 :     (* to their phi nodes. *)
86 :     predKill : bool array (* killed predecessor edges (because of DIE or STABILIZE *)
87 :     }
88 :    
89 :     (* a stack of pending joins. The first component specifies the path index of the current
90 :     * path to the join.
91 :     *)
92 :     type pending_joins = (int * join) list
93 :    
94 :     (* create a new pending-join node *)
95 : jhr 1232 fun newJoin (env, arity) = JOIN{
96 :     env = env, arity = ref arity, nd = IL.Node.mkJOIN [], phiMap = ref VMap.empty,
97 : jhr 1116 predKill = Array.array(arity, false)
98 :     }
99 :    
100 :     (* record that a path to the top join in the stack has been killed because f DIE or STABILIZE *)
101 :     fun killPath ((i, JOIN{arity, predKill, ...}) :: _) = (
102 :     arity := !arity - 1;
103 :     Array.update (predKill, i, true))
104 :     | killPath _ = ()
105 :    
106 :     (* record an assignment to the IL variable dstVar (corresponding to the Simple AST variable
107 :     * srcVar) in the current pending-join node. The predIndex specifies which path into the
108 :     * JOIN node this assignment occurs on.
109 :     *)
110 : jhr 1232 fun recordAssign ([], _, _) = ()
111 :     | recordAssign ((predIndex, JOIN{env, phiMap, predKill, nd, ...})::_, srcVar, dstVar) = let
112 : jhr 1116 val arity = Array.length predKill (* the original arity before any killPath calls *)
113 :     val m = !phiMap
114 :     in
115 :     case VMap.find (env, srcVar)
116 :     of NONE => () (* local temporary *)
117 :     | SOME dstVar' => (case VMap.find (m, srcVar)
118 :     of NONE => let
119 :     val lhs = newVar srcVar
120 :     val rhs = List.tabulate (arity, fn i => if (i = predIndex) then dstVar else dstVar')
121 :     in
122 : jhr 1232 (*
123 :     print(concat["recordAssign: ", Var.uniqueNameOf srcVar, " --> ", IL.Var.toString lhs,
124 :     " @ ", IL.Node.toString nd, "\n"]);
125 :     *)
126 : jhr 1116 phiMap := VMap.insert (m, srcVar, (lhs, rhs))
127 :     end
128 :     | SOME(lhs, rhs) => let
129 :     fun update (i, l as x::r) = if (i = predIndex)
130 :     then dstVar::r
131 :     else x::update(i+1, r)
132 :     | update _ = raise Fail "invalid predecessor index"
133 :     in
134 :     phiMap := VMap.insert (m, srcVar, (lhs, update(0, rhs)))
135 :     end
136 :     (* end case *))
137 :     (* end case *)
138 :     end
139 :    
140 :     (* complete a pending join operation by filling in the phi nodes from the phi map and
141 :     * updating the environment.
142 :     *)
143 : jhr 1232 fun commitJoin (joinStk, JOIN{env, arity, nd, phiMap, predKill}) = (case !arity
144 : jhr 1116 of 0 => (env, NONE)
145 : jhr 1766 | 1 => let
146 :     (* there is only one path to the join, so we do not need phi nodes, but
147 :     * we still need to propogate assignments to the next join on the stack.
148 :     *)
149 :     val IL.ND{kind=IL.JOIN{phis, ...}, ...} = nd
150 :     val ix = let (* find pred of this join *)
151 :     fun find i = if Array.sub(predKill, i) then find(i+1) else i
152 :     in
153 :     find 0
154 :     end
155 :     fun doVar (srcVar, (_, xs), env) = let
156 :     val dstVar = List.nth(xs, ix)
157 :     in
158 :     (*
159 :     print(concat["doVar (", Var.uniqueNameOf srcVar, ", ", IL.phiToString phi, ", _) @ ", IL.Node.toString nd, "\n"]);
160 :     *)
161 :     recordAssign (joinStk, srcVar, dstVar);
162 :     VMap.insert (env, srcVar, dstVar)
163 :     end
164 :     val env = VMap.foldli doVar env (!phiMap)
165 :     in
166 :     (env, SOME nd)
167 :     end
168 : jhr 1116 | n => if (n = Array.length predKill)
169 :     then let
170 :     val IL.ND{kind=IL.JOIN{phis, ...}, ...} = nd
171 :     fun doVar (srcVar, phi as (dstVar, _), (env, phis)) = (
172 : jhr 1232 (*
173 :     print(concat["doVar (", Var.uniqueNameOf srcVar, ", ", IL.phiToString phi, ", _) @ ", IL.Node.toString nd, "\n"]);
174 :     *)
175 :     recordAssign (joinStk, srcVar, dstVar);
176 : jhr 1116 (VMap.insert (env, srcVar, dstVar), phi::phis))
177 :     val (env, phis') = VMap.foldli doVar (env, []) (!phiMap)
178 :     in
179 :     phis := phis';
180 :     (env, SOME nd)
181 :     end
182 :     else raise Fail "FIXME: prune killed paths."
183 :     (* end case *))
184 :    
185 : jhr 168 (* expression translation *)
186 : jhr 1116 fun cvtExp (env : env, lhs, exp) = (case exp
187 : jhr 1640 of S.E_Var x => [IL.ASSGN(lhs, IL.VAR(lookup env x))]
188 :     | S.E_Lit lit => [IL.ASSGN(lhs, IL.LIT lit)]
189 : jhr 176 | S.E_Tuple xs => raise Fail "E_Tuple not implemeted"
190 : jhr 188 | S.E_Apply(f, tyArgs, args, ty) => let
191 :     val args' = List.map (lookup env) args
192 :     in
193 :     TranslateBasis.translate (lhs, f, tyArgs, args')
194 :     end
195 : jhr 1640 | S.E_Cons args => [IL.ASSGN(lhs, IL.CONS(IL.Var.ty lhs, List.map (lookup env) args))]
196 : jhr 400 | S.E_Slice(x, indices, ty) => let
197 :     val x = lookup env x
198 :     val mask = List.map isSome indices
199 :     fun cvt NONE = NONE
200 :     | cvt (SOME x) = SOME(lookup env x)
201 :     val indices = List.mapPartial cvt indices
202 :     in
203 :     if List.all (fn b => b) mask
204 : jhr 1640 then [IL.ASSGN(lhs, IL.OP(HighOps.TensorSub(IL.Var.ty x), x::indices))]
205 :     else [IL.ASSGN(lhs, IL.OP(HighOps.Slice(IL.Var.ty lhs, mask), x::indices))]
206 : jhr 400 end
207 : jhr 1301 | S.E_Input(_, name, desc, NONE) =>
208 : jhr 1640 [IL.ASSGN(lhs, IL.OP(HighOps.Input(IL.Var.ty lhs, name, desc), []))]
209 : jhr 1301 | S.E_Input(_, name, desc, SOME dflt) =>
210 : jhr 1640 [IL.ASSGN(lhs, IL.OP(HighOps.InputWithDefault(IL.Var.ty lhs, name, desc), [lookup env dflt]))]
211 :     | S.E_LoadImage(info, name) => [IL.ASSGN(lhs, IL.OP(HighOps.LoadImage info, [lookup env name]))]
212 : jhr 176 (* end case *))
213 : jhr 168
214 : jhr 1640 (* add nodes to save the strand state, followed by an exit node *)
215 :     fun saveStrandState (env, (srcState, dstState), exit) = let
216 :     val stateOut = List.map (lookup env) srcState
217 :     fun save (x, x', cfg) = IL.CFG.appendNode (cfg, IL.Node.mkSAVE(x, x'))
218 :     in
219 :     IL.CFG.appendNode (
220 :     ListPair.foldlEq save IL.CFG.empty (dstState, stateOut),
221 :     exit)
222 :     end
223 :     handle ex => raise ex
224 :    
225 : jhr 1116 fun cvtBlock (state, env : env, joinStk, S.Block stms) = let
226 :     fun cvt (env : env, cfg, []) = (cfg, env)
227 :     | cvt (env, cfg, stm::stms) = (case stm
228 :     of S.S_Var x => let
229 :     val x' = newVar x
230 :     in
231 :     cvt (VMap.insert (env, x, x'), cfg, stms)
232 :     end
233 :     | S.S_Assign(lhs, rhs) => let
234 :     val lhs' = newVar lhs
235 :     val assigns = cvtExp (env, lhs', rhs)
236 :     in
237 : jhr 1232 (*
238 :     print "doAssign\n";
239 :     *)
240 :     recordAssign (joinStk, lhs, lhs');
241 : jhr 1116 cvt (
242 :     VMap.insert(env, lhs, lhs'),
243 :     IL.CFG.concat(cfg, IL.CFG.mkBlock assigns),
244 :     stms)
245 :     end
246 :     | S.S_IfThenElse(x, b0, b1) => let
247 : jhr 192 val x' = lookup env x
248 : jhr 1232 val join = newJoin (env, 2)
249 : jhr 1116 val (cfg0, _) = cvtBlock (state, env, (0, join)::joinStk, b0)
250 :     val (cfg1, _) = cvtBlock (state, env, (1, join)::joinStk, b1)
251 :     val cond = IL.Node.mkCOND {
252 :     cond = x',
253 :     trueBranch = IL.Node.dummy,
254 :     falseBranch = IL.Node.dummy
255 :     }
256 : jhr 190 in
257 : jhr 1116 IL.Node.addEdge (IL.CFG.exit cfg, cond);
258 : jhr 1232 case commitJoin (joinStk, join)
259 : jhr 1116 of (env, SOME joinNd) => (
260 :     if IL.CFG.isEmpty cfg0
261 :     then (
262 :     IL.Node.setTrueBranch (cond, joinNd);
263 :     IL.Node.setPred (joinNd, cond))
264 :     else (
265 :     IL.Node.setTrueBranch (cond, IL.CFG.entry cfg0);
266 :     IL.Node.setPred (IL.CFG.entry cfg0, cond);
267 :     IL.Node.addEdge (IL.CFG.exit cfg0, joinNd));
268 :     if IL.CFG.isEmpty cfg1
269 :     then (
270 :     IL.Node.setFalseBranch (cond, joinNd);
271 :     IL.Node.setPred (joinNd, cond))
272 :     else (
273 :     IL.Node.setFalseBranch (cond, IL.CFG.entry cfg1);
274 :     IL.Node.setPred (IL.CFG.entry cfg1, cond);
275 :     IL.Node.addEdge (IL.CFG.exit cfg1, joinNd));
276 :     cvt (
277 :     env,
278 : jhr 1339 IL.CFG.concat (
279 :     cfg,
280 :     IL.CFG{entry = cond, exit = joinNd}),
281 : jhr 1116 stms))
282 :     (* the join node has only zero predecessors, so
283 :     * it was killed.
284 :     *)
285 :     | (env, NONE) => raise Fail "unimplemented" (* FIXME *)
286 : jhr 192 (* end case *)
287 : jhr 190 end
288 : jhr 1116 | S.S_New(strandId, args) => let
289 :     val nd = IL.Node.mkNEW{
290 :     strand = strandId,
291 :     args = List.map (lookup env) args
292 :     }
293 : jhr 192 in
294 : jhr 1116 cvt (env, IL.CFG.appendNode (cfg, nd), stms)
295 : jhr 194 end
296 : jhr 1116 | S.S_Die => (
297 :     killPath joinStk;
298 :     (IL.CFG.appendNode (cfg, IL.Node.mkDIE ()), env))
299 : jhr 1640 | S.S_Stabilize => (
300 :     killPath joinStk;
301 :     (IL.CFG.concat (cfg, saveStrandState (env, state, IL.Node.mkSTABILIZE())), env))
302 :     | S.S_Print args => let
303 :     val args = List.map (lookup env) args
304 :     val nd = IL.Node.mkMASSIGN([], Op.Print(List.map IL.Var.ty args), args)
305 :     in
306 :     cvt (env, IL.CFG.appendNode (cfg, nd), stms)
307 :     end
308 : jhr 192 (* end case *))
309 :     in
310 : jhr 1116 cvt (env, IL.CFG.empty, stms)
311 : jhr 192 end
312 : jhr 1339 (*DEBUG*)handle ex => raise ex
313 : jhr 168
314 : jhr 1232 fun cvtTopLevelBlock (env, blk, mkExit) = let
315 : jhr 1640 val (cfg, env) = cvtBlock (([], []), env, [], blk)
316 :     val cfg = IL.CFG.prependNode (IL.Node.mkENTRY(), cfg)
317 :     val cfg = IL.CFG.concat (cfg, mkExit env)
318 : jhr 256 in
319 : jhr 1640 (cfg, env)
320 : jhr 256 end
321 : jhr 1339 (*DEBUG*)handle ex => raise ex
322 : jhr 256
323 : jhr 1116 (* FIXME: the following function could be refactored with cvtTopLevelBlock to share code *)
324 : jhr 1232 fun cvtFragmentBlock (env0, blk) = let
325 : jhr 1640 val (cfg, env) = cvtBlock (([], []), env0, [], blk)
326 : jhr 1116 val entry = IL.Node.mkENTRY ()
327 : jhr 1232 (* the live variables out are those that were not live coming in *)
328 :     val liveOut = VMap.foldli
329 :     (fn (x, x', xs) => if VMap.inDomain(env0, x) then xs else x'::xs)
330 :     [] env
331 :     val exit = IL.Node.mkFRAGMENT liveOut
332 : jhr 1116 in
333 :     if IL.CFG.isEmpty cfg
334 :     then IL.Node.addEdge (entry, exit)
335 :     else (
336 :     IL.Node.addEdge (entry, IL.CFG.entry cfg);
337 : jhr 1232 IL.Node.addEdge (IL.CFG.exit cfg, exit));
338 : jhr 1116 (IL.CFG{entry = entry, exit = exit}, env)
339 :     end
340 : jhr 1339 (*DEBUG*)handle ex => raise ex
341 : jhr 1116
342 : jhr 1640 fun cvtMethod (env, name, state, svars, blk) = let
343 :     (* load the state into fresh variables *)
344 :     val (env, loadCFG) = let
345 :     (* allocate shadow variables for the state variables *)
346 :     val (env, stateIn) = freshVars (env, state)
347 :     fun load (x, x') = IL.ASSGN(x, IL.STATE x')
348 :     in
349 :     (env, IL.CFG.mkBlock (ListPair.map load (stateIn, svars)))
350 :     end
351 : jhr 1116 (* convert the body of the method *)
352 : jhr 1640 val (cfg, env) = cvtBlock ((state, svars), env, [], blk)
353 : jhr 1116 (* add the entry/exit nodes *)
354 :     val entry = IL.Node.mkENTRY ()
355 : jhr 1640 val loadCFG = IL.CFG.prependNode (entry, loadCFG)
356 : jhr 1444 val exit = (case name
357 : jhr 1640 of StrandUtil.Update => IL.Node.mkACTIVE ()
358 :     | StrandUtil.Stabilize => IL.Node.mkRETURN []
359 : jhr 1444 (* end case *))
360 : jhr 1640 val body = IL.CFG.concat (loadCFG, cfg)
361 :     (*DEBUG**val _ = prEnv (StrandUtil.nameToString name, env);*)
362 :     (* FIXME: the following code doesn't work properly *)
363 :     val body = if IL.Node.hasSucc(IL.CFG.exit body)
364 :     then IL.CFG.concat (body, saveStrandState (env, (state, svars), exit))
365 :     else IL.CFG{entry = IL.CFG.entry body, exit = exit}
366 : jhr 1116 in
367 :     IL.Method{
368 :     name = name,
369 : jhr 1640 body = body
370 : jhr 1116 }
371 :     end
372 : jhr 1640 (*DEBUG*)handle ex => (print(concat["error in cvtMethod(", StrandUtil.nameToString name, ", ...)\n"]); raise ex)
373 : jhr 1116
374 :     (* convert the initially code *)
375 :     fun cvtInitially (env, S.Initially{isArray, rangeInit, create, iters}) = let
376 :     val S.C_Create{argInit, name, args} = create
377 :     fun cvtIter ({param, lo, hi}, (env, iters)) = let
378 :     val param' = newVar param
379 :     val env = VMap.insert (env, param, param')
380 :     val iter = (param', lookup env lo, lookup env hi)
381 : jhr 256 in
382 : jhr 1116 (env, iter::iters)
383 : jhr 256 end
384 : jhr 1116 val (cfg, env) = cvtFragmentBlock (env, rangeInit)
385 :     val (env, iters) = List.foldl cvtIter (env, []) iters
386 :     val (argInitCFG, env) = cvtFragmentBlock (env, argInit)
387 : jhr 256 in
388 : jhr 1116 IL.Initially{
389 :     isArray = isArray,
390 :     rangeInit = cfg,
391 :     iters = List.rev iters,
392 :     create = (argInitCFG, name, List.map (lookup env) args)
393 :     }
394 : jhr 256 end
395 :    
396 : jhr 1640 (* check strands for properties *)
397 :     fun checkProps strands = let
398 :     val hasDie = ref false
399 :     val hasNew = ref false
400 :     fun chkStm e = (case e
401 :     of S.S_IfThenElse(_, b1, b2) => (chkBlk b1; chkBlk b2)
402 :     | S.S_New _ => (hasNew := true)
403 :     | S.S_Die => (hasDie := true)
404 :     | _ => ()
405 :     (* end case *))
406 :     and chkBlk (S.Block body) = List.app chkStm body
407 :     fun chkStrand (S.Strand{stateInit, methods, ...}) = let
408 :     fun chkMeth (S.Method(_, body)) = chkBlk body
409 :     in
410 :     chkBlk stateInit;
411 :     List.app chkMeth methods
412 :     end
413 :     fun condCons (x, v, l) = if !x then v::l else l
414 :     in
415 :     List.app chkStrand strands;
416 :     condCons (hasDie, StrandUtil.StrandsMayDie,
417 :     condCons (hasNew, StrandUtil.NewStrands, []))
418 :     end
419 :    
420 : jhr 1116 fun translate (S.Program{globals, globalInit, init, strands}) = let
421 : jhr 1640 val (globalInit, env) = let
422 :     fun mkExit env = let
423 :     val nd = IL.Node.mkRETURN(VMap.listItems env)
424 :     in
425 :     IL.CFG{entry = nd, exit = nd}
426 :     end
427 :     in
428 :     cvtTopLevelBlock (VMap.empty, globalInit, mkExit)
429 :     end
430 : jhr 1116 (* construct a reduced environment that just defines the globals. *)
431 :     val env = let
432 : jhr 200 val lookup = lookup env
433 : jhr 1116 fun cvtVar (x, env) = VMap.insert(env, x, lookup x)
434 :     val env = List.foldl cvtVar VMap.empty globals
435 : jhr 200 in
436 : jhr 1116 env
437 : jhr 200 end
438 : jhr 1116 val init = cvtInitially (env, init)
439 : jhr 511 fun cvtStrand (S.Strand{name, params, state, stateInit, methods}) = let
440 : jhr 1232 (* extend the global environment with the strand's parameters *)
441 : jhr 200 val (env, params) = let
442 :     fun cvtParam (x, (env, xs)) = let
443 :     val x' = newVar x
444 :     in
445 :     (VMap.insert(env, x, x'), x'::xs)
446 :     end
447 :     val (env, params) = List.foldl cvtParam (env, []) params
448 :     in
449 :     (env, List.rev params)
450 :     end
451 : jhr 1640 (* create the state variables *)
452 :     val svars = let
453 :     fun newSVar x = IL.StateVar.new (
454 :     Var.kindOf x = S.StrandOutputVar,
455 :     Var.nameOf x, cvtTy(Var.monoTypeOf x))
456 :     in
457 :     List.map newSVar state
458 :     end
459 : jhr 1232 (* convert the state initialization code *)
460 :     val (stateInit, env) = let
461 : jhr 1640 fun mkExit env = saveStrandState (env, (state, svars), IL.Node.mkSINIT())
462 : jhr 1232 in
463 :     cvtTopLevelBlock (env, stateInit, mkExit)
464 :     end
465 : jhr 1640 fun cvtMeth (S.Method(name, blk)) = cvtMethod (env, name, state, svars, blk)
466 : jhr 200 in
467 : jhr 511 IL.Strand{
468 : jhr 200 name = name,
469 :     params = params,
470 : jhr 1640 state = svars,
471 : jhr 200 stateInit = stateInit,
472 : jhr 1116 methods = List.map cvtMeth methods
473 : jhr 200 }
474 :     end
475 : jhr 511 val prog = IL.Program{
476 : jhr 1640 props = checkProps strands,
477 : jhr 1116 globalInit = globalInit,
478 :     initially = init,
479 :     strands = List.map cvtStrand strands
480 :     }
481 : jhr 511 in
482 :     Census.init prog;
483 :     prog
484 : jhr 200 end
485 : jhr 176
486 : jhr 137 end

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