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

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