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

SCM Repository

[diderot] Annotation of /branches/vis15/src/compiler/simplify/simplify.sml
ViewVC logotype

Annotation of /branches/vis15/src/compiler/simplify/simplify.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 4433 - (view) (download)

1 : jhr 3437 (* simplify.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 3468 * Simplify the AST representation. This phase involves the following transformations:
9 :     *
10 : jhr 4317 * - types are simplified by removing meta variables (which will have been resolved)
11 : jhr 3468 *
12 : jhr 4317 * - expressions are simplified to involve a single operation on variables
13 : jhr 3468 *
14 : jhr 4317 * - global reductions are converted to MapReduce statements
15 : jhr 3468 *
16 : jhr 4317 * - other comprehensions and reductions are converted to foreach loops
17 : jhr 3468 *
18 : jhr 4317 * - unreachable code is pruned
19 : jhr 3468 *
20 : jhr 4317 * - negation of literal integers and reals are constant folded
21 : jhr 3437 *)
22 :    
23 :     structure Simplify : sig
24 :    
25 : jhr 4371 val transform : Error.err_stream * AST.program * GlobalEnv.t -> Simple.program
26 : jhr 3437
27 :     end = struct
28 :    
29 :     structure TU = TypeUtil
30 :     structure S = Simple
31 : jhr 3445 structure STy = SimpleTypes
32 :     structure Ty = Types
33 : jhr 3437 structure VMap = Var.Map
34 : jhr 4193 structure II = ImageInfo
35 : jhr 4359 structure BV = BasisVars
36 : jhr 3437
37 : jhr 4371 (* context for simplification *)
38 :     type context = {errStrm : Error.err_stream, gEnv : GlobalEnv.t}
39 :    
40 :     fun error ({errStrm, gEnv}, msg) = Error.error (errStrm, msg)
41 :     fun warning ({errStrm, gEnv}, msg) = Error.warning (errStrm, msg)
42 :    
43 : jhr 4432 (* error message for when a nrrd image file is incompatible with the declared image type *)
44 :     fun badImageNrrd (cxt, nrrdFile, nrrdInfo, expectedDim, expectedShp) = let
45 :     val NrrdInfo.NrrdInfo{dim, nElems, ...} = nrrdInfo
46 :     val expectedNumElems = List.foldl (op * ) 1 expectedShp
47 :     val prefix = String.concat[
48 :     "image file \"", nrrdFile, "\" is incompatible with expected type image(",
49 :     Int.toString expectedDim, ")[",
50 :     String.concatWithMap "," Int.toString expectedShp, "]"
51 :     ]
52 :     in
53 :     case (dim = expectedDim, nElems = expectedNumElems)
54 :     of (false, true) => error (cxt, [
55 :     prefix, "; its dimension is ", Int.toString dim
56 :     ])
57 :     | (true, false) => error (cxt, [
58 :     prefix, "; it has ", Int.toString nElems, " sample per voxel"
59 :     ])
60 :     | _ => error (cxt, [
61 :     prefix, "; its dimension is ", Int.toString dim, " and it has ",
62 :     Int.toString nElems, " sample per voxel"
63 :     ])
64 :     (* end case *)
65 :     end
66 : jhr 4428
67 : jhr 3445 (* convert a Types.ty to a SimpleTypes.ty *)
68 :     fun cvtTy ty = (case ty
69 :     of Ty.T_Var(Ty.TV{bind, ...}) => (case !bind
70 :     of NONE => raise Fail "unresolved type variable"
71 :     | SOME ty => cvtTy ty
72 :     (* end case *))
73 :     | Ty.T_Bool => STy.T_Bool
74 :     | Ty.T_Int => STy.T_Int
75 :     | Ty.T_String => STy.T_String
76 :     | Ty.T_Sequence(ty, NONE) => STy.T_Sequence(cvtTy ty, NONE)
77 : jhr 3452 | Ty.T_Sequence(ty, SOME dim) => STy.T_Sequence(cvtTy ty, SOME(TU.monoDim dim))
78 : jhr 4317 | Ty.T_Strand id => STy.T_Strand id
79 : jhr 4207 | Ty.T_Kernel _ => STy.T_Kernel
80 : jhr 3445 | Ty.T_Tensor shape => STy.T_Tensor(TU.monoShape shape)
81 : jhr 4193 | Ty.T_Image{dim, shape} =>
82 : jhr 4317 STy.T_Image(II.mkInfo(TU.monoDim dim, TU.monoShape shape))
83 : jhr 3445 | Ty.T_Field{diff, dim, shape} => STy.T_Field{
84 :     diff = TU.monoDiff diff,
85 :     dim = TU.monoDim dim,
86 :     shape = TU.monoShape shape
87 :     }
88 : jhr 4163 | Ty.T_Fun(tys1, ty2) => raise Fail "unexpected T_Fun in Simplify"
89 : jhr 4317 | Ty.T_Error => raise Fail "unexpected T_Error in Simplify"
90 : jhr 3445 (* end case *))
91 : jhr 3437
92 : jhr 3811 fun apiTypeOf x = let
93 : jhr 4317 fun cvtTy STy.T_Bool = APITypes.BoolTy
94 :     | cvtTy STy.T_Int = APITypes.IntTy
95 :     | cvtTy STy.T_String = APITypes.StringTy
96 :     | cvtTy (STy.T_Sequence(ty, len)) = APITypes.SeqTy(cvtTy ty, len)
97 :     | cvtTy (STy.T_Tensor shape) = APITypes.TensorTy shape
98 :     | cvtTy (STy.T_Image info) =
99 :     APITypes.ImageTy(II.dim info, II.voxelShape info)
100 :     | cvtTy ty = raise Fail "bogus API type"
101 :     in
102 :     cvtTy (SimpleVar.typeOf x)
103 :     end
104 : jhr 3811
105 : jhr 4117 fun newTemp (ty as STy.T_Image _) = SimpleVar.new ("img", SimpleVar.LocalVar, ty)
106 :     | newTemp ty = SimpleVar.new ("_t", SimpleVar.LocalVar, ty)
107 : jhr 3437
108 : jhr 4163 (* a property to map AST function variables to SimpleAST functions *)
109 :     local
110 :     fun cvt x = let
111 : jhr 4317 val Ty.T_Fun(paramTys, resTy) = Var.monoTypeOf x
112 :     in
113 :     SimpleFunc.new (Var.nameOf x, cvtTy resTy, List.map cvtTy paramTys)
114 :     end
115 : jhr 4163 in
116 :     val {getFn = cvtFunc, ...} = Var.newProp cvt
117 :     end
118 :    
119 : jhr 3456 (* a property to map AST variables to SimpleAST variables *)
120 :     local
121 :     fun cvt x = SimpleVar.new (Var.nameOf x, Var.kindOf x, cvtTy(Var.monoTypeOf x))
122 : jhr 4193 val {getFn, setFn, ...} = Var.newProp cvt
123 : jhr 3456 in
124 : jhr 4193 val cvtVar = getFn
125 :     fun newVarWithType (x, ty) = let
126 : jhr 4317 val x' = SimpleVar.new (Var.nameOf x, Var.kindOf x, ty)
127 :     in
128 :     setFn (x, x');
129 :     x'
130 :     end
131 : jhr 3456 end
132 : jhr 3452
133 : jhr 3456 fun cvtVars xs = List.map cvtVar xs
134 : jhr 3452
135 : jhr 3437 (* make a block out of a list of statements that are in reverse order *)
136 : jhr 3501 fun mkBlock stms = S.Block{props = PropList.newHolder(), code = List.rev stms}
137 : jhr 3437
138 : jhr 4393 (* make a variable definition *)
139 :     fun mkDef (x, e) = S.S_Var(x, SOME e)
140 :    
141 : jhr 4394 fun mkRDiv (res, a, b) = mkDef (res, S.E_Prim(BV.div_rr, [], [a, b], STy.realTy))
142 :     fun mkToReal (res, a) =
143 :     mkDef (res, S.E_Coerce{srcTy = STy.T_Int, dstTy = STy.realTy, x = a})
144 :     fun mkLength (res, elemTy, xs) =
145 :     mkDef (res, S.E_Prim(BV.fn_length, [STy.TY elemTy], [xs], STy.T_Int))
146 :    
147 : jhr 3437 (* simplify a statement into a single statement (i.e., a block if it expands
148 :     * into more than one new statement).
149 :     *)
150 : jhr 4371 fun simplifyBlock (cxt, stm) = mkBlock (simplifyStmt (cxt, stm, []))
151 : jhr 3437
152 : jhr 4193 (* convert the lhs variable of a var decl or assignment; if the rhs is a LoadImage,
153 :     * then we use the info from the proxy image to determine the type of the lhs
154 :     * variable.
155 :     *)
156 :     and cvtLHS (lhs, S.E_LoadImage(_, _, info)) = newVarWithType(lhs, STy.T_Image info)
157 :     | cvtLHS (lhs, _) = cvtVar lhs
158 :    
159 : jhr 3437 (* simplify the statement stm where stms is a reverse-order list of preceeding simplified
160 :     * statements. This function returns a reverse-order list of simplified statements.
161 :     * Note that error reporting is done in the typechecker, but it does not prune unreachable
162 :     * code.
163 :     *)
164 : jhr 4371 and simplifyStmt (cxt, stm, stms) : S.stmt list = (case stm
165 : jhr 3437 of AST.S_Block body => let
166 : jhr 3456 fun simplify ([], stms) = stms
167 : jhr 4371 | simplify (stm::r, stms) = simplify (r, simplifyStmt (cxt, stm, stms))
168 : jhr 3437 in
169 : jhr 3456 simplify (body, stms)
170 : jhr 3437 end
171 : jhr 3452 | AST.S_Decl(x, NONE) => let
172 : jhr 3456 val x' = cvtVar x
173 : jhr 3452 in
174 : jhr 3465 S.S_Var(x', NONE) :: stms
175 : jhr 3452 end
176 :     | AST.S_Decl(x, SOME e) => let
177 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, stms)
178 : jhr 4193 val x' = cvtLHS (x, e')
179 : jhr 3437 in
180 : jhr 3465 S.S_Var(x', SOME e') :: stms
181 : jhr 3437 end
182 : jhr 4310 (* FIXME: we should also define a "boolean negate" operation on AST expressions so that we can
183 : jhr 4254 * handle both cases!
184 :     *)
185 :     | AST.S_IfThenElse(AST.E_Orelse(e1, e2), s1 as AST.S_Block[], s2) =>
186 : jhr 4371 simplifyStmt (cxt, AST.S_IfThenElse(e1, s1, AST.S_IfThenElse(e2, s1, s2)), stms)
187 : jhr 4254 | AST.S_IfThenElse(AST.E_Andalso(e1, e2), s1, s2 as AST.S_Block[]) =>
188 : jhr 4371 simplifyStmt (cxt, AST.S_IfThenElse(e1, AST.S_IfThenElse(e2, s1, s2), s2), stms)
189 : jhr 3437 | AST.S_IfThenElse(e, s1, s2) => let
190 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
191 :     val s1 = simplifyBlock (cxt, s1)
192 :     val s2 = simplifyBlock (cxt, s2)
193 : jhr 3437 in
194 : jhr 3456 S.S_IfThenElse(x, s1, s2) :: stms
195 : jhr 3437 end
196 : jhr 4317 | AST.S_Foreach((x, e), body) => let
197 : jhr 4371 val (stms, xs') = simplifyExpToVar (cxt, e, stms)
198 :     val body' = simplifyBlock (cxt, body)
199 : jhr 4317 in
200 :     S.S_Foreach(cvtVar x, xs', body') :: stms
201 :     end
202 : jhr 3452 | AST.S_Assign((x, _), e) => let
203 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, stms)
204 : jhr 4193 val x' = cvtLHS (x, e')
205 : jhr 3437 in
206 : jhr 4193 S.S_Assign(x', e') :: stms
207 : jhr 3437 end
208 :     | AST.S_New(name, args) => let
209 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
210 : jhr 3437 in
211 : jhr 3456 S.S_New(name, xs) :: stms
212 : jhr 3437 end
213 : jhr 3456 | AST.S_Continue => S.S_Continue :: stms
214 :     | AST.S_Die => S.S_Die :: stms
215 :     | AST.S_Stabilize => S.S_Stabilize :: stms
216 : jhr 3437 | AST.S_Return e => let
217 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
218 : jhr 3437 in
219 : jhr 3456 S.S_Return x :: stms
220 : jhr 3437 end
221 :     | AST.S_Print args => let
222 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
223 : jhr 3437 in
224 : jhr 3456 S.S_Print xs :: stms
225 : jhr 3437 end
226 :     (* end case *))
227 :    
228 : jhr 4371 and simplifyExp (cxt, exp, stms) = let
229 : jhr 4317 fun doBorderCtl (f, args) = let
230 : jhr 4359 val (ctl, arg) = if Var.same(BV.image_border, f)
231 : jhr 4317 then (BorderCtl.Default(hd args), hd(tl args))
232 : jhr 4359 else if Var.same(BV.image_clamp, f)
233 : jhr 4317 then (BorderCtl.Clamp, hd args)
234 : jhr 4359 else if Var.same(BV.image_mirror, f)
235 : jhr 4317 then (BorderCtl.Mirror, hd args)
236 : jhr 4359 else if Var.same(BV.image_wrap, f)
237 : jhr 4317 then (BorderCtl.Wrap, hd args)
238 :     else raise Fail "impossible"
239 :     in
240 :     S.E_BorderCtl(ctl, arg)
241 :     end
242 :     fun doPrimApply (f, tyArgs, args, ty) = let
243 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
244 : jhr 4378 fun cvtTyArg (Types.TYPE tv) = S.TY(cvtTy(TU.resolve tv))
245 :     | cvtTyArg (Types.DIFF dv) = S.DIFF(TU.monoDiff(TU.resolveDiff dv))
246 :     | cvtTyArg (Types.SHAPE sv) = S.SHAPE(TU.monoShape(TU.resolveShape sv))
247 :     | cvtTyArg (Types.DIM dv) = S.DIM(TU.monoDim(TU.resolveDim dv))
248 : jhr 4317 in
249 :     if Basis.isBorderCtl f
250 :     then (stms, doBorderCtl (f, xs))
251 : jhr 4368 else if Var.same(f, BV.fn_sphere_im)
252 : jhr 4371 then let
253 : jhr 4378 (* get the strand type for the query *)
254 :     val tyArgs as [S.TY(STy.T_Strand strand)] = List.map cvtTyArg tyArgs
255 :     (* get the strand environment for the strand *)
256 :     val SOME sEnv = GlobalEnv.findStrand(#gEnv cxt, strand)
257 :     fun result (query, pos) =
258 :     (stms, S.E_Prim(query, tyArgs, cvtVar pos::xs, cvtTy ty))
259 :     in
260 :     (* extract the position variable and spatial dimension *)
261 :     case (StrandEnv.findPosVar sEnv, StrandEnv.getSpaceDim sEnv)
262 :     of (SOME pos, SOME 1) => result (BV.fn_sphere1_r, pos)
263 :     | (SOME pos, SOME 2) => result (BV.fn_sphere2_t, pos)
264 :     | (SOME pos, SOME 3) => result (BV.fn_sphere3_t, pos)
265 :     | _ => raise Fail "impossible"
266 :     (* end case *)
267 :     end
268 : jhr 4317 else (case Var.kindOf f
269 :     of Var.BasisVar => let
270 :     val tyArgs = List.map cvtTyArg tyArgs
271 :     in
272 :     (stms, S.E_Prim(f, tyArgs, xs, cvtTy ty))
273 :     end
274 :     | _ => raise Fail "bogus prim application"
275 :     (* end case *))
276 :     end
277 :     in
278 :     case exp
279 :     of AST.E_Var(x, _) => (case Var.kindOf x
280 :     of Var.BasisVar => let
281 :     val ty = cvtTy(Var.monoTypeOf x)
282 :     val x' = newTemp ty
283 :     val stm = S.S_Var(x', SOME(S.E_Prim(x, [], [], ty)))
284 :     in
285 :     (stm::stms, S.E_Var x')
286 :     end
287 :     | _ => (stms, S.E_Var(cvtVar x))
288 :     (* end case *))
289 :     | AST.E_Lit lit => (stms, S.E_Lit lit)
290 :     | AST.E_Kernel h => (stms, S.E_Kernel h)
291 :     | AST.E_Select(e, (fld, _)) => let
292 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
293 : jhr 4317 in
294 :     (stms, S.E_Select(x, cvtVar fld))
295 :     end
296 :     | AST.E_Prim(rator, tyArgs, args as [e], ty) => (case e
297 : jhr 4359 of AST.E_Lit(Literal.Int n) => if Var.same(BV.neg_i, rator)
298 : jhr 4317 then (stms, S.E_Lit(Literal.Int(~n))) (* constant-fold negation of integer literals *)
299 :     else doPrimApply (rator, tyArgs, args, ty)
300 :     | AST.E_Lit(Literal.Real f) =>
301 : jhr 4359 if Var.same(BV.neg_t, rator)
302 : jhr 4317 then (stms, S.E_Lit(Literal.Real(RealLit.negate f))) (* constant-fold negation of real literals *)
303 :     else doPrimApply (rator, tyArgs, args, ty)
304 : jhr 4364 (* QUESTION: is there common code in handling a reduction over a sequence of strands vs. over a strand set? *)
305 : jhr 4317 | AST.E_Comprehension(e', (x, e''), seqTy) => if Basis.isReductionOp rator
306 :     then let
307 : jhr 4371 val (stms, xs) = simplifyExpToVar (cxt, e'', stms)
308 : jhr 4393 val (bodyStms, bodyResult) = simplifyExpToVar (cxt, e', [])
309 : jhr 4317 val seqTy' as STy.T_Sequence(elemTy, NONE) = cvtTy seqTy
310 : jhr 4393 fun mkReductionLoop (redOp, bodyStms, bodyResult, stms) = let
311 :     val {rator, init, mvs} = Util.reductionInfo redOp
312 :     val acc = SimpleVar.new ("accum", Var.LocalVar, cvtTy ty)
313 :     val initStm = S.S_Var(acc, SOME(S.E_Lit init))
314 :     val updateStm = S.S_Assign(acc,
315 :     S.E_Prim(rator, mvs, [acc, bodyResult], seqTy'))
316 :     val foreachStm = S.S_Foreach(cvtVar x, xs,
317 :     mkBlock(updateStm :: bodyStms))
318 :     in
319 :     (foreachStm :: initStm :: stms, S.E_Var acc)
320 :     end
321 :     in
322 :     case Util.identifyReduction rator
323 :     of Util.MEAN => let
324 :     val (stms, S.E_Var resultV) = mkReductionLoop (
325 :     Reductions.SUM, bodyStms, bodyResult, stms)
326 :     val num = SimpleVar.new ("num", Var.LocalVar, STy.T_Int)
327 :     val rNum = SimpleVar.new ("rNum", Var.LocalVar, STy.realTy)
328 :     val mean = SimpleVar.new ("mean", Var.LocalVar, STy.realTy)
329 :     val stms =
330 : jhr 4394 mkRDiv (mean, resultV, rNum) ::
331 :     mkToReal (rNum, num) ::
332 :     mkLength (num, elemTy, xs) ::
333 : jhr 4393 stms
334 :     in
335 :     (stms, S.E_Var mean)
336 :     end
337 :     | Util.VARIANCE => raise Fail "FIXME: VARIANCE"
338 :     | Util.RED red => mkReductionLoop (red, bodyStms, bodyResult, stms)
339 :     (* end case *)
340 :     end
341 : jhr 4317 else doPrimApply (rator, tyArgs, args, ty)
342 :     | AST.E_ParallelMap(e', x, xs, _) =>
343 :     if Basis.isReductionOp rator
344 :     then let
345 : jhr 4394 val (result, stms) = simplifyReduction (cxt, rator, e', x, xs, ty, stms)
346 : jhr 4317 in
347 : jhr 4394 (stms, S.E_Var result)
348 : jhr 4317 end
349 :     else raise Fail "unsupported operation on parallel map"
350 :     | _ => doPrimApply (rator, tyArgs, args, ty)
351 :     (* end case *))
352 :     | AST.E_Prim(f, tyArgs, args, ty) => doPrimApply (f, tyArgs, args, ty)
353 :     | AST.E_Apply((f, _), args, ty) => let
354 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, args, stms)
355 : jhr 4317 in
356 :     case Var.kindOf f
357 :     of Var.FunVar => (stms, S.E_Apply(SimpleFunc.use(cvtFunc f), xs))
358 :     | _ => raise Fail "bogus application"
359 :     (* end case *)
360 :     end
361 :     | AST.E_Comprehension(e, (x, e'), seqTy) => let
362 :     (* convert a comprehension to a foreach loop over the sequence defined by e' *)
363 : jhr 4371 val (stms, xs) = simplifyExpToVar (cxt, e', stms)
364 :     val (bodyStms, bodyResult) = simplifyExpToVar (cxt, e, [])
365 : jhr 4317 val seqTy' as STy.T_Sequence(elemTy, NONE) = cvtTy seqTy
366 :     val acc = SimpleVar.new ("accum", Var.LocalVar, seqTy')
367 :     val initStm = S.S_Var(acc, SOME(S.E_Seq([], seqTy')))
368 :     val updateStm = S.S_Assign(acc,
369 : jhr 4359 S.E_Prim(BV.at_dT, [S.TY elemTy], [acc, bodyResult], seqTy'))
370 : jhr 4317 val foreachStm = S.S_Foreach(cvtVar x, xs, mkBlock(updateStm :: bodyStms))
371 :     in
372 :     (foreachStm :: initStm :: stms, S.E_Var acc)
373 :     end
374 :     | AST.E_ParallelMap(e, x, xs, ty) => raise Fail "FIXME: ParallelMap"
375 :     | AST.E_Tensor(es, ty) => let
376 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, es, stms)
377 : jhr 4317 in
378 :     (stms, S.E_Tensor(xs, cvtTy ty))
379 :     end
380 :     | AST.E_Seq(es, ty) => let
381 : jhr 4371 val (stms, xs) = simplifyExpsToVars (cxt, es, stms)
382 : jhr 4317 in
383 :     (stms, S.E_Seq(xs, cvtTy ty))
384 :     end
385 :     | AST.E_Slice(e, indices, ty) => let (* tensor slicing *)
386 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
387 : jhr 4317 fun f NONE = NONE
388 :     | f (SOME(AST.E_Lit(Literal.Int i))) = SOME(Int.fromLarge i)
389 :     | f _ = raise Fail "expected integer literal in slice"
390 :     val indices = List.map f indices
391 :     in
392 :     (stms, S.E_Slice(x, indices, cvtTy ty))
393 :     end
394 :     | AST.E_Cond(e1, e2, e3, ty) => let
395 :     (* a conditional expression gets turned into an if-then-else statememt *)
396 :     val result = newTemp(cvtTy ty)
397 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e1, S.S_Var(result, NONE) :: stms)
398 : jhr 4317 fun simplifyBranch e = let
399 : jhr 4371 val (stms, e) = simplifyExp (cxt, e, [])
400 : jhr 4317 in
401 :     mkBlock (S.S_Assign(result, e)::stms)
402 :     end
403 :     val s1 = simplifyBranch e2
404 :     val s2 = simplifyBranch e3
405 :     in
406 :     (S.S_IfThenElse(x, s1, s2) :: stms, S.E_Var result)
407 :     end
408 :     | AST.E_Orelse(e1, e2) => simplifyExp (
409 : jhr 4371 cxt,
410 : jhr 4317 AST.E_Cond(e1, AST.E_Lit(Literal.Bool true), e2, Ty.T_Bool),
411 :     stms)
412 :     | AST.E_Andalso(e1, e2) => simplifyExp (
413 : jhr 4371 cxt,
414 : jhr 4317 AST.E_Cond(e1, e2, AST.E_Lit(Literal.Bool false), Ty.T_Bool),
415 :     stms)
416 :     | AST.E_LoadNrrd(_, nrrd, ty) => (case cvtTy ty
417 :     of ty as STy.T_Sequence(_, NONE) => (stms, S.E_LoadSeq(ty, nrrd))
418 :     | ty as STy.T_Image info => let
419 :     val dim = II.dim info
420 :     val shape = II.voxelShape info
421 :     in
422 : jhr 4371 case NrrdInfo.getInfo (#errStrm cxt, nrrd)
423 : jhr 4317 of SOME nrrdInfo => (case II.fromNrrd(nrrdInfo, dim, shape)
424 :     of NONE => (
425 : jhr 4432 badImageNrrd (cxt, nrrd, nrrdInfo, dim, shape);
426 : jhr 4317 (stms, S.E_LoadImage(ty, nrrd, II.mkInfo(dim, shape))))
427 :     | SOME imgInfo =>
428 :     (stms, S.E_LoadImage(STy.T_Image imgInfo, nrrd, imgInfo))
429 :     (* end case *))
430 :     | NONE => (
431 : jhr 4433 error (cxt, [
432 :     "proxy-image file \"", nrrd, "\" does not exist"
433 : jhr 4317 ]);
434 :     (stms, S.E_LoadImage(ty, nrrd, II.mkInfo(dim, shape))))
435 :     (* end case *)
436 :     end
437 :     | _ => raise Fail "bogus type for E_LoadNrrd"
438 :     (* end case *))
439 :     | AST.E_Coerce{dstTy, e=AST.E_Lit(Literal.Int n), ...} => (case cvtTy dstTy
440 :     of SimpleTypes.T_Tensor[] => (stms, S.E_Lit(Literal.Real(RealLit.fromInt n)))
441 :     | _ => raise Fail "impossible: bad coercion"
442 :     (* end case *))
443 :     | AST.E_Coerce{srcTy, dstTy, e} => let
444 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
445 : jhr 4317 val dstTy = cvtTy dstTy
446 :     val result = newTemp dstTy
447 :     val rhs = S.E_Coerce{srcTy = cvtTy srcTy, dstTy = dstTy, x = x}
448 :     in
449 :     (S.S_Var(result, SOME rhs)::stms, S.E_Var result)
450 :     end
451 :     (* end case *)
452 :     end
453 : jhr 3437
454 : jhr 4371 and simplifyExpToVar (cxt, exp, stms) = let
455 :     val (stms, e) = simplifyExp (cxt, exp, stms)
456 : jhr 3437 in
457 :     case e
458 :     of S.E_Var x => (stms, x)
459 :     | _ => let
460 :     val x = newTemp (S.typeOf e)
461 :     in
462 : jhr 3465 (S.S_Var(x, SOME e)::stms, x)
463 : jhr 3437 end
464 :     (* end case *)
465 :     end
466 :    
467 : jhr 4371 and simplifyExpsToVars (cxt, exps, stms) = let
468 : jhr 3437 fun f ([], xs, stms) = (stms, List.rev xs)
469 :     | f (e::es, xs, stms) = let
470 : jhr 4371 val (stms, x) = simplifyExpToVar (cxt, e, stms)
471 : jhr 3437 in
472 :     f (es, x::xs, stms)
473 :     end
474 :     in
475 :     f (exps, [], stms)
476 :     end
477 :    
478 : jhr 4359 (* simplify a parallel map-reduce *)
479 : jhr 4394 and simplifyReduction (cxt, rator, e, x, xs, resTy, stms) = let
480 : jhr 4378 val result = SimpleVar.new ("res", Var.LocalVar, cvtTy resTy)
481 : jhr 4368 val x' = cvtVar x
482 : jhr 4371 val (bodyStms, bodyResult) = simplifyExpToVar (cxt, e, [])
483 : jhr 4378 (* convert the domain from a variable to a StrandSets.t value *)
484 :     val domain = if Var.same(BV.set_active, xs) then StrandSets.ACTIVE
485 :     else if Var.same(BV.set_all, xs) then StrandSets.ALL
486 :     else if Var.same(BV.set_stable, xs) then StrandSets.STABLE
487 :     else raise Fail "impossible: not a strand set"
488 : jhr 4368 val (func, args) = Util.makeFunction(
489 :     Var.nameOf rator, mkBlock(S.S_Return bodyResult :: bodyStms),
490 :     SimpleVar.typeOf bodyResult)
491 : jhr 4359
492 : jhr 4394 in
493 :     case Util.identifyReduction rator
494 :     of Util.MEAN => let
495 :     val mapReduceStm = S.S_MapReduce[
496 :     S.MapReduce{
497 :     result = result, reduction = Reductions.SUM, mapf = func,
498 :     args = args, source = x', domain = domain
499 :     }]
500 :     val num = SimpleVar.new ("num", Var.LocalVar, STy.T_Int)
501 :     val rNum = SimpleVar.new ("rNum", Var.LocalVar, STy.realTy)
502 :     val mean = SimpleVar.new ("mean", Var.LocalVar, STy.realTy)
503 :     val numStrandsOp = (case domain
504 :     of StrandSets.ACTIVE => BV.numActive
505 :     | StrandSets.ALL => BV.numStrands
506 :     | StrandSets.STABLE => BV.numStable
507 :     (* end case *))
508 :     val stms =
509 :     mkRDiv (mean, result, rNum) ::
510 :     mkToReal (rNum, num) ::
511 :     mkDef (num, S.E_Prim(numStrandsOp, [], [], STy.T_Int)) ::
512 :     mapReduceStm ::
513 :     stms
514 :     in
515 :     (mean, stms)
516 :     end
517 :     | Util.VARIANCE => raise Fail "FIXME: variance reduction"
518 :     | Util.RED rator' => let
519 :     val mapReduceStm = S.S_MapReduce[
520 :     S.MapReduce{
521 :     result = result, reduction = rator', mapf = func, args = args,
522 :     source = x', domain = domain
523 :     }]
524 :     in
525 :     (result, mapReduceStm :: stms)
526 :     end
527 :     (* end case *)
528 :     end
529 :    
530 : jhr 4113 (* simplify a block and then prune unreachable and dead code *)
531 : jhr 4371 fun simplifyAndPruneBlock cxt blk =
532 :     DeadCode.eliminate (simplifyBlock (cxt, blk))
533 : jhr 4113
534 : jhr 4371 fun simplifyStrand (cxt, strand) = let
535 : jhr 4368 val AST.Strand{
536 :     name, params, spatialDim, state, stateInit, initM, updateM, stabilizeM
537 :     } = strand
538 : jhr 3456 val params' = cvtVars params
539 :     fun simplifyState ([], xs, stms) = (List.rev xs, mkBlock stms)
540 :     | simplifyState ((x, optE) :: r, xs, stms) = let
541 :     val x' = cvtVar x
542 : jhr 4317 in
543 :     case optE
544 :     of NONE => simplifyState (r, x'::xs, stms)
545 :     | SOME e => let
546 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, stms)
547 : jhr 4317 in
548 :     simplifyState (r, x'::xs, S.S_Assign(x', e') :: stms)
549 :     end
550 :     (* end case *)
551 :     end
552 : jhr 3456 val (xs, stm) = simplifyState (state, [], [])
553 : jhr 3437 in
554 : jhr 3452 S.Strand{
555 :     name = name,
556 :     params = params',
557 : jhr 4368 spatialDim = spatialDim,
558 : jhr 3456 state = xs,
559 : jhr 4317 stateInit = stm,
560 : jhr 4371 initM = Option.map (simplifyAndPruneBlock cxt) initM,
561 :     updateM = simplifyAndPruneBlock cxt updateM,
562 :     stabilizeM = Option.map (simplifyAndPruneBlock cxt) stabilizeM
563 : jhr 3452 }
564 : jhr 3437 end
565 :    
566 : jhr 4371 fun transform (errStrm, prog, gEnv) = let
567 : jhr 4317 val AST.Program{
568 :     props, const_dcls, input_dcls, globals, globInit, strand, create, init, update
569 :     } = prog
570 : jhr 4378 val cxt = {errStrm = errStrm, gEnv = gEnv}
571 : jhr 4317 val consts' = ref[]
572 :     val constInit = ref[]
573 :     val inputs' = ref[]
574 :     val globals' = ref[]
575 :     val globalInit = ref[]
576 :     val funcs = ref[]
577 :     fun simplifyConstDcl (x, SOME e) = let
578 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, [])
579 : jhr 4317 val x' = cvtVar x
580 :     in
581 :     consts' := x' :: !consts';
582 :     constInit := S.S_Assign(x', e') :: (stms @ !constInit)
583 :     end
584 :     fun simplifyInputDcl ((x, NONE), desc) = let
585 :     val x' = cvtVar x
586 :     val init = (case SimpleVar.typeOf x'
587 : jhr 4432 of STy.T_Image info => (
588 :     warning(cxt, [
589 :     "assuming a sample type of ", RawTypes.toString(II.sampleTy info),
590 :     " for '", SimpleVar.nameOf x',
591 :     "'; specify a proxy-image file to override the default sample type"
592 :     ]);
593 :     S.Image info)
594 : jhr 4317 | _ => S.NoDefault
595 :     (* end case *))
596 :     val inp = S.INP{
597 :     var = x',
598 :     name = Var.nameOf x,
599 :     ty = apiTypeOf x',
600 :     desc = desc,
601 :     init = init
602 :     }
603 :     in
604 :     inputs' := inp :: !inputs'
605 :     end
606 :     | simplifyInputDcl ((x, SOME(AST.E_LoadNrrd(tvs, nrrd, ty))), desc) = let
607 :     val (x', init) = (case Var.monoTypeOf x
608 :     of Ty.T_Sequence(_, NONE) => (cvtVar x, S.LoadSeq nrrd)
609 :     | Ty.T_Image{dim, shape} => let
610 :     val dim = TU.monoDim dim
611 :     val shape = TU.monoShape shape
612 :     in
613 : jhr 4371 case NrrdInfo.getInfo (#errStrm cxt, nrrd)
614 : jhr 4317 of SOME nrrdInfo => (case II.fromNrrd(nrrdInfo, dim, shape)
615 :     of NONE => (
616 : jhr 4432 badImageNrrd (cxt, nrrd, nrrdInfo, dim, shape);
617 : jhr 4317 (cvtVar x, S.Image(II.mkInfo(dim, shape))))
618 :     | SOME info =>
619 :     (newVarWithType(x, STy.T_Image info), S.Proxy(nrrd, info))
620 :     (* end case *))
621 :     | NONE => (
622 : jhr 4433 error (cxt, [
623 :     "proxy-image file \"", nrrd, "\" does not exist"
624 : jhr 4317 ]);
625 :     (cvtVar x, S.Image(II.mkInfo(dim, shape))))
626 :     (* end case *)
627 :     end
628 :     | _ => raise Fail "impossible"
629 :     (* end case *))
630 :     val inp = S.INP{
631 :     var = x',
632 :     name = Var.nameOf x,
633 :     ty = apiTypeOf x',
634 :     desc = desc,
635 :     init = init
636 :     }
637 :     in
638 :     inputs' := inp :: !inputs'
639 :     end
640 :     | simplifyInputDcl ((x, SOME e), desc) = let
641 :     val x' = cvtVar x
642 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, [])
643 : jhr 4317 val inp = S.INP{
644 :     var = x',
645 :     name = Var.nameOf x,
646 :     ty = apiTypeOf x',
647 :     desc = desc,
648 :     init = S.ConstExpr
649 :     }
650 :     in
651 :     inputs' := inp :: !inputs';
652 :     constInit := S.S_Assign(x', e') :: (stms @ !constInit)
653 :     end
654 :     fun simplifyGlobalDcl (AST.D_Var(x, NONE)) = globals' := cvtVar x :: !globals'
655 :     | simplifyGlobalDcl (AST.D_Var(x, SOME e)) = let
656 : jhr 4371 val (stms, e') = simplifyExp (cxt, e, [])
657 : jhr 4317 val x' = cvtLHS (x, e')
658 :     in
659 :     globals' := x' :: !globals';
660 :     globalInit := S.S_Assign(x', e') :: (stms @ !globalInit)
661 :     end
662 :     | simplifyGlobalDcl (AST.D_Func(f, params, body)) = let
663 :     val f' = cvtFunc f
664 :     val params' = cvtVars params
665 : jhr 4371 val body' = simplifyAndPruneBlock cxt body
666 : jhr 4317 in
667 :     funcs := S.Func{f=f', params=params', body=body'} :: !funcs
668 :     end
669 :     val () = (
670 :     List.app simplifyConstDcl const_dcls;
671 :     List.app simplifyInputDcl input_dcls;
672 :     List.app simplifyGlobalDcl globals)
673 :     (* make the global-initialization block *)
674 :     val globInit = (case globInit
675 : jhr 4371 of SOME stm => mkBlock (simplifyStmt (cxt, stm, !globalInit))
676 : jhr 4317 | NONE => mkBlock (!globalInit)
677 :     (* end case *))
678 :     (* if the globInit block is non-empty, record the fact in the property list *)
679 :     val props = (case globInit
680 :     of S.Block{code=[], ...} => props
681 :     | _ => Properties.GlobalInit :: props
682 :     (* end case *))
683 : jhr 3452 in
684 :     S.Program{
685 :     props = props,
686 : jhr 4317 consts = List.rev(!consts'),
687 : jhr 3452 inputs = List.rev(!inputs'),
688 : jhr 4317 constInit = mkBlock (!constInit),
689 : jhr 3452 globals = List.rev(!globals'),
690 : jhr 3995 globInit = globInit,
691 : jhr 3452 funcs = List.rev(!funcs),
692 : jhr 4371 strand = simplifyStrand (cxt, strand),
693 :     create = Create.map (simplifyAndPruneBlock cxt) create,
694 :     init = Option.map (simplifyAndPruneBlock cxt) init,
695 :     update = Option.map (simplifyAndPruneBlock cxt) update
696 : jhr 3452 }
697 :     end
698 :    
699 : jhr 3437 end

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