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

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