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

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