Home My Page Projects Code Snippets Project Openings diderot
Summary Activity Tracker Tasks SCM

SCM Repository

[diderot] Annotation of /branches/vis12/src/compiler/cl-target/cl-target.sml
ViewVC logotype

Annotation of /branches/vis12/src/compiler/cl-target/cl-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1714 - (view) (download)

1 : jhr 1671 (* cl-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 :     structure ToCL = TreeToCL
16 :     structure N = CNames
17 :     structure P = Paths
18 :     structure HF = CLHeaderFrag
19 :     structure SF = CLSchedFrag
20 :    
21 :     (* revmap f l == List.rev(List.map f l) *)
22 :     fun revmap f = let
23 :     fun rmap ([], l) = l
24 :     | rmap (x::r, l) = rmap (r, f x :: l)
25 :     in
26 :     fn l => rmap (l, [])
27 :     end
28 :    
29 :     (* common arithmetic *)
30 :     fun #+# (a, b) = CL.mkBinOp(a, CL.#+, b)
31 :     fun #*# (a, b) = CL.mkBinOp(a, CL.#*, b)
32 :     infix 5 #+#
33 :     infix 6 #*#
34 :    
35 :     (* translate TreeIL types to shadow types *)
36 :     fun shadowTy ty = (case ty
37 :     of Ty.BoolTy => CL.T_Named "cl_uint"
38 :     | Ty.IntTy => CL.T_Named(RN.shadowIntTy ())
39 :     | Ty.TensorTy[] => CL.T_Named(RN.shadowRealTy ())
40 :     | Ty.TensorTy[n] => CL.T_Named(RN.shadowVecTy n)
41 :     | Ty.TensorTy[n, m] => CL.T_Named(RN.shadowMatTy(n,m))
42 :     | Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}) => CL.T_Named(RN.shadowImageTy dim)
43 :     | _ => raise Fail(concat["TreeToC.trType(", Ty.toString ty, ")"])
44 :     (* end case *))
45 :    
46 :     (* FIXME: add comments that more clearly explain the difference between convertToShadow and
47 :     * convertStrandToShadow
48 :     *)
49 :     (* translate TreeIL types to shadow types *)
50 :     fun convertToShadow (ty, name) = (case ty
51 :     of Ty.IntTy => CL.mkAssign(
52 :     CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name),
53 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name))
54 :     | Ty.TensorTy[n]=> CL.mkCall(RN.convertToShadowVec n, [
55 :     CL.mkUnOp(CL.%&, CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name)),
56 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name)
57 :     ])
58 :     | Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}) => CL.mkCall(RN.shadowImageFunc dim, [
59 :     CL.mkVar "context",
60 :     CL.mkUnOp(CL.%&, CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name)),
61 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name)
62 :     ])
63 :     | Ty.TensorTy[n, m] => CL.mkCall(RN.convertToShadowMat(m,n), [
64 :     CL.mkSelect(CL.mkVar RN.shadowGlaobalsName, name),
65 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name)
66 :     ])
67 :     | _ => CL.mkAssign(
68 :     CL.mkSelect(CL.mkVar RN.shadowGlaobalsName,name),
69 :     CL.mkIndirect(CL.mkVar RN.globalsVarName, name))
70 :     (* end case *))
71 :    
72 :     (* generate code to convert strand TreeIL types to shadow types *)
73 :     fun convertStrandToShadow (ty, name, selfIn, selfOut) = (case ty
74 :     of Ty.IntTy => CL.mkAssign(
75 :     CL.mkIndirect(CL.mkVar selfIn, name),
76 :     CL.mkIndirect(CL.mkVar selfOut, name))
77 :     | Ty.TensorTy[n]=> CL.mkCall(RN.convertToShadowVec n, [
78 :     CL.mkUnOp(CL.%&, CL.mkIndirect(CL.mkVar selfIn, name)),
79 :     CL.mkIndirect(CL.mkVar selfOut, name)
80 :     ])
81 :     | Ty.TensorTy[n, m] => CL.mkCall(RN.convertToShadowMat(m,n), [
82 :     CL.mkUnOp(CL.%&, CL.mkIndirect(CL.mkVar selfIn, name)),
83 :     CL.mkIndirect(CL.mkVar selfOut, name)
84 :     ])
85 :     | _ => CL.mkAssign(
86 :     CL.mkIndirect(CL.mkVar selfIn, name),
87 :     CL.mkIndirect(CL.mkVar selfOut, name))
88 :     (* end case *))
89 :    
90 :     (* helper functions for specifying parameters in various address spaces *)
91 :     fun clParam (spc, ty, x) = CL.PARAM([spc], ty, x)
92 :     fun globalParam (ty, x) = CL.PARAM(["__global"], ty, x)
93 :     fun constantParam (ty, x) = CL.PARAM(["__constant"], ty, x)
94 :     fun localParam (ty, x) = CL.PARAM(["__local"], ty, x)
95 :     fun privateParam (ty, x) = CL.PARAM(["__private"], ty, x)
96 :    
97 :     (* OpenCL global pointer type *)
98 :     fun globalPtr ty = CL.T_Qual("__global", CL.T_Ptr ty)
99 :    
100 :     (* lvalue/rvalue state variable *)
101 :     fun lvalueSV name = CL.mkIndirect(CL.mkVar "selfOut", name)
102 :     fun rvalueSV name = CL.mkIndirect(CL.mkVar "selfIn", name)
103 :    
104 :     (* C variable translation *)
105 :     structure TrCVar =
106 :     struct
107 :     type env = CL.typed_var TreeIL.Var.Map.map
108 :     fun lookup (env, x) = (case V.Map.find (env, x)
109 :     of SOME(CL.V(_, x')) => x'
110 :     | NONE => raise Fail(concat["TrCVar.lookup(_, ", V.name x, ")"])
111 :     (* end case *))
112 :     (* translate a variable that occurs in an l-value context (i.e., as the target of an assignment) *)
113 :     fun lvalueVar (env, x) = (case V.kind x
114 : jhr 1706 of IL.VK_Local => CL.mkVar(lookup(env, x))
115 :     | _ => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
116 : jhr 1671 (* end case *))
117 :     (* translate a variable that occurs in an r-value context *)
118 :     fun rvalueVar (env, x) = (case V.kind x
119 : jhr 1706 of IL.VK_Local => CL.mkVar(lookup(env, x))
120 :     | _ => CL.mkIndirect(CL.mkVar RN.globalsVarName, lookup(env, x))
121 : jhr 1671 (* end case *))
122 :     (* translate a strand state variable that occurs in an l-value context *)
123 :     fun lvalueStateVar (IL.SV{name, ...}) = lvalueSV name
124 :     (* translate a strand state variable that occurs in an r-value context *)
125 :     fun rvalueStateVar (IL.SV{name, ...}) = rvalueSV name
126 :     end
127 :    
128 :     structure ToC = TreeToCFn (TrCVar)
129 :    
130 :     type var = CL.typed_var
131 :     type exp = CL.exp
132 :     type stm = CL.stm
133 :    
134 :     (* OpenCL specific types *)
135 :     val clIntTy = CL.T_Named "cl_int"
136 :     val clProgramTy = CL.T_Named "cl_program"
137 :     val clKernelTy = CL.T_Named "cl_kernel"
138 :     val clCmdQueueTy = CL.T_Named "cl_command_queue"
139 :     val clContextTy = CL.T_Named "cl_context"
140 :     val clDeviceIdTy = CL.T_Named "cl_device_id"
141 :     val clPlatformIdTy = CL.T_Named "cl_platform_id"
142 :     val clMemoryTy = CL.T_Named "cl_mem"
143 :     val globPtrTy = CL.T_Ptr(CL.T_Named RN.globalsTy)
144 :     (* FIXME: what are these for? *)
145 :     datatype shadow_env = STRAND_SHADOW | GLOBAL_SHADOW
146 :    
147 :     (* variable or field that is mirrored between host and GPU *)
148 :     type mirror_var = {
149 :     (* FIXME: perhaps it would be cleaner to just track the TreeIL type of the variable? *)
150 :     hostTy : CL.ty, (* variable type on Host (i.e., C type) *)
151 :     shadowTy : CL.ty, (* host-side shadow type of GPU type *)
152 :     gpuTy : CL.ty, (* variable's type on GPU (i.e., OpenCL type) *)
153 :     hToS: stm, (* the statement that converts the variable to its *)
154 :     (* shadow representation *)
155 :     var : CL.var (* variable name *)
156 :     }
157 :    
158 :     datatype strand = Strand of {
159 :     name : string,
160 :     tyName : string,
161 :     state : mirror_var list,
162 :     output : (Ty.ty * CL.var), (* the strand's output variable (only one for now) *)
163 :     code : CL.decl list ref,
164 :     init_code: CL.decl ref
165 :     }
166 :    
167 :     datatype program = Prog of {
168 : jhr 1705 tgt : TargetUtil.target_desc, (* info about target *)
169 : jhr 1671 globals : mirror_var list ref,
170 :     topDecls : CL.decl list ref,
171 :     strands : strand AtomTable.hash_table,
172 :     initially : CL.decl ref,
173 :     numDims: int ref, (* number of dimensions in initially iteration *)
174 :     imgGlobals: (string * int) list ref,
175 :     prFn: CL.decl ref,
176 :     outFn: CL.decl ref
177 :     }
178 :    
179 :     datatype env = ENV of {
180 :     info : env_info,
181 :     vMap : var V.Map.map,
182 :     scope : scope
183 :     }
184 :    
185 :     and env_info = INFO of {
186 :     prog : program
187 :     }
188 :    
189 :     and scope
190 :     = NoScope
191 :     | GlobalScope
192 :     | InitiallyScope
193 :     | StrandScope (* strand initialization *)
194 :     | MethodScope of StrandUtil.method_name (* method body; vars are state variables *)
195 :    
196 :     (* the supprted widths of vectors of reals on the target. *)
197 :     (* FIXME: for OpenCL 1.1, 3 is also valid *)
198 :     fun vectorWidths () = [2, 4, 8, 16]
199 :    
200 :     (* we do not support printing on the OpenCL target *)
201 :     val supportsPrinting = false
202 :    
203 :     (* tests for whether various expression forms can appear inline *)
204 :     fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
205 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
206 :    
207 :     (* TreeIL to target translations *)
208 :     structure Tr =
209 :     struct
210 :     fun fragment (ENV{info, vMap, scope}, blk) = let
211 :     val (vMap, stms) = (case scope
212 :     of GlobalScope => ToC.trFragment (vMap, blk)
213 :     | InitiallyScope => ToC.trFragment (vMap, blk)
214 :     | _ => ToCL.trFragment (vMap, blk)
215 :     (* end case *))
216 :     in
217 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
218 :     end
219 :     fun block (ENV{vMap, scope, ...}, blk) = (case scope
220 :     of StrandScope => ToC.trBlock (vMap, blk)
221 :     | MethodScope name => ToCL.trBlock (vMap, blk)
222 :     | InitiallyScope => ToCL.trBlock (vMap, blk)
223 :     | _ => ToC.trBlock (vMap, blk)
224 :     (* end case *))
225 :     fun exp (ENV{vMap, ...}, e) = ToCL.trExp(vMap, e)
226 :     end
227 :    
228 :     (* variables *)
229 :     structure Var =
230 :     struct
231 :     fun mirror (ty, name, shadowEnv) = {
232 :     hostTy = ToC.trType ty,
233 :     shadowTy = shadowTy ty,
234 :     gpuTy = ToCL.trType ty,
235 :     hToS = case shadowEnv
236 :     of GLOBAL_SHADOW => convertToShadow (ty, name)
237 :     | STRAND_SHADOW => convertStrandToShadow(ty, name, "selfIn", "selfOut")
238 :     (* end case *),
239 :     var = name
240 :     }
241 :     fun name (ToCL.V(_, name)) = name
242 :     fun global (Prog{globals, imgGlobals, ...}, name, ty) = let
243 :     val x = mirror (ty, name, GLOBAL_SHADOW)
244 :     fun isImgGlobal (Ty.ImageTy(ImageInfo.ImgInfo{dim, ...}), name) =
245 :     imgGlobals := (name,dim) :: !imgGlobals
246 :     | isImgGlobal _ = ()
247 :     in
248 :     globals := x :: !globals;
249 :     isImgGlobal (ty, name);
250 :     ToCL.V(#gpuTy x, name)
251 :     end
252 :     fun param x = ToCL.V(ToCL.trType(V.ty x), V.name x)
253 :     end
254 :    
255 :     (* environments *)
256 :     structure Env =
257 :     struct
258 :     (* create a new environment *)
259 :     fun new prog = ENV{
260 :     info=INFO{prog = prog},
261 :     vMap = V.Map.empty,
262 :     scope = NoScope
263 :     }
264 :     (* define the current translation context *)
265 :     fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
266 :     val scopeGlobal = setScope GlobalScope
267 :     val scopeInitially = setScope InitiallyScope
268 :     fun scopeStrand env = setScope StrandScope env
269 :     fun scopeMethod (env, name) = setScope (MethodScope name) env
270 :     (* bind a TreeIL varaiable to a target variable *)
271 :     fun bind (ENV{info, vMap, scope}, x, x') = ENV{
272 :     info = info,
273 :     vMap = V.Map.insert(vMap, x, x'),
274 :     scope = scope
275 :     }
276 :     end
277 :    
278 :     (* programs *)
279 :     structure Program =
280 :     struct
281 : jhr 1705 fun new (tgt : TargetUtil.target_desc) = (
282 :     RN.initTargetSpec (#double tgt);
283 :     CNames.initTargetSpec {double = #double tgt, long = false};
284 : jhr 1671 Prog{
285 : jhr 1705 tgt = tgt,
286 : jhr 1671 globals = ref [],
287 :     topDecls = ref [],
288 :     strands = AtomTable.mkTable (16, Fail "strand table"),
289 :     initially = ref(CL.D_Comment["missing initially"]),
290 :     numDims = ref 0,
291 :     imgGlobals = ref[],
292 :     prFn = ref(CL.D_Comment(["No Print Function"])),
293 :     outFn = ref(CL.D_Comment(["No Output Function"]))
294 :     })
295 :    
296 :     (* register the code that is used to register command-line options for input variables *)
297 :     fun inputs (Prog{topDecls, ...}, stm) = let
298 :     val inputsFn = CL.D_Func(
299 :     [], CL.voidTy, RN.registerOpts,
300 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
301 :     stm)
302 :     in
303 :     topDecls := inputsFn :: !topDecls
304 :     end
305 :    
306 :     (* register the global initialization part of a program *)
307 :     fun init (Prog{topDecls, ...}, init) = let
308 :     val globalsDecl = CL.mkAssign(CL.mkVar RN.globalsVarName,
309 :     CL.mkApply("malloc", [CL.mkSizeof(CL.T_Named RN.globalsTy)]))
310 :     val initFn = CL.D_Func(
311 :     [], CL.voidTy, RN.initGlobals, [],
312 :     CL.mkBlock[
313 :     globalsDecl,
314 :     CL.mkCall(RN.initGlobalsHelper, [CL.mkVar RN.globalsVarName])
315 :     ])
316 :     val initHelperFn = CL.D_Func(
317 :     [], CL.voidTy, RN.initGlobalsHelper,
318 :     [CL.PARAM([], globPtrTy, RN.globalsVarName)],
319 :     init)
320 :     val shutdownFn = CL.D_Func(
321 :     [], CL.voidTy, RN.shutdown,
322 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
323 :     CL.S_Block[])
324 :     in
325 :     topDecls := shutdownFn :: initFn :: initHelperFn :: !topDecls
326 :     end
327 :    
328 :     (* create and register the initially function for a program *)
329 :     fun initially {
330 : jhr 1705 prog = Prog{strands, initially, numDims, ...},
331 : jhr 1671 isArray : bool,
332 :     iterPrefix : stm list,
333 :     iters : (var * exp * exp) list,
334 :     createPrefix : stm list,
335 :     strand : Atom.atom,
336 :     args : exp list
337 :     } = let
338 :     val name = Atom.toString strand
339 :     val nDims = List.length iters
340 :     val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
341 :     fun mapi f xs = let
342 :     fun mapf (_, []) = []
343 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
344 :     in
345 :     mapf (0, xs)
346 :     end
347 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
348 :     val sizeInit = mapi
349 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
350 :     (i, CL.I_Exp(CL.mkBinOp(hi, CL.#-, lo) #+# CL.mkIntTy(1, ty)))
351 :     ) iters
352 :     (* code to allocate the world and initial strands *)
353 :     val wrld = "wrld"
354 :     val allocCode = [
355 :     CL.mkComment["allocate initial block of strands"],
356 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
357 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
358 :     CL.mkDecl(worldTy, wrld,
359 :     SOME(CL.I_Exp(CL.mkApply(N.allocInitially, [
360 :     CL.mkVar "ProgramName",
361 :     CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)),
362 :     CL.mkBool isArray,
363 :     CL.mkIntTy(IntInf.fromInt nDims, CL.int32),
364 :     CL.mkVar "base",
365 :     CL.mkVar "size"
366 :     ]))))
367 :     ]
368 :     (* create the loop nest for the initially iterations *)
369 :     val indexVar = "ix"
370 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
371 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
372 :     CL.mkDecl(strandTy, "sp",
373 :     SOME(CL.I_Exp(
374 :     CL.mkCast(strandTy,
375 :     CL.mkApply(N.inState, [CL.mkVar "wrld", CL.mkVar indexVar]))))),
376 :     CL.mkCall(N.strandInit name, CL.mkVar "sp" :: args),
377 :     CL.mkAssign(CL.mkVar indexVar, CL.mkVar indexVar #+# CL.mkIntTy(1, CL.uint32))
378 :     ])
379 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
380 :     val body = mkLoopNest iters
381 :     in
382 :     CL.mkFor(
383 :     [(ty, param, lo)],
384 :     CL.mkBinOp(CL.mkVar param, CL.#<=, hi),
385 :     [CL.mkPostOp(CL.mkVar param, CL.^++)],
386 :     body)
387 :     end
388 :     val iterCode = [
389 :     CL.mkComment["initially"],
390 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.mkIntTy(0, CL.uint32)))),
391 :     mkLoopNest iters
392 :     ]
393 :     val body = CL.mkBlock(
394 :     iterPrefix @
395 :     allocCode @
396 :     iterCode @
397 :     [CL.mkReturn(SOME(CL.mkVar "wrld"))])
398 :     val initFn = CL.D_Func([], worldTy, N.initially, [], body)
399 :     in
400 :     numDims := nDims;
401 :     initially := initFn
402 :     end
403 :    
404 :    
405 :     (***** OUTPUT *****)
406 :    
407 :     fun genStrandPrint (Strand{name, tyName, state, output, code, ...}) = let
408 :     (* the print function *)
409 :     val prFnName = concat[name, "Print"]
410 :     val prFn = let
411 :     val params = [
412 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
413 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "self")
414 :     ]
415 :     val (ty, x) = output
416 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
417 :     val prArgs = (case ty
418 :     of Ty.IntTy => [CL.mkStr(!N.gIntFormat ^ "\n"), outState]
419 :     | Ty.SeqTy(Ty.IntTy, d) => let
420 :     fun sel i = CL.mkApply(
421 :     "VSUB",
422 :     [outState, CL.mkInt(IntInf.fromInt i)])
423 :     val fmt = CL.mkStr(
424 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
425 :     ^ "\n")
426 :     val args = List.tabulate (d, sel)
427 :     in
428 :     fmt :: args
429 :     end
430 :     | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
431 :     | Ty.TensorTy[d] => let
432 :     fun sel i = CL.mkApply(
433 :     "VSUB",
434 :     [outState, CL.mkInt(IntInf.fromInt i)])
435 :     val fmt = CL.mkStr(
436 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
437 :     ^ "\n")
438 :     val args = List.tabulate (d, sel)
439 :     in
440 :     fmt :: args
441 :     end
442 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
443 :     (* end case *))
444 :     in
445 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
446 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
447 :     end
448 :     in
449 :     prFn
450 :     end
451 :    
452 : jhr 1705 fun genStrandTyDef (targetTy,Strand{state,...}, tyName) = (case state
453 :     of [] => CL.D_Comment(["No Strand Defintiion Included"])
454 :     | _ => CL.D_StructDef(revmap (fn x => (targetTy x, #var x)) state, tyName)
455 :     (* end case *))
456 : jhr 1671
457 :     (* generates the globals buffers and arguments function *)
458 :     fun genConvertShadowTypes (Strand{name, tyName, state,...}) = let
459 : jhr 1705 (* Declare opencl setup objects *)
460 : jhr 1671 val errVar = "err"
461 :     val params = [
462 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
463 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "selfIn")
464 :     ]
465 :     val body = List.map (fn (x:mirror_var) => #hToS x) state
466 :     in
467 :     CL.D_Func([], CL.voidTy, RN.strandConvertName name, params, CL.mkBlock body)
468 :     end
469 :    
470 :     (* generates the opencl buffers for the image data *)
471 :     fun getGlobalDataBuffers (globals, imgGlobals, contextVar, errVar) = let
472 :     val globalBuffErr = "error creating OpenCL global buffer\n"
473 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
474 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
475 :     CL.mkCall("exit",[CL.mkInt 1])]))
476 :     val shadowTypeDecl =
477 :     CL.mkDecl(CL.T_Named(RN.shadowGlobalsTy), RN.shadowGlaobalsName, NONE)
478 :     val globalToShadowStms = List.map (fn (x:mirror_var) => #hToS x) globals
479 :     val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
480 :     val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
481 :     CL.mkApply("clCreateBuffer", [
482 :     CL.mkVar contextVar,
483 :     CL.mkBinOp(CL.mkVar "CL_MEM_READ_ONLY", CL.#|, CL.mkVar "CL_MEM_COPY_HOST_PTR"),
484 :     CL.mkSizeof(CL.T_Named RN.shadowGlobalsTy),
485 :     CL.mkUnOp(CL.%&,CL.mkVar RN.shadowGlaobalsName),
486 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
487 :     ]))
488 :     fun genDataBuffers ([],_,_,_) = []
489 :     | genDataBuffers ((var,nDims)::globals, contextVar, errVar,errFn) = let
490 :     val hostVar = CL.mkIndirect(CL.mkVar RN.globalsVarName, var)
491 :     val size = CL.mkIndirect(hostVar, "dataSzb")
492 :     in
493 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE) ::
494 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var),
495 :     CL.mkApply("clCreateBuffer", [
496 :     CL.mkVar contextVar,
497 :     CL.mkVar "CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR",
498 :     size,
499 :     CL.mkIndirect(hostVar, "data"),
500 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
501 :     ])) ::
502 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " global buffer\n"]) ::
503 :     genDataBuffers(globals,contextVar,errVar,errFn)
504 :     end
505 :     in
506 :     [shadowTypeDecl] @ globalToShadowStms
507 :     @ [globalBufferDecl, globalBuffer,errorFn(globalBuffErr)]
508 :     @ genDataBuffers(imgGlobals,contextVar,errVar,errorFn)
509 :     end
510 :    
511 :     (* generates the kernel arguments for the image data *)
512 :     fun genGlobalArguments (globals, count, kernelVar, errVar) = let
513 :     val globalArgErr = "error creating OpenCL global argument\n"
514 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
515 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
516 :     CL.mkCall("exit",[CL.mkInt 1])]))
517 :     val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.&=,
518 :     CL.mkApply("clSetKernelArg",
519 :     [CL.mkVar kernelVar,
520 :     CL.mkPostOp(CL.mkVar count, CL.^++),
521 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
522 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
523 :     fun genDataArguments ([],_,_,_,_) = []
524 :     | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar,errFn) =
525 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.$=,
526 :     CL.mkApply("clSetKernelArg",
527 :     [CL.mkVar kernelVar,
528 :     CL.mkPostOp(CL.mkVar count, CL.^++),
529 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
530 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
531 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " argument\n"]) ::
532 :     genDataArguments (globals,count,kernelVar,errVar,errFn)
533 :     in
534 :     globalArgument :: errorFn globalArgErr ::
535 :     genDataArguments(globals, count, kernelVar, errVar,errorFn)
536 :     end
537 :    
538 :     (* generates the globals buffers and arguments function *)
539 :     fun genGlobalBuffersArgs (globals,imgGlobals) = let
540 :     (* Delcare opencl setup objects *)
541 :     val errVar = "err"
542 :     val params = [
543 :     CL.PARAM([],CL.T_Named("cl_context"), "context"),
544 :     CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
545 :     CL.PARAM([],CL.T_Named("cl_command_queue"), "cmdQ"),
546 :     CL.PARAM([],CL.T_Named("int"), "argStart")
547 :     ]
548 :     val body = (case globals
549 :     of [] => [CL.mkReturn(NONE)]
550 :     | _ => let
551 :     val clGlobalBuffers =
552 :     getGlobalDataBuffers(globals, !imgGlobals, "context", errVar)
553 :     val clGlobalArguments =
554 :     genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
555 :     in
556 :     (* Body: put all the statments together *)
557 :     CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt 0)))
558 :     :: clGlobalBuffers @ clGlobalArguments
559 :     end
560 :     (*end of case*))
561 :     in
562 :     CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
563 :     end
564 :    
565 :     (* generate the global image meta-data and data parameters *)
566 :     fun genKeneralGlobalParams ((name,tyname)::[],line) =
567 :     concat[line, "__global void *", RN.addBufferSuffixData name]
568 :     | genKeneralGlobalParams ([],line) = line
569 :     | genKeneralGlobalParams ((name,tyname)::rest, line) =
570 :     genKeneralGlobalParams(rest, concat[line, "__global void *", RN.addBufferSuffixData name, ",\n"])
571 :    
572 :     fun genUpdateMethod (Strand{name, tyName, state,...}, globals, imgGlobals) = let
573 :     val imageDataStms = List.map
574 :     (fn (x,_) => concat[
575 :     RN.globalImageDataName, ".", RN.imageDataName x, " = ",
576 :     RN.addBufferSuffixData x, ";","\n"
577 :     ])
578 :     (!imgGlobals)
579 :     fun select ([], a, _) = a
580 :     | select (_, _, b) = b
581 :     val placeHolders = [
582 :     (RN.place_holders, tyName),
583 :     (RN.p_addDatPtr, select (!imgGlobals, "", ",")),
584 :     (RN.p_addGlobals, select (!globals, "", ",")),
585 :     (RN.p_globals, select (!globals, "", "__global Diderot_Globals_t *diderotGlobals")),
586 :     (RN.p_globalVar, select (!globals, "0", RN.globalsVarName)),
587 :     (RN.p_dataVar, select (!globals, "0", RN.globalImageDataName)),
588 :     (RN.p_dataPtr, genKeneralGlobalParams (!imgGlobals, "")),
589 :     (RN.p_dataAssign, select (!imgGlobals, "",
590 :     String.concat("Diderot_data_ptr_t diderotDataPtrs;\n" :: imageDataStms)))
591 :     ]
592 :     in
593 :     CL.verbatim [CLUpdateFrag.text] placeHolders
594 :     end
595 :    
596 :     fun genStrandCopy(Strand{tyName,name,state,...}) = let
597 :     val params = [
598 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
599 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut")
600 :     ]
601 :     val assignStms = List.rev(
602 :     List.map
603 :     (fn x => CL.mkAssign(lvalueSV(#var x), rvalueSV(#var x)))
604 :     state)
605 :     in
606 :     CL.D_Func([""], CL.voidTy, RN.strandCopy, params,CL.mkBlock(assignStms))
607 :     end
608 :    
609 :     (* generate a global structure type definition from the list of globals *)
610 :     fun genGlobalStruct (_, [], _) = CL.D_Comment(["No Global Definition"])
611 :     | genGlobalStruct (targetTy, globals, tyName) = let
612 :     val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
613 :     in
614 :     CL.D_StructDef(globs, tyName)
615 :     end
616 :    
617 :     (* generate a global structure type definition from the image data of the image globals *)
618 :     fun genImageDataStruct ([], _) = CL.D_Comment(["No Image Data Ptrs Definition"])
619 :     | genImageDataStruct (imgGlobals, tyName) = let
620 :     val globs = List.map
621 :     (fn (x, _) => (globalPtr CL.voidTy, RN.imageDataName x))
622 :     imgGlobals
623 :     in
624 :     CL.D_StructDef(globs, tyName)
625 :     end
626 :    
627 :     fun genGlobals (declFn, targetTy, globals) = let
628 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
629 :     in
630 :     List.app doVar globals
631 :     end
632 :    
633 :     fun genOutputFun(Strand{name, output,tyName, state, code,...}) = let
634 :     (* the output function *)
635 :     val outFnName = concat[name, "_Output"]
636 :     val outFun = let
637 :     val params = [
638 :     CL.PARAM([], CL.T_Ptr CL.voidTy, "outS"),
639 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
640 :     ]
641 :     (* the type and access expression for the strand's output variable *)
642 :     val (outTy, outState) = (#1 output, CL.mkIndirect(CL.mkVar "self", #2 output))
643 :     val outState = CL.mkUnOp(CL.%&, outState)
644 :     in
645 :     CL.D_Func(["static"], CL.voidTy, outFnName, params,
646 :     CL.mkCall("memcpy", [CL.mkVar "outS", outState, CL.mkSizeof(shadowTy outTy)] ))
647 :     end
648 :     in
649 :     outFun
650 :     end
651 :    
652 :     fun genStrandDesc (outFn,Strand{name, output,tyName, state, code,...}) = let
653 :     (* the output function *)
654 :     val outFnName = concat[name, "_Output"]
655 :     (* the strand's descriptor object *)
656 :     val descI = let
657 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
658 :     val (outTy, _) = output
659 :     in
660 :     CL.I_Struct[
661 :     ("name", CL.I_Exp(CL.mkStr name)),
662 :     ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandTy name)))),
663 :     ("shadowStrandSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandShadowTy (RN.strandTy name))))),
664 :     (* FIXME: we may need to add a shadowOutputSzb field too for OpenCL *)
665 :     ("outputSzb", CL.I_Exp(CL.mkSizeof(shadowTy outTy))),
666 :     ("nrrdType", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdType outTy))),
667 :     ("nrrdSzb", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdSize outTy))),
668 :     ("update", fnPtr("update_method_t", "0")),
669 :     ("strandCopy", fnPtr("convert_method_t", RN.strandConvertName name)),
670 :     ("print", fnPtr("print_method_t", RN.strandPrintName name)),
671 :     ("output", fnPtr("output_method_t", outFnName)) (* FIXME *)
672 :     ]
673 :     end
674 :     val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
675 :     in
676 :     desc
677 :     end
678 :    
679 :     (* generate the table of strand descriptors *)
680 :     fun genStrandTable (declFn, strands) = let
681 :     val nStrands = length strands
682 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)))
683 :     fun genInits (_, []) = []
684 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
685 :     in
686 :     declFn (CL.D_Var([], CL.int32, N.numStrands,
687 :     SOME(CL.I_Exp(CL.mkIntTy(IntInf.fromInt nStrands, CL.int32)))));
688 :     declFn (CL.D_Var([],
689 :     CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
690 :     N.strands,
691 :     SOME(CL.I_Array(genInits (0, strands)))))
692 :     end
693 :    
694 :     fun genSrc (baseName, prog) = let
695 :     val Prog{
696 : jhr 1713 tgt,
697 : jhr 1705 globals, topDecls, strands, initially,
698 : jhr 1671 imgGlobals, numDims,outFn, ...
699 :     } = prog
700 :     val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
701 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
702 :     val clOutS = TextIO.openOut clFileName
703 :     val cOutS = TextIO.openOut cFileName
704 :     val clppStrm = PrintAsCL.new clOutS
705 :     val cppStrm = PrintAsC.new cOutS
706 :     fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
707 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
708 :     val strands = AtomTable.listItems strands
709 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
710 :     in
711 :     (* Generate the OpenCL file *)
712 :     (* Retrieve the header information *)
713 :     clppDecl (CL.verbatim [HF.text] [
714 :     ("OUTFILE", clFileName),
715 :     ("SRCFILE", OS.Path.joinBaseExt{base=baseName, ext=SOME "diderot"}),
716 : jhr 1713 ("DIDEROT_FLOAT_PRECISION", TargetUtil.floatPrecisionDef tgt),
717 :     ("DIDEROT_INT_PRECISION", TargetUtil.intPrecisionDef tgt)
718 : jhr 1671 ]);
719 :     (* if there are no globals, then define a dummy type *)
720 :     if List.null(!globals)
721 :     then clppDecl (CL.D_Verbatim["typedef void ", RN.globalsTy, ";\n"])
722 :     else ();
723 :     (* if there are no images, then define a dummy type *)
724 :     if List.null(!imgGlobals)
725 :     then clppDecl (CL.D_Verbatim["typedef void * ", RN.imageDataType, ";\n"])
726 :     else ();
727 :     (* Retrieve the scheduler kernels and functions *)
728 :     clppDecl (CL.D_Verbatim[SF.text]);
729 :     clppDecl (CL.D_Verbatim[CLEigen2x2Frag.text]);
730 :     clppDecl (CL.D_Verbatim[CLEigen3x3Frag.text]);
731 :     clppDecl (genGlobalStruct (#gpuTy, !globals, RN.globalsTy));
732 :     clppDecl (genImageDataStruct(!imgGlobals, RN.imageDataType));
733 :     clppDecl (genStrandTyDef(#gpuTy, strand, tyName));
734 :     List.app clppDecl (!code);
735 :     clppDecl (genStrandCopy strand);
736 :     clppDecl (genUpdateMethod(strand, globals, imgGlobals));
737 :     (* Generate the Host C file *)
738 :     cppDecl (CL.D_Verbatim[
739 : jhr 1713 concat["#define " ^ TargetUtil.floatPrecisionDef tgt, "\n"],
740 :     concat["#define " ^ TargetUtil.intPrecisionDef tgt, "\n"],
741 :     concat["#define " ^ TargetUtil.targetDef tgt, "\n"],
742 : jhr 1671 "#include \"Diderot/diderot.h\"\n"
743 : jhr 1705 ]);
744 :     case !globals
745 :     of [] => cppDecl (CL.D_Verbatim[concat["typedef void ", RN.globalsTy, ";\n"] ])
746 :     | _ => ()
747 :     (* end case *);
748 : jhr 1671 cppDecl (CL.D_Var(["static"], CL.charPtr, "ProgramName",
749 : jhr 1713 SOME(CL.I_Exp(CL.mkStr(#srcFile tgt)))));
750 : jhr 1671 cppDecl (genGlobalStruct (#hostTy, !globals, RN.globalsTy));
751 :     cppDecl (genGlobalStruct (#shadowTy, !globals, RN.shadowGlobalsTy));
752 :     (* FIXME: does this really need to be a global? *)
753 :     cppDecl (CL.D_Var(["static"], globPtrTy, RN.globalsVarName, NONE));
754 :     cppDecl (genStrandTyDef (#hostTy, strand, tyName));
755 :     cppDecl (genStrandTyDef (#shadowTy, strand, RN.strandShadowTy tyName));
756 :     cppDecl (genConvertShadowTypes strand);
757 :     cppDecl (!init_code);
758 :     cppDecl (genStrandPrint strand);
759 :     cppDecl (genOutputFun strand);
760 :     List.app cppDecl (List.rev (!topDecls));
761 :     cppDecl (genGlobalBuffersArgs (!globals,imgGlobals));
762 :     List.app (fn strand => cppDecl (genStrandDesc (outFn,strand))) strands;
763 :     genStrandTable (cppDecl, strands);
764 :     cppDecl (!initially);
765 :     PrintAsC.close cppStrm;
766 :     PrintAsCL.close clppStrm;
767 :     TextIO.closeOut cOutS;
768 :     TextIO.closeOut clOutS
769 :     end
770 :    
771 :     (* output the code to the filesystem. The string is the basename of the source file *)
772 : jhr 1705 fun generate (prog as Prog{tgt, ...}) = let
773 :     val {outDir, outBase, exec, double, parallel, debug, ...} = tgt
774 : jhr 1671 fun condCons (true, x, xs) = x::xs
775 :     | condCons (false, _, xs) = xs
776 :     (* generate the C compiler flags *)
777 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
778 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
779 :     val cflags = if debug
780 :     then #debug Paths.cflags :: cflags
781 :     else #ndebug Paths.cflags :: cflags
782 :     val cflags = #base Paths.cflags :: cflags
783 :     (* generate the loader flags *)
784 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
785 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
786 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
787 : jhr 1706 val rtLib = TargetUtil.runtimeName tgt
788 : jhr 1671 val ldOpts = rtLib :: extraLibs
789 : jhr 1705 val basename = OS.Path.joinDirFile{dir=outDir, file=outBase}
790 : jhr 1671 in
791 :     genSrc (basename, prog);
792 :     RunCC.compile (basename, cflags);
793 : jhr 1714 RunCC.linkExec (basename, ldOpts)
794 : jhr 1671 end
795 :    
796 :     end (* Program *)
797 :    
798 :     (* strands *)
799 :     structure Strand =
800 :     struct
801 :    
802 :     fun define (Prog{strands, ...}, strandId, state) = let
803 :     val name = Atom.toString strandId
804 :     (* the output state variable *)
805 :     val outputVar = (case List.filter IL.StateVar.isOutput state
806 :     of [] => raise Fail("no output specified for strand " ^ name)
807 :     | [x] => (IL.StateVar.ty x, IL.StateVar.name x)
808 :     | _ => raise Fail("multiple outputs in " ^ name)
809 :     (* end case *))
810 :     (* the state variables *)
811 :     val state = let
812 :     fun cvt x = Var.mirror (IL.StateVar.ty x, IL.StateVar.name x, STRAND_SHADOW)
813 :     in
814 :     List.map cvt state
815 :     end
816 :     val strand = Strand{
817 :     name = name,
818 :     tyName = RN.strandTy name,
819 :     state = state,
820 :     output = outputVar,
821 :     code = ref [],
822 :     init_code = ref (CL.D_Comment(["no init code"]))
823 :     }
824 :     in
825 :     AtomTable.insert strands (strandId, strand);
826 :     strand
827 :     end
828 :    
829 :     (* return the strand with the given name *)
830 :     fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
831 :    
832 :     (* register the strand-state initialization code. The variables are the strand
833 :     * parameters.
834 :     *)
835 :     fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
836 :     val fName = RN.strandInit name
837 :     val params =
838 :     clParam ("",CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
839 :     List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
840 :     val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
841 :     in
842 :     init_code := initFn
843 :     end
844 :    
845 :     (* register a strand method *)
846 :     fun method (Strand{name, tyName, code,...}, methName, body) = let
847 :     val params = [
848 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfIn"),
849 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfOut"),
850 :     globalParam (CL.T_Ptr(CL.T_Named (RN.globalsTy)), RN.globalsVarName),
851 :     CL.PARAM([],CL.T_Named(RN.imageDataType),RN.globalImageDataName)
852 :     ]
853 :     val (fName,resTy) = (case methName
854 :     of StrandUtil.Update => (RN.strandUpdate,CL.T_Named "StrandStatus_t")
855 :     | StrandUtil.Stabilize => (name ^ StrandUtil.nameToString methName, CL.voidTy)
856 :     (* end case *))
857 :     val methFn = CL.D_Func([], resTy, fName, params, body)
858 :     in
859 :     code := methFn :: !code
860 :     end
861 :    
862 :     end
863 :    
864 :     end
865 :    
866 :     structure CLBackEnd = CodeGenFn(CLTarget)

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