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

SCM Repository

[diderot] Annotation of /branches/vis15/src/compiler/cfg-ir/ssa-fn.sml
ViewVC logotype

Annotation of /branches/vis15/src/compiler/cfg-ir/ssa-fn.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 3613 - (view) (download)

1 : jhr 3470 (* ssa-fn.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 3475 * The SSAFn functor is used to generate the High, Med, and Low IRs in the Diderot
9 :     * compiler. These IRs have the same program and control-flow structure, but differ
10 : jhr 3470 * in their types and operators.
11 :     *)
12 :    
13 :     functor SSAFn (
14 :    
15 : jhr 3508 val irName : string
16 : jhr 3470
17 :     structure Ty : SSA_TYPES
18 :     structure Op : OPERATORS where type ty = Ty.ty
19 :    
20 :     ) : SSA = struct
21 :    
22 :     structure Ty = Ty
23 :     structure Op = Op
24 :    
25 : jhr 3508 val irName = irName
26 : jhr 3470
27 :     (***** CFG *****)
28 :    
29 : jhr 3527 datatype global_kind = datatype GlobalVarKind.t
30 :    
31 : jhr 3470 datatype cfg = CFG of {
32 :     entry : node, (* the entry node of a graph; not necessarily an ENTRY node *)
33 :     exit : node (* the exit node of a graph; not necessarily an EXIT node. *)
34 :     }
35 :    
36 :     and node = ND of {
37 :     id : Stamp.stamp,
38 :     props : PropList.holder,
39 :     kind : node_kind
40 :     }
41 :    
42 :     and node_kind
43 :     = NULL
44 :     | ENTRY of {
45 :     succ : node ref
46 :     }
47 :     | JOIN of {
48 :     preds : node list ref, (* includes fake control-flow edges *)
49 :     mask : bool list ref, (* true for incoming fake edges *)
50 :     phis : phi list ref, (* data-flow joins corresponding to the edges in preds *)
51 :     succ : node ref
52 :     }
53 :     | COND of {
54 :     pred : node ref,
55 : jhr 3536 cond : var ref, (* the variable being tested (we use a ref to allow rewriting) *)
56 : jhr 3470 trueBranch : node ref,
57 :     falseBranch : node ref
58 :     }
59 : jhr 3473 | FOREACH of { (* foreach-loop; this node combines aspects of the COND
60 :     * and JOIN nodes. *)
61 : jhr 3502 pred : node ref, (* the predecessor *)
62 : jhr 3473 phis : phi list ref, (* phi nodes (as in JOIN) *)
63 :     mask : bool list ref, (* true for incoming fake edges *)
64 :     var : var, (* the loop variable *)
65 : jhr 3536 src : var ref, (* the source of values being iterated over *)
66 : jhr 3502 bodyEntry : node ref, (* the loop body entry node *)
67 :     bodyExit : node ref, (* the loop body exit node *)
68 : jhr 3473 succ : node ref (* the loop-exit edge *)
69 :     }
70 : jhr 3470 | COM of { (* comment *)
71 :     pred : node ref,
72 :     text : string list,
73 :     succ : node ref
74 :     }
75 :     | ASSIGN of { (* local-variable assignment *)
76 :     pred : node ref,
77 :     stm : assign,
78 :     succ : node ref
79 :     }
80 :     | MASSIGN of { (* multi-assignment *)
81 :     pred : node ref,
82 :     stm : massign,
83 :     succ : node ref
84 :     }
85 :     | GASSIGN of { (* global variable assignment *)
86 :     pred: node ref,
87 :     lhs : global_var,
88 :     rhs : var,
89 :     succ : node ref
90 :     }
91 :     | NEW of { (* create new strand instance *)
92 :     pred : node ref,
93 :     strand : Atom.atom,
94 :     args : var list,
95 :     succ : node ref
96 :     }
97 :     | SAVE of { (* save state variable *)
98 :     pred: node ref,
99 :     lhs : state_var,
100 :     rhs : var,
101 :     succ : node ref
102 :     }
103 :     | EXIT of { (* includes die and stabilize *)
104 :     pred : node ref,
105 :     kind : ExitKind.kind, (* kind of exit node *)
106 :     succ : node option ref (* optional fake control-flow edge for when the EXIT is *)
107 :     (* not the CFG exit node *)
108 :     }
109 :    
110 :     and rhs
111 :     = GLOBAL of global_var (* read global variable *)
112 :     | STATE of state_var (* read strand state variable *)
113 :     | VAR of var
114 :     | LIT of Literal.t
115 :     | OP of Op.rator * var list
116 :     | CONS of var list * Ty.ty (* tensor-value construction *)
117 :     | SEQ of var list * Ty.ty (* sequence-value construction *)
118 :     | EINAPP of Ein.ein * var list
119 :    
120 :     and var = V of {
121 :     name : string, (* name *)
122 :     id : Stamp.stamp, (* unique ID *)
123 :     ty : Ty.ty, (* type *)
124 :     bind : var_bind ref, (* binding *)
125 :     useCnt : int ref, (* count of uses *)
126 :     props : PropList.holder
127 :     }
128 :    
129 :     and var_bind
130 :     = VB_NONE
131 :     | VB_RHS of rhs (* defined by an assignment (includes globals and state variables) *)
132 :     | VB_MULTIOP of int * Op.rator * var list
133 :     (* n'th result of operator in multi-assignment *)
134 :     | VB_PHI of var option list (* defined by a phi node *)
135 :     | VB_PARAM (* parameter to a strand *)
136 : jhr 3522 | VB_ITER (* bound in a foreach loop *)
137 : jhr 3470
138 :     (***** global variables *****)
139 :     and global_var = GV of {
140 :     id : Stamp.stamp, (* variable's unique ID *)
141 :     name : string, (* variable's name *)
142 :     ty : Ty.ty, (* variable's type *)
143 : jhr 3506 kind : global_kind, (* the variable kind *)
144 : jhr 3538 updated : bool, (* true if the global variable is modified in the *)
145 :     (* global-update code *)
146 : jhr 3550 binding : var option ref, (* the local variable used to define this global variable
147 :     * (i.e., in a GASSIGN node). This field will be NONE
148 :     * for mutable variables.
149 :     *)
150 : jhr 3517 useCnt : int ref, (* count of uses *)
151 : jhr 3470 props : PropList.holder
152 :     }
153 :    
154 :     (***** strand state variables *****)
155 :     and state_var = SV of {
156 :     id : Stamp.stamp, (* variable's unique ID *)
157 :     name : string, (* variable's name *)
158 :     ty : Ty.ty, (* variable's type *)
159 :     output : bool, (* true for output variables *)
160 :     props : PropList.holder
161 :     }
162 :    
163 :     withtype assign = (var * rhs)
164 :     and massign = (var list * Op.rator * var list)
165 :     and phi = (var * var option list) (* NONE for fake edges *)
166 :    
167 :     datatype assignment
168 :     = ASSGN of assign
169 :     | MASSGN of massign
170 :     | GASSGN of (global_var * var)
171 :     | SAV of (state_var * var)
172 :    
173 :     (***** Program representation *****)
174 :    
175 : jhr 3505 type input = global_var Inputs.input
176 :    
177 : jhr 3470 datatype program = Program of {
178 :     props : Properties.t list,
179 : jhr 3485 consts : global_var list, (* large constant variables *)
180 : jhr 3505 inputs : input list, (* global input variables *)
181 :     constInit : cfg, (* code that initializes constants and inputs *)
182 : jhr 3485 globals : global_var list, (* other global variables *)
183 : jhr 3470 globalInit : cfg, (* CFG to initialize other globals (if any) *)
184 : jhr 3485 strand : strand, (* the strand definition *)
185 :     create : create, (* initial strand creation *)
186 :     update : cfg option (* optional update code. *)
187 : jhr 3470 }
188 :    
189 :     and strand = Strand of {
190 :     name : Atom.atom,
191 :     params : var list,
192 :     state : state_var list,
193 :     stateInit : cfg,
194 : jhr 3485 initM : cfg option,
195 :     updateM : cfg,
196 :     stabilizeM : cfg option
197 : jhr 3470 }
198 :    
199 : jhr 3485 and create = Create of {
200 :     dim : int option, (* grid dimension; NONE for collections *)
201 :     code : cfg (* the loop nest for creating the strands *)
202 : jhr 3470 }
203 :    
204 :     structure GlobalVar =
205 :     struct
206 : jhr 3538 fun new (kind, isUpdated, name, ty) = GV{
207 : jhr 3470 id = Stamp.new(),
208 :     name = name,
209 :     ty = ty,
210 : jhr 3506 kind = kind,
211 : jhr 3538 updated = isUpdated,
212 : jhr 3550 binding = ref NONE,
213 : jhr 3517 useCnt = ref 0,
214 : jhr 3470 props = PropList.newHolder()
215 :     }
216 :     fun name (GV{name, ...}) = name
217 :     fun uniqueName (GV{id, name, ...}) = name ^ Stamp.toString id
218 : jhr 3506 fun kind (GV{kind, ...}) = kind
219 : jhr 3538 fun isUpdated (GV{updated, ...}) = updated
220 : jhr 3550 fun bindingOf (GV{binding, ...}) = !binding
221 :     fun setBinding (GV{binding, ...}, x) = (binding := SOME x)
222 : jhr 3470 fun ty (GV{ty, ...}) = ty
223 : jhr 3506 fun isInput (GV{kind=InputVar, ...}) = true
224 :     | isInput _ = false
225 : jhr 3517 fun useCount (GV{useCnt, ...}) = !useCnt
226 : jhr 3470 fun same (GV{id=a, ...}, GV{id=b, ...}) = Stamp.same(a, b)
227 :     fun compare (GV{id=a, ...}, GV{id=b, ...}) = Stamp.compare(a, b)
228 :     fun hash (GV{id, ...}) = Stamp.hash id
229 :     fun toString (GV{id, name, ...}) = concat["globals.", name, Stamp.toString id]
230 :     (* properties *)
231 :     fun newProp initFn = PropList.newProp (fn (GV{props, ...}) => props, initFn)
232 :     fun newFlag () = PropList.newFlag (fn (GV{props, ...}) => props)
233 :     (* collections *)
234 :     local
235 :     structure V =
236 :     struct
237 :     type ord_key = global_var
238 :     val compare = compare
239 :     end
240 :     in
241 :     structure Map = RedBlackMapFn (V)
242 :     structure Set = RedBlackSetFn (V)
243 :     end
244 :     structure Tbl = HashTableFn (
245 :     struct
246 :     type hash_key = global_var
247 :     val hashVal = hash
248 :     val sameKey = same
249 :     end)
250 :     end
251 :    
252 :     structure StateVar =
253 :     struct
254 :     fun new (isOut, name, ty) = SV{
255 :     id = Stamp.new(),
256 :     name = name,
257 :     ty = ty,
258 :     output = isOut,
259 :     props = PropList.newHolder()
260 :     }
261 :     fun name (SV{name, ...}) = name
262 :     fun ty (SV{ty, ...}) = ty
263 :     fun isOutput (SV{output, ...}) = output
264 :     fun same (SV{id=a, ...}, SV{id=b, ...}) = Stamp.same(a, b)
265 :     fun compare (SV{id=a, ...}, SV{id=b, ...}) = Stamp.compare(a, b)
266 :     fun hash (SV{id, ...}) = Stamp.hash id
267 :     fun toString (SV{name, ...}) = "self." ^ name
268 :     (* properties *)
269 :     fun newProp initFn = PropList.newProp (fn (SV{props, ...}) => props, initFn)
270 :     fun newFlag () = PropList.newFlag (fn (SV{props, ...}) => props)
271 :     (* collections *)
272 :     local
273 :     structure V =
274 :     struct
275 :     type ord_key = state_var
276 :     val compare = compare
277 :     end
278 :     in
279 :     structure Map = RedBlackMapFn (V)
280 :     structure Set = RedBlackSetFn (V)
281 :     end
282 :     structure Tbl = HashTableFn (
283 :     struct
284 :     type hash_key = state_var
285 :     val hashVal = hash
286 :     val sameKey = same
287 :     end)
288 :     end
289 :    
290 :     structure Var =
291 :     struct
292 :     fun new (name, ty) = V{
293 :     name = name,
294 :     id = Stamp.new(),
295 :     ty = ty,
296 :     bind = ref VB_NONE,
297 :     useCnt = ref 0,
298 :     props = PropList.newHolder()
299 :     }
300 :     fun copy (V{name, ty, ...}) = new (name, ty)
301 :     fun name (V{name, ...}) = name
302 :     fun ty (V{ty, ...}) = ty
303 :     fun binding (V{bind, ...}) = !bind
304 :     fun setBinding (V{bind, ...}, vb) = bind := vb
305 :     fun useCount (V{useCnt, ...}) = !useCnt
306 :     fun same (V{id=a, ...}, V{id=b, ...}) = Stamp.same(a, b)
307 :     fun compare (V{id=a, ...}, V{id=b, ...}) = Stamp.compare(a, b)
308 :     fun hash (V{id, ...}) = Stamp.hash id
309 :     fun toString (V{name, id, ...}) = name ^ Stamp.toString id
310 : jhr 3586 fun getDef x = (case binding x
311 :     of VB_RHS rhs => (case rhs
312 : jhr 3613 of GLOBAL gv => if GlobalVar.isInput gv
313 :     then rhs (* inputs could be different at runtime! *)
314 :     else (case GlobalVar.bindingOf gv
315 :     of SOME x => getDef x
316 :     | NONE => rhs
317 :     (* end case *))
318 : jhr 3586 | VAR x => getDef x
319 :     | _ => rhs
320 :     (* end case *))
321 :     | _ => VAR x
322 :     (* end case *))
323 : jhr 3470 (* properties *)
324 :     fun newProp initFn = PropList.newProp (fn (V{props, ...}) => props, initFn)
325 :     fun newFlag () = PropList.newFlag (fn (V{props, ...}) => props)
326 :     (* collections *)
327 :     local
328 :     structure V =
329 :     struct
330 :     type ord_key = var
331 :     val compare = compare
332 :     end
333 :     in
334 :     structure Map = RedBlackMapFn (V)
335 :     structure Set = RedBlackSetFn (V)
336 :     end
337 :     structure Tbl = HashTableFn (
338 :     struct
339 :     type hash_key = var
340 :     val hashVal = hash
341 :     val sameKey = same
342 :     end)
343 :     end
344 :    
345 :     structure Node =
346 :     struct
347 :     fun id (ND{id, ...}) = id
348 :     fun kind (ND{kind, ...}) = kind
349 :     fun same (ND{id=a, ...}, ND{id=b, ...}) = Stamp.same(a, b)
350 :     fun compare (ND{id=a, ...}, ND{id=b, ...}) = Stamp.compare(a, b)
351 :     fun hash (ND{id, ...}) = Stamp.hash id
352 :     fun toString (ND{id, kind, ...}) = let
353 :     val tag = (case kind
354 :     of NULL => "NULL"
355 :     | ENTRY _ => "ENTRY"
356 :     | JOIN _ => "JOIN"
357 :     | COND _ => "COND"
358 : jhr 3473 | FOREACH _ => "FOREACH"
359 : jhr 3470 | COM _ => "COM"
360 :     | ASSIGN _ => "ASSIGN"
361 :     | MASSIGN _ => "MASSIGN"
362 :     | GASSIGN _ => "GASSIGN"
363 :     | NEW _ => "NEW"
364 :     | SAVE _ => "SAVE"
365 :     | EXIT{kind, ...} => ExitKind.toString kind
366 :     (* end case *))
367 :     in
368 :     tag ^ Stamp.toString id
369 :     end
370 :     fun new kind = ND{id = Stamp.new(), props = PropList.newHolder(), kind = kind}
371 :     (* variable defs and uses *)
372 :     fun uses (ND{kind, ...}) = (case kind
373 :     of JOIN{phis, ...} => let
374 :     fun add ([], ys) = ys
375 :     | add (SOME x :: xs, ys) = add(xs, x::ys)
376 :     | add (NONE :: xs, ys) = add(xs, ys)
377 :     in
378 :     List.foldr (fn ((_, xs), ys) => add(xs, ys)) [] (!phis)
379 :     end
380 : jhr 3536 | COND{cond, ...} => [!cond]
381 : jhr 3473 | FOREACH{src, phis, ...} => let
382 :     fun add ([], ys) = ys
383 :     | add (SOME x :: xs, ys) = add(xs, x::ys)
384 :     | add (NONE :: xs, ys) = add(xs, ys)
385 :     in
386 : jhr 3536 List.foldr (fn ((_, xs), ys) => add(xs, ys)) [!src] (!phis)
387 : jhr 3473 end
388 : jhr 3470 | ASSIGN{stm=(y, rhs), ...} => (case rhs
389 :     of GLOBAL _ => []
390 :     | STATE _ => []
391 :     | VAR x => [x]
392 :     | LIT _ => []
393 :     | OP(_, args) => args
394 :     | CONS(args, _) => args
395 :     | SEQ(args, _) => args
396 :     | EINAPP(_, args) => args
397 :     (* end case *))
398 :     | MASSIGN{stm=(_, _, args), ...} => args
399 :     | GASSIGN{rhs, ...} => [rhs]
400 :     | NEW{args, ...} => args
401 :     | SAVE{rhs, ...} => [rhs]
402 :     | _ => []
403 :     (* end case *))
404 :     fun defs (ND{kind, ...}) = (case kind
405 :     of JOIN{phis, ...} => List.map #1 (!phis)
406 : jhr 3473 | FOREACH{var, phis, ...} => var :: List.map #1 (!phis)
407 : jhr 3470 | ASSIGN{stm=(y, _), ...} => [y]
408 :     | MASSIGN{stm=(ys, _, _), ...} => ys
409 :     | _ => []
410 :     (* end case *))
411 :     val dummy = new NULL
412 :     fun mkENTRY () = new (ENTRY{succ = ref dummy})
413 :     fun mkJOIN phis = new (JOIN{preds = ref [], mask = ref [], phis = ref phis, succ = ref dummy})
414 :     fun mkCOND cond = new (COND{
415 : jhr 3536 pred = ref dummy, cond = ref cond,
416 : jhr 3470 trueBranch = ref dummy, falseBranch = ref dummy
417 :     })
418 : jhr 3522 fun mkFOREACH (var, src) = (
419 :     Var.setBinding (var, VB_ITER);
420 :     new (FOREACH{
421 :     pred = ref dummy,
422 :     phis = ref [], mask = ref [],
423 : jhr 3536 var = var, src = ref src,
424 : jhr 3522 bodyEntry = ref dummy,
425 :     bodyExit = ref dummy,
426 :     succ = ref dummy
427 :     }))
428 : jhr 3470 fun mkCOM text = new (COM{pred = ref dummy, text = text, succ = ref dummy})
429 :     fun mkASSIGN (lhs, rhs) = (
430 :     Var.setBinding (lhs, VB_RHS rhs);
431 :     new (ASSIGN{pred = ref dummy, stm = (lhs, rhs), succ = ref dummy}))
432 :     fun mkMASSIGN (lhs, rator, args) = let
433 :     fun setB (_, []) = ()
434 :     | setB (i, x::xs) = (
435 :     Var.setBinding (x, VB_MULTIOP(i, rator, args));
436 :     setB (i+1, xs))
437 :     in
438 :     setB (0, lhs);
439 :     new (MASSIGN{pred = ref dummy, stm = (lhs, rator, args), succ = ref dummy})
440 :     end
441 : jhr 3586 fun mkGASSIGN (lhs, rhs) = (
442 :     if not(GlobalVar.isUpdated lhs) then GlobalVar.setBinding(lhs, rhs) else ();
443 :     new (GASSIGN{pred = ref dummy, lhs = lhs, rhs = rhs, succ = ref dummy}))
444 : jhr 3470 fun mkNEW {strand, args} = new (NEW{
445 :     pred = ref dummy, strand = strand, args = args, succ = ref dummy
446 :     })
447 :     fun mkSAVE (lhs, rhs) = new (SAVE{
448 :     pred = ref dummy, lhs = lhs, rhs = rhs, succ = ref dummy
449 :     })
450 : jhr 3505 fun mkEXIT kind = new (EXIT{kind = kind, pred = ref dummy, succ = ref NONE})
451 :     fun mkRETURN () = mkEXIT ExitKind.RETURN
452 :     fun mkACTIVE () = mkEXIT ExitKind.ACTIVE
453 :     fun mkSTABILIZE () = mkEXIT ExitKind.STABILIZE
454 :     fun mkDIE () = mkEXIT ExitKind.DIE
455 :     fun mkUNREACHABLE () = mkEXIT ExitKind.UNREACHABLE
456 : jhr 3470 fun isNULL (ND{kind=NULL, ...}) = true
457 :     | isNULL _ = false
458 :     (* is a node reachable from the CFG entry; UNREACHABLE exit nodes and JOINs with no real
459 :     * predecessors are unreachable.
460 :     *)
461 :     fun isReachable (ND{kind=EXIT{kind=ExitKind.UNREACHABLE, ...}, ...}) = false
462 :     | isReachable (ND{kind=JOIN{mask, ...}, ...}) = List.exists not (!mask)
463 :     | isReachable _ = true
464 :     (* editing node edges *)
465 :     fun hasPred (ND{kind, ...}) = (case kind
466 :     of NULL => false
467 :     | ENTRY _ => false
468 :     | _ => true
469 :     (* end case *))
470 :     fun setPred (nd0 as ND{kind, ...}, nd) = (case kind
471 :     of NULL => raise Fail("setPred on NULL node " ^ toString nd0)
472 :     | ENTRY _ => raise Fail("setPred on ENTRY node " ^ toString nd0)
473 :     | JOIN{preds, ...} => preds := !preds @ [nd] (* assume preds are added in order *)
474 : jhr 3502 | FOREACH{pred, ...} => pred := nd
475 : jhr 3470 | COND{pred, ...} => pred := nd
476 :     | COM{pred, ...} => pred := nd
477 :     | ASSIGN{pred, ...} => pred := nd
478 :     | MASSIGN{pred, ...} => pred := nd
479 :     | GASSIGN{pred, ...} => pred := nd
480 :     | NEW{pred, ...} => pred := nd
481 :     | SAVE{pred, ...} => pred := nd
482 :     | EXIT{pred, ...} => pred := nd
483 :     (* end case *))
484 :     fun preds (nd as ND{kind, ...}) = (case kind
485 :     of NULL => [] (*raise Fail("preds on NULL node "^toString nd)*)
486 :     | ENTRY _ => []
487 :     | JOIN{preds, ...} => !preds
488 :     | COND{pred, ...} => [!pred]
489 : jhr 3502 | FOREACH{pred, bodyExit, ...} => [!pred, !bodyExit]
490 : jhr 3470 | COM{pred, ...} => [!pred]
491 :     | ASSIGN{pred, ...} => [!pred]
492 :     | MASSIGN{pred, ...} => [!pred]
493 :     | GASSIGN{pred, ...} => [!pred]
494 :     | NEW{pred, ...} => [!pred]
495 :     | SAVE{pred, ...} => [!pred]
496 :     | EXIT{pred, ...} => [!pred]
497 :     (* end case *))
498 :     fun hasSucc (ND{kind, ...}) = (case kind
499 :     of NULL => false
500 :     | ENTRY _ => true
501 :     | JOIN _ => true
502 :     | COND _ => true
503 :     | COM _ => true
504 : jhr 3473 | FOREACH _ => true
505 : jhr 3470 | ASSIGN _ => true
506 :     | MASSIGN _ => true
507 :     | GASSIGN _ => true
508 :     | NEW _ => true
509 :     | SAVE _ => true
510 :     | EXIT{succ=ref(SOME _), ...} => true
511 :     | EXIT _ => false
512 :     (* end case *))
513 :     fun setSucc (nd0 as ND{kind, ...}, nd) = (case kind
514 :     of NULL => raise Fail("setSucc on NULL node "^toString nd0)
515 :     | ENTRY{succ} => succ := nd
516 :     | JOIN{succ, ...} => succ := nd
517 :     | COND _ => raise Fail("setSucc on COND node "^toString nd0)
518 : jhr 3501 | FOREACH{succ, ...} => succ := nd
519 : jhr 3470 | COM{succ, ...} => succ := nd
520 :     | ASSIGN{succ, ...} => succ := nd
521 :     | MASSIGN{succ, ...} => succ := nd
522 :     | GASSIGN{succ, ...} => succ := nd
523 :     | NEW{succ, ...} => succ := nd
524 :     | SAVE{succ, ...} => succ := nd
525 :     | EXIT{succ, ...} => succ := SOME nd
526 :     (* end case *))
527 :     fun succs (ND{kind, ...}) = (case kind
528 :     of NULL => [] (*raise Fail("succs on NULL node "^toString nd)*)
529 :     | ENTRY{succ} => [!succ]
530 :     | JOIN{succ, ...} => [!succ]
531 :     | COND{trueBranch, falseBranch, ...} => [!trueBranch, !falseBranch]
532 : jhr 3502 | FOREACH{bodyEntry, succ, ...} => [!bodyEntry, !succ]
533 : jhr 3470 | COM{succ, ...} => [!succ]
534 :     | ASSIGN{succ, ...} => [!succ]
535 :     | MASSIGN{succ, ...} => [!succ]
536 :     | GASSIGN{succ, ...} => [!succ]
537 :     | NEW{succ, ...} => [!succ]
538 :     | SAVE{succ, ...} => [!succ]
539 :     | EXIT{succ=ref(SOME nd), ...} => [nd]
540 :     | EXIT _ => []
541 :     (* end case *))
542 :     (* QUESTION: should these functions also do the setPred operation? *)
543 :     fun setTrueBranch (ND{kind=COND{trueBranch, ...}, ...}, nd) = trueBranch := nd
544 :     | setTrueBranch (nd, _) = raise Fail("setTrueBranch on " ^ toString nd)
545 :     fun setFalseBranch (ND{kind=COND{falseBranch, ...}, ...}, nd) = falseBranch := nd
546 :     | setFalseBranch (nd, _) = raise Fail("setFalseBranch on " ^ toString nd)
547 : jhr 3502 fun setBodyEntry (ND{kind=FOREACH{bodyEntry, ...}, ...}, nd) = bodyEntry := nd
548 :     | setBodyEntry (nd, _) = raise Fail("setBodyEntry on " ^ toString nd)
549 :     fun setBodyExit (ND{kind=FOREACH{bodyExit, ...}, ...}, nd) = bodyExit := nd
550 :     | setBodyExit (nd, _) = raise Fail("setBodyExit on " ^ toString nd)
551 : jhr 3470 fun setEdgeMask (ND{kind=JOIN{mask, ...}, ...}, mask') = mask := mask'
552 :     | setEdgeMask (nd, _) = raise Fail("setEdgeMask on " ^ toString nd)
553 :     fun addEdge (nd1, nd2) = (
554 :     if hasSucc nd1
555 :     then (
556 :     setSucc (nd1, nd2);
557 :     setPred (nd2, nd1))
558 :     else ())
559 :     (*DEBUG*)handle ex => (
560 :     print(concat["error in addEdge(", toString nd1, ",", toString nd2, ")\n"]);
561 :     raise ex)
562 : jhr 3536 (* FIXME: the names replaceInEdge and replaceOutEdge are backwards! *)
563 : jhr 3502 (* replace the edge src-->oldDst by the edge src-->dst *)
564 : jhr 3470 fun replaceInEdge {src, oldDst, dst} = (
565 :     (* first set the successor of src *)
566 :     case kind src
567 :     of COND{trueBranch, falseBranch, ...} =>
568 :     if same(!trueBranch, oldDst)
569 :     then trueBranch := dst
570 :     else falseBranch := dst
571 : jhr 3502 | FOREACH{bodyEntry, succ, ...} =>
572 :     if same(!bodyEntry, oldDst)
573 :     then bodyEntry := dst
574 :     else succ := dst
575 : jhr 3470 | _ => setSucc (src, dst)
576 :     (* end case *);
577 :     (* then set the predecessor of dst *)
578 : jhr 3536 case kind oldDst
579 :     of FOREACH{bodyExit, pred, ...} =>
580 :     if same(!bodyExit, src)
581 :     then setBodyExit (dst, src)
582 :     else setPred (dst, src)
583 :     | _ => setPred (dst, src)
584 :     (* end case *))
585 : jhr 3470 (*DEBUG*)handle ex => (
586 :     print(concat["error in replaceInEdge(", toString src, ",", toString oldDst, ",", toString dst, ")\n"]);
587 :     raise ex)
588 : jhr 3502 (* replace the edge oldSrc-->dst by the edge src-->dst *)
589 : jhr 3470 fun replaceOutEdge {oldSrc, src, dst} = (
590 :     (* first set the successor of src *)
591 :     case kind oldSrc
592 :     of COND{trueBranch, falseBranch, ...} =>
593 :     if same(!trueBranch, dst)
594 :     then setTrueBranch (src, dst)
595 :     else setFalseBranch (src, dst)
596 : jhr 3502 | FOREACH{bodyEntry, succ, ...} =>
597 :     if same(!bodyEntry, dst)
598 :     then setBodyEntry (src, dst)
599 :     else setSucc (src, dst)
600 : jhr 3470 | _ => setSucc (src, dst)
601 :     (* end case *);
602 :     (* then set the predecessor of dst *)
603 :     case kind dst
604 :     of JOIN{preds, ...} => let
605 :     fun edit [] = raise Fail "replaceOutEdge: cannot find predecessor"
606 :     | edit (nd::nds) = if same(nd, oldSrc) then src::nds else nd::edit nds
607 :     in
608 :     preds := edit (!preds)
609 :     end
610 : jhr 3502 | FOREACH{bodyExit, pred, ...} =>
611 :     if same(!bodyExit, oldSrc)
612 :     then bodyExit := src
613 :     else pred := src
614 : jhr 3470 | _ => setPred (dst, src)
615 :     (* end case *))
616 :     (*DEBUG*)handle ex => (
617 :     print(concat["error in replaceOutEdge(", toString oldSrc, ",", toString src, ",", toString dst, ")\n"]);
618 :     raise ex)
619 :     (* properties *)
620 :     fun newProp initFn =
621 :     PropList.newProp (fn (ND{props, ...}) => props, initFn)
622 :     fun newFlag () =
623 :     PropList.newFlag (fn (ND{props, ...}) => props)
624 :     end
625 :    
626 :     structure CFG =
627 :     struct
628 :     val empty = CFG{entry = Node.dummy, exit = Node.dummy}
629 :    
630 :     fun isEmpty (CFG{entry, exit}) =
631 :     Node.same(entry, exit) andalso Node.isNULL entry
632 :    
633 :     (* create a basic block from a list of assignments *)
634 :     fun mkBlock [] = empty
635 :     | mkBlock (stm::stms) = let
636 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
637 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
638 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
639 :     | mkNode (SAV stm) = Node.mkSAVE stm
640 :     val entry = mkNode stm
641 :     fun f (stm, prev) = let
642 :     val nd = mkNode stm
643 :     in
644 :     Node.addEdge (prev, nd);
645 :     nd
646 :     end
647 :     val exit = List.foldl f entry stms
648 :     in
649 :     CFG{entry = entry, exit = exit}
650 :     end
651 :    
652 :     (* entry/exit nodes of a CFG *)
653 :     fun entry (CFG{entry = nd, ...}) = nd
654 :     fun exit (CFG{exit = nd, ...}) = nd
655 :    
656 :     (* DFS sorting of the graph rooted at the entry to a statement; the resulting list will
657 :     * be in preorder with parents before children.
658 :     *)
659 :     fun sort (CFG{entry, ...}) = let
660 :     val {getFn, setFn} = PropList.newFlag (fn (ND{props, ...}) => props)
661 :     fun dfs (nd, l) =
662 :     if getFn nd
663 :     then l
664 :     else (
665 :     setFn (nd, true);
666 :     nd :: List.foldl dfs l (Node.succs nd))
667 :     val nodes = dfs (entry, [])
668 :     in
669 :     List.app (fn nd => setFn(nd, false)) nodes;
670 :     nodes
671 :     end
672 :    
673 :     (* apply a function to all of the nodes in the graph rooted at the entry to the statement *)
674 :     fun apply (f : node -> unit) (CFG{entry, ...}) = let
675 :     val {getFn, setFn} = Node.newFlag()
676 :     fun dfs (nd, l) =
677 :     if getFn nd
678 :     then l
679 :     else (
680 :     f nd; (* visit *)
681 :     setFn (nd, true);
682 :     nd :: List.foldl dfs l (Node.succs nd))
683 :     val nodes = dfs (entry, [])
684 :     in
685 :     List.app (fn nd => setFn(nd, false)) nodes
686 :     end
687 :    
688 :     (* delete a simple node from a CFG *)
689 :     fun deleteNode (nd as ND{kind, ...}) = let
690 :     val (pred, succ) = (case kind
691 :     of COM{pred = ref pred, succ = ref succ, ...} => (pred, succ)
692 :     | ASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
693 :     | MASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
694 :     | GASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
695 :     | NEW{pred = ref pred, succ = ref succ, ...} => (pred, succ)
696 :     | SAVE{pred = ref pred, succ = ref succ, ...} => (pred, succ)
697 :     | _ => raise Fail(concat["unsupported deleteNode(", Node.toString nd, ")\n"])
698 :     (* end case *))
699 :     in
700 :     (* replace the predecessor edge from succ to nd with an edge from succ to pred *)
701 :     case Node.kind succ
702 :     of JOIN{preds, ...} => let
703 :     fun edit [] = raise Fail "deleteNode: cannot find predecessor"
704 :     | edit (nd'::nds) = if Node.same(nd', nd) then pred::nds else nd'::edit nds
705 :     in
706 :     preds := edit (!preds)
707 :     end
708 : jhr 3536 | FOREACH{pred=pred', bodyExit, ...} =>
709 :     if Node.same(!pred', nd)
710 :     then pred' := pred
711 :     else bodyExit := pred
712 : jhr 3470 | _ => Node.setPred (succ, pred)
713 :     (* end case *);
714 :     (* replace the successor edge from pred to nd with an edge from pred to succ *)
715 :     case Node.kind pred
716 :     of COND{trueBranch, falseBranch, ...} => (
717 :     (* note that we treat each branch independently, so that we handle the
718 :     * situation where both branches are the same node.
719 :     *)
720 :     if Node.same(!trueBranch, nd)
721 : jhr 3536 then trueBranch := succ
722 : jhr 3470 else ();
723 :     if Node.same(!falseBranch, nd)
724 : jhr 3536 then falseBranch := succ
725 : jhr 3470 else ())
726 : jhr 3536 | FOREACH{bodyEntry, succ=succ', ...} =>
727 :     if Node.same(!bodyEntry, nd)
728 :     then bodyEntry := succ
729 :     else succ' := succ
730 : jhr 3470 | _ => Node.setSucc (pred, succ)
731 :     (* end case *)
732 :     end
733 :     (*DEBUG*)handle ex => (
734 :     print(concat["error in deleteNode(", Node.toString nd, ")\n"]);
735 :     raise ex)
736 :    
737 :     (* replace a simple node in a cfg with a subgraph *)
738 :     fun replaceNode (oldNd as ND{kind, ...}, node) = (case kind
739 :     of ASSIGN{pred, succ, ...} => (
740 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
741 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
742 :     | MASSIGN{pred, succ, ...} => (
743 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
744 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
745 :     | GASSIGN{pred, succ, ...} => (
746 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
747 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
748 :     | NEW{pred, succ, ...} => (
749 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
750 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
751 :     | SAVE{pred, succ, ...} => (
752 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
753 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
754 :     | EXIT{pred, succ=ref NONE, ...} =>
755 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node}
756 :     | _ => raise Fail(concat[
757 :     "unsupported replaceNode(", Node.toString oldNd, ", ", Node.toString node, ")"
758 :     ])
759 :     (* end case *))
760 :    
761 :     (* replace a simple node in a cfg with a subgraph *)
762 :     fun replaceNodeWithCFG (nd as ND{kind, ...}, cfg as CFG{entry, exit}) =
763 :     if isEmpty cfg
764 :     then deleteNode nd
765 :     else (case kind
766 :     of ASSIGN{pred, succ, ...} => (
767 :     Node.replaceInEdge {src = !pred, oldDst = nd, dst = entry};
768 :     Node.replaceOutEdge {oldSrc = nd, src = exit, dst = !succ})
769 :     | MASSIGN{pred, succ, ...} => (
770 :     Node.replaceInEdge {src = !pred, oldDst = nd, dst = entry};
771 :     Node.replaceOutEdge {oldSrc = nd, src = exit, dst = !succ})
772 :     | _ => raise Fail "unsupported replaceNodeWithCFG"
773 :     (* end case *))
774 :    
775 :     (* concatenate two CFGs *)
776 :     fun concat (cfg1 as CFG{entry=e1, exit=x1}, cfg2 as CFG{entry=e2, exit=x2}) =
777 :     if isEmpty cfg1 then cfg2
778 :     else if isEmpty cfg2 then cfg1
779 :     else (
780 :     Node.setSucc (x1, e2);
781 :     Node.setPred (e2, x1);
782 :     CFG{entry = e1, exit = x2})
783 :     (*DEBUG*)handle ex => (
784 :     print(String.concat["error in concat({", Node.toString e1, ",", Node.toString x1,
785 :     "},{", Node.toString e2, ",", Node.toString x2, "})\n"]);
786 :     raise ex)
787 :    
788 :     (* prepend a node to a CFG *)
789 :     fun prependNode (nd, cfg as CFG{entry, exit}) =
790 :     if isEmpty cfg
791 :     then CFG{entry=nd, exit=nd}
792 :     else (
793 :     Node.setSucc (nd, entry);
794 :     Node.setPred (entry, nd);
795 :     CFG{entry=nd, exit=exit})
796 :    
797 :     (* append a node to a CFG *)
798 :     fun appendNode (cfg as CFG{entry, exit}, nd) =
799 :     if isEmpty cfg
800 :     then CFG{entry=nd, exit=nd}
801 :     else (
802 :     Node.setPred (nd, exit);
803 :     Node.setSucc (exit, nd);
804 :     CFG{entry=entry, exit=nd})
805 :    
806 :     (* insert a block of assignments at the beginning of the CFG. If the CFG has an ENTRY
807 :     * node, then the block is inserted immediatly following the entry.
808 :     *)
809 :     fun prependBlock ([], cfg) = cfg
810 :     | prependBlock (stms, cfg as CFG{entry, exit}) = (case entry
811 :     of ND{kind=ENTRY{succ}, ...} => let
812 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
813 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
814 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
815 :     | mkNode (SAV stm) = Node.mkSAVE stm
816 :     fun f (stm, succ) = let
817 :     val nd = mkNode stm
818 :     in
819 :     Node.addEdge (nd, succ);
820 :     nd
821 :     end
822 :     val first = List.foldr f (!succ) stms
823 :     in
824 :     succ := first;
825 :     Node.setPred (first, entry);
826 :     cfg
827 :     end
828 :     | _ => concat(mkBlock stms, cfg)
829 :     (* end case *))
830 :    
831 :     (* insert a block of assignments at the end of the CFG argument If the CFG has an EXIT
832 :     * node, then the block is inserted immediatly before the exit.
833 :     *)
834 :     fun appendBlock (cfg, []) = cfg
835 :     | appendBlock (cfg as CFG{entry, exit}, stms) = (case exit
836 :     of ND{kind=EXIT{pred, ...}, ...} => let
837 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
838 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
839 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
840 :     | mkNode (SAV stm) = Node.mkSAVE stm
841 :     fun f (stm, prev) = let
842 :     val nd = mkNode stm
843 :     in
844 :     Node.addEdge (prev, nd);
845 :     nd
846 :     end
847 :     val last = List.foldl f (!pred) stms
848 :     in
849 :     pred := last;
850 :     Node.setSucc(last, exit);
851 :     cfg
852 :     end
853 :     | _ => concat(cfg, mkBlock stms)
854 :     (* end case *))
855 :     end
856 :    
857 :     structure RHS =
858 :     struct
859 :     fun vars rhs = (case rhs
860 :     of GLOBAL _ => []
861 :     | STATE _ => []
862 :     | VAR x => [x]
863 :     | LIT _ => []
864 :     | OP(rator, xs) => xs
865 :     | CONS(xs, _) => xs
866 :     | SEQ(xs, _) => xs
867 :     | EINAPP(_, xs) => xs
868 :     (* end case *))
869 :    
870 :     fun map f = let
871 :     fun mapf rhs = (case rhs
872 :     of GLOBAL _ => rhs
873 :     | STATE _ => rhs
874 :     | VAR x => VAR(f x)
875 :     | LIT _ => rhs
876 :     | OP(rator, xs) => OP(rator, List.map f xs)
877 :     | CONS(xs, ty) => CONS(List.map f xs, ty)
878 :     | SEQ(xs, ty) => SEQ(List.map f xs, ty)
879 :     | EINAPP(ein, xs) => EINAPP(ein, List.map f xs)
880 :     (* end case *))
881 :     in
882 :     mapf
883 :     end
884 :    
885 :     fun app f = let
886 :     fun appf rhs = (case rhs
887 :     of GLOBAL _ => ()
888 :     | STATE _ => ()
889 :     | VAR x => f x
890 :     | LIT _ => ()
891 :     | OP(rator, xs) => List.app f xs
892 :     | CONS(xs, _) => List.app f xs
893 :     | SEQ(xs, _) => List.app f xs
894 :     | EINAPP(_, xs) => List.app f xs
895 :     (* end case *))
896 :     in
897 :     appf
898 :     end
899 :    
900 :     (* return a string representation of a rhs *)
901 :     fun toString rhs = (case rhs
902 :     of GLOBAL x => GlobalVar.toString x
903 :     | STATE x => StateVar.toString x
904 :     | VAR x => Var.toString x
905 :     | LIT lit => Literal.toString lit
906 :     | OP(rator, xs) => String.concat [
907 :     Op.toString rator,
908 :     "(", String.concatWithMap "," Var.toString xs, ")"
909 :     ]
910 :     | CONS(xs, ty) => String.concat [
911 :     "<", Ty.toString ty, ">[",
912 :     String.concatWithMap "," Var.toString xs, "]"
913 :     ]
914 :     | SEQ(xs, ty) => String.concat [
915 :     "<", Ty.toString ty, ">{",
916 :     String.concatWithMap "," Var.toString xs, "}"
917 :     ]
918 :     | EINAPP(ein, xs) => String.concat [
919 : jhr 3535 EinPP.toString ein, " (",
920 :     String.concatWithMap "," Var.toString xs, ")"
921 : jhr 3470 ]
922 :     (* end case *))
923 :     end
924 : jhr 3586
925 : jhr 3470 (* return a string representation of a variable binding *)
926 :     fun vbToString VB_NONE = "NONE"
927 :     | vbToString (VB_RHS rhs) = concat["RHS(", RHS.toString rhs, ")"]
928 :     | vbToString (VB_MULTIOP(i, rator, xs)) = concat[
929 :     "MULTIOP(", Op.toString rator,
930 :     "[", String.concatWithMap "," Var.toString xs, "])"
931 :     ]
932 :     | vbToString (VB_PHI xs) = concat[
933 :     "PHI(",
934 :     String.concatWithMap "," (fn NONE => "_" | SOME x => Var.toString x) xs, ")"
935 :     ]
936 :     | vbToString VB_PARAM = "PARAM"
937 : jhr 3522 | vbToString VB_ITER = "ITER"
938 : jhr 3470
939 :     (* return a string representation of a PHI node *)
940 :     fun phiToString (y, xs) = String.concat [
941 :     Ty.toString(Var.ty y), " ", Var.toString y, " = PHI(",
942 :     String.concatWithMap "," (fn NONE => "_" | SOME x => Var.toString x) xs, ")"
943 :     ]
944 :    
945 :     (* return a string representation of an assignment *)
946 :     fun assignToString (y, rhs) =
947 :     String.concat [Ty.toString(Var.ty y), " ", Var.toString y, " = ", RHS.toString rhs]
948 :     fun massignToString (ys, rator, xs) = String.concat [
949 :     "(", String.concatWithMap ","
950 :     (fn y => concat[Ty.toString(Var.ty y), " ", Var.toString y]) ys,
951 :     " = ", Op.toString rator,
952 :     "(", String.concatWithMap "," Var.toString xs, ")"
953 :     ]
954 :     fun assignmentToString (ASSGN asgn) = assignToString asgn
955 :     | assignmentToString (MASSGN masgn) = massignToString masgn
956 :     | assignmentToString (GASSGN(lhs, rhs)) = String.concat[
957 :     GlobalVar.toString lhs, " = ", Var.toString rhs
958 :     ]
959 :     | assignmentToString (SAV(lhs, rhs)) = String.concat[
960 :     StateVar.toString lhs, " = ", Var.toString rhs
961 :     ]
962 :    
963 :     end (* SSAFn *)

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