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

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