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 1333 - (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 1333 numDims: int ref, (* number of dimensions in initially iteration *)
83 : jhr 1273 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 1331 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 : jhr 1332 numDims = ref 0,
209 : jhr 1307 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 1331 val globalsDecl = CL.mkAssign(CL.E_Var RN.globalsVarName,
237 : lamonts 1316 CL.mkApply("malloc", [CL.mkApply("sizeof",[CL.mkVar RN.globalsTy])]))
238 :     val initGlobalsCall = CL.mkCall(RN.initGlobalsHelper,[])
239 : jhr 1331 val initFn = CL.D_Func(
240 : lamonts 1316 [], CL.voidTy, RN.initGlobals, [],
241 :     CL.mkBlock([globalsDecl,initGlobalsCall]))
242 :     val initFn_helper = CL.D_Func(
243 :     [], CL.voidTy, RN.initGlobalsHelper, [],
244 : jhr 1286 init)
245 : jhr 1307 val shutdownFn = CL.D_Func(
246 :     [], CL.voidTy, RN.shutdown,
247 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
248 :     CL.S_Block[])
249 :     in
250 : lamonts 1316 topDecls := shutdownFn :: initFn :: initFn_helper :: !topDecls
251 : jhr 1307 end
252 : jhr 1333 (* create and register the initially function for a program *)
253 : jhr 1307 fun initially {
254 : jhr 1332 prog = Prog{name=progName, strands, initially, numDims, ...},
255 : jhr 1307 isArray : bool,
256 :     iterPrefix : stm list,
257 :     iters : (var * exp * exp) list,
258 :     createPrefix : stm list,
259 :     strand : Atom.atom,
260 :     args : exp list
261 :     } = let
262 :     val name = Atom.toString strand
263 :     val nDims = List.length iters
264 :     val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
265 :     fun mapi f xs = let
266 :     fun mapf (_, []) = []
267 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
268 :     in
269 :     mapf (0, xs)
270 :     end
271 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
272 :     val sizeInit = mapi
273 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
274 :     (i, CL.I_Exp(CL.mkBinOp(CL.mkBinOp(hi, CL.#-, lo), CL.#+, CL.E_Int(1, ty))))
275 :     ) iters
276 :     (* code to allocate the world and initial strands *)
277 :     val wrld = "wrld"
278 :     val allocCode = [
279 :     CL.mkComment["allocate initial block of strands"],
280 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
281 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
282 :     CL.mkDecl(worldTy, wrld,
283 :     SOME(CL.I_Exp(CL.E_Apply(N.allocInitially, [
284 :     CL.mkVar "ProgramName",
285 :     CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)),
286 :     CL.E_Bool isArray,
287 :     CL.E_Int(IntInf.fromInt nDims, CL.int32),
288 :     CL.E_Var "base",
289 :     CL.E_Var "size"
290 :     ]))))
291 :     ]
292 : lamonts 1316 (* create the loop nest for the initially iterations
293 : jhr 1307 val indexVar = "ix"
294 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
295 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
296 :     CL.mkDecl(strandTy, "sp",
297 :     SOME(CL.I_Exp(
298 :     CL.E_Cast(strandTy,
299 :     CL.E_Apply(N.inState, [CL.E_Var "wrld", CL.E_Var indexVar]))))),
300 : jhr 1315 CL.mkCall(N.strandInit name,
301 : jhr 1326 CL.E_Var RN.globalsVarName :: CL.E_Var "sp" :: args),
302 : jhr 1307 CL.mkAssign(CL.E_Var indexVar, CL.mkBinOp(CL.E_Var indexVar, CL.#+, CL.E_Int(1, CL.uint32)))
303 :     ])
304 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
305 :     val body = mkLoopNest iters
306 :     in
307 :     CL.mkFor(
308 :     [(ty, param, lo)],
309 :     CL.mkBinOp(CL.E_Var param, CL.#<=, hi),
310 :     [CL.mkPostOp(CL.E_Var param, CL.^++)],
311 :     body)
312 :     end
313 :     val iterCode = [
314 :     CL.mkComment["initially"],
315 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.E_Int(0, CL.uint32)))),
316 :     mkLoopNest iters
317 : lamonts 1316 ] *)
318 : jhr 1307 val body = CL.mkBlock(
319 :     iterPrefix @
320 :     allocCode @
321 :     [CL.mkReturn(SOME(CL.E_Var "wrld"))])
322 : lamonts 1316 val initFn = CL.D_Func([], worldTy, N.initially, [], body)
323 : jhr 1307 in
324 : jhr 1333 numDims := nDims;
325 : jhr 1307 initially := initFn
326 :     end
327 : jhr 1281
328 : lamonts 1305 (***** OUTPUT *****)
329 : jhr 1307 fun genStrandPrint (Strand{name, tyName, state, output, code,...}) = let
330 : jhr 1326 (* the print function *)
331 : jhr 1307 val prFnName = concat[name, "_print"]
332 :     val prFn = let
333 : jhr 1326 val params = [
334 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
335 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
336 :     ]
337 :     val SOME(ty, x) = !output
338 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
339 :     val prArgs = (case ty
340 :     of Ty.IVecTy 1 => [CL.E_Str(!N.gIntFormat ^ "\n"), outState]
341 :     | Ty.IVecTy d => let
342 :     val fmt = CL.mkStr(
343 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
344 :     ^ "\n")
345 :     val args = List.tabulate (d, fn i => ToC.ivecIndex(outState, d, i))
346 :     in
347 :     fmt :: args
348 :     end
349 :     | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
350 :     | Ty.TensorTy[d] => let
351 :     val fmt = CL.mkStr(
352 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
353 :     ^ "\n")
354 :     val args = List.tabulate (d, fn i => ToC.vecIndex(outState, d, i))
355 :     in
356 :     fmt :: args
357 :     end
358 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
359 :     (* end case *))
360 :     in
361 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
362 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
363 :     end
364 : jhr 1307 in
365 : jhr 1326 prFn
366 : jhr 1307 end
367 : lamonts 1305
368 : jhr 1307 fun genStrandTyDef (targetTy, Strand{tyName, state,...}) =
369 : jhr 1261 (* the type declaration for the strand's state struct *)
370 :     CL.D_StructDef(
371 : jhr 1307 List.rev (List.map (fn x => (targetTy x, #var x)) (!state)),
372 :     tyName)
373 : lamonts 1305
374 : jhr 1308 (* generates the load kernel function *)
375 : jhr 1307
376 :     (* generates the opencl buffers for the image data *)
377 : jhr 1315 fun getGlobalDataBuffers (globals,contextVar,errVar) = let
378 : jhr 1307 val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
379 :     val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
380 :     CL.mkApply("clCreateBuffer", [
381 :     CL.mkVar contextVar,
382 : lamonts 1328 CL.mkVar "CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR",
383 : jhr 1307 CL.mkApply("sizeof",[CL.mkVar RN.globalsTy]),
384 :     CL.mkVar RN.globalsVarName,
385 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
386 :     ]))
387 : jhr 1326 fun genDataBuffers ([],_,_) = []
388 :     | genDataBuffers ((var,nDims)::globals, contextVar, errVar) = let
389 :     val hostVar = CL.mkIndirect(CL.mkVar RN.globalsVarName, var)
390 : jhr 1313 (* FIXME: use CL constructors to build expressions (not strings) *)
391 : jhr 1326 fun sizeExp i = CL.mkSubscript(CL.mkIndirect(hostVar, "size"), CL.mkInt i)
392 :     val size = CL.mkBinOp(CL.mkApply("sizeof",[CL.mkVar "float"]), CL.#*, sizeExp 0)
393 :     val size = if (nDims > 1)
394 :     then CL.mkBinOp(size, CL.#*, sizeExp 1)
395 :     else size
396 :     val size = if (nDims > 2)
397 :     then CL.mkBinOp(size, CL.#*, sizeExp 2)
398 :     else size
399 :     in
400 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffix var ,NONE)::
401 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE)::
402 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffix var),
403 :     CL.mkApply("clCreateBuffer", [
404 :     CL.mkVar contextVar,
405 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
406 :     CL.mkApply("sizeof",[CL.mkVar (RN.imageTy nDims)]),
407 :     hostVar,
408 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
409 :     ])) ::
410 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var),
411 :     CL.mkApply("clCreateBuffer", [
412 :     CL.mkVar contextVar,
413 :     CL.mkVar "CL_MEM_COPY_HOST_PTR",
414 :     size,
415 :     CL.mkIndirect(hostVar, "data"),
416 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
417 :     ])) :: genDataBuffers(globals,contextVar,errVar)
418 :     end
419 : jhr 1307 in
420 : jhr 1326 globalBufferDecl :: globalBuffer :: genDataBuffers(globals,contextVar,errVar)
421 : jhr 1307 end
422 : lamonts 1264
423 : jhr 1309 (* generates the kernel arguments for the image data *)
424 : jhr 1313 fun genGlobalArguments (globals, count, kernelVar, errVar) = let
425 : jhr 1326 val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,
426 :     CL.mkApply("clSetKernelArg",
427 :     [CL.mkVar kernelVar,
428 :     CL.mkPostOp(CL.E_Var count, CL.^++),
429 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
430 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
431 :     fun genDataArguments ([],_,_,_) = []
432 :     | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar) =
433 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,
434 :     CL.mkApply("clSetKernelArg",
435 :     [CL.mkVar kernelVar,
436 :     CL.mkPostOp(CL.E_Var count, CL.^++),
437 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
438 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffix var))]))) ::
439 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.|=,
440 :     CL.mkApply("clSetKernelArg",
441 :     [CL.mkVar kernelVar,
442 :     CL.mkPostOp(CL.E_Var count, CL.^++),
443 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
444 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
445 :     genDataArguments (globals,count,kernelVar,errVar)
446 :     in
447 :     globalArgument :: genDataArguments(globals, count, kernelVar, errVar)
448 :     end
449 : lamonts 1264
450 : lamonts 1305 (* generates the globals buffers and arguments function *)
451 : jhr 1307 fun genGlobalBuffersArgs (imgGlobals) = let
452 : jhr 1273 (* Delcare opencl setup objects *)
453 :     val errVar = "err"
454 :     val imgDataSizeVar = "image_dataSize"
455 : jhr 1315 val params = [
456 : lamonts 1305 CL.PARAM([],CL.T_Named("cl_context"), "context"),
457 : jhr 1307 CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
458 :     CL.PARAM([],CL.T_Named("int"), "argStart")
459 : jhr 1273 ]
460 : jhr 1313 val clGlobalBuffers = getGlobalDataBuffers(!imgGlobals, "context", errVar)
461 :     val clGlobalArguments = genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
462 : jhr 1307 (* Body put all the statments together *)
463 : jhr 1314 val body = CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt 0)))
464 : jhr 1326 :: clGlobalBuffers @ clGlobalArguments
465 : jhr 1313 in
466 : jhr 1307 CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
467 :     end
468 : lamonts 1305
469 : jhr 1307 (* generate the data and global parameters *)
470 :     fun genKeneralGlobalParams ((name,tyname)::rest) =
471 : jhr 1326 CL.PARAM([], CL.T_Ptr(CL.T_Named (RN.imageTy tyname)), RN.addBufferSuffix name) ::
472 :     CL.PARAM([], CL.T_Ptr(CL.voidTy), RN.addBufferSuffixData name) ::
473 : jhr 1307 genKeneralGlobalParams rest
474 :     | genKeneralGlobalParams [] = []
475 :    
476 :     (*generate code for intilizing kernel global data *)
477 :     (* FIXME: should use List.map here *)
478 : lamonts 1316 fun initGlobalImages ((name, tyname)::rest) =
479 :     CL.mkAssign(CL.mkIndirect(CL.E_Var RN.globalsVarName, name), CL.mkVar (RN.addBufferSuffix name)) ::
480 :     CL.mkAssign(CL.mkIndirect(CL.E_Var RN.globalsVarName,concat[name,"->","data"]),CL.mkVar (RN.addBufferSuffixData name)) ::
481 :     initGlobalImages rest
482 :     | initGlobalImages [] = []
483 :    
484 : jhr 1331 (* generate the main kernel function for the .cl file *)
485 : jhr 1307 fun genKernelFun (strand, nDims, globals, imgGlobals) = let
486 :     val Strand{name, tyName, state, output, code,...} = strand
487 :     val fName = RN.kernelFuncName;
488 :     val inState = "strand_in"
489 :     val outState = "strand_out"
490 :     val params = [
491 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
492 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
493 : lamonts 1328 CL.PARAM(["__global"], CL.intTy, "width"),
494 : jhr 1331 CL.PARAM([], CL.T_Ptr(CL.T_Named RN.globalsTy), RN.globalsVarName)
495 : jhr 1307 ] @ genKeneralGlobalParams(!imgGlobals)
496 :     val thread_ids = if nDims = 1
497 : jhr 1331 then [
498 :     CL.mkDecl(CL.intTy, "x",
499 :     SOME(CL.I_Exp(CL.mkApply(RN.getGlobalThreadId,[CL.mkInt 0]))))
500 :     ]
501 :     else if nDims = 2
502 :     then [
503 :     CL.mkDecl(CL.intTy, "x",
504 :     SOME(CL.I_Exp(CL.mkApply(RN.getGlobalThreadId,[CL.mkInt 0])))),
505 :     CL.mkDecl(CL.intTy, "y",
506 :     SOME(CL.I_Exp(CL.mkApply(RN.getGlobalThreadId,[CL.mkInt 1]))))
507 :     ]
508 :     else raise Fail "nDims > 2"
509 : jhr 1307 val strandDecl = [
510 : jhr 1331 CL.mkDecl(CL.T_Named tyName, inState, NONE),
511 :     CL.mkDecl(CL.T_Named tyName, outState, NONE)
512 :     ]
513 : jhr 1309 val strandObjects = if nDims = 1
514 : jhr 1326 then [
515 :     CL.mkAssign( CL.mkVar inState, CL.mkSubscript(CL.mkVar "selfIn", CL.mkStr "x")),
516 :     CL.mkAssign(CL.mkVar outState,CL.mkSubscript(CL.mkVar "selfOut", CL.mkStr "x"))
517 :     ]
518 :     else let
519 : jhr 1332 val index = CL.mkBinOp(
520 :     CL.mkBinOp(CL.mkVar "x", CL.#*, CL.mkVar "width"), CL.#+, CL.mkVar "y")
521 : jhr 1326 in [
522 :     CL.mkAssign(CL.mkVar inState, CL.mkSubscript(CL.mkVar "selfIn",index)),
523 :     CL.mkAssign(CL.mkVar outState,CL.mkSubscript(CL.mkVar "selfOut",index))
524 :     ] end
525 : jhr 1314 val status = CL.mkDecl(CL.intTy, "status", SOME(CL.I_Exp(CL.mkInt 0)))
526 : jhr 1333 val strandInitStm = CL.mkCall(RN.strandInit name, [
527 :     CL.E_Var RN.globalsVarName,
528 :     CL.mkUnOp(CL.%&, CL.E_Var inState),
529 :     CL.E_Var "x",
530 :     (* FIXME: if nDims = 1, then "y" is not defined! the arguments to this call should really come from
531 :     * the initially code!
532 :     *)
533 :     CL.E_Var "y"])
534 :     val local_vars = thread_ids
535 :     @ initGlobalImages(!imgGlobals)
536 :     @ strandDecl
537 :     @ strandObjects
538 :     @ [strandInitStm,status]
539 : jhr 1331 val while_exp = CL.mkBinOp(
540 : jhr 1326 CL.mkBinOp(CL.mkVar "status",CL.#!=, CL.mkVar RN.kStabilize),
541 :     CL.#||,
542 :     CL.mkBinOp(CL.mkVar "status", CL.#!=, CL.mkVar RN.kDie))
543 : jhr 1307 val whileBody = CL.mkBlock [
544 : jhr 1333 (* FIXME: need a barrier synchronization at beginning of loop *)
545 : jhr 1307 CL.mkAssign(CL.mkVar "status",
546 :     CL.mkApply(RN.strandUpdate name,
547 : lamonts 1316 [CL.mkUnOp(CL.%&,CL.mkVar inState), CL.mkUnOp(CL.%&,CL.mkVar outState),CL.E_Var RN.globalsVarName])),
548 : jhr 1333 (* FIXME: why is there a call to stabilize here? *)
549 : jhr 1307 CL.mkCall(RN.strandStabilize name,
550 : lamonts 1316 [CL.mkUnOp(CL.%&,CL.mkVar inState), CL.mkUnOp(CL.%&,CL.mkVar outState),CL.E_Var RN.globalsVarName])
551 : jhr 1307 ]
552 :     val whileBlock = [CL.mkWhile(while_exp, whileBody)]
553 : jhr 1333 val body = CL.mkBlock(local_vars @ whileBlock)
554 : jhr 1307 in
555 :     CL.D_Func(["__kernel"], CL.voidTy, fName, params, body)
556 :     end
557 :     (* generate a global structure from the globals *)
558 :     fun genGlobalStruct (targetTy, globals) = let
559 :     val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
560 :     in
561 :     CL.D_StructDef(globs, RN.globalsTy)
562 :     end
563 :     fun genGlobals (declFn, targetTy, globals) = let
564 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
565 :     in
566 :     List.app doVar globals
567 :     end
568 : lamonts 1264
569 : jhr 1326 fun genStrandDesc (Strand{name, output, ...}) = let
570 :     (* the strand's descriptor object *)
571 :     val descI = let
572 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
573 :     val SOME(outTy, _) = !output
574 :     in
575 :     CL.I_Struct[
576 :     ("name", CL.I_Exp(CL.mkStr name)),
577 :     ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(N.strandTy name)))),
578 : jhr 1315 (*
579 : jhr 1326 ("outputSzb", CL.I_Exp(CL.mkSizeof(ToC.trTy outTy))),
580 : jhr 1315 *)
581 : jhr 1326 ("update", fnPtr("update_method_t", "0")),
582 :     ("print", fnPtr("print_method_t", name ^ "_print"))
583 :     ]
584 :     end
585 :     val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
586 :     in
587 :     desc
588 :     end
589 : jhr 1315
590 :     (* generate the table of strand descriptors *)
591 : jhr 1326 fun genStrandTable (declFn, strands) = let
592 :     val nStrands = length strands
593 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)))
594 :     fun genInits (_, []) = []
595 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
596 :     in
597 :     declFn (CL.D_Var([], CL.int32, N.numStrands,
598 :     SOME(CL.I_Exp(CL.E_Int(IntInf.fromInt nStrands, CL.int32)))));
599 :     declFn (CL.D_Var([],
600 :     CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
601 :     N.strands,
602 :     SOME(CL.I_Array(genInits (0, strands)))))
603 :     end
604 : jhr 1315
605 : jhr 1308 fun genSrc (baseName, prog) = let
606 : jhr 1326 val Prog{name,double, globals, topDecls, strands, initially, imgGlobals, numDims, ...} = prog
607 : jhr 1307 val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
608 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
609 :     val clOutS = TextIO.openOut clFileName
610 :     val cOutS = TextIO.openOut cFileName
611 :     val clppStrm = PrintAsCL.new clOutS
612 :     val cppStrm = PrintAsC.new cOutS
613 : jhr 1321 val progName = name
614 : jhr 1307 fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
615 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
616 :     val strands = AtomTable.listItems strands
617 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
618 :     in
619 : jhr 1273 (* Generate the OpenCl file *)
620 :     clppDecl (CL.D_Verbatim([
621 :     if double
622 :     then "#define DIDEROT_DOUBLE_PRECISION"
623 :     else "#define DIDEROT_SINGLE_PRECISION",
624 :     "#define DIDEROT_TARGET_CL",
625 : lamonts 1305 "#include \"Diderot/cl-diderot.h\""
626 : jhr 1273 ]));
627 : jhr 1307 clppDecl (genGlobalStruct (#gpuTy, !globals));
628 :     clppDecl (genStrandTyDef(#gpuTy, strand));
629 : jhr 1326 clppDecl (!init_code);
630 : jhr 1273 List.app clppDecl (!code);
631 : lamonts 1328 clppDecl (genKernelFun (strand, !numDims, globals, imgGlobals));
632 :     (* Generate the Host C file *)
633 : jhr 1273 cppDecl (CL.D_Verbatim([
634 :     if double
635 :     then "#define DIDEROT_DOUBLE_PRECISION"
636 :     else "#define DIDEROT_SINGLE_PRECISION",
637 :     "#define DIDEROT_TARGET_CL",
638 :     "#include \"Diderot/diderot.h\""
639 :     ]));
640 : jhr 1326 cppDecl (CL.D_Var(["static"], CL.charPtr, "ProgramName",
641 :     SOME(CL.I_Exp(CL.mkStr progName))));
642 : jhr 1307 cppDecl (genGlobalStruct (#hostTy, !globals));
643 : jhr 1326 cppDecl (CL.D_Var(["static"], CL.T_Ptr(CL.T_Named RN.globalsTy), RN.globalsVarName, NONE));
644 : jhr 1308 cppDecl (genStrandTyDef (#hostTy, strand));
645 : jhr 1307 cppDecl (genStrandPrint strand);
646 : jhr 1273 List.app cppDecl (List.rev (!topDecls));
647 : jhr 1315 cppDecl (genGlobalBuffersArgs imgGlobals);
648 : jhr 1326 List.app (fn strand => cppDecl (genStrandDesc strand)) strands;
649 :     genStrandTable (cppDecl, strands);
650 : jhr 1307 cppDecl (!initially);
651 :     PrintAsC.close cppStrm;
652 :     PrintAsCL.close clppStrm;
653 :     TextIO.closeOut cOutS;
654 :     TextIO.closeOut clOutS
655 :     end
656 : lamonts 1264
657 : lamonts 1244 (* output the code to a file. The string is the basename of the file, the extension
658 :     * is provided by the target.
659 :     *)
660 : jhr 1307 fun generate (basename, prog as Prog{double, parallel, debug, ...}) = let
661 :     fun condCons (true, x, xs) = x::xs
662 :     | condCons (false, _, xs) = xs
663 :     (* generate the C compiler flags *)
664 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
665 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
666 :     val cflags = if debug
667 :     then #debug Paths.cflags :: cflags
668 :     else #ndebug Paths.cflags :: cflags
669 :     val cflags = #base Paths.cflags :: cflags
670 :     (* generate the loader flags *)
671 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
672 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
673 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
674 :     val rtLib = TargetUtil.runtimeName {
675 :     target = TargetUtil.TARGET_CL,
676 :     parallel = parallel, double = double, debug = debug
677 :     }
678 :     val ldOpts = rtLib :: extraLibs
679 :     in
680 :     genSrc (basename, prog);
681 :     RunCC.compile (basename, cflags);
682 :     RunCC.link (basename, ldOpts)
683 : jhr 1273 end
684 : lamonts 1244
685 : jhr 1273 end
686 : lamonts 1264
687 : lamonts 1244 (* strands *)
688 :     structure Strand =
689 :     struct
690 : jhr 1261 fun define (Prog{strands, ...}, strandId) = let
691 :     val name = Atom.toString strandId
692 :     val strand = Strand{
693 :     name = name,
694 :     tyName = RN.strandTy name,
695 :     state = ref [],
696 :     output = ref NONE,
697 : lamonts 1271 code = ref [],
698 : jhr 1273 init_code = ref (CL.D_Comment(["no init code"]))
699 : jhr 1261 }
700 :     in
701 :     AtomTable.insert strands (strandId, strand);
702 :     strand
703 :     end
704 : lamonts 1244
705 :     (* return the strand with the given name *)
706 : jhr 1261 fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
707 : lamonts 1244
708 :     (* register the strand-state initialization code. The variables are the strand
709 :     * parameters.
710 :     *)
711 : jhr 1308 fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
712 : jhr 1261 val fName = RN.strandInit name
713 :     val params =
714 : jhr 1326 CL.PARAM([], globPtrTy, RN.globalsVarName) ::
715 : jhr 1261 CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
716 : jhr 1273 List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
717 : jhr 1261 val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
718 :     in
719 : jhr 1273 init_code := initFn
720 : jhr 1261 end
721 : lamonts 1244
722 :     (* register a strand method *)
723 : lamonts 1271 fun method (Strand{name, tyName, code,...}, methName, body) = let
724 : jhr 1261 val fName = concat[name, "_", methName]
725 :     val params = [
726 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
727 : lamonts 1316 CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
728 : jhr 1326 CL.PARAM([], CL.T_Ptr(CL.T_Named (RN.globalsTy)), RN.globalsVarName)
729 : jhr 1261 ]
730 :     val methFn = CL.D_Func([], CL.int32, fName, params, body)
731 :     in
732 : jhr 1273 code := methFn :: !code
733 : jhr 1261 end
734 :    
735 : jhr 1273 fun output (Strand{output, ...}, ty, ToCL.V(_, x)) = output := SOME(ty, x)
736 : lamonts 1244
737 :     end
738 :    
739 :     end
740 :    
741 :     structure CLBackEnd = CodeGenFn(CLTarget)

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