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

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