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 3485 - (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 3473 | FOREACH _ => raise Fail("setSucc on FOREACH node "^toString nd0)
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 :     fun setExitBranch (ND{kind=FOREACH{succ, ...}, ...}, nd) = succ := nd
515 :     | setExitBranch (nd, _) = raise Fail("setExitBranch on " ^ toString nd)
516 : jhr 3470 fun setEdgeMask (ND{kind=JOIN{mask, ...}, ...}, mask') = mask := mask'
517 :     | setEdgeMask (nd, _) = raise Fail("setEdgeMask on " ^ toString nd)
518 :     fun addEdge (nd1, nd2) = (
519 :     if hasSucc nd1
520 :     then (
521 :     setSucc (nd1, nd2);
522 :     setPred (nd2, nd1))
523 :     else ())
524 :     (*DEBUG*)handle ex => (
525 :     print(concat["error in addEdge(", toString nd1, ",", toString nd2, ")\n"]);
526 :     raise ex)
527 :     fun replaceInEdge {src, oldDst, dst} = (
528 :     (* first set the successor of src *)
529 :     case kind src
530 :     of COND{trueBranch, falseBranch, ...} =>
531 :     if same(!trueBranch, oldDst)
532 :     then trueBranch := dst
533 :     else falseBranch := dst
534 :     | _ => setSucc (src, dst)
535 :     (* end case *);
536 :     (* then set the predecessor of dst *)
537 :     setPred (dst, src))
538 :     (*DEBUG*)handle ex => (
539 :     print(concat["error in replaceInEdge(", toString src, ",", toString oldDst, ",", toString dst, ")\n"]);
540 :     raise ex)
541 :     fun replaceOutEdge {oldSrc, src, dst} = (
542 :     (* first set the successor of src *)
543 :     case kind oldSrc
544 :     of COND{trueBranch, falseBranch, ...} =>
545 :     if same(!trueBranch, dst)
546 :     then setTrueBranch (src, dst)
547 :     else setFalseBranch (src, dst)
548 :     | _ => setSucc (src, dst)
549 :     (* end case *);
550 :     (* then set the predecessor of dst *)
551 :     case kind dst
552 :     of JOIN{preds, ...} => let
553 :     fun edit [] = raise Fail "replaceOutEdge: cannot find predecessor"
554 :     | edit (nd::nds) = if same(nd, oldSrc) then src::nds else nd::edit nds
555 :     in
556 :     preds := edit (!preds)
557 :     end
558 :     | _ => setPred (dst, src)
559 :     (* end case *))
560 :     (*DEBUG*)handle ex => (
561 :     print(concat["error in replaceOutEdge(", toString oldSrc, ",", toString src, ",", toString dst, ")\n"]);
562 :     raise ex)
563 :     (* properties *)
564 :     fun newProp initFn =
565 :     PropList.newProp (fn (ND{props, ...}) => props, initFn)
566 :     fun newFlag () =
567 :     PropList.newFlag (fn (ND{props, ...}) => props)
568 :     end
569 :    
570 :     structure CFG =
571 :     struct
572 :     val empty = CFG{entry = Node.dummy, exit = Node.dummy}
573 :    
574 :     fun isEmpty (CFG{entry, exit}) =
575 :     Node.same(entry, exit) andalso Node.isNULL entry
576 :    
577 :     (* create a basic block from a list of assignments *)
578 :     fun mkBlock [] = empty
579 :     | mkBlock (stm::stms) = let
580 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
581 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
582 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
583 :     | mkNode (SAV stm) = Node.mkSAVE stm
584 :     val entry = mkNode stm
585 :     fun f (stm, prev) = let
586 :     val nd = mkNode stm
587 :     in
588 :     Node.addEdge (prev, nd);
589 :     nd
590 :     end
591 :     val exit = List.foldl f entry stms
592 :     in
593 :     CFG{entry = entry, exit = exit}
594 :     end
595 :    
596 :     (* entry/exit nodes of a CFG *)
597 :     fun entry (CFG{entry = nd, ...}) = nd
598 :     fun exit (CFG{exit = nd, ...}) = nd
599 :    
600 :     (* return the list of variables that are live at exit from a CFG *)
601 :     fun liveAtExit cfg = (case Node.kind(exit cfg)
602 :     of EXIT{live, ...} => live
603 :     | _ => raise Fail "bogus exit node"
604 :     (* end case *))
605 :    
606 :     (* DFS sorting of the graph rooted at the entry to a statement; the resulting list will
607 :     * be in preorder with parents before children.
608 :     *)
609 :     fun sort (CFG{entry, ...}) = let
610 :     val {getFn, setFn} = PropList.newFlag (fn (ND{props, ...}) => props)
611 :     fun dfs (nd, l) =
612 :     if getFn nd
613 :     then l
614 :     else (
615 :     setFn (nd, true);
616 :     nd :: List.foldl dfs l (Node.succs nd))
617 :     val nodes = dfs (entry, [])
618 :     in
619 :     List.app (fn nd => setFn(nd, false)) nodes;
620 :     nodes
621 :     end
622 :    
623 :     (* apply a function to all of the nodes in the graph rooted at the entry to the statement *)
624 :     fun apply (f : node -> unit) (CFG{entry, ...}) = let
625 :     val {getFn, setFn} = Node.newFlag()
626 :     fun dfs (nd, l) =
627 :     if getFn nd
628 :     then l
629 :     else (
630 :     f nd; (* visit *)
631 :     setFn (nd, true);
632 :     nd :: List.foldl dfs l (Node.succs nd))
633 :     val nodes = dfs (entry, [])
634 :     in
635 :     List.app (fn nd => setFn(nd, false)) nodes
636 :     end
637 :    
638 :     (* delete a simple node from a CFG *)
639 :     fun deleteNode (nd as ND{kind, ...}) = let
640 :     val (pred, succ) = (case kind
641 :     of COM{pred = ref pred, succ = ref succ, ...} => (pred, succ)
642 :     | ASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
643 :     | MASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
644 :     | GASSIGN{pred = ref pred, succ = ref succ, ...} => (pred, succ)
645 :     | NEW{pred = ref pred, succ = ref succ, ...} => (pred, succ)
646 :     | SAVE{pred = ref pred, succ = ref succ, ...} => (pred, succ)
647 :     | _ => raise Fail(concat["unsupported deleteNode(", Node.toString nd, ")\n"])
648 :     (* end case *))
649 :     in
650 :     (* replace the predecessor edge from succ to nd with an edge from succ to pred *)
651 :     case Node.kind succ
652 :     of JOIN{preds, ...} => let
653 :     fun edit [] = raise Fail "deleteNode: cannot find predecessor"
654 :     | edit (nd'::nds) = if Node.same(nd', nd) then pred::nds else nd'::edit nds
655 :     in
656 :     preds := edit (!preds)
657 :     end
658 :     | _ => Node.setPred (succ, pred)
659 :     (* end case *);
660 :     (* replace the successor edge from pred to nd with an edge from pred to succ *)
661 :     case Node.kind pred
662 :     of COND{trueBranch, falseBranch, ...} => (
663 :     (* note that we treat each branch independently, so that we handle the
664 :     * situation where both branches are the same node.
665 :     *)
666 :     if Node.same(!trueBranch, nd)
667 :     then Node.setTrueBranch(pred, succ)
668 :     else ();
669 :     if Node.same(!falseBranch, nd)
670 :     then Node.setFalseBranch(pred, succ)
671 :     else ())
672 :     | _ => Node.setSucc (pred, succ)
673 :     (* end case *)
674 :     end
675 :     (*DEBUG*)handle ex => (
676 :     print(concat["error in deleteNode(", Node.toString nd, ")\n"]);
677 :     raise ex)
678 :    
679 :     (* replace a simple node in a cfg with a subgraph *)
680 :     fun replaceNode (oldNd as ND{kind, ...}, node) = (case kind
681 :     of ASSIGN{pred, succ, ...} => (
682 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
683 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
684 :     | MASSIGN{pred, succ, ...} => (
685 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
686 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
687 :     | GASSIGN{pred, succ, ...} => (
688 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
689 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
690 :     | NEW{pred, succ, ...} => (
691 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
692 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
693 :     | SAVE{pred, succ, ...} => (
694 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node};
695 :     Node.replaceOutEdge {oldSrc = oldNd, src = node, dst = !succ})
696 :     | EXIT{pred, succ=ref NONE, ...} =>
697 :     Node.replaceInEdge {src = !pred, oldDst = oldNd, dst = node}
698 :     | _ => raise Fail(concat[
699 :     "unsupported replaceNode(", Node.toString oldNd, ", ", Node.toString node, ")"
700 :     ])
701 :     (* end case *))
702 :    
703 :     (* replace a simple node in a cfg with a subgraph *)
704 :     fun replaceNodeWithCFG (nd as ND{kind, ...}, cfg as CFG{entry, exit}) =
705 :     if isEmpty cfg
706 :     then deleteNode nd
707 :     else (case kind
708 :     of ASSIGN{pred, succ, ...} => (
709 :     Node.replaceInEdge {src = !pred, oldDst = nd, dst = entry};
710 :     Node.replaceOutEdge {oldSrc = nd, src = exit, dst = !succ})
711 :     | MASSIGN{pred, succ, ...} => (
712 :     Node.replaceInEdge {src = !pred, oldDst = nd, dst = entry};
713 :     Node.replaceOutEdge {oldSrc = nd, src = exit, dst = !succ})
714 :     | _ => raise Fail "unsupported replaceNodeWithCFG"
715 :     (* end case *))
716 :    
717 :     (* concatenate two CFGs *)
718 :     fun concat (cfg1 as CFG{entry=e1, exit=x1}, cfg2 as CFG{entry=e2, exit=x2}) =
719 :     if isEmpty cfg1 then cfg2
720 :     else if isEmpty cfg2 then cfg1
721 :     else (
722 :     Node.setSucc (x1, e2);
723 :     Node.setPred (e2, x1);
724 :     CFG{entry = e1, exit = x2})
725 :     (*DEBUG*)handle ex => (
726 :     print(String.concat["error in concat({", Node.toString e1, ",", Node.toString x1,
727 :     "},{", Node.toString e2, ",", Node.toString x2, "})\n"]);
728 :     raise ex)
729 :    
730 :     (* prepend a node to a CFG *)
731 :     fun prependNode (nd, cfg as CFG{entry, exit}) =
732 :     if isEmpty cfg
733 :     then CFG{entry=nd, exit=nd}
734 :     else (
735 :     Node.setSucc (nd, entry);
736 :     Node.setPred (entry, nd);
737 :     CFG{entry=nd, exit=exit})
738 :    
739 :     (* append a node to a CFG *)
740 :     fun appendNode (cfg as CFG{entry, exit}, nd) =
741 :     if isEmpty cfg
742 :     then CFG{entry=nd, exit=nd}
743 :     else (
744 :     Node.setPred (nd, exit);
745 :     Node.setSucc (exit, nd);
746 :     CFG{entry=entry, exit=nd})
747 :    
748 :     (* insert a block of assignments at the beginning of the CFG. If the CFG has an ENTRY
749 :     * node, then the block is inserted immediatly following the entry.
750 :     *)
751 :     fun prependBlock ([], cfg) = cfg
752 :     | prependBlock (stms, cfg as CFG{entry, exit}) = (case entry
753 :     of ND{kind=ENTRY{succ}, ...} => let
754 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
755 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
756 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
757 :     | mkNode (SAV stm) = Node.mkSAVE stm
758 :     fun f (stm, succ) = let
759 :     val nd = mkNode stm
760 :     in
761 :     Node.addEdge (nd, succ);
762 :     nd
763 :     end
764 :     val first = List.foldr f (!succ) stms
765 :     in
766 :     succ := first;
767 :     Node.setPred (first, entry);
768 :     cfg
769 :     end
770 :     | _ => concat(mkBlock stms, cfg)
771 :     (* end case *))
772 :    
773 :     (* insert a block of assignments at the end of the CFG argument If the CFG has an EXIT
774 :     * node, then the block is inserted immediatly before the exit.
775 :     *)
776 :     fun appendBlock (cfg, []) = cfg
777 :     | appendBlock (cfg as CFG{entry, exit}, stms) = (case exit
778 :     of ND{kind=EXIT{pred, ...}, ...} => let
779 :     fun mkNode (ASSGN stm) = Node.mkASSIGN stm
780 :     | mkNode (MASSGN stm) = Node.mkMASSIGN stm
781 :     | mkNode (GASSGN stm) = Node.mkGASSIGN stm
782 :     | mkNode (SAV stm) = Node.mkSAVE stm
783 :     fun f (stm, prev) = let
784 :     val nd = mkNode stm
785 :     in
786 :     Node.addEdge (prev, nd);
787 :     nd
788 :     end
789 :     val last = List.foldl f (!pred) stms
790 :     in
791 :     pred := last;
792 :     Node.setSucc(last, exit);
793 :     cfg
794 :     end
795 :     | _ => concat(cfg, mkBlock stms)
796 :     (* end case *))
797 :    
798 :     (* update the exit of a CFG by modifying the live variable list *)
799 :     fun updateExit (CFG{entry, exit as ND{kind, ...}}, f) = let
800 :     val newExit = (case kind
801 :     of EXIT{pred, kind, live, succ=ref NONE} => let
802 :     val newNd = Node.mkEXIT(kind, f live)
803 :     in
804 :     Node.replaceInEdge {src = !pred, oldDst = exit, dst = newNd};
805 :     newNd
806 :     end
807 :     | _ => raise Fail "bogus exit node for updateExit"
808 :     (* end case *))
809 :     in
810 :     CFG{entry=entry, exit=newExit}
811 :     end
812 :     end
813 :    
814 :     structure RHS =
815 :     struct
816 :     fun vars rhs = (case rhs
817 :     of GLOBAL _ => []
818 :     | STATE _ => []
819 :     | VAR x => [x]
820 :     | LIT _ => []
821 :     | OP(rator, xs) => xs
822 :     | CONS(xs, _) => xs
823 :     | SEQ(xs, _) => xs
824 :     | EINAPP(_, xs) => xs
825 :     (* end case *))
826 :    
827 :     fun map f = let
828 :     fun mapf rhs = (case rhs
829 :     of GLOBAL _ => rhs
830 :     | STATE _ => rhs
831 :     | VAR x => VAR(f x)
832 :     | LIT _ => rhs
833 :     | OP(rator, xs) => OP(rator, List.map f xs)
834 :     | CONS(xs, ty) => CONS(List.map f xs, ty)
835 :     | SEQ(xs, ty) => SEQ(List.map f xs, ty)
836 :     | EINAPP(ein, xs) => EINAPP(ein, List.map f xs)
837 :     (* end case *))
838 :     in
839 :     mapf
840 :     end
841 :    
842 :     fun app f = let
843 :     fun appf rhs = (case rhs
844 :     of GLOBAL _ => ()
845 :     | STATE _ => ()
846 :     | VAR x => f x
847 :     | LIT _ => ()
848 :     | OP(rator, xs) => List.app f xs
849 :     | CONS(xs, _) => List.app f xs
850 :     | SEQ(xs, _) => List.app f xs
851 :     | EINAPP(_, xs) => List.app f xs
852 :     (* end case *))
853 :     in
854 :     appf
855 :     end
856 :    
857 :     (* return a string representation of a rhs *)
858 :     fun toString rhs = (case rhs
859 :     of GLOBAL x => GlobalVar.toString x
860 :     | STATE x => StateVar.toString x
861 :     | VAR x => Var.toString x
862 :     | LIT lit => Literal.toString lit
863 :     | OP(rator, xs) => String.concat [
864 :     Op.toString rator,
865 :     "(", String.concatWithMap "," Var.toString xs, ")"
866 :     ]
867 :     | CONS(xs, ty) => String.concat [
868 :     "<", Ty.toString ty, ">[",
869 :     String.concatWithMap "," Var.toString xs, "]"
870 :     ]
871 :     | SEQ(xs, ty) => String.concat [
872 :     "<", Ty.toString ty, ">{",
873 :     String.concatWithMap "," Var.toString xs, "}"
874 :     ]
875 :     (* FIXME: proper printing of Ein applications *)
876 :     | EINAPP(ein, xs) => String.concat [
877 :     "EIN(", String.concatWithMap "," Var.toString xs, ")"
878 :     ]
879 :     (* end case *))
880 :     end
881 :    
882 :     (* return a string representation of a variable binding *)
883 :     fun vbToString VB_NONE = "NONE"
884 :     | vbToString (VB_RHS rhs) = concat["RHS(", RHS.toString rhs, ")"]
885 :     | vbToString (VB_MULTIOP(i, rator, xs)) = concat[
886 :     "MULTIOP(", Op.toString rator,
887 :     "[", String.concatWithMap "," Var.toString xs, "])"
888 :     ]
889 :     | vbToString (VB_PHI xs) = concat[
890 :     "PHI(",
891 :     String.concatWithMap "," (fn NONE => "_" | SOME x => Var.toString x) xs, ")"
892 :     ]
893 :     | vbToString VB_PARAM = "PARAM"
894 :    
895 :     (* return a string representation of a PHI node *)
896 :     fun phiToString (y, xs) = String.concat [
897 :     Ty.toString(Var.ty y), " ", Var.toString y, " = PHI(",
898 :     String.concatWithMap "," (fn NONE => "_" | SOME x => Var.toString x) xs, ")"
899 :     ]
900 :    
901 :     (* return a string representation of an assignment *)
902 :     fun assignToString (y, rhs) =
903 :     String.concat [Ty.toString(Var.ty y), " ", Var.toString y, " = ", RHS.toString rhs]
904 :     fun massignToString (ys, rator, xs) = String.concat [
905 :     "(", String.concatWithMap ","
906 :     (fn y => concat[Ty.toString(Var.ty y), " ", Var.toString y]) ys,
907 :     " = ", Op.toString rator,
908 :     "(", String.concatWithMap "," Var.toString xs, ")"
909 :     ]
910 :     fun assignmentToString (ASSGN asgn) = assignToString asgn
911 :     | assignmentToString (MASSGN masgn) = massignToString masgn
912 :     | assignmentToString (GASSGN(lhs, rhs)) = String.concat[
913 :     GlobalVar.toString lhs, " = ", Var.toString rhs
914 :     ]
915 :     | assignmentToString (SAV(lhs, rhs)) = String.concat[
916 :     StateVar.toString lhs, " = ", Var.toString rhs
917 :     ]
918 :    
919 :     end (* SSAFn *)

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