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

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

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