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 1279 - (view) (download)

1 : lamonts 1244 (* c-target.sml
2 :     *
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 1244
17 : jhr 1273 type var = ToCL.var
18 : lamonts 1244 type exp = CL.exp
19 :     type stm = CL.stm
20 :    
21 : jhr 1279 (* OpenCL specific types *)
22 :     val clProgramTy = CL.T_Named "cl_program"
23 :     val clKernelTy = CL.T_Named "cl_kernel"
24 :     val clCmdQueueTy = CL.T_Named "cl_command_queue"
25 :     val clContextTy = CL.T_Named "cl_context"
26 :     val clDeviceIdTy = CL.T_Named "cl_device_id"
27 :     val clPlatformIdTy = CL.T_Named "cl_platform_id"
28 :     val clMemoryTy = CL.T_Named "cl_mem"
29 :    
30 : lamonts 1244 datatype strand = Strand of {
31 : jhr 1261 name : string,
32 :     tyName : string,
33 :     state : var list ref,
34 :     output : (Ty.ty * CL.var) option ref, (* the strand's output variable (only one for now) *)
35 : lamonts 1271 code : CL.decl list ref,
36 : jhr 1273 init_code: CL.decl ref
37 : lamonts 1244 }
38 :    
39 :     datatype program = Prog of {
40 : jhr 1278 name : string, (* stem of source file *)
41 : jhr 1261 double : bool, (* true for double-precision support *)
42 :     parallel : bool, (* true for multithreaded (or multi-GPU) target *)
43 :     debug : bool, (* true for debug support in executable *)
44 :     globals : CL.decl list ref,
45 :     topDecls : CL.decl list ref,
46 :     strands : strand AtomTable.hash_table,
47 :     initially : CL.stm list ref,
48 : jhr 1273 numDims: int ref,
49 :     imgGlobals: (string * int) list ref,
50 :     prFn: CL.decl ref
51 :     }
52 : lamonts 1244
53 :     datatype env = ENV of {
54 : jhr 1261 info : env_info,
55 :     vMap : var V.Map.map,
56 :     scope : scope
57 : lamonts 1244 }
58 :    
59 :     and env_info = INFO of {
60 : jhr 1261 prog : program
61 : lamonts 1244 }
62 :    
63 :     and scope
64 :     = NoScope
65 :     | GlobalScope
66 :     | InitiallyScope
67 : jhr 1261 | StrandScope of TreeIL.var list (* strand initialization *)
68 :     | MethodScope of TreeIL.var list (* method body; vars are state variables *)
69 : lamonts 1244
70 : jhr 1273 (* the supprted widths of vectors of reals on the target. *)
71 :     (* FIXME: for OpenCL 1.1, 3 is also valid *)
72 :     fun vectorWidths () = [2, 4, 8, 16]
73 : lamonts 1244
74 :     (* tests for whether various expression forms can appear inline *)
75 : jhr 1261 fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
76 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
77 : lamonts 1244
78 :     (* TreeIL to target translations *)
79 :     structure Tr =
80 :     struct
81 : jhr 1261 fun fragment (ENV{info, vMap, scope}, blk) = let
82 : jhr 1273 val (vMap, stms) = ToCL.trFragment (vMap, blk)
83 : jhr 1261 in
84 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
85 :     end
86 :     fun saveState cxt stateVars (env, args, stm) = (
87 :     ListPair.foldrEq
88 : jhr 1273 (fn (x, e, stms) => ToCL.trAssign(env, x, e)@stms)
89 : jhr 1261 [stm]
90 :     (stateVars, args)
91 :     ) handle ListPair.UnequalLengths => (
92 :     print(concat["saveState ", cxt, ": length mismatch; ", Int.toString(List.length args), " args\n"]);
93 :     raise Fail(concat["saveState ", cxt, ": length mismatch"]))
94 :     fun block (ENV{vMap, scope, ...}, blk) = (case scope
95 : jhr 1273 of StrandScope stateVars => ToCL.trBlock (vMap, saveState "StrandScope" stateVars, blk)
96 :     | MethodScope stateVars => ToCL.trBlock (vMap, saveState "MethodScope" stateVars, blk)
97 :     | _ => ToCL.trBlock (vMap, fn (_, _, stm) => [stm], blk)
98 : jhr 1261 (* end case *))
99 : jhr 1273 fun exp (ENV{vMap, ...}, e) = ToCL.trExp(vMap, e)
100 : lamonts 1244 end
101 :    
102 :     (* variables *)
103 :     structure Var =
104 :     struct
105 : jhr 1273 fun name (ToCL.V(_, name)) = name
106 : jhr 1278 fun global (Prog{globals, imgGlobals, ...}, name, ty) = let
107 : jhr 1273 val ty' = ToCL.trType ty
108 : jhr 1261 fun isImgGlobal (imgGlobals, Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}), name) = imgGlobals := (name,dim):: !imgGlobals
109 :     | isImgGlobal (imgGlobals, _, _) = ()
110 :     in
111 :     globals := CL.D_Var([], ty', name, NONE) :: !globals;
112 :     isImgGlobal(imgGlobals,ty,name);
113 : jhr 1273 ToCL.V(ty', name)
114 : jhr 1261 end
115 : jhr 1273 fun param x = ToCL.V(ToCL.trType(V.ty x), V.name x)
116 : jhr 1261 fun state (Strand{state, ...}, x) = let
117 : jhr 1273 val ty' = ToCL.trType(V.ty x)
118 :     val x' = ToCL.V(ty', V.name x)
119 : jhr 1261 in
120 :     state := x' :: !state;
121 :     x'
122 :     end
123 : lamonts 1244 end
124 :    
125 :     (* environments *)
126 :     structure Env =
127 :     struct
128 :     (* create a new environment *)
129 : jhr 1261 fun new prog = ENV{
130 :     info=INFO{prog = prog},
131 :     vMap = V.Map.empty,
132 :     scope = NoScope
133 :     }
134 : lamonts 1244 (* define the current translation context *)
135 : jhr 1261 fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
136 :     val scopeGlobal = setScope GlobalScope
137 :     val scopeInitially = setScope InitiallyScope
138 :     fun scopeStrand (env, svars) = setScope (StrandScope svars) env
139 :     fun scopeMethod (env, svars) = setScope (MethodScope svars) env
140 : lamonts 1244 (* bind a TreeIL varaiable to a target variable *)
141 : jhr 1261 fun bind (ENV{info, vMap, scope}, x, x') = ENV{
142 :     info = info,
143 :     vMap = V.Map.insert(vMap, x, x'),
144 :     scope = scope
145 :     }
146 : lamonts 1244 end
147 :    
148 :     (* programs *)
149 :     structure Program =
150 :     struct
151 : jhr 1278 fun new {name, double, parallel, debug} = (
152 : jhr 1261 RN.initTargetSpec double;
153 :     Prog{
154 : jhr 1278 name = name,
155 : jhr 1261 double = double, parallel = parallel, debug = debug,
156 : lamonts 1271 globals = ref [],
157 : jhr 1261 topDecls = ref [],
158 :     strands = AtomTable.mkTable (16, Fail "strand table"),
159 :     initially = ref([CL.S_Comment["missing initially"]]),
160 : lamonts 1264 numDims = ref(0),
161 :     imgGlobals = ref[],
162 :     prFn = ref(CL.D_Comment(["No Print Function"]))
163 : jhr 1261 })
164 : lamonts 1244 (* register the global initialization part of a program *)
165 : lamonts 1264 fun globalIndirects (globals,stms) = let
166 : jhr 1278 fun getGlobals(CL.D_Var(_,_,globalVar,_)::rest) = CL.mkAssign(CL.mkIndirect(CL.mkVar RN.globalsVarName,globalVar),CL.mkVar globalVar)::getGlobals(rest)
167 : jhr 1273 | getGlobals([]) = []
168 :     | getGlobals(_::rest) = getGlobals(rest)
169 :     in
170 :     stms @ getGlobals(globals)
171 :     end
172 : jhr 1261
173 :     (* register the code that is used to register command-line options for input variables *)
174 :     fun inputs (Prog{topDecls, ...}, stm) = let
175 :     val inputsFn = CL.D_Func(
176 :     [], CL.voidTy, RN.registerOpts,
177 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
178 :     stm)
179 :     in
180 :     topDecls := inputsFn :: !topDecls
181 :     end
182 :    
183 : jhr 1278 fun init (Prog{globals, topDecls,...}, CL.S_Block(init)) = let
184 : jhr 1261 val params = [
185 : jhr 1273 CL.PARAM([], CL.T_Ptr(CL.T_Named RN.globalsTy), RN.globalsVarName)
186 :     ]
187 : jhr 1261 val body = CL.S_Block(globalIndirects(!globals,init))
188 :     val initFn = CL.D_Func([], CL.voidTy, RN.initGlobals, params, body)
189 :     in
190 :     topDecls := initFn :: !topDecls
191 :     end
192 :     | init (Prog{globals,topDecls,...}, init) = let
193 :     val params = [
194 : jhr 1273 CL.PARAM([], CL.T_Ptr(CL.T_Named RN.globalsTy), RN.globalsVarName)
195 :     ]
196 : jhr 1261 val initFn = CL.D_Func([], CL.voidTy, RN.initGlobals, params, init)
197 :     in
198 :     topDecls := initFn :: !topDecls
199 :     end
200 :    
201 : lamonts 1244 (* create and register the initially function for a program *)
202 : jhr 1261 fun initially {
203 : jhr 1278 prog = Prog{strands, initially, numDims,...},
204 : jhr 1261 isArray : bool,
205 :     iterPrefix : stm list,
206 :     iters : (var * exp * exp) list,
207 :     createPrefix : stm list,
208 :     strand : Atom.atom,
209 :     args : exp list
210 :     } = let
211 :     val name = Atom.toString strand
212 :     val nDims = List.length iters
213 :     fun mapi f xs = let
214 :     fun mapf (_, []) = []
215 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
216 :     in
217 :     mapf (0, xs)
218 :     end
219 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
220 :     val sizeInit = mapi
221 : jhr 1273 (fn (i, (ToCL.V(ty, _), lo, hi)) =>
222 : jhr 1278 (i, CL.I_Exp(CL.mkBinOp(CL.mkBinOp(hi, CL.#-, lo), CL.#+, CL.mkInt(1, ty))))
223 : jhr 1261 ) iters
224 :     val numStrandsVar = "numStrandsVar"
225 :     val allocCode = iterPrefix @ [
226 :     CL.mkComment["allocate initial block of strands"],
227 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
228 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
229 : jhr 1278 CL.mkDecl(CL.int32,"numDims",SOME(CL.I_Exp(CL.mkInt(IntInf.fromInt nDims, CL.int32))))
230 : jhr 1273 ]
231 : jhr 1278 val numStrandsLoopBody = CL.mkExpStm(CL.mkAssignOp(CL.mkVar numStrandsVar, CL.*=,CL.mkSubscript(CL.mkVar "size",CL.mkVar "i")))
232 :     val numStrandsLoop = CL.mkFor([(CL.intTy, "i", CL.mkInt(0,CL.intTy))],
233 :     CL.mkBinOp(CL.mkVar "i", CL.#<, CL.mkVar "numDims"),
234 :     [CL.mkPostOp(CL.mkVar "i", CL.^++)], numStrandsLoopBody)
235 : jhr 1273 in
236 :     numDims := nDims;
237 :     initially := allocCode @ [numStrandsLoop]
238 :     end
239 : lamonts 1256
240 :    
241 : lamonts 1244 (***** OUTPUT *****)
242 : jhr 1278 fun genStrandInit(Strand{name,tyName,state,output,code,...},nDims) = let
243 :     val params = [
244 :     CL.PARAM([], CL.T_Ptr(CL.uint32), "sizes" ),
245 :     CL.PARAM([], CL.intTy, "width"),
246 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "strands")
247 :     ]
248 :     val body = let
249 :     fun loopParams 3 = ["x", "y", "k"]
250 :     | loopParams 2 = ["x", "y"]
251 :     | loopParams 1 = ["x"]
252 :     | loopParams _ = raise Fail "genStrandInit: missing size dim"
253 :     fun mkLoopNest ([], _, nDims) = if nDims = 1
254 :     then CL.mkBlock [
255 :     CL.mkCall(RN.strandInit name, [
256 :     CL.mkUnOp(CL.%&,CL.mkSubscript(CL.mkVar "strands",CL.mkStr "x")),
257 :     CL.mkVar "x"])
258 :     ]
259 : lamonts 1271 else let
260 : jhr 1278 val index = CL.mkBinOp(CL.mkBinOp(CL.mkVar "x",CL.#*,CL.mkVar "width"),CL.#+,CL.mkVar "y")
261 : lamonts 1271 in
262 : jhr 1278 CL.mkBlock([CL.mkCall(RN.strandInit name, [CL.mkUnOp(CL.%&,CL.mkSubscript(CL.mkVar "strands",index)),
263 :     CL.mkVar "x", CL.mkVar"y"])])
264 : lamonts 1271 end
265 :    
266 :     | mkLoopNest (param::rest,count,nDims) = let
267 :     val body = mkLoopNest (rest, count + 1,nDims)
268 :     in
269 :     CL.mkFor(
270 : jhr 1278 [(CL.intTy, param, CL.mkInt(0,CL.intTy))],
271 :     CL.mkBinOp(CL.mkVar param, CL.#<, CL.mkSubscript(CL.mkVar "sizes",CL.mkInt(count,CL.intTy))),
272 :     [CL.mkPostOp(CL.mkVar param, CL.^++)],
273 : lamonts 1271 body)
274 :     end
275 :     in
276 :     [mkLoopNest ((loopParams nDims),0,nDims)]
277 :     end
278 :     in
279 :     CL.D_Func(["static"], CL.voidTy, RN.strandInitSetup, params,CL.mkBlock(body))
280 :     end
281 :     fun genStrandPrint (Strand{name, tyName, state, output, code,...},nDims) = let
282 : lamonts 1264 (* the print function *)
283 :     val prFnName = concat[name, "_print"]
284 :    
285 :     val prFn = let
286 :     val params = [
287 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
288 : lamonts 1271 CL.PARAM([], CL.T_Ptr(CL.uint32), "sizes" ),
289 : lamonts 1264 CL.PARAM([], CL.intTy, "width"),
290 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
291 :     ]
292 :    
293 :     val SOME(ty, x) = !output
294 :     val outState = if nDims = 1 then
295 : jhr 1278 CL.mkSelect(CL.mkSubscript(CL.mkVar "self",CL.mkVar "x"), x)
296 : lamonts 1264 else if nDims = 2 then
297 :     CL.mkSelect(CL.mkSubscript(CL.mkVar "self",
298 : jhr 1278 CL.mkBinOp(CL.mkBinOp(CL.mkVar "x",CL.#*,CL.mkVar "width"),CL.#+,CL.mkVar "y")), x)
299 : lamonts 1264
300 :     else CL.mkSelect(CL.mkVar "self",x)
301 :    
302 :     val prArgs = (case ty
303 : jhr 1278 of Ty.IVecTy 1 => [CL.mkStr(!RN.gIntFormat ^ "\n"), outState]
304 : lamonts 1264 | Ty.IVecTy d => let
305 : jhr 1278 val fmt = CL.mkStr(
306 : lamonts 1264 String.concatWith " " (List.tabulate(d, fn _ => !RN.gIntFormat))
307 :     ^ "\n")
308 : jhr 1273 val args = List.tabulate (d, fn i => ToCL.vecIndex(outState, i))
309 : lamonts 1264 in
310 :     fmt :: args
311 :     end
312 : jhr 1278 | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
313 : lamonts 1264 | Ty.TensorTy[d] => let
314 : jhr 1278 val fmt = CL.mkStr(
315 : lamonts 1264 String.concatWith " " (List.tabulate(d, fn _ => "%f"))
316 :     ^ "\n")
317 : jhr 1273 val args = List.tabulate (d, fn i => ToCL.vecIndex(outState, i))
318 : lamonts 1264 in
319 :     fmt :: args
320 :     end
321 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
322 :     (* end case *))
323 :    
324 :     val body = let
325 :    
326 :     fun loopParams (3) =
327 :     "x"::"y"::"k"::[]
328 :     | loopParams (2) =
329 :     "x"::"y"::[]
330 :     | loopParams (1) =
331 :     "x"::[]
332 :     | loopParams (_) =
333 :     raise Fail("genStrandPrint: unsupported output type " ^ Ty.toString ty)
334 :    
335 :     fun mkLoopNest ([],_) =
336 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs)
337 :     | mkLoopNest (param::rest,count) = let
338 :     val body = mkLoopNest (rest, count + 1)
339 :     in
340 :     CL.mkFor(
341 : jhr 1278 [(CL.intTy, param, CL.mkInt(0,CL.intTy))],
342 :     CL.mkBinOp(CL.mkVar param, CL.#<, CL.mkSubscript(CL.mkVar "sizes",CL.mkInt(count,CL.intTy))),
343 :     [CL.mkPostOp(CL.mkVar param, CL.^++)],
344 : lamonts 1264 body)
345 :     end
346 :     in
347 :     [mkLoopNest ((loopParams nDims),0)]
348 :     end
349 :    
350 :     in
351 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,CL.mkBlock(body))
352 :     end
353 :     in
354 :     prFn
355 :     end
356 : jhr 1261 fun genStrandTyDef (Strand{tyName, state,...}) =
357 :     (* the type declaration for the strand's state struct *)
358 :     CL.D_StructDef(
359 : jhr 1273 List.rev (List.map (fn ToCL.V(ty, x) => (ty, x)) (!state)),
360 : jhr 1261 tyName)
361 :    
362 :    
363 : lamonts 1264 (* generates the load kernel function *)
364 : jhr 1261 (* FIXME: this code might be part of the runtime system *)
365 : lamonts 1264 fun genKernelLoader() =
366 :     CL.D_Verbatim ( ["/* Loads the Kernel from a file */",
367 :     "char * loadKernel (const char * filename) {",
368 :     "struct stat statbuf;",
369 :     "FILE *fh;",
370 :     "char *source;",
371 :     "fh = fopen(filename, \"r\");",
372 :     "if (fh == 0)",
373 :     " return 0;",
374 :     "stat(filename, &statbuf);",
375 :     "source = (char *) malloc(statbuf.st_size + 1);",
376 :     "fread(source, statbuf.st_size, 1, fh);",
377 :     "fread(source, statbuf.st_size, 1, fh);",
378 :     "return source;",
379 :     "}"])
380 :     (* generates the opencl buffers for the image data *)
381 :     fun getGlobalDataBuffers(globals,count,contextVar,errVar) = let
382 : jhr 1279 val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
383 : jhr 1278 val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]), CL.mkApply("clCreateBuffer",
384 :     [CL.mkVar contextVar,
385 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
386 :     CL.mkApply("sizeof",[CL.mkVar RN.globalsTy]),
387 :     CL.mkVar RN.globalsVarName,
388 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)]))
389 : jhr 1261
390 : lamonts 1264 fun genDataBuffers([],_,_,_) = []
391 :     | genDataBuffers((var,nDims)::globals,count,contextVar,errVar) = let
392 :     (* FIXME: use CL constructors to build expressions (not strings) *)
393 :     val size = if nDims = 1 then
394 : jhr 1278 CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*,
395 :     CL.mkIndirect(CL.mkVar var, "size[0]"))
396 : lamonts 1264 else if nDims = 2 then
397 : jhr 1278 CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*,
398 :     CL.mkIndirect(CL.mkVar var, concat["size[0]", " * ", var, "->size[1]"]))
399 : lamonts 1264 else
400 : jhr 1278 CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*,
401 :     CL.mkIndirect(CL.mkVar var,concat["size[0]", " * ", var, "->size[1] * ", var, "->size[2]"]))
402 : lamonts 1264
403 :     in
404 : jhr 1279 CL.mkDecl(clMemoryTy, RN.addBufferSuffix var ,NONE)::
405 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE)::
406 : jhr 1278 CL.mkAssign(CL.mkVar(RN.addBufferSuffix var), CL.mkApply("clCreateBuffer",
407 :     [CL.mkVar contextVar,
408 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
409 :     CL.mkApply("sizeof",[CL.mkVar (RN.imageTy nDims)]),
410 :     CL.mkVar var,
411 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])) ::
412 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var), CL.mkApply("clCreateBuffer",
413 :     [CL.mkVar contextVar,
414 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
415 : lamonts 1264 size,
416 : jhr 1278 CL.mkIndirect(CL.mkVar var,"data"),
417 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])):: genDataBuffers(globals,count + 2,contextVar,errVar)
418 : lamonts 1264 end
419 :     in
420 :     [globalBufferDecl] @ [globalBuffer] @ genDataBuffers(globals,count + 2,contextVar,errVar)
421 :     end
422 :    
423 : jhr 1261
424 : lamonts 1264 (* generates the kernel arguments for the image data *)
425 :     fun genGlobalArguments(globals,count,kernelVar,errVar) = let
426 : jhr 1278 val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,CL.mkApply("clSetKernelArg",
427 :     [CL.mkVar kernelVar,
428 :     CL.mkInt(count,CL.intTy),
429 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
430 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
431 : lamonts 1264
432 :     fun genDataArguments([],_,_,_) = []
433 :     | genDataArguments((var,nDims)::globals,count,kernelVar,errVar) =
434 :    
435 : jhr 1278 CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=, CL.mkApply("clSetKernelArg",
436 :     [CL.mkVar kernelVar,
437 :     CL.mkInt(count,CL.intTy),
438 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
439 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffix var))])))::
440 : lamonts 1264
441 : jhr 1278 CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,CL.mkApply("clSetKernelArg",
442 :     [CL.mkVar kernelVar,
443 :     CL.mkInt((count + 1),CL.intTy),
444 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
445 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))):: genDataArguments (globals, count + 2,kernelVar,errVar)
446 : lamonts 1264
447 :     in
448 :    
449 :     [globalArgument] @ genDataArguments(globals,count + 1,kernelVar,errVar)
450 :    
451 :     end
452 :    
453 :     (* generates the main function of host code *)
454 :     fun genHostMain() = let
455 : jhr 1278 val setupCall = [CL.mkCall(RN.setupFName,[CL.mkVar RN.globalsVarName])]
456 : jhr 1273 val globalsDecl = CL.mkDecl(
457 :     CL.T_Ptr(CL.T_Named RN.globalsTy),
458 :     RN.globalsVarName,
459 : jhr 1278 SOME(CL.I_Exp(CL.mkApply("malloc", [CL.mkApply("sizeof",[CL.mkVar RN.globalsTy])]))))
460 :     val initGlobalsCall = CL.mkCall(RN.initGlobals,[CL.mkVar RN.globalsVarName])
461 :     val returnStm = [CL.mkReturn(SOME(CL.mkInt(0,CL.intTy)))]
462 : jhr 1273 val params = [
463 :     CL.PARAM([],CL.intTy, "argc"),
464 :     CL.PARAM([],CL.charArrayPtr,"argv")
465 :     ]
466 :     val body = CL.mkBlock([globalsDecl] @ [initGlobalsCall] @ setupCall @ returnStm)
467 :     in
468 :     CL.D_Func([],CL.intTy,"main",params,body)
469 :     end
470 : lamonts 1264
471 : jhr 1273 (* generates the host-side setup function *)
472 :     fun genHostSetupFunc (strand as Strand{name,tyName,...}, filename, nDims, initially, imgGlobals) = let
473 :     (* Delcare opencl setup objects *)
474 :     val programVar= "program"
475 :     val kernelVar = "kernel"
476 :     val cmdVar = "queue"
477 :     val inStateVar = "selfin"
478 :     val outStateVar = "selfout"
479 :     val stateSizeVar= "state_mem_size"
480 :     val clInstateVar = "clSelfIn"
481 :     val clOutStateVar = "clSelfOut"
482 :     val clGlobals = "clGlobals"
483 :     val sourcesVar = "sources"
484 :     val contextVar = "context"
485 :     val errVar = "err"
486 :     val imgDataSizeVar = "image_dataSize"
487 :     val globalVar = "global_work_size"
488 :     val localVar = "local_work_size"
489 :     val clFNVar = "filename"
490 :     val numStrandsVar = "numStrandsVar"
491 :     val headerFNVar = "header"
492 :     val deviceVar = "device"
493 :     val platformsVar = "platforms"
494 :     val numPlatformsVar = "num_platforms"
495 :     val numDevicesVar = "num_devices"
496 : jhr 1278 val assertStm = CL.mkCall("assert",[CL.mkBinOp(CL.mkVar errVar, CL.#==, CL.mkVar "CL_SUCCESS")])
497 : jhr 1273 val params = [
498 :     CL.PARAM([],CL.T_Named("cl_device_id"), deviceVar)
499 :     ]
500 :     val declarations = [
501 : jhr 1279 CL.mkDecl(clProgramTy, programVar, NONE),
502 :     CL.mkDecl(clKernelTy, kernelVar, NONE),
503 :     CL.mkDecl(clCmdQueueTy, cmdVar, NONE),
504 :     CL.mkDecl(clContextTy, contextVar, NONE),
505 : jhr 1273 CL.mkDecl(CL.intTy, errVar, NONE),
506 : jhr 1278 CL.mkDecl(CL.intTy, numStrandsVar, SOME(CL.I_Exp(CL.mkInt(1,CL.intTy)))),
507 : jhr 1273 CL.mkDecl(CL.intTy, stateSizeVar, NONE),
508 :     CL.mkDecl(CL.intTy, "width", NONE),
509 :     CL.mkDecl(CL.intTy, imgDataSizeVar, NONE),
510 : jhr 1279 (*CL.mkDecl(clDeviceIdTy, deviceVar, NONE), *)
511 : jhr 1273 CL.mkDecl(CL.T_Ptr(CL.T_Named tyName), inStateVar,NONE),
512 : jhr 1279 CL.mkDecl(clMemoryTy,clInstateVar,NONE),
513 :     CL.mkDecl(clMemoryTy,clOutStateVar,NONE),
514 : jhr 1273 CL.mkDecl(CL.T_Ptr(CL.T_Named tyName), outStateVar,NONE),
515 : jhr 1278 CL.mkDecl(CL.charPtr, clFNVar,SOME(CL.I_Exp(CL.mkStr filename))),
516 : jhr 1273 (* FIXME: use Paths.diderotInclude *)
517 : jhr 1278 CL.mkDecl(CL.charPtr, headerFNVar,SOME(CL.I_Exp(CL.mkStr "../src/include/Diderot/cl-types.h"))),
518 : jhr 1273 CL.mkDecl(CL.T_Array(CL.charPtr,SOME(2)),sourcesVar,NONE),
519 :     CL.mkDecl(CL.T_Array(CL.T_Named "size_t",SOME(nDims)),globalVar,NONE),
520 :     CL.mkDecl(CL.T_Array(CL.T_Named "size_t",SOME(nDims)),localVar,NONE),
521 : jhr 1278 CL.mkDecl(CL.intTy,numDevicesVar,SOME(CL.I_Exp(CL.mkInt(~1,CL.intTy)))),
522 : jhr 1273 CL.mkDecl(CL.T_Array(CL.T_Named "cl_platform_id", SOME(1)), platformsVar, NONE),
523 : jhr 1278 CL.mkDecl(CL.intTy,"num_platforms",SOME(CL.I_Exp(CL.mkInt(~1,CL.intTy))))
524 : jhr 1273 ]
525 :     (* Setup Global Variables *)
526 :     val globalsDecl = CL.mkDecl(
527 :     CL.T_Ptr(CL.T_Named RN.globalsTy),
528 :     RN.globalsVarName,
529 : jhr 1278 SOME(CL.I_Exp(CL.mkApply("malloc", [CL.mkApply("sizeof",[CL.mkVar RN.globalsTy])]))))
530 :     val initGlobalsCall = CL.mkCall(RN.initGlobals,[CL.mkVar RN.globalsVarName])
531 : lamonts 1271
532 :     (* Retrieve the platforms
533 : jhr 1278 val platformStm = [CL.mkAssign(CL.mkVar errVar, CL.mkApply("clGetPlatformIDs",
534 :     [CL.mkInt(10,CL.intTy),
535 :     CL.mkVar platformsVar,
536 :     CL.mkUnOp(CL.%&,CL.mkVar numPlatformsVar)])),
537 : lamonts 1264 assertStm]
538 :    
539 : jhr 1278 val devicesStm = [CL.mkAssign(CL.mkVar errVar, CL.mkApply("clGetDeviceIDs",
540 :     [CL.mkSubscript(CL.mkVar platformsVar,CL.mkInt(0,CL.intTy)),
541 :     CL.mkVar "CL_DEVICE_TYPE_GPU",
542 :     CL.mkInt(1,CL.intTy),
543 :     CL.mkUnOp(CL.%&,CL.mkVar deviceVar),
544 :     CL.mkUnOp(CL.%&,CL.mkVar numDevicesVar)])),
545 : lamonts 1271 assertStm] *)
546 : lamonts 1264
547 :     (* Create Context *)
548 : jhr 1278 val contextStm = [CL.mkAssign(CL.mkVar contextVar, CL.mkApply("clCreateContext",
549 :     [CL.mkInt(0,CL.intTy),
550 :     CL.mkInt(1,CL.intTy),
551 :     CL.mkUnOp(CL.%&,CL.mkVar deviceVar),
552 :     CL.mkVar "NULL",
553 :     CL.mkVar "NULL",
554 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])),
555 : lamonts 1264 assertStm]
556 :    
557 :     (* Create Command Queue *)
558 : jhr 1278 val commandStm = [CL.mkAssign(CL.mkVar cmdVar, CL.mkApply("clCreateCommandQueue",
559 :     [CL.mkVar contextVar,
560 :     CL.mkVar deviceVar,
561 :     CL.mkInt(0,CL.intTy),
562 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])),
563 : lamonts 1264 assertStm]
564 :    
565 :    
566 :     (*Create Program/Build/Kernel with Source statement *)
567 : jhr 1278 val createProgStm = CL.mkAssign(CL.mkVar programVar, CL.mkApply("clCreateProgramWithSource",
568 :     [CL.mkVar contextVar,
569 :     CL.mkInt(2,CL.intTy),
570 :     CL.mkCast(CL.T_Ptr(CL.T_Named("const char *")),CL.mkUnOp(CL.%&,CL.mkVar sourcesVar)),
571 :     CL.mkVar "NULL",
572 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)]))
573 : lamonts 1264
574 :     (* FIXME: Remove after testing purposes, Build Log for OpenCL*)
575 : jhr 1278 val buildLog = [CL.mkAssign(CL.mkVar errVar, CL.mkApply("clBuildProgram",
576 :     [CL.mkVar programVar,
577 :     CL.mkInt(0,CL.intTy),
578 :     CL.mkVar "NULL",
579 :     CL.mkVar "NULL",
580 :     CL.mkVar "NULL",
581 :     CL.mkVar "NULL"])),
582 : lamonts 1271 CL.mkDecl(CL.charPtr, "build", NONE),
583 :     CL.mkDecl(CL.T_Named("size_t"),"ret_val_size",NONE),
584 : jhr 1278 CL.mkAssign(CL.mkVar errVar, CL.mkApply("clGetProgramBuildInfo",
585 :     [CL.mkVar programVar,
586 :     CL.mkVar deviceVar,
587 :     CL.mkVar "CL_PROGRAM_BUILD_LOG",
588 :     CL.mkInt(0,CL.intTy),
589 :     CL.mkVar "NULL",
590 :     CL.mkUnOp(CL.%&,CL.mkVar "ret_val_size")])),
591 :     CL.mkAssign(CL.mkVar "build", CL.mkApply("malloc", [CL.mkVar "ret_val_size"])),
592 :     CL.mkAssign(CL.mkVar errVar, CL.mkApply("clGetProgramBuildInfo",
593 :     [CL.mkVar programVar,
594 :     CL.mkVar deviceVar,
595 :     CL.mkVar "CL_PROGRAM_BUILD_LOG",
596 :     CL.mkVar "ret_val_size",
597 :     CL.mkVar "build",
598 :     CL.mkVar "NULL"])),
599 :     CL.mkAssign(CL.mkSubscript(CL.mkVar "build",CL.mkVar "ret_val_size"),CL.mkVar ("'\\" ^ "0'")),
600 :     CL.mkCall("printf",[CL.mkStr ( "Build Log:" ^ "\n" ^ "%s" ^ "\n"), CL.mkVar "build"])]
601 : lamonts 1264
602 :    
603 :    
604 :    
605 : jhr 1278 val createKernel = CL.mkAssign(CL.mkVar kernelVar, CL.mkApply("clCreateKernel",
606 :     [CL.mkVar programVar,
607 :     CL.mkStr RN.kernelFuncName,
608 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)]))
609 : lamonts 1264
610 :    
611 :     val create_build_stms = [createProgStm,assertStm] @ buildLog @ [assertStm,createKernel,assertStm]
612 :    
613 :    
614 :    
615 :     (* Create Memory Buffers for Strand States and Globals *)
616 : jhr 1278 val strandSize = CL.mkAssign(CL.mkVar stateSizeVar,CL.mkBinOp(CL.mkApply("sizeof",
617 :     [CL.mkVar tyName]), CL.#*,CL.mkVar numStrandsVar))
618 : lamonts 1271
619 : jhr 1278 val clStrandObjects = [CL.mkAssign(CL.mkVar clInstateVar, CL.mkApply("clCreateBuffer",
620 :     [CL.mkVar contextVar,
621 :     CL.mkVar "CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR",
622 :     CL.mkVar stateSizeVar,
623 :     CL.mkVar "NULL",
624 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)])),
625 :     CL.mkAssign(CL.mkVar clOutStateVar, CL.mkApply("clCreateBuffer",
626 :     [CL.mkVar contextVar,
627 :     CL.mkVar "CL_MEM_READ_WRITE",
628 :     CL.mkVar stateSizeVar,
629 :     CL.mkVar "NULL",
630 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)]))]
631 : lamonts 1271
632 :    
633 :     (* Setup up selfOut variable *)
634 : jhr 1278 val strandsArrays = [CL.mkAssign(CL.mkVar outStateVar, CL.mkApply("malloc", [CL.mkBinOp(CL.mkVar numStrandsVar,
635 :     CL.#*, CL.mkApply("sizeof",[CL.mkVar tyName]))])),
636 :     CL.mkAssign(CL.mkVar inStateVar, CL.mkApply("malloc", [CL.mkBinOp(CL.mkVar numStrandsVar,
637 :     CL.#*, CL.mkApply("sizeof",[CL.mkVar tyName]))]))]
638 : lamonts 1271
639 :    
640 :     (* Initialize Width Parameter *)
641 :     val widthDel = if nDims = 2 then
642 : jhr 1278 CL.mkAssign(CL.mkVar "width",CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(1, CL.intTy)))
643 : lamonts 1271 else
644 : jhr 1278 CL.mkAssign(CL.mkVar "width",CL.mkInt(0,CL.intTy))
645 : lamonts 1271
646 :    
647 : jhr 1278 val strands_init = CL.mkCall(RN.strandInitSetup, [
648 :     CL.mkVar "size", CL.mkVar "width", CL.mkVar inStateVar
649 :     ])
650 : lamonts 1271
651 : lamonts 1264 val clGlobalBuffers = getGlobalDataBuffers(!imgGlobals,3,contextVar,errVar)
652 :    
653 :    
654 :     (* Load the Kernel and Header Files *)
655 : jhr 1278 val sourceStms = [CL.mkAssign(CL.mkSubscript(CL.mkVar sourcesVar,CL.mkInt(1,CL.intTy)),
656 :     CL.mkApply(RN.clLoaderFN, [CL.mkVar clFNVar])),
657 :     CL.mkAssign(CL.mkSubscript(CL.mkVar sourcesVar,CL.mkInt(0,CL.intTy)),
658 :     CL.mkApply(RN.clLoaderFN, [CL.mkVar headerFNVar]))]
659 : lamonts 1271
660 : jhr 1278 (* val sourceStms = [CL.mkAssign(CL.mkSubscript(CL.mkVar sourcesVar,CL.mkInt(1,CL.intTy)),
661 :     CL.mkApply(RN.clLoaderFN, [CL.mkVar clFNVar]))] *)
662 : lamonts 1271
663 : lamonts 1264
664 : jhr 1261 (* Created Enqueue Statements *)
665 :     (* FIXME: simplify this code by function abstraction *)
666 : lamonts 1264 val enqueueStm = if nDims = 1
667 : jhr 1278 then [CL.mkAssign(CL.mkVar errVar,
668 : lamonts 1264 CL.mkApply("clEnqueueNDRangeKernel",
669 : jhr 1278 [CL.mkVar cmdVar,
670 :     CL.mkVar kernelVar,
671 :     CL.mkInt(1,CL.intTy),
672 :     CL.mkVar "NULL",
673 :     CL.mkVar globalVar,
674 :     CL.mkVar localVar,
675 :     CL.mkInt(0,CL.intTy),
676 :     CL.mkVar "NULL",
677 :     CL.mkVar "NULL"])),CL.mkCall("clFinish",[CL.mkVar cmdVar])]
678 : lamonts 1264 else if nDims = 2 then
679 : jhr 1278 [CL.mkAssign(CL.mkVar errVar,
680 : lamonts 1264 CL.mkApply("clEnqueueNDRangeKernel",
681 : jhr 1278 [CL.mkVar cmdVar,
682 :     CL.mkVar kernelVar,
683 :     CL.mkInt(2,CL.intTy),
684 :     CL.mkVar "NULL",
685 :     CL.mkVar globalVar,
686 :     CL.mkVar localVar,
687 :     CL.mkInt(0,CL.intTy),
688 :     CL.mkVar "NULL",
689 :     CL.mkVar "NULL"])),CL.mkCall("clFinish",[CL.mkVar cmdVar])]
690 : lamonts 1264 else
691 : jhr 1278 [CL.mkAssign(CL.mkVar errVar,
692 : lamonts 1264 CL.mkApply("clEnqueueNDRangeKernel",
693 : jhr 1278 [CL.mkVar cmdVar,
694 :     CL.mkVar kernelVar,
695 :     CL.mkInt(3,CL.intTy),
696 :     CL.mkVar "NULL",
697 :     CL.mkVar globalVar,
698 :     CL.mkVar localVar,
699 :     CL.mkInt(0,CL.intTy),
700 :     CL.mkVar "NULL",
701 :     CL.mkVar "NULL"])),CL.mkCall("clFinish",[CL.mkVar cmdVar])]
702 : lamonts 1264
703 : lamonts 1271
704 : lamonts 1264
705 :     (* Setup Global and Local variables *)
706 :    
707 :     val globalAndlocalStms = if nDims = 1 then
708 : jhr 1278 [CL.mkAssign(CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(0,CL.intTy)),
709 :     CL.mkSubscript(CL.mkVar "size", CL.mkInt(0,CL.intTy))),
710 :     CL.mkAssign(CL.mkSubscript(CL.mkVar localVar, CL.mkInt(0,CL.intTy)),
711 :     CL.mkVar "16")]
712 : lamonts 1264
713 :    
714 :     else if nDims = 2 then
715 : jhr 1278 [CL.mkAssign(CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(0,CL.intTy)),
716 :     CL.mkSubscript(CL.mkVar "size", CL.mkInt(0,CL.intTy))),
717 :     CL.mkAssign(CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(1,CL.intTy)),
718 :     CL.mkSubscript(CL.mkVar "size", CL.mkInt(1,CL.intTy))),
719 :     CL.mkAssign(CL.mkSubscript(CL.mkVar localVar, CL.mkInt(0,CL.intTy)),
720 :     CL.mkVar "16"),
721 :     CL.mkAssign(CL.mkSubscript(CL.mkVar localVar, CL.mkInt(1,CL.intTy)),
722 :     CL.mkVar "16")]
723 : lamonts 1264
724 :     else
725 : jhr 1278 [CL.mkAssign(CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(0,CL.intTy)),
726 :     CL.mkSubscript(CL.mkVar "size", CL.mkInt(0,CL.intTy))),
727 :     CL.mkAssign(CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(1,CL.intTy)),
728 :     CL.mkSubscript(CL.mkVar "size", CL.mkInt(1,CL.intTy))),
729 :     CL.mkAssign(CL.mkSubscript(CL.mkVar globalVar, CL.mkInt(2,CL.intTy)),
730 :     CL.mkSubscript(CL.mkVar "size", CL.mkInt(2,CL.intTy))),
731 :     CL.mkAssign(CL.mkSubscript(CL.mkVar localVar, CL.mkInt(0,CL.intTy)),
732 :     CL.mkVar "16"),
733 :     CL.mkAssign(CL.mkSubscript(CL.mkVar localVar, CL.mkInt(1,CL.intTy)),
734 :     CL.mkVar "16"),
735 :     CL.mkAssign(CL.mkSubscript(CL.mkVar localVar, CL.mkInt(2,CL.intTy)),
736 :     CL.mkVar "16")]
737 : lamonts 1264
738 : lamonts 1244
739 : lamonts 1264
740 :     (* Setup Kernel arguments *)
741 : jhr 1278 val kernelArguments = [CL.mkAssign(CL.mkVar errVar,CL.mkApply("clSetKernelArg",
742 :     [CL.mkVar kernelVar,
743 :     CL.mkInt(0,CL.intTy),
744 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
745 :     CL.mkUnOp(CL.%&,CL.mkVar clInstateVar)])),
746 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar, CL.|=,CL.mkApply("clSetKernelArg",
747 :     [CL.mkVar kernelVar,
748 :     CL.mkInt(1,CL.intTy),
749 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
750 :     CL.mkUnOp(CL.%&,CL.mkVar clOutStateVar)]))),
751 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar, CL.|=,CL.mkApply("clSetKernelArg",
752 :     [CL.mkVar kernelVar,
753 :     CL.mkInt(2,CL.intTy),
754 :     CL.mkApply("sizeof",[CL.mkVar "int"]),
755 :     CL.mkUnOp(CL.%&,CL.mkVar "width")])))]
756 : lamonts 1264
757 :     val clGlobalArguments = genGlobalArguments(!imgGlobals,3,kernelVar,errVar) @ [assertStm]
758 :    
759 :     (* Retrieve output *)
760 : jhr 1278 val outputStm = CL.mkAssign(CL.mkVar errVar,
761 : lamonts 1264 CL.mkApply("clEnqueueReadBuffer",
762 : jhr 1278 [CL.mkVar cmdVar,
763 :     CL.mkVar clOutStateVar,
764 :     CL.mkVar "CL_TRUE",
765 :     CL.mkInt(0,CL.intTy),
766 :     CL.mkVar stateSizeVar,
767 :     CL.mkVar outStateVar,
768 :     CL.mkInt(0,CL.intTy),
769 :     CL.mkVar "NULL",
770 :     CL.mkVar "NULL"]))
771 : lamonts 1264
772 :     (* Free all the objects *)
773 : jhr 1278 val freeStms = [CL.mkCall("clReleaseKernel",[CL.mkVar kernelVar]),
774 :     CL.mkCall("clReleaseProgram",[CL.mkVar programVar ]),
775 :     CL.mkCall("clReleaseCommandQueue",[CL.mkVar cmdVar]),
776 :     CL.mkCall("clReleaseContext",[CL.mkVar contextVar]),
777 :     CL.mkCall("clReleaseMemObject",[CL.mkVar clInstateVar]),
778 :     CL.mkCall("clReleaseMemObject",[CL.mkVar clOutStateVar])]
779 : lamonts 1264
780 :    
781 :     (*Setup Strand Print Function *)
782 :     val outputData = [CL.mkDecl(CL.T_Ptr(CL.T_Named("FILE")), "outS", SOME(CL.I_Exp(CL.mkApply("fopen",
783 : jhr 1278 [CL.mkStr "mip.txt",
784 :     CL.mkStr "w"])))),
785 : lamonts 1264 CL.mkCall(concat[name, "_print"],
786 : jhr 1278 [CL.mkVar "outS",
787 :     CL.mkVar "size",
788 :     CL.mkVar "width",
789 :     CL.mkVar outStateVar])]
790 : lamonts 1271
791 : lamonts 1264
792 :    
793 :     (* Body put all the statments together *)
794 : jhr 1273 val body = declarations @ [globalsDecl,initGlobalsCall] (*@ platformStm @ devicesStm *) @ contextStm @ commandStm @ !initially @ [strandSize] @
795 : lamonts 1271 strandsArrays @ globalAndlocalStms @ [widthDel,strands_init] @ clStrandObjects @ clGlobalBuffers @ sourceStms @ create_build_stms (*@
796 :     kernelArguments @ clGlobalArguments @ enqueueStm @ [outputStm] @ freeStms @ outputData *)
797 : lamonts 1264
798 :     in
799 :    
800 :     CL.D_Func([],CL.voidTy,RN.setupFName,params,CL.mkBlock(body))
801 :    
802 :     end
803 :     (* generate the data and global parameters *)
804 :     fun genKeneralGlobalParams ((name,tyname)::rest) =
805 : lamonts 1271 CL.PARAM([], CL.T_Ptr(CL.T_Named RN.globalsTy), concat[RN.globalsVarName]) ::
806 :     CL.PARAM([], CL.T_Ptr(CL.T_Named (RN.imageTy tyname)),RN.addBufferSuffix name) ::
807 :     CL.PARAM([], CL.T_Ptr(CL.voidTy),RN.addBufferSuffixData name) ::
808 : lamonts 1264 genKeneralGlobalParams(rest)
809 :    
810 :     | genKeneralGlobalParams ([]) = []
811 :    
812 :     (*generate code for intilizing kernel global data *)
813 :     fun initKernelGlobals (globals,imgGlobals) = let
814 :     fun initGlobalStruct (CL.D_Var(_, _ , name, _)::rest) =
815 : jhr 1278 CL.mkAssign(CL.mkVar name, CL.mkIndirect(CL.mkVar RN.globalsVarName, name)) ::
816 : lamonts 1264 initGlobalStruct(rest)
817 :     | initGlobalStruct ( _::rest) = initGlobalStruct(rest)
818 :     | initGlobalStruct([]) = []
819 :    
820 :     fun initGlobalImages((name,tyname)::rest) =
821 : jhr 1278 CL.mkAssign(CL.mkVar name, CL.mkVar (RN.addBufferSuffix name)) ::
822 :     CL.mkAssign(CL.mkIndirect(CL.mkVar name,"data"),CL.mkVar (RN.addBufferSuffixData name)) ::
823 : lamonts 1264 initGlobalImages(rest)
824 :     | initGlobalImages([]) = []
825 :     in
826 :     initGlobalStruct(globals) @ initGlobalImages(imgGlobals)
827 :     end
828 :    
829 :     (* generate the main kernel function for the .cl file *)
830 : lamonts 1271 fun genKernelFun(Strand{name, tyName, state, output, code,...},nDims,globals,imgGlobals) = let
831 : lamonts 1264 val fName = RN.kernelFuncName;
832 :     val inState = "strand_in"
833 :     val outState = "strand_out"
834 :     val params = [
835 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
836 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
837 :     CL.PARAM(["__global"], CL.intTy, "width")
838 :     ] @ genKeneralGlobalParams(!imgGlobals)
839 :     val thread_ids = if nDims = 1
840 : jhr 1278 then [CL.mkDecl(CL.intTy, "x", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy)))),
841 :     CL.mkAssign(CL.mkVar "x",CL.mkApply(RN.getGlobalThreadId,[CL.mkInt(0,CL.intTy)]))]
842 : lamonts 1264 else
843 : jhr 1278 [CL.mkDecl(CL.intTy, "x", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy)))),
844 :     CL.mkDecl(CL.intTy, "y", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy)))),
845 :     CL.mkAssign(CL.mkVar "x", CL.mkApply(RN.getGlobalThreadId,[CL.mkInt(0,CL.intTy)])),
846 :     CL.mkAssign(CL.mkVar "y",CL.mkApply(RN.getGlobalThreadId,[CL.mkInt(1,CL.intTy)]))]
847 : lamonts 1264
848 :     val strandDecl = [CL.mkDecl(CL.T_Named tyName, inState, NONE),
849 :     CL.mkDecl(CL.T_Named tyName, outState,NONE)]
850 :     val strandObjects = if nDims = 1
851 : jhr 1278 then [CL.mkAssign(CL.mkSubscript(CL.mkVar "selfIn",CL.mkStr "x"),
852 :     CL.mkVar inState),
853 :     CL.mkAssign(CL.mkSubscript(CL.mkVar "selfOut",CL.mkStr "x"),
854 :     CL.mkVar outState)]
855 : lamonts 1264 else let
856 : jhr 1278 val index = CL.mkBinOp(CL.mkBinOp(CL.mkVar "x",CL.#*,CL.mkVar "width"),CL.#+,CL.mkVar "y")
857 : lamonts 1264 in
858 : jhr 1278 [CL.mkAssign(CL.mkSubscript(CL.mkVar "selfIn",index),
859 :     CL.mkVar inState),
860 :     CL.mkAssign(CL.mkSubscript(CL.mkVar "selfOut",index),
861 :     CL.mkVar outState)]
862 : lamonts 1264 end
863 :    
864 :    
865 : jhr 1278 val status = CL.mkDecl(CL.intTy, "status", SOME(CL.I_Exp(CL.mkInt(0, CL.intTy))))
866 : lamonts 1271 val local_vars = thread_ids @ initKernelGlobals(!globals,!imgGlobals) @ strandDecl @ strandObjects @ [status]
867 : jhr 1278 val while_exp = CL.mkBinOp(CL.mkBinOp(CL.mkVar "status",CL.#!=, CL.mkVar RN.kStabilize),CL.#||,CL.mkBinOp(CL.mkVar "status", CL.#!=, CL.mkVar RN.kDie))
868 :     val while_body = [CL.mkAssign(CL.mkVar "status", CL.mkApply(RN.strandUpdate name,[ CL.mkUnOp(CL.%&,CL.mkVar inState), CL.mkUnOp(CL.%&,CL.mkVar outState)])),
869 :     CL.mkCall(RN.strandStabilize name,[ CL.mkUnOp(CL.%&,CL.mkVar inState), CL.mkUnOp(CL.%&,CL.mkVar outState)])]
870 : lamonts 1264
871 :     val whileBlock = [CL.mkWhile(while_exp,CL.mkBlock while_body)]
872 :    
873 :     val body = CL.mkBlock(local_vars @ whileBlock)
874 :     in
875 :     CL.D_Func(["__kernel"], CL.voidTy, fName, params, body)
876 :     end
877 :     (* generate a global structure from the globals *)
878 :     fun genGlobalStruct(globals) = let
879 :     fun getGlobals(CL.D_Var(_,ty,globalVar,_)::rest) = (ty,globalVar)::getGlobals(rest)
880 :     | getGlobals([]) = []
881 :     | getGlobals(_::rest) = getGlobals(rest)
882 :     in
883 :     CL.D_StructDef(getGlobals(globals),RN.globalsTy)
884 :     end
885 :    
886 : lamonts 1244 (* generate the table of strand descriptors *)
887 : jhr 1261 fun genStrandTable (ppStrm, strands) = let
888 :     val nStrands = length strands
889 : jhr 1278 fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.mkVar(RN.strandDesc name)))
890 : jhr 1261 fun genInits (_, []) = []
891 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
892 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
893 :     in
894 :     ppDecl (CL.D_Var([], CL.int32, RN.numStrands,
895 : jhr 1278 SOME(CL.I_Exp(CL.mkInt(IntInf.fromInt nStrands, CL.int32)))));
896 : jhr 1261 ppDecl (CL.D_Var([],
897 :     CL.T_Array(CL.T_Ptr(CL.T_Named RN.strandDescTy), SOME nStrands),
898 :     RN.strands,
899 :     SOME(CL.I_Array(genInits (0, strands)))))
900 :     end
901 : lamonts 1244
902 : lamonts 1264
903 :     fun genSrc (baseName, Prog{double,globals, topDecls, strands, initially,imgGlobals,numDims,...}) = let
904 :     val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
905 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
906 :     val clOutS = TextIO.openOut clFileName
907 :     val cOutS = TextIO.openOut cFileName
908 : jhr 1273 (* FIXME: need to use PrintAsC and PrintAsCL *)
909 : lamonts 1264 val clppStrm = PrintAsC.new clOutS
910 :     val cppStrm = PrintAsC.new cOutS
911 :     fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
912 :     fun clppDecl dcl = PrintAsC.output(clppStrm, dcl)
913 :     val strands = AtomTable.listItems strands
914 : jhr 1273 val [strand as Strand{name, tyName, code,init_code, ...}] = strands
915 : lamonts 1264 in
916 : jhr 1273 (* Generate the OpenCl file *)
917 :     clppDecl (CL.D_Verbatim([
918 :     if double
919 :     then "#define DIDEROT_DOUBLE_PRECISION"
920 :     else "#define DIDEROT_SINGLE_PRECISION",
921 :     "#define DIDEROT_TARGET_CL",
922 :     "#include \"Diderot/cl-types.h\""
923 :     ]));
924 :     List.app clppDecl (List.rev (!globals));
925 :     clppDecl (genGlobalStruct (!globals));
926 :     clppDecl (genStrandTyDef strand);
927 :     List.app clppDecl (!code);
928 :     clppDecl (genKernelFun (strand,!numDims,globals,imgGlobals));
929 :     (* Generate the Host file .c *)
930 :     cppDecl (CL.D_Verbatim([
931 :     if double
932 :     then "#define DIDEROT_DOUBLE_PRECISION"
933 :     else "#define DIDEROT_SINGLE_PRECISION",
934 :     "#define DIDEROT_TARGET_CL",
935 :     "#include \"Diderot/diderot.h\""
936 :     ]));
937 :     List.app cppDecl (List.rev (!globals));
938 :     cppDecl (genGlobalStruct (!globals));
939 :     cppDecl (genStrandTyDef strand);
940 :     cppDecl (!init_code);
941 :     cppDecl (genStrandInit(strand,!numDims));
942 :     cppDecl (genStrandPrint(strand,!numDims));
943 :     (* cppDecl (genKernelLoader());*)
944 :     List.app cppDecl (List.rev (!topDecls));
945 :     cppDecl (genHostSetupFunc (strand, clFileName, !numDims, initially, imgGlobals));
946 : lamonts 1264 PrintAsC.close cppStrm;
947 :     PrintAsC.close clppStrm;
948 :     TextIO.closeOut cOutS;
949 :     TextIO.closeOut clOutS
950 :     end
951 :    
952 : lamonts 1244 (* output the code to a file. The string is the basename of the file, the extension
953 :     * is provided by the target.
954 :     *)
955 : lamonts 1264 fun generate (basename, prog as Prog{double, parallel, debug, ...}) = let
956 :     fun condCons (true, x, xs) = x::xs
957 :     | condCons (false, _, xs) = xs
958 :     (* generate the C compiler flags *)
959 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
960 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
961 :     val cflags = if debug
962 :     then #debug Paths.cflags :: cflags
963 :     else #ndebug Paths.cflags :: cflags
964 :     val cflags = #base Paths.cflags :: cflags
965 :     (* generate the loader flags *)
966 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
967 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
968 : lamonts 1271 val extraLibs = #cl Paths.extraLibs :: extraLibs
969 : lamonts 1264 val rtLib = TargetUtil.runtimeName {
970 :     target = TargetUtil.TARGET_CL,
971 :     parallel = parallel, double = double, debug = debug
972 :     }
973 :     val ldOpts = rtLib :: extraLibs
974 :     in
975 : lamonts 1271 genSrc (basename, prog);
976 :     RunCC.compile (basename, cflags);
977 :     RunCC.link (basename, ldOpts)
978 : jhr 1273 end
979 : lamonts 1244
980 : jhr 1273 end
981 : lamonts 1264
982 : lamonts 1244 (* strands *)
983 :     structure Strand =
984 :     struct
985 : jhr 1261 fun define (Prog{strands, ...}, strandId) = let
986 :     val name = Atom.toString strandId
987 :     val strand = Strand{
988 :     name = name,
989 :     tyName = RN.strandTy name,
990 :     state = ref [],
991 :     output = ref NONE,
992 : lamonts 1271 code = ref [],
993 : jhr 1273 init_code = ref (CL.D_Comment(["no init code"]))
994 : jhr 1261 }
995 :     in
996 :     AtomTable.insert strands (strandId, strand);
997 :     strand
998 :     end
999 : lamonts 1244
1000 :     (* return the strand with the given name *)
1001 : jhr 1261 fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
1002 : lamonts 1244
1003 :     (* register the strand-state initialization code. The variables are the strand
1004 :     * parameters.
1005 :     *)
1006 : lamonts 1271 fun init (Strand{name, tyName, code,init_code, ...}, params, init) = let
1007 : jhr 1261 val fName = RN.strandInit name
1008 :     val params =
1009 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
1010 : jhr 1273 List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
1011 : jhr 1261 val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
1012 :     in
1013 : jhr 1273 init_code := initFn
1014 : jhr 1261 end
1015 : lamonts 1244
1016 :     (* register a strand method *)
1017 : lamonts 1271 fun method (Strand{name, tyName, code,...}, methName, body) = let
1018 : jhr 1261 val fName = concat[name, "_", methName]
1019 :     val params = [
1020 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
1021 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut")
1022 :     ]
1023 :     val methFn = CL.D_Func([], CL.int32, fName, params, body)
1024 :     in
1025 : jhr 1273 code := methFn :: !code
1026 : jhr 1261 end
1027 :    
1028 : jhr 1273 fun output (Strand{output, ...}, ty, ToCL.V(_, x)) = output := SOME(ty, x)
1029 : lamonts 1244
1030 :     end
1031 :    
1032 :     end
1033 :    
1034 :     structure CLBackEnd = CodeGenFn(CLTarget)

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