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

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