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

SCM Repository

[diderot] Annotation of /branches/pure-cfg/src/compiler/cl-target/cl-target.sml
ViewVC logotype

Annotation of /branches/pure-cfg/src/compiler/cl-target/cl-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1459 - (view) (download)

1 : jhr 1315 (* cl-target.sml
2 : lamonts 1244 *
3 :     * COPYRIGHT (c) 2011 The Diderot Project (http://diderot-language.cs.uchicago.edu)
4 :     * All rights reserved.
5 :     *)
6 :    
7 :     structure CLTarget : TARGET =
8 :     struct
9 :    
10 :     structure IL = TreeIL
11 :     structure V = IL.Var
12 :     structure Ty = IL.Ty
13 :     structure CL = CLang
14 :     structure RN = RuntimeNames
15 : jhr 1273 structure ToCL = TreeToCL
16 : lamonts 1305 structure N = CNames
17 : lamonts 1244
18 : jhr 1358 (* translate TreeIL types to shadow types *)
19 :     fun shadowTy ty = (case ty
20 : jhr 1363 of Ty.BoolTy => CL.T_Named "cl_bool"
21 : jhr 1358 | Ty.StringTy => raise Fail "unexpected string type"
22 :     | Ty.IVecTy 1 => CL.T_Named(RN.shadowIntTy ())
23 :     | Ty.IVecTy n => raise Fail "unexpected int vector type"
24 :     | Ty.TensorTy[] => CL.T_Named(RN.shadowRealTy ())
25 :     | Ty.TensorTy[n] => CL.T_Named(RN.shadowVecTy n)
26 :     | Ty.TensorTy[n, m] => CL.T_Named(RN.shadowMatTy(n,m))
27 :     | Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}) => CL.T_Named(RN.shadowImageTy dim)
28 :     | _ => raise Fail(concat["TreeToC.trType(", Ty.toString ty, ")"])
29 :     (* end case *))
30 : lamonts 1408
31 :     (* translate TreeIL types to shadow types *)
32 : jhr 1430 fun convertToShadow (ty, name) = (case ty
33 :     of Ty.IVecTy 1 => CL.mkAssign(
34 :     CL.mkSelect(CL.mkVar(RN.shadowGlaobalsName),name),
35 :     CL.mkIndirect(CL.mkVar(RN.globalsVarName), name))
36 :     | Ty.TensorTy[n]=> CL.mkCall(RN.convertToShadowVec n, [
37 :     CL.mkSelect(CL.mkVar(RN.shadowGlaobalsName),name),
38 :     CL.mkIndirect(CL.mkVar(RN.globalsVarName), name)
39 :     ])
40 :     | Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}) => CL.mkCall(RN.shadowImageFunc dim, [
41 :     CL.mkVar "context",
42 :     CL.mkUnOp(CL.%&,CL.mkSelect(CL.mkVar(RN.shadowGlaobalsName),name)),
43 :     CL.mkIndirect(CL.mkVar(RN.globalsVarName),name)
44 :     ])
45 :     | Ty.TensorTy[n, m] => CL.mkCall(RN.convertToShadowMat(m,n), [
46 :     CL.mkSelect(CL.mkVar(RN.shadowGlaobalsName),name),
47 :     CL.mkIndirect(CL.mkVar(RN.globalsVarName), name)
48 :     ])
49 :     | _ => CL.mkAssign(
50 :     CL.mkSelect(CL.mkVar(RN.shadowGlaobalsName),name),
51 :     CL.mkIndirect(CL.mkVar(RN.globalsVarName), name))
52 :     (* end case *))
53 : jhr 1358
54 : jhr 1343 (* helper functions for specifying parameters in various address spaces *)
55 :     fun clParam (spc, ty, x) = CL.PARAM([spc], ty, x)
56 :     fun globalParam (ty, x) = CL.PARAM(["__global"], ty, x)
57 :     fun constantParam (ty, x) = CL.PARAM(["__constant"], ty, x)
58 :     fun localParam (ty, x) = CL.PARAM(["__local"], ty, x)
59 :     fun privateParam (ty, x) = CL.PARAM(["__private"], ty, x)
60 :    
61 : jhr 1421 (* OpenCL global pointer type *)
62 :     fun globalPtr ty = CL.T_Qual("__global", CL.T_Ptr ty)
63 :    
64 : jhr 1315 (* C variable translation *)
65 :     structure TrCVar =
66 : lamonts 1305 struct
67 :     type env = CL.typed_var TreeIL.Var.Map.map
68 :     fun lookup (env, x) = (case V.Map.find (env, x)
69 :     of SOME(CL.V(_, x')) => x'
70 : jhr 1315 | NONE => raise Fail(concat["TrCVar.lookup(_, ", V.name x, ")"])
71 : lamonts 1305 (* end case *))
72 :     (* translate a variable that occurs in an l-value context (i.e., as the target of an assignment) *)
73 :     fun lvalueVar (env, x) = (case V.kind x
74 : jhr 1315 of IL.VK_Global => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
75 : lamonts 1305 | IL.VK_State strand => CL.mkIndirect(CL.mkVar "selfOut", lookup(env, x))
76 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
77 :     (* end case *))
78 :     (* translate a variable that occurs in an r-value context *)
79 :     fun rvalueVar (env, x) = (case V.kind x
80 : jhr 1315 of IL.VK_Global => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
81 : lamonts 1305 | IL.VK_State strand => CL.mkIndirect(CL.mkVar "selfIn", lookup(env, x))
82 :     | IL.VK_Local => CL.mkVar(lookup(env, x))
83 :     (* end case *))
84 : jhr 1285 end
85 :    
86 :     structure ToC = TreeToCFn (TrCVar)
87 :    
88 :     type var = CL.typed_var
89 : lamonts 1244 type exp = CL.exp
90 :     type stm = CL.stm
91 :    
92 : jhr 1313 (* OpenCL specific types *)
93 :     val clIntTy = CL.T_Named "cl_int"
94 : jhr 1279 val clProgramTy = CL.T_Named "cl_program"
95 :     val clKernelTy = CL.T_Named "cl_kernel"
96 :     val clCmdQueueTy = CL.T_Named "cl_command_queue"
97 :     val clContextTy = CL.T_Named "cl_context"
98 :     val clDeviceIdTy = CL.T_Named "cl_device_id"
99 :     val clPlatformIdTy = CL.T_Named "cl_platform_id"
100 :     val clMemoryTy = CL.T_Named "cl_mem"
101 : jhr 1313 val globPtrTy = CL.T_Ptr(CL.T_Named RN.globalsTy)
102 : jhr 1279
103 : jhr 1307 (* variable or field that is mirrored between host and GPU *)
104 :     type mirror_var = {
105 : jhr 1430 (* FIXME: perhaps it would be cleaner to just track the TreeIL type of the variable? *)
106 : jhr 1307 hostTy : CL.ty, (* variable type on Host (i.e., C type) *)
107 : jhr 1358 shadowTy : CL.ty, (* host-side shadow type of GPU type *)
108 : jhr 1307 gpuTy : CL.ty, (* variable's type on GPU (i.e., OpenCL type) *)
109 : jhr 1430 hToS: stm, (* the statement that converts the variable to its *)
110 :     (* shadow representation *)
111 : jhr 1307 var : CL.var (* variable name *)
112 :     }
113 :    
114 : lamonts 1244 datatype strand = Strand of {
115 : jhr 1261 name : string,
116 :     tyName : string,
117 : jhr 1307 state : mirror_var list ref,
118 : jhr 1358 output : (Ty.ty * CL.var) option ref, (* the strand's output variable (only one for now) *)
119 : lamonts 1271 code : CL.decl list ref,
120 : jhr 1273 init_code: CL.decl ref
121 : lamonts 1244 }
122 :    
123 :     datatype program = Prog of {
124 : jhr 1307 name : string, (* stem of source file *)
125 : jhr 1261 double : bool, (* true for double-precision support *)
126 :     parallel : bool, (* true for multithreaded (or multi-GPU) target *)
127 :     debug : bool, (* true for debug support in executable *)
128 : jhr 1307 globals : mirror_var list ref,
129 : jhr 1261 topDecls : CL.decl list ref,
130 :     strands : strand AtomTable.hash_table,
131 : lamonts 1305 initially : CL.decl ref,
132 : jhr 1333 numDims: int ref, (* number of dimensions in initially iteration *)
133 : jhr 1273 imgGlobals: (string * int) list ref,
134 :     prFn: CL.decl ref
135 :     }
136 : lamonts 1244
137 :     datatype env = ENV of {
138 : jhr 1261 info : env_info,
139 :     vMap : var V.Map.map,
140 :     scope : scope
141 : lamonts 1244 }
142 :    
143 :     and env_info = INFO of {
144 : jhr 1261 prog : program
145 : lamonts 1244 }
146 :    
147 :     and scope
148 :     = NoScope
149 :     | GlobalScope
150 :     | InitiallyScope
151 : jhr 1261 | StrandScope of TreeIL.var list (* strand initialization *)
152 : jhr 1443 | MethodScope of MethodName.name * TreeIL.var list (* method body; vars are state variables *)
153 : lamonts 1244
154 : jhr 1273 (* the supprted widths of vectors of reals on the target. *)
155 :     (* FIXME: for OpenCL 1.1, 3 is also valid *)
156 :     fun vectorWidths () = [2, 4, 8, 16]
157 : lamonts 1244
158 :     (* tests for whether various expression forms can appear inline *)
159 : jhr 1261 fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
160 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
161 : lamonts 1244
162 :     (* TreeIL to target translations *)
163 :     structure Tr =
164 :     struct
165 : jhr 1261 fun fragment (ENV{info, vMap, scope}, blk) = let
166 : jhr 1308 val (vMap, stms) = (case scope
167 : jhr 1326 of GlobalScope => ToC.trFragment (vMap, blk)
168 : jhr 1321 (* NOTE: if we move strand initialization to the GPU, then we'll have to change the following code! *)
169 : jhr 1326 | InitiallyScope => ToC.trFragment (vMap, blk)
170 :     | _ => ToCL.trFragment (vMap, blk)
171 :     (* end case *))
172 : jhr 1261 in
173 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
174 :     end
175 : jhr 1315 fun block (ENV{vMap, scope, ...}, blk) = let
176 : jhr 1326 fun saveState cxt stateVars trAssign (env, args, stm) = (
177 :     ListPair.foldrEq
178 :     (fn (x, e, stms) => trAssign(env, x, e)@stms)
179 :     [stm]
180 :     (stateVars, args)
181 :     ) handle ListPair.UnequalLengths => (
182 :     print(concat["saveState ", cxt, ": length mismatch; ", Int.toString(List.length args), " args\n"]);
183 :     raise Fail(concat["saveState ", cxt, ": length mismatch"]))
184 :     in
185 :     case scope
186 : jhr 1315 (* NOTE: if we move strand initialization to the GPU, then we'll have to change the following code! *)
187 : jhr 1326 of StrandScope stateVars =>
188 : jhr 1353 ToCL.trBlock (vMap, saveState "StrandScope" stateVars ToCL.trAssign, blk)
189 : jhr 1443 | MethodScope(name, stateVars) =>
190 : jhr 1326 ToCL.trBlock (vMap, saveState "MethodScope" stateVars ToCL.trAssign, blk)
191 :     | InitiallyScope => ToCL.trBlock (vMap, fn (_, _, stm) => [stm], blk)
192 :     | _ => ToC.trBlock (vMap, fn (_, _, stm) => [stm], blk)
193 :     (* end case *)
194 :     end
195 : jhr 1273 fun exp (ENV{vMap, ...}, e) = ToCL.trExp(vMap, e)
196 : lamonts 1244 end
197 :    
198 :     (* variables *)
199 :     structure Var =
200 :     struct
201 : jhr 1358 fun mirror (ty, name) = {
202 :     hostTy = ToC.trType ty,
203 :     shadowTy = shadowTy ty,
204 :     gpuTy = ToCL.trType ty,
205 : lamonts 1408 hToS = convertToShadow(ty,name),
206 : jhr 1358 var = name
207 :     }
208 : jhr 1273 fun name (ToCL.V(_, name)) = name
209 : jhr 1307 fun global (Prog{globals, imgGlobals, ...}, name, ty) = let
210 : jhr 1358 val x = mirror (ty, name)
211 : jhr 1307 fun isImgGlobal (Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}), name) =
212 :     imgGlobals := (name,dim) :: !imgGlobals
213 :     | isImgGlobal _ = ()
214 : jhr 1261 in
215 : jhr 1307 globals := x :: !globals;
216 :     isImgGlobal (ty, name);
217 :     ToCL.V(#gpuTy x, name)
218 : jhr 1261 end
219 : jhr 1273 fun param x = ToCL.V(ToCL.trType(V.ty x), V.name x)
220 : jhr 1261 fun state (Strand{state, ...}, x) = let
221 : jhr 1307 val ty = V.ty x
222 : jhr 1358 val x' = mirror (ty, V.name x)
223 : jhr 1261 in
224 :     state := x' :: !state;
225 : jhr 1307 ToCL.V(#gpuTy x', #var x')
226 : jhr 1261 end
227 : lamonts 1244 end
228 :    
229 :     (* environments *)
230 :     structure Env =
231 :     struct
232 :     (* create a new environment *)
233 : jhr 1261 fun new prog = ENV{
234 :     info=INFO{prog = prog},
235 :     vMap = V.Map.empty,
236 :     scope = NoScope
237 :     }
238 : lamonts 1244 (* define the current translation context *)
239 : jhr 1261 fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
240 :     val scopeGlobal = setScope GlobalScope
241 :     val scopeInitially = setScope InitiallyScope
242 :     fun scopeStrand (env, svars) = setScope (StrandScope svars) env
243 : jhr 1443 fun scopeMethod (env, name, svars) = setScope (MethodScope(name, svars)) env
244 : lamonts 1244 (* bind a TreeIL varaiable to a target variable *)
245 : jhr 1261 fun bind (ENV{info, vMap, scope}, x, x') = ENV{
246 :     info = info,
247 :     vMap = V.Map.insert(vMap, x, x'),
248 :     scope = scope
249 :     }
250 : lamonts 1244 end
251 :    
252 :     (* programs *)
253 :     structure Program =
254 :     struct
255 : jhr 1278 fun new {name, double, parallel, debug} = (
256 : jhr 1261 RN.initTargetSpec double;
257 : jhr 1286 CNames.initTargetSpec double;
258 : jhr 1261 Prog{
259 : jhr 1307 name = name,
260 : jhr 1261 double = double, parallel = parallel, debug = debug,
261 : jhr 1331 globals = ref [],
262 : jhr 1261 topDecls = ref [],
263 :     strands = AtomTable.mkTable (16, Fail "strand table"),
264 : jhr 1307 initially = ref(CL.D_Comment["missing initially"]),
265 : jhr 1332 numDims = ref 0,
266 : jhr 1307 imgGlobals = ref[],
267 :     prFn = ref(CL.D_Comment(["No Print Function"]))
268 : jhr 1261 })
269 : jhr 1357
270 : jhr 1261 (* register the code that is used to register command-line options for input variables *)
271 :     fun inputs (Prog{topDecls, ...}, stm) = let
272 :     val inputsFn = CL.D_Func(
273 :     [], CL.voidTy, RN.registerOpts,
274 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
275 :     stm)
276 :     in
277 :     topDecls := inputsFn :: !topDecls
278 :     end
279 :    
280 : jhr 1286 (* register the global initialization part of a program *)
281 : jhr 1307 fun init (Prog{topDecls, ...}, init) = let
282 : jhr 1331 val globalsDecl = CL.mkAssign(CL.E_Var RN.globalsVarName,
283 : jhr 1358 CL.mkApply("malloc", [CL.mkSizeof(CL.T_Named RN.globalsTy)]))
284 : jhr 1331 val initFn = CL.D_Func(
285 : lamonts 1316 [], CL.voidTy, RN.initGlobals, [],
286 : jhr 1358 CL.mkBlock[
287 : jhr 1430 globalsDecl,
288 :     CL.mkCall(RN.initGlobalsHelper, [CL.mkVar RN.globalsVarName])
289 :     ])
290 : jhr 1357 val initHelperFn = CL.D_Func(
291 : jhr 1358 [], CL.voidTy, RN.initGlobalsHelper,
292 : jhr 1430 [CL.PARAM([], globPtrTy, RN.globalsVarName)],
293 : jhr 1286 init)
294 : jhr 1307 val shutdownFn = CL.D_Func(
295 :     [], CL.voidTy, RN.shutdown,
296 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
297 :     CL.S_Block[])
298 :     in
299 : jhr 1357 topDecls := shutdownFn :: initFn :: initHelperFn :: !topDecls
300 : jhr 1307 end
301 : jhr 1357
302 : lamonts 1458 (* create and register the initially function for a program *)
303 : jhr 1307 fun initially {
304 : lamonts 1458 prog = Prog{name=progName, strands, initially,numDims, ...},
305 : jhr 1307 isArray : bool,
306 :     iterPrefix : stm list,
307 :     iters : (var * exp * exp) list,
308 :     createPrefix : stm list,
309 :     strand : Atom.atom,
310 :     args : exp list
311 :     } = let
312 :     val name = Atom.toString strand
313 :     val nDims = List.length iters
314 :     val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
315 :     fun mapi f xs = let
316 :     fun mapf (_, []) = []
317 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
318 :     in
319 :     mapf (0, xs)
320 :     end
321 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
322 :     val sizeInit = mapi
323 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
324 :     (i, CL.I_Exp(CL.mkBinOp(CL.mkBinOp(hi, CL.#-, lo), CL.#+, CL.E_Int(1, ty))))
325 :     ) iters
326 :     (* code to allocate the world and initial strands *)
327 :     val wrld = "wrld"
328 :     val allocCode = [
329 :     CL.mkComment["allocate initial block of strands"],
330 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
331 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
332 :     CL.mkDecl(worldTy, wrld,
333 : lamonts 1458 SOME(CL.I_Exp(CL.E_Apply(N.allocInitially, [
334 : jhr 1307 CL.mkVar "ProgramName",
335 :     CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)),
336 :     CL.E_Bool isArray,
337 :     CL.E_Int(IntInf.fromInt nDims, CL.int32),
338 :     CL.E_Var "base",
339 :     CL.E_Var "size"
340 :     ]))))
341 :     ]
342 : lamonts 1458 (* create the loop nest for the initially iterations *)
343 :     val indexVar = "ix"
344 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
345 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
346 :     CL.mkDecl(strandTy, "sp",
347 :     SOME(CL.I_Exp(
348 :     CL.E_Cast(strandTy,
349 :     CL.E_Apply(N.inState, [CL.E_Var "wrld", CL.mkBinOp(CL.mkVar indexVar, CL.#*, CL.mkSizeof(CL.T_Named (N.strandDesc name)))]))))),
350 :     CL.mkCall(N.strandInit name, CL.E_Var "sp" :: args),
351 :     CL.mkAssign(CL.E_Var indexVar, CL.mkBinOp(CL.E_Var indexVar, CL.#+, CL.E_Int(1, CL.uint32)))
352 :     ])
353 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
354 :     val body = mkLoopNest iters
355 :     in
356 :     CL.mkFor(
357 :     [(ty, param, lo)],
358 :     CL.mkBinOp(CL.E_Var param, CL.#<=, hi),
359 :     [CL.mkPostOp(CL.E_Var param, CL.^++)],
360 :     body)
361 :     end
362 :     val iterCode = [
363 :     CL.mkComment["initially"],
364 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.E_Int(0, CL.uint32)))),
365 :     mkLoopNest iters
366 :     ]
367 : jhr 1307 val body = CL.mkBlock(
368 :     iterPrefix @
369 :     allocCode @
370 : lamonts 1458 iterCode @
371 : jhr 1307 [CL.mkReturn(SOME(CL.E_Var "wrld"))])
372 : lamonts 1316 val initFn = CL.D_Func([], worldTy, N.initially, [], body)
373 : jhr 1307 in
374 : jhr 1333 numDims := nDims;
375 : jhr 1307 initially := initFn
376 :     end
377 : jhr 1281
378 : lamonts 1458
379 : lamonts 1305 (***** OUTPUT *****)
380 : jhr 1430 (* FIXME: I think that the iteration and test for stable strands can be moved into the runtime, which
381 :     * will make the print function compatible with the C target version.
382 :     *)
383 : jhr 1431 fun genStrandPrint (Strand{name, tyName, state, output, code, ...}) = let
384 : jhr 1326 (* the print function *)
385 : jhr 1382 val prFnName = concat[name, "Print"]
386 : jhr 1307 val prFn = let
387 : jhr 1326 val params = [
388 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
389 : jhr 1431 CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
390 : jhr 1326 ]
391 :     val SOME(ty, x) = !output
392 : jhr 1432 val outState = CL.mkIndirect(CL.mkVar "self", x)
393 : jhr 1326 val prArgs = (case ty
394 :     of Ty.IVecTy 1 => [CL.E_Str(!N.gIntFormat ^ "\n"), outState]
395 :     | Ty.IVecTy d => let
396 : jhr 1432 fun sel i = CL.mkSubscript(CL.mkSelect(outState, "s"),
397 :     CL.mkInt(IntInf.fromInt i))
398 : jhr 1326 val fmt = CL.mkStr(
399 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
400 :     ^ "\n")
401 : jhr 1432 val args = List.tabulate (d, sel)
402 : jhr 1326 in
403 :     fmt :: args
404 :     end
405 :     | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
406 :     | Ty.TensorTy[d] => let
407 : jhr 1432 fun sel i = CL.mkSubscript(CL.mkSelect(outState, "s"),
408 :     CL.mkInt(IntInf.fromInt i))
409 : jhr 1326 val fmt = CL.mkStr(
410 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
411 :     ^ "\n")
412 : jhr 1432 val args = List.tabulate (d, sel)
413 : jhr 1326 in
414 :     fmt :: args
415 :     end
416 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
417 :     (* end case *))
418 :     in
419 : jhr 1432 CL.D_Func(["static"], CL.voidTy, prFnName, params,
420 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
421 : jhr 1326 end
422 : jhr 1307 in
423 : jhr 1326 prFn
424 : jhr 1307 end
425 : lamonts 1305
426 : lamonts 1429 fun genStrandTyDef (targetTy, Strand{state,...},tyName) =
427 : jhr 1261 (* the type declaration for the strand's state struct *)
428 :     CL.D_StructDef(
429 : jhr 1307 List.rev (List.map (fn x => (targetTy x, #var x)) (!state)),
430 :     tyName)
431 : jhr 1358
432 : lamonts 1458
433 :     fun genStrandCopy(Strand{tyName,name,state,...}) = let
434 :     val params = [
435 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
436 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut")
437 :     ]
438 :     val assignStms = List.rev(List.map(fn x => CL.mkAssign(CL.mkIndirect(CL.E_Var "selfOut", #var x),
439 :     CL.mkIndirect(CL.E_Var "selfIn", #var x))) (!state))
440 :     in
441 :     CL.D_Func([""], CL.voidTy, RN.strandCopy name, params,CL.mkBlock(assignStms))
442 :     end
443 :    
444 : jhr 1307 (* generates the opencl buffers for the image data *)
445 : lamonts 1398 fun getGlobalDataBuffers (globals, imgGlobals, contextVar, errVar) = let
446 : jhr 1431 val globalBuffErr = "error creating OpenCL global buffer\n"
447 : jhr 1344 fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.E_Var errVar, CL.#!=, CL.E_Var "CL_SUCCESS"),
448 :     CL.mkBlock([CL.mkCall("fprintf",[CL.E_Var "stderr", CL.E_Str msg]),
449 :     CL.mkCall("exit",[CL.mkInt 1])]))
450 : jhr 1405 val shadowTypeDecl =
451 :     CL.mkDecl(CL.T_Named(RN.shadowGlobalsTy), RN.shadowGlaobalsName, NONE)
452 : lamonts 1408 val globalToShadowStms = List.map (fn (x:mirror_var) => #hToS x ) globals
453 : jhr 1358 val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
454 : jhr 1307 val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
455 :     CL.mkApply("clCreateBuffer", [
456 :     CL.mkVar contextVar,
457 : jhr 1407 CL.mkBinOp(CL.mkVar "CL_MEM_READ_ONLY", CL.#|, CL.mkVar "CL_MEM_COPY_HOST_PTR"),
458 : lamonts 1398 CL.mkSizeof(CL.T_Named RN.shadowGlobalsTy),
459 :     CL.mkUnOp(CL.%&,CL.mkVar RN.shadowGlaobalsName),
460 : jhr 1307 CL.mkUnOp(CL.%&,CL.mkVar errVar)
461 :     ]))
462 : lamonts 1341 fun genDataBuffers ([],_,_,_) = []
463 :     | genDataBuffers ((var,nDims)::globals, contextVar, errVar,errFn) = let
464 : jhr 1326 val hostVar = CL.mkIndirect(CL.mkVar RN.globalsVarName, var)
465 : lamonts 1398 val size = CL.mkIndirect(hostVar, "dataSzb")
466 : jhr 1326 in
467 : lamonts 1398 CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE) ::
468 : jhr 1326 CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var),
469 :     CL.mkApply("clCreateBuffer", [
470 :     CL.mkVar contextVar,
471 : lamonts 1398 CL.mkVar "CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR",
472 : jhr 1326 size,
473 :     CL.mkIndirect(hostVar, "data"),
474 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
475 : jhr 1344 ])) ::
476 : jhr 1431 errFn(concat["error in creating ",RN.addBufferSuffixData var, " global buffer\n"]) ::
477 : jhr 1358 genDataBuffers(globals,contextVar,errVar,errFn)
478 : jhr 1326 end
479 : jhr 1307 in
480 : lamonts 1408 [shadowTypeDecl] @ globalToShadowStms
481 : lamonts 1398 @ [globalBufferDecl, globalBuffer,errorFn(globalBuffErr)]
482 :     @ genDataBuffers(imgGlobals,contextVar,errVar,errorFn)
483 : jhr 1307 end
484 : lamonts 1264
485 : jhr 1309 (* generates the kernel arguments for the image data *)
486 : jhr 1313 fun genGlobalArguments (globals, count, kernelVar, errVar) = let
487 : jhr 1431 val globalArgErr = "error creating OpenCL global argument\n"
488 : jhr 1343 fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.E_Var errVar, CL.#!=, CL.E_Var "CL_SUCCESS"),
489 : jhr 1344 CL.mkBlock([CL.mkCall("fprintf",[CL.E_Var "stderr", CL.E_Str msg]),
490 :     CL.mkCall("exit",[CL.mkInt 1])]))
491 : lamonts 1398 val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.&=,
492 : jhr 1326 CL.mkApply("clSetKernelArg",
493 :     [CL.mkVar kernelVar,
494 :     CL.mkPostOp(CL.E_Var count, CL.^++),
495 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
496 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
497 : lamonts 1341 fun genDataArguments ([],_,_,_,_) = []
498 : lamonts 1398 | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar,errFn) =
499 : lamonts 1341 CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.$=,
500 : jhr 1326 CL.mkApply("clSetKernelArg",
501 :     [CL.mkVar kernelVar,
502 :     CL.mkPostOp(CL.E_Var count, CL.^++),
503 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
504 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
505 : jhr 1431 errFn(concat["error in creating ",RN.addBufferSuffixData var, " argument\n"]) ::
506 : lamonts 1341 genDataArguments (globals,count,kernelVar,errVar,errFn)
507 : jhr 1326 in
508 : jhr 1431 globalArgument :: errorFn globalArgErr ::
509 :     genDataArguments(globals, count, kernelVar, errVar,errorFn)
510 : jhr 1326 end
511 : lamonts 1264
512 : lamonts 1305 (* generates the globals buffers and arguments function *)
513 : lamonts 1398 fun genGlobalBuffersArgs (globals,imgGlobals) = let
514 : jhr 1273 (* Delcare opencl setup objects *)
515 :     val errVar = "err"
516 :     val imgDataSizeVar = "image_dataSize"
517 : jhr 1315 val params = [
518 : lamonts 1305 CL.PARAM([],CL.T_Named("cl_context"), "context"),
519 : jhr 1307 CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
520 : jhr 1344 CL.PARAM([],CL.T_Named("cl_command_queue"), "cmdQ"),
521 : jhr 1307 CL.PARAM([],CL.T_Named("int"), "argStart")
522 : jhr 1273 ]
523 : lamonts 1398 val clGlobalBuffers = getGlobalDataBuffers(globals,!imgGlobals, "context", errVar)
524 : jhr 1313 val clGlobalArguments = genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
525 : jhr 1307 (* Body put all the statments together *)
526 : jhr 1314 val body = CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt 0)))
527 : jhr 1326 :: clGlobalBuffers @ clGlobalArguments
528 : jhr 1313 in
529 : jhr 1307 CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
530 :     end
531 : lamonts 1305
532 : jhr 1307 (* generate the data and global parameters *)
533 :     fun genKeneralGlobalParams ((name,tyname)::rest) =
534 : jhr 1343 globalParam (CL.T_Ptr(CL.voidTy), RN.addBufferSuffixData name) ::
535 : jhr 1307 genKeneralGlobalParams rest
536 :     | genKeneralGlobalParams [] = []
537 :    
538 : jhr 1331 (* generate the main kernel function for the .cl file *)
539 : jhr 1307 fun genKernelFun (strand, nDims, globals, imgGlobals) = let
540 :     val Strand{name, tyName, state, output, code,...} = strand
541 :     val fName = RN.kernelFuncName;
542 :     val inState = "strand_in"
543 : lamonts 1341 val outState = "strand_out"
544 : jhr 1345 val tempVar = "tmp"
545 : lamonts 1458
546 :     val (workerOffset,localOffset) = if nDims = 1 then
547 :     ( CL.mkApply(RN.getGroupId,[CL.mkInt 0]), CL.mkApply(RN.getLocalThreadId,[CL.mkInt 0]) )
548 :     else if nDims = 2 then
549 :     (CL.mkBinOp(CL.mkBinOp(CL.mkApply(RN.getGroupId,[CL.mkInt 0]),CL.#*, CL.mkApply(RN.getNumGroups,[CL.mkInt 1])),CL.#+,CL.mkApply(RN.getGroupId,[CL.mkInt 1])),
550 :     CL.mkBinOp(CL.mkBinOp(CL.mkApply(RN.getLocalThreadId,[CL.mkInt 0]),CL.#*, CL.mkApply(RN.getLocalSize,[CL.mkInt 1])),CL.#+,CL.mkApply(RN.getLocalThreadId,[CL.mkInt 1])))
551 :     else
552 :     ( CL.mkBinOp(CL.mkBinOp(CL.mkBinOp(
553 :     CL.mkBinOp(CL.mkApply(RN.getGroupId,[CL.mkInt 0]), CL.#*, CL.mkApply(RN.getNumGroups,[CL.mkInt 1])),CL.#*, CL.mkApply(RN.getLocalSize,[CL.mkInt 2])), CL.#+,
554 :     CL.mkBinOp(CL.mkApply(RN.getGroupId,[CL.mkInt 1]),CL.#*,CL.mkApply(RN.getLocalSize,[CL.mkInt 1]))),CL.#+,CL.mkApply(RN.getGroupId,[CL.mkInt 2])),
555 :     CL.mkBinOp(CL.mkBinOp(CL.mkBinOp(
556 :     CL.mkBinOp(CL.mkApply(RN.getLocalThreadId,[CL.mkInt 0]), CL.#*, CL.mkApply(RN.getLocalSize,[CL.mkInt 1])),CL.#*, CL.mkApply(RN.getLocalSize,[CL.mkInt 2])), CL.#+,
557 :     CL.mkBinOp(CL.mkApply(RN.getLocalThreadId,[CL.mkInt 1]),CL.#*,CL.mkApply(RN.getLocalSize,[CL.mkInt 1]))),CL.#+,CL.mkApply(RN.getLocalThreadId,[CL.mkInt 2])) )
558 :    
559 :     val params = [
560 : lamonts 1457 globalParam(CL.T_Ptr(CL.T_Named tyName), "strands"),
561 :     globalParam(CL.T_Ptr(CL.T_Num(RawTypes.RT_UInt8)), "strandStatus"),
562 : lamonts 1458 globalParam(CL.T_Ptr(CL.intTy), "workerQueue"),
563 :     globalParam(CL.T_Ptr(CL.intTy),"numAvail"),
564 : lamonts 1457 clParam("",CL.intTy,"numStrands"),
565 : lamonts 1458 clParam("",CL.intTy,"limit")] @
566 : jhr 1430 [globalParam(globPtrTy, RN.globalsVarName)] @
567 :     genKeneralGlobalParams(!imgGlobals)
568 : lamonts 1457
569 : lamonts 1458 val index_ids = [
570 :     CL.mkDecl(CL.intTy, "workerIndex",
571 :     SOME(CL.I_Exp(workerOffset))),
572 :     CL.mkDecl(CL.intTy, "strandIndex",
573 :     SOME(CL.I_Exp(CL.mkBinOp(CL.mkBinOp(CL.mkSubscript(CL.mkVar "workQueue",CL.mkVar "workerIndex"),CL.#+,localOffset),CL.#*,CL.mkVar "limit"))))
574 : jhr 1331 ]
575 : lamonts 1458
576 :     val strandDecl = [
577 :     CL.mkDecl(CL.T_Named tyName, "selfIn", NONE),
578 :     CL.mkDecl(CL.T_Named tyName, "selfOut", NONE)
579 : jhr 1331 ]
580 : lamonts 1398 val imageDataDecl = CL.mkDecl(CL.T_Named(RN.imageDataType),RN.globalImageDataName,NONE)
581 :     val imageDataStms = List.map (fn (x,_) =>
582 :     CL.mkAssign(CL.mkSelect(CL.mkVar(RN.globalImageDataName),RN.imageDataName x),
583 :     CL.mkVar(RN.addBufferSuffixData x))) (!imgGlobals)
584 : lamonts 1458
585 :     val status = [CL.mkDecl(CL.intTy, "status", NONE)]
586 : lamonts 1457
587 :    
588 : lamonts 1458 fun strandCopy(inStrand, outStrand) = CL.mkCall(RN.strandCopy name,[inStrand,outStrand])
589 :     val updateStm = CL.mkAssign(CL.mkVar "status",
590 :     CL.mkApply(RN.strandUpdate name,
591 :     [CL.mkVar inState,
592 :     CL.mkVar outState,
593 :     CL.mkVar RN.globalsVarName,
594 :     CL.mkVar RN.globalImageDataName]))
595 : lamonts 1457
596 : lamonts 1458 (* CL.mkBlock([CL.mkAssign(CL.mkSubscript(CL.mkVar "strandStatus",CL.mkVar "strandIndex"),CL.mkVar RN.kStable),
597 :     strandCopy(CL.mkUnOp(CL.%&,CL.mkVar "selfOut"),CL.mkBinOp(CL.mkVar "strands", CL.#+, CL.mkVar "strandIndex")),
598 :     CL.mkCall(RN.atom_dec,[CL.mkUnOp(CL.%&,CL.mkSubcript(CL.mkVar "numAvail",CL.mkInt 0))])]),
599 :     CL.mkBlock([CL.mkIfThen(CL.mkBinOp(CL.E_Var "status", CL.#==, CL.E_Var RN.kDie),
600 :     CL.mkBlock([CL.mkAssign(CL.mkSubscript(CL.mkVar "strandStatus",CL.mkVar "strandIndex"),CL.mkVar RN.kDie),
601 :     strandCopy(CL.mkUnOp(CL.%&,CL.mkVar "selfOut"),CL.mkBinOp(CL.mkVar "strands", CL.#+, CL.mkVar "strandIndex")),
602 :     CL.mkCall(RN.atom_dec,[CL.mkUnOp(CL.%&,CL.mkSubscript(CL.mkVar "numAvail",CL.mkInt 0))])])) *)
603 : lamonts 1457
604 : lamonts 1458 val statusIf = CL.mkIfThenElse(CL.mkBinOp(CL.E_Var "status", CL.#==, CL.E_Var RN.kStabilize),
605 :     CL.mkBlock([CL.mkAssign(CL.mkSubscript(CL.mkVar "strandStatus",CL.mkVar "strandIndex"),CL.mkVar RN.kStable),
606 :     strandCopy(CL.mkUnOp(CL.%&,CL.mkVar "selfOut"),CL.mkBinOp(CL.mkVar "strands", CL.#+, CL.mkVar "strandIndex")),
607 :     CL.mkCall(RN.atom_dec,[CL.mkUnOp(CL.%&,CL.mkSubscript(CL.mkVar "numAvail",CL.mkInt 0))])]),
608 :     CL.mkBlock([CL.mkIfThen(CL.mkBinOp(CL.E_Var "status", CL.#==, CL.E_Var RN.kDie),
609 :     CL.mkBlock([CL.mkAssign(CL.mkSubscript(CL.mkVar "strandStatus",CL.mkVar "strandIndex"),CL.mkVar RN.kDie),
610 :     strandCopy(CL.mkUnOp(CL.%&,CL.mkVar "selfOut"),CL.mkBinOp(CL.mkVar "strands", CL.#+, CL.mkVar "strandIndex")),
611 :     CL.mkCall(RN.atom_dec,[CL.mkUnOp(CL.%&,CL.mkSubscript(CL.mkVar "numAvail",CL.mkInt 0))])]))]))
612 : lamonts 1457
613 : lamonts 1458 val incStrand = CL.mkExpStm(CL.mkPostOp(CL.mkVar "strandIndex",CL.^++))
614 : lamonts 1457
615 : lamonts 1458 val forStablize = CL.mkFor( [(CL.intTy,"idx",CL.mkInt 0)], CL.mkBinOp(CL.mkBinOp(CL.mkVar "idx", CL.#<, CL.mkVar "limit"),CL.#&&,
616 :     CL.mkBinOp(CL.mkVar "strandIndex", CL.#<, CL.mkVar "numStrands")),
617 :     [CL.mkPostOp(CL.mkVar "idx", CL.^++)], CL.mkBlock(
618 :     [
619 :     strandCopy(CL.mkUnOp(CL.%&,CL.mkVar "selfIn"),CL.mkBinOp(CL.mkVar "strands", CL.#+, CL.mkVar "strandIndex")),
620 :     updateStm,
621 :     statusIf,
622 :     incStrand
623 :     ]))
624 : lamonts 1457
625 : lamonts 1458 val local_vars = index_ids
626 : lamonts 1398 @ [imageDataDecl]
627 :     @ imageDataStms
628 : jhr 1333 @ strandDecl
629 : lamonts 1458 @ status
630 :    
631 :     val body = CL.mkBlock(local_vars @ [forStablize])
632 : jhr 1307 in
633 :     CL.D_Func(["__kernel"], CL.voidTy, fName, params, body)
634 :     end
635 : lamonts 1457
636 : jhr 1358 (* generate a global structure type definition from the list of globals *)
637 :     fun genGlobalStruct (targetTy, globals, tyName) = let
638 : jhr 1307 val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
639 :     in
640 : jhr 1358 CL.D_StructDef(globs, tyName)
641 : jhr 1307 end
642 : lamonts 1398
643 :     (* generate a global structure type definition from the image data of the image globals *)
644 :     fun genImageDataStruct (imgGlobals, tyName) = let
645 : jhr 1421 val globs = List.map
646 :     (fn (x, _) => (globalPtr CL.voidTy, RN.imageDataName x))
647 :     imgGlobals
648 : lamonts 1398 in
649 :     CL.D_StructDef(globs, tyName)
650 :     end
651 : lamonts 1341
652 : jhr 1307 fun genGlobals (declFn, targetTy, globals) = let
653 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
654 :     in
655 :     List.app doVar globals
656 :     end
657 : lamonts 1264
658 : jhr 1326 fun genStrandDesc (Strand{name, output, ...}) = let
659 :     (* the strand's descriptor object *)
660 :     val descI = let
661 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
662 :     val SOME(outTy, _) = !output
663 :     in
664 :     CL.I_Struct[
665 :     ("name", CL.I_Exp(CL.mkStr name)),
666 : jhr 1431 ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandTy name)))),
667 : jhr 1315 (*
668 : jhr 1326 ("outputSzb", CL.I_Exp(CL.mkSizeof(ToC.trTy outTy))),
669 : jhr 1315 *)
670 : jhr 1326 ("update", fnPtr("update_method_t", "0")),
671 : jhr 1382 ("print", fnPtr("print_method_t", name ^ "Print"))
672 : jhr 1326 ]
673 :     end
674 :     val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
675 :     in
676 :     desc
677 :     end
678 : jhr 1315
679 :     (* generate the table of strand descriptors *)
680 : jhr 1326 fun genStrandTable (declFn, strands) = let
681 :     val nStrands = length strands
682 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)))
683 :     fun genInits (_, []) = []
684 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
685 :     in
686 :     declFn (CL.D_Var([], CL.int32, N.numStrands,
687 :     SOME(CL.I_Exp(CL.E_Int(IntInf.fromInt nStrands, CL.int32)))));
688 :     declFn (CL.D_Var([],
689 :     CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
690 :     N.strands,
691 :     SOME(CL.I_Array(genInits (0, strands)))))
692 :     end
693 : jhr 1315
694 : jhr 1308 fun genSrc (baseName, prog) = let
695 : jhr 1326 val Prog{name,double, globals, topDecls, strands, initially, imgGlobals, numDims, ...} = prog
696 : jhr 1307 val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
697 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
698 :     val clOutS = TextIO.openOut clFileName
699 :     val cOutS = TextIO.openOut cFileName
700 :     val clppStrm = PrintAsCL.new clOutS
701 :     val cppStrm = PrintAsC.new cOutS
702 : jhr 1321 val progName = name
703 : jhr 1307 fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
704 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
705 :     val strands = AtomTable.listItems strands
706 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
707 :     in
708 : jhr 1273 (* Generate the OpenCl file *)
709 :     clppDecl (CL.D_Verbatim([
710 :     if double
711 :     then "#define DIDEROT_DOUBLE_PRECISION"
712 :     else "#define DIDEROT_SINGLE_PRECISION",
713 :     "#define DIDEROT_TARGET_CL",
714 : lamonts 1305 "#include \"Diderot/cl-diderot.h\""
715 : jhr 1273 ]));
716 : jhr 1358 clppDecl (genGlobalStruct (#gpuTy, !globals, RN.globalsTy));
717 : lamonts 1398 clppDecl (genImageDataStruct(!imgGlobals,RN.imageDataType));
718 : lamonts 1429 clppDecl (genStrandTyDef(#gpuTy, strand,tyName));
719 : lamonts 1458 clppDecl (genStrandCopy(strand));
720 : jhr 1273 List.app clppDecl (!code);
721 : lamonts 1328 clppDecl (genKernelFun (strand, !numDims, globals, imgGlobals));
722 :     (* Generate the Host C file *)
723 : jhr 1273 cppDecl (CL.D_Verbatim([
724 :     if double
725 :     then "#define DIDEROT_DOUBLE_PRECISION"
726 :     else "#define DIDEROT_SINGLE_PRECISION",
727 :     "#define DIDEROT_TARGET_CL",
728 :     "#include \"Diderot/diderot.h\""
729 :     ]));
730 : jhr 1326 cppDecl (CL.D_Var(["static"], CL.charPtr, "ProgramName",
731 :     SOME(CL.I_Exp(CL.mkStr progName))));
732 : jhr 1358 cppDecl (genGlobalStruct (#hostTy, !globals, RN.globalsTy));
733 :     cppDecl (genGlobalStruct (#shadowTy, !globals, RN.shadowGlobalsTy));
734 :     (* FIXME: does this really need to be a global? *)
735 :     cppDecl (CL.D_Var(["static"], globPtrTy, RN.globalsVarName, NONE));
736 : jhr 1431 cppDecl (genStrandTyDef (#shadowTy, strand, tyName));
737 : lamonts 1459 cppDecl (!init_code);
738 : jhr 1307 cppDecl (genStrandPrint strand);
739 : jhr 1273 List.app cppDecl (List.rev (!topDecls));
740 : lamonts 1398 cppDecl (genGlobalBuffersArgs (!globals,imgGlobals));
741 : jhr 1326 List.app (fn strand => cppDecl (genStrandDesc strand)) strands;
742 :     genStrandTable (cppDecl, strands);
743 : jhr 1307 cppDecl (!initially);
744 :     PrintAsC.close cppStrm;
745 :     PrintAsCL.close clppStrm;
746 :     TextIO.closeOut cOutS;
747 :     TextIO.closeOut clOutS
748 :     end
749 : lamonts 1264
750 : jhr 1358 (* output the code to the filesystem. The string is the basename of the source file *)
751 : jhr 1307 fun generate (basename, prog as Prog{double, parallel, debug, ...}) = let
752 :     fun condCons (true, x, xs) = x::xs
753 :     | condCons (false, _, xs) = xs
754 :     (* generate the C compiler flags *)
755 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
756 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
757 :     val cflags = if debug
758 :     then #debug Paths.cflags :: cflags
759 :     else #ndebug Paths.cflags :: cflags
760 :     val cflags = #base Paths.cflags :: cflags
761 :     (* generate the loader flags *)
762 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
763 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
764 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
765 :     val rtLib = TargetUtil.runtimeName {
766 :     target = TargetUtil.TARGET_CL,
767 :     parallel = parallel, double = double, debug = debug
768 :     }
769 :     val ldOpts = rtLib :: extraLibs
770 :     in
771 : lamonts 1341 genSrc (basename, prog);
772 : jhr 1307 RunCC.compile (basename, cflags);
773 :     RunCC.link (basename, ldOpts)
774 : jhr 1273 end
775 : lamonts 1244
776 : jhr 1430 end (* Program *)
777 : lamonts 1264
778 : lamonts 1244 (* strands *)
779 :     structure Strand =
780 :     struct
781 : jhr 1261 fun define (Prog{strands, ...}, strandId) = let
782 :     val name = Atom.toString strandId
783 :     val strand = Strand{
784 :     name = name,
785 :     tyName = RN.strandTy name,
786 :     state = ref [],
787 :     output = ref NONE,
788 : lamonts 1271 code = ref [],
789 : jhr 1273 init_code = ref (CL.D_Comment(["no init code"]))
790 : jhr 1261 }
791 :     in
792 :     AtomTable.insert strands (strandId, strand);
793 :     strand
794 :     end
795 : lamonts 1244
796 :     (* return the strand with the given name *)
797 : jhr 1261 fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
798 : lamonts 1244
799 :     (* register the strand-state initialization code. The variables are the strand
800 :     * parameters.
801 :     *)
802 : jhr 1308 fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
803 : jhr 1261 val fName = RN.strandInit name
804 :     val params =
805 : jhr 1343 globalParam (globPtrTy, RN.globalsVarName) ::
806 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
807 : jhr 1273 List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
808 : jhr 1261 val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
809 :     in
810 : jhr 1273 init_code := initFn
811 : jhr 1261 end
812 : jhr 1358
813 : lamonts 1244 (* register a strand method *)
814 : lamonts 1271 fun method (Strand{name, tyName, code,...}, methName, body) = let
815 : jhr 1443 val fName = concat[name, "_", MethodName.toString methName]
816 : jhr 1261 val params = [
817 : jhr 1343 globalParam (CL.T_Ptr(CL.T_Named tyName), "selfIn"),
818 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfOut"),
819 : lamonts 1398 globalParam (CL.T_Ptr(CL.T_Named (RN.globalsTy)), RN.globalsVarName),
820 :     CL.PARAM([],CL.T_Named(RN.imageDataType),RN.globalImageDataName)
821 : jhr 1261 ]
822 : jhr 1443 val resTy = (case methName
823 :     of MethodName.Update => CL.T_Named "StrandStatus_t"
824 :     | MethodName.Stabilize => CL.voidTy
825 :     (* end case *))
826 :     val methFn = CL.D_Func([], resTy, fName, params, body)
827 : jhr 1261 in
828 : jhr 1273 code := methFn :: !code
829 : jhr 1261 end
830 :    
831 : jhr 1273 fun output (Strand{output, ...}, ty, ToCL.V(_, x)) = output := SOME(ty, x)
832 : lamonts 1244
833 :     end
834 :    
835 :     end
836 :    
837 :     structure CLBackEnd = CodeGenFn(CLTarget)

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