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 1853 - (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 : jhr 1853 structure N = CNames
16 : jhr 1671 structure ToCL = TreeToCL
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 : jhr 1793 | Ty.ImageTy info => CL.T_Named(RN.shadowImageTy(ImageInfo.dim info))
43 : jhr 1671 | _ => 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 : jhr 1793 | Ty.ImageTy info => CL.mkCall(RN.shadowImageFunc(ImageInfo.dim info), [
59 : jhr 1671 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 : jhr 1853 fun clParam spc (ty, x) = CL.PARAM([spc], ty, x)
92 :     val globalParam = clParam "__global"
93 :     val constantParam = clParam "__constant"
94 :     val localParam = clParam "__local"
95 :     val privateParam = clParam "__private"
96 : jhr 1671
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 : jhr 1793 fun isImgGlobal (Ty.ImageTy info, name) =
245 :     imgGlobals := (name, ImageInfo.dim info) :: !imgGlobals
246 : jhr 1671 | 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 : jhr 1853
279 :     (* strands *)
280 :     structure Strand =
281 :     struct
282 :    
283 :     fun define (Prog{strands, ...}, strandId, state) = let
284 :     val name = Atom.toString strandId
285 :     (* the output state variable *)
286 :     val outputVar = (case List.filter IL.StateVar.isOutput state
287 :     of [] => raise Fail("no output specified for strand " ^ name)
288 :     | [x] => (IL.StateVar.ty x, IL.StateVar.name x)
289 :     | _ => raise Fail("multiple outputs in " ^ name)
290 :     (* end case *))
291 :     (* the state variables *)
292 :     val state = let
293 :     fun cvt x = Var.mirror (IL.StateVar.ty x, IL.StateVar.name x, STRAND_SHADOW)
294 :     in
295 :     List.map cvt state
296 :     end
297 :     val strand = Strand{
298 :     name = name,
299 :     tyName = RN.strandTy name,
300 :     state = state,
301 :     output = outputVar,
302 :     code = ref [],
303 :     init_code = ref (CL.D_Comment(["no init code"]))
304 :     }
305 :     in
306 :     AtomTable.insert strands (strandId, strand);
307 :     strand
308 :     end
309 :    
310 :     (* return the strand with the given name *)
311 :     fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
312 :    
313 :     (* register the strand-state initialization code. The variables are the strand
314 :     * parameters.
315 :     *)
316 :     fun init (Strand{name, tyName, code, init_code, ...}, params, init) = let
317 :     val fName = RN.strandInit name
318 :     val params =
319 :     clParam "" (CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
320 :     List.map (fn (ToCL.V(ty, x)) => CL.PARAM([], ty, x)) params
321 :     val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
322 :     in
323 :     init_code := initFn
324 :     end
325 :    
326 :     (* register a strand method *)
327 :     fun method (Strand{name, tyName, code,...}, methName, body) = let
328 :     val params = [
329 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfIn"),
330 :     globalParam (CL.T_Ptr(CL.T_Named tyName), "selfOut"),
331 :     globalParam (CL.T_Ptr(CL.T_Named (RN.globalsTy)), RN.globalsVarName),
332 :     clParam "" (CL.T_Named(RN.imageDataType), RN.globalImageDataName)
333 :     ]
334 :     val (fName,resTy) = (case methName
335 :     of StrandUtil.Update => (RN.strandUpdate,CL.T_Named "StrandStatus_t")
336 :     | StrandUtil.Stabilize => (name ^ StrandUtil.nameToString methName, CL.voidTy)
337 :     (* end case *))
338 :     val methFn = CL.D_Func([], resTy, fName, params, body)
339 :     in
340 :     code := methFn :: !code
341 :     end
342 :    
343 :     end (* Strand *)
344 :    
345 : jhr 1671 (* programs *)
346 :     structure Program =
347 :     struct
348 : jhr 1705 fun new (tgt : TargetUtil.target_desc) = (
349 :     RN.initTargetSpec (#double tgt);
350 :     CNames.initTargetSpec {double = #double tgt, long = false};
351 : jhr 1671 Prog{
352 : jhr 1705 tgt = tgt,
353 : jhr 1671 globals = ref [],
354 :     topDecls = ref [],
355 :     strands = AtomTable.mkTable (16, Fail "strand table"),
356 :     initially = ref(CL.D_Comment["missing initially"]),
357 :     numDims = ref 0,
358 :     imgGlobals = ref[],
359 :     prFn = ref(CL.D_Comment(["No Print Function"])),
360 :     outFn = ref(CL.D_Comment(["No Output Function"]))
361 :     })
362 :    
363 :     (* register the code that is used to register command-line options for input variables *)
364 : jhr 1803 fun inputs (Prog{topDecls, ...}, env, blk) = let
365 : jhr 1671 val inputsFn = CL.D_Func(
366 :     [], CL.voidTy, RN.registerOpts,
367 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
368 : jhr 1803 Tr.block (env, blk))
369 : jhr 1671 in
370 :     topDecls := inputsFn :: !topDecls
371 :     end
372 :    
373 :     (* register the global initialization part of a program *)
374 :     fun init (Prog{topDecls, ...}, init) = let
375 :     val globalsDecl = CL.mkAssign(CL.mkVar RN.globalsVarName,
376 :     CL.mkApply("malloc", [CL.mkSizeof(CL.T_Named RN.globalsTy)]))
377 :     val initFn = CL.D_Func(
378 :     [], CL.voidTy, RN.initGlobals, [],
379 :     CL.mkBlock[
380 :     globalsDecl,
381 :     CL.mkCall(RN.initGlobalsHelper, [CL.mkVar RN.globalsVarName])
382 :     ])
383 :     val initHelperFn = CL.D_Func(
384 :     [], CL.voidTy, RN.initGlobalsHelper,
385 :     [CL.PARAM([], globPtrTy, RN.globalsVarName)],
386 :     init)
387 :     val shutdownFn = CL.D_Func(
388 :     [], CL.voidTy, RN.shutdown,
389 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
390 :     CL.S_Block[])
391 :     in
392 :     topDecls := shutdownFn :: initFn :: initHelperFn :: !topDecls
393 :     end
394 :    
395 :     (* create and register the initially function for a program *)
396 :     fun initially {
397 : jhr 1718 prog = Prog{tgt, strands, initially, numDims, ...},
398 : jhr 1671 isArray : bool,
399 :     iterPrefix : stm list,
400 :     iters : (var * exp * exp) list,
401 :     createPrefix : stm list,
402 :     strand : Atom.atom,
403 :     args : exp list
404 :     } = let
405 :     val name = Atom.toString strand
406 :     val nDims = List.length iters
407 : jhr 1718 val worldTy = CL.T_Ptr(CL.T_Named(N.worldTy tgt))
408 : jhr 1671 fun mapi f xs = let
409 :     fun mapf (_, []) = []
410 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
411 :     in
412 :     mapf (0, xs)
413 :     end
414 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
415 :     val sizeInit = mapi
416 :     (fn (i, (CL.V(ty, _), lo, hi)) =>
417 :     (i, CL.I_Exp(CL.mkBinOp(hi, CL.#-, lo) #+# CL.mkIntTy(1, ty)))
418 :     ) iters
419 :     (* code to allocate the world and initial strands *)
420 :     val wrld = "wrld"
421 :     val allocCode = [
422 :     CL.mkComment["allocate initial block of strands"],
423 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
424 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
425 :     CL.mkDecl(worldTy, wrld,
426 :     SOME(CL.I_Exp(CL.mkApply(N.allocInitially, [
427 :     CL.mkVar "ProgramName",
428 :     CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)),
429 :     CL.mkBool isArray,
430 :     CL.mkIntTy(IntInf.fromInt nDims, CL.int32),
431 :     CL.mkVar "base",
432 :     CL.mkVar "size"
433 :     ]))))
434 :     ]
435 :     (* create the loop nest for the initially iterations *)
436 :     val indexVar = "ix"
437 :     val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
438 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
439 :     CL.mkDecl(strandTy, "sp",
440 :     SOME(CL.I_Exp(
441 :     CL.mkCast(strandTy,
442 :     CL.mkApply(N.inState, [CL.mkVar "wrld", CL.mkVar indexVar]))))),
443 :     CL.mkCall(N.strandInit name, CL.mkVar "sp" :: args),
444 :     CL.mkAssign(CL.mkVar indexVar, CL.mkVar indexVar #+# CL.mkIntTy(1, CL.uint32))
445 :     ])
446 :     | mkLoopNest ((CL.V(ty, param), lo, hi)::iters) = let
447 :     val body = mkLoopNest iters
448 :     in
449 :     CL.mkFor(
450 :     [(ty, param, lo)],
451 :     CL.mkBinOp(CL.mkVar param, CL.#<=, hi),
452 :     [CL.mkPostOp(CL.mkVar param, CL.^++)],
453 :     body)
454 :     end
455 :     val iterCode = [
456 :     CL.mkComment["initially"],
457 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.mkIntTy(0, CL.uint32)))),
458 :     mkLoopNest iters
459 :     ]
460 :     val body = CL.mkBlock(
461 :     iterPrefix @
462 :     allocCode @
463 :     iterCode @
464 :     [CL.mkReturn(SOME(CL.mkVar "wrld"))])
465 : jhr 1718 val initFn = CL.D_Func([], worldTy, N.initially tgt, [], body)
466 : jhr 1671 in
467 :     numDims := nDims;
468 :     initially := initFn
469 :     end
470 :    
471 :    
472 :     (***** OUTPUT *****)
473 :    
474 :     fun genStrandPrint (Strand{name, tyName, state, output, code, ...}) = let
475 :     (* the print function *)
476 :     val prFnName = concat[name, "Print"]
477 :     val prFn = let
478 :     val params = [
479 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
480 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "self")
481 :     ]
482 :     val (ty, x) = output
483 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
484 :     val prArgs = (case ty
485 :     of Ty.IntTy => [CL.mkStr(!N.gIntFormat ^ "\n"), outState]
486 :     | Ty.SeqTy(Ty.IntTy, d) => let
487 :     fun sel i = CL.mkApply(
488 :     "VSUB",
489 :     [outState, CL.mkInt(IntInf.fromInt i)])
490 :     val fmt = CL.mkStr(
491 :     String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
492 :     ^ "\n")
493 :     val args = List.tabulate (d, sel)
494 :     in
495 :     fmt :: args
496 :     end
497 :     | Ty.TensorTy[] => [CL.mkStr "%f\n", outState]
498 :     | Ty.TensorTy[d] => let
499 :     fun sel i = CL.mkApply(
500 :     "VSUB",
501 :     [outState, CL.mkInt(IntInf.fromInt i)])
502 :     val fmt = CL.mkStr(
503 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
504 :     ^ "\n")
505 :     val args = List.tabulate (d, sel)
506 :     in
507 :     fmt :: args
508 :     end
509 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
510 :     (* end case *))
511 :     in
512 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
513 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
514 :     end
515 :     in
516 :     prFn
517 :     end
518 :    
519 : jhr 1705 fun genStrandTyDef (targetTy,Strand{state,...}, tyName) = (case state
520 :     of [] => CL.D_Comment(["No Strand Defintiion Included"])
521 : jhr 1716 | _ => CL.D_StructDef(
522 :     NONE,
523 :     revmap (fn x => (targetTy x, #var x)) state,
524 :     SOME tyName)
525 : jhr 1705 (* end case *))
526 : jhr 1671
527 :     (* generates the globals buffers and arguments function *)
528 :     fun genConvertShadowTypes (Strand{name, tyName, state,...}) = let
529 : jhr 1705 (* Declare opencl setup objects *)
530 : jhr 1671 val errVar = "err"
531 :     val params = [
532 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut"),
533 :     CL.PARAM([], CL.T_Ptr(CL.T_Named(RN.strandShadowTy tyName)), "selfIn")
534 :     ]
535 :     val body = List.map (fn (x:mirror_var) => #hToS x) state
536 :     in
537 :     CL.D_Func([], CL.voidTy, RN.strandConvertName name, params, CL.mkBlock body)
538 :     end
539 :    
540 :     (* generates the opencl buffers for the image data *)
541 :     fun getGlobalDataBuffers (globals, imgGlobals, contextVar, errVar) = let
542 :     val globalBuffErr = "error creating OpenCL global buffer\n"
543 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
544 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
545 :     CL.mkCall("exit",[CL.mkInt 1])]))
546 :     val shadowTypeDecl =
547 :     CL.mkDecl(CL.T_Named(RN.shadowGlobalsTy), RN.shadowGlaobalsName, NONE)
548 :     val globalToShadowStms = List.map (fn (x:mirror_var) => #hToS x) globals
549 :     val globalBufferDecl = CL.mkDecl(clMemoryTy,concat[RN.globalsVarName,"_cl"],NONE)
550 :     val globalBuffer = CL.mkAssign(CL.mkVar(concat[RN.globalsVarName,"_cl"]),
551 :     CL.mkApply("clCreateBuffer", [
552 :     CL.mkVar contextVar,
553 :     CL.mkBinOp(CL.mkVar "CL_MEM_READ_ONLY", CL.#|, CL.mkVar "CL_MEM_COPY_HOST_PTR"),
554 :     CL.mkSizeof(CL.T_Named RN.shadowGlobalsTy),
555 :     CL.mkUnOp(CL.%&,CL.mkVar RN.shadowGlaobalsName),
556 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
557 :     ]))
558 :     fun genDataBuffers ([],_,_,_) = []
559 :     | genDataBuffers ((var,nDims)::globals, contextVar, errVar,errFn) = let
560 :     val hostVar = CL.mkIndirect(CL.mkVar RN.globalsVarName, var)
561 :     val size = CL.mkIndirect(hostVar, "dataSzb")
562 :     in
563 :     CL.mkDecl(clMemoryTy, RN.addBufferSuffixData var ,NONE) ::
564 :     CL.mkAssign(CL.mkVar(RN.addBufferSuffixData var),
565 :     CL.mkApply("clCreateBuffer", [
566 :     CL.mkVar contextVar,
567 :     CL.mkVar "CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR",
568 :     size,
569 :     CL.mkIndirect(hostVar, "data"),
570 :     CL.mkUnOp(CL.%&,CL.mkVar errVar)
571 :     ])) ::
572 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " global buffer\n"]) ::
573 :     genDataBuffers(globals,contextVar,errVar,errFn)
574 :     end
575 :     in
576 :     [shadowTypeDecl] @ globalToShadowStms
577 :     @ [globalBufferDecl, globalBuffer,errorFn(globalBuffErr)]
578 :     @ genDataBuffers(imgGlobals,contextVar,errVar,errorFn)
579 :     end
580 :    
581 :     (* generates the kernel arguments for the image data *)
582 :     fun genGlobalArguments (globals, count, kernelVar, errVar) = let
583 :     val globalArgErr = "error creating OpenCL global argument\n"
584 :     fun errorFn msg = CL.mkIfThen(CL.mkBinOp(CL.mkVar errVar, CL.#!=, CL.mkVar "CL_SUCCESS"),
585 :     CL.mkBlock([CL.mkCall("fprintf",[CL.mkVar "stderr", CL.mkStr msg]),
586 :     CL.mkCall("exit",[CL.mkInt 1])]))
587 :     val globalArgument = CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.&=,
588 :     CL.mkApply("clSetKernelArg",
589 :     [CL.mkVar kernelVar,
590 :     CL.mkPostOp(CL.mkVar count, CL.^++),
591 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
592 :     CL.mkUnOp(CL.%&,CL.mkVar(concat[RN.globalsVarName,"_cl"]))])))
593 :     fun genDataArguments ([],_,_,_,_) = []
594 :     | genDataArguments ((var,nDims)::globals,count,kernelVar,errVar,errFn) =
595 :     CL.mkExpStm(CL.mkAssignOp(CL.mkVar errVar,CL.$=,
596 :     CL.mkApply("clSetKernelArg",
597 :     [CL.mkVar kernelVar,
598 :     CL.mkPostOp(CL.mkVar count, CL.^++),
599 :     CL.mkApply("sizeof",[CL.mkVar "cl_mem"]),
600 :     CL.mkUnOp(CL.%&,CL.mkVar(RN.addBufferSuffixData var))]))) ::
601 :     errFn(concat["error in creating ",RN.addBufferSuffixData var, " argument\n"]) ::
602 :     genDataArguments (globals,count,kernelVar,errVar,errFn)
603 :     in
604 :     globalArgument :: errorFn globalArgErr ::
605 :     genDataArguments(globals, count, kernelVar, errVar,errorFn)
606 :     end
607 :    
608 :     (* generates the globals buffers and arguments function *)
609 :     fun genGlobalBuffersArgs (globals,imgGlobals) = let
610 :     (* Delcare opencl setup objects *)
611 :     val errVar = "err"
612 :     val params = [
613 :     CL.PARAM([],CL.T_Named("cl_context"), "context"),
614 :     CL.PARAM([],CL.T_Named("cl_kernel"), "kernel"),
615 :     CL.PARAM([],CL.T_Named("cl_command_queue"), "cmdQ"),
616 :     CL.PARAM([],CL.T_Named("int"), "argStart")
617 :     ]
618 :     val body = (case globals
619 :     of [] => [CL.mkReturn(NONE)]
620 :     | _ => let
621 :     val clGlobalBuffers =
622 :     getGlobalDataBuffers(globals, !imgGlobals, "context", errVar)
623 :     val clGlobalArguments =
624 :     genGlobalArguments(!imgGlobals, "argStart", "kernel", errVar)
625 :     in
626 :     (* Body: put all the statments together *)
627 :     CL.mkDecl(clIntTy, errVar, SOME(CL.I_Exp(CL.mkInt 0)))
628 :     :: clGlobalBuffers @ clGlobalArguments
629 :     end
630 :     (*end of case*))
631 :     in
632 :     CL.D_Func([],CL.voidTy,RN.globalsSetupName,params,CL.mkBlock(body))
633 :     end
634 :    
635 :     (* generate the global image meta-data and data parameters *)
636 :     fun genKeneralGlobalParams ((name,tyname)::[],line) =
637 :     concat[line, "__global void *", RN.addBufferSuffixData name]
638 :     | genKeneralGlobalParams ([],line) = line
639 :     | genKeneralGlobalParams ((name,tyname)::rest, line) =
640 :     genKeneralGlobalParams(rest, concat[line, "__global void *", RN.addBufferSuffixData name, ",\n"])
641 :    
642 :     fun genUpdateMethod (Strand{name, tyName, state,...}, globals, imgGlobals) = let
643 :     val imageDataStms = List.map
644 :     (fn (x,_) => concat[
645 :     RN.globalImageDataName, ".", RN.imageDataName x, " = ",
646 :     RN.addBufferSuffixData x, ";","\n"
647 :     ])
648 :     (!imgGlobals)
649 :     fun select ([], a, _) = a
650 :     | select (_, _, b) = b
651 :     val placeHolders = [
652 :     (RN.place_holders, tyName),
653 :     (RN.p_addDatPtr, select (!imgGlobals, "", ",")),
654 :     (RN.p_addGlobals, select (!globals, "", ",")),
655 :     (RN.p_globals, select (!globals, "", "__global Diderot_Globals_t *diderotGlobals")),
656 :     (RN.p_globalVar, select (!globals, "0", RN.globalsVarName)),
657 :     (RN.p_dataVar, select (!globals, "0", RN.globalImageDataName)),
658 :     (RN.p_dataPtr, genKeneralGlobalParams (!imgGlobals, "")),
659 :     (RN.p_dataAssign, select (!imgGlobals, "",
660 :     String.concat("Diderot_data_ptr_t diderotDataPtrs;\n" :: imageDataStms)))
661 :     ]
662 :     in
663 :     CL.verbatim [CLUpdateFrag.text] placeHolders
664 :     end
665 :    
666 :     fun genStrandCopy(Strand{tyName,name,state,...}) = let
667 :     val params = [
668 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
669 :     CL.PARAM(["__global"], CL.T_Ptr(CL.T_Named tyName), "selfOut")
670 :     ]
671 :     val assignStms = List.rev(
672 :     List.map
673 :     (fn x => CL.mkAssign(lvalueSV(#var x), rvalueSV(#var x)))
674 :     state)
675 :     in
676 :     CL.D_Func([""], CL.voidTy, RN.strandCopy, params,CL.mkBlock(assignStms))
677 :     end
678 :    
679 :     (* generate a global structure type definition from the list of globals *)
680 :     fun genGlobalStruct (_, [], _) = CL.D_Comment(["No Global Definition"])
681 :     | genGlobalStruct (targetTy, globals, tyName) = let
682 :     val globs = List.map (fn (x : mirror_var) => (targetTy x, #var x)) globals
683 :     in
684 : jhr 1716 CL.D_StructDef(NONE, globs, SOME tyName)
685 : jhr 1671 end
686 :    
687 :     (* generate a global structure type definition from the image data of the image globals *)
688 :     fun genImageDataStruct ([], _) = CL.D_Comment(["No Image Data Ptrs Definition"])
689 :     | genImageDataStruct (imgGlobals, tyName) = let
690 :     val globs = List.map
691 :     (fn (x, _) => (globalPtr CL.voidTy, RN.imageDataName x))
692 :     imgGlobals
693 :     in
694 : jhr 1716 CL.D_StructDef(NONE, globs, SOME tyName)
695 : jhr 1671 end
696 :    
697 :     fun genGlobals (declFn, targetTy, globals) = let
698 :     fun doVar (x : mirror_var) = declFn (CL.D_Var([], targetTy x, #var x, NONE))
699 :     in
700 :     List.app doVar globals
701 :     end
702 :    
703 :     fun genOutputFun(Strand{name, output,tyName, state, code,...}) = let
704 :     (* the output function *)
705 :     val outFnName = concat[name, "_Output"]
706 :     val outFun = let
707 :     val params = [
708 :     CL.PARAM([], CL.T_Ptr CL.voidTy, "outS"),
709 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
710 :     ]
711 :     (* the type and access expression for the strand's output variable *)
712 :     val (outTy, outState) = (#1 output, CL.mkIndirect(CL.mkVar "self", #2 output))
713 :     val outState = CL.mkUnOp(CL.%&, outState)
714 :     in
715 :     CL.D_Func(["static"], CL.voidTy, outFnName, params,
716 :     CL.mkCall("memcpy", [CL.mkVar "outS", outState, CL.mkSizeof(shadowTy outTy)] ))
717 :     end
718 :     in
719 :     outFun
720 :     end
721 :    
722 :     fun genStrandDesc (outFn,Strand{name, output,tyName, state, code,...}) = let
723 :     (* the output function *)
724 :     val outFnName = concat[name, "_Output"]
725 :     (* the strand's descriptor object *)
726 :     val descI = let
727 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
728 :     val (outTy, _) = output
729 :     in
730 :     CL.I_Struct[
731 :     ("name", CL.I_Exp(CL.mkStr name)),
732 :     ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandTy name)))),
733 :     ("shadowStrandSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandShadowTy (RN.strandTy name))))),
734 :     (* FIXME: we may need to add a shadowOutputSzb field too for OpenCL *)
735 :     ("outputSzb", CL.I_Exp(CL.mkSizeof(shadowTy outTy))),
736 : jhr 1789 (* DEPRECATED
737 : jhr 1671 ("nrrdType", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdType outTy))),
738 : jhr 1789 ("nrrdSzb", CL.I_Exp(CL.mkInt (NrrdTypes.toNrrdSize outTy))),
739 :     *)
740 : jhr 1671 ("update", fnPtr("update_method_t", "0")),
741 :     ("strandCopy", fnPtr("convert_method_t", RN.strandConvertName name)),
742 :     ("print", fnPtr("print_method_t", RN.strandPrintName name)),
743 :     ("output", fnPtr("output_method_t", outFnName)) (* FIXME *)
744 :     ]
745 :     end
746 :     val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
747 :     in
748 :     desc
749 :     end
750 :    
751 :     (* generate the table of strand descriptors *)
752 :     fun genStrandTable (declFn, strands) = let
753 :     val nStrands = length strands
754 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.mkVar(N.strandDesc name)))
755 :     fun genInits (_, []) = []
756 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
757 :     in
758 :     declFn (CL.D_Var([], CL.int32, N.numStrands,
759 :     SOME(CL.I_Exp(CL.mkIntTy(IntInf.fromInt nStrands, CL.int32)))));
760 :     declFn (CL.D_Var([],
761 :     CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
762 :     N.strands,
763 :     SOME(CL.I_Array(genInits (0, strands)))))
764 :     end
765 :    
766 :     fun genSrc (baseName, prog) = let
767 :     val Prog{
768 : jhr 1713 tgt,
769 : jhr 1705 globals, topDecls, strands, initially,
770 : jhr 1671 imgGlobals, numDims,outFn, ...
771 :     } = prog
772 :     val clFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "cl"}
773 :     val cFileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
774 :     val clOutS = TextIO.openOut clFileName
775 :     val cOutS = TextIO.openOut cFileName
776 :     val clppStrm = PrintAsCL.new clOutS
777 :     val cppStrm = PrintAsC.new cOutS
778 :     fun cppDecl dcl = PrintAsC.output(cppStrm, dcl)
779 :     fun clppDecl dcl = PrintAsCL.output(clppStrm, dcl)
780 :     val strands = AtomTable.listItems strands
781 :     val [strand as Strand{name, tyName, code, init_code, ...}] = strands
782 :     in
783 :     (* Generate the OpenCL file *)
784 :     (* Retrieve the header information *)
785 :     clppDecl (CL.verbatim [HF.text] [
786 :     ("OUTFILE", clFileName),
787 :     ("SRCFILE", OS.Path.joinBaseExt{base=baseName, ext=SOME "diderot"}),
788 : jhr 1713 ("DIDEROT_FLOAT_PRECISION", TargetUtil.floatPrecisionDef tgt),
789 :     ("DIDEROT_INT_PRECISION", TargetUtil.intPrecisionDef tgt)
790 : jhr 1671 ]);
791 :     (* if there are no globals, then define a dummy type *)
792 :     if List.null(!globals)
793 :     then clppDecl (CL.D_Verbatim["typedef void ", RN.globalsTy, ";\n"])
794 :     else ();
795 :     (* if there are no images, then define a dummy type *)
796 :     if List.null(!imgGlobals)
797 :     then clppDecl (CL.D_Verbatim["typedef void * ", RN.imageDataType, ";\n"])
798 :     else ();
799 :     (* Retrieve the scheduler kernels and functions *)
800 :     clppDecl (CL.D_Verbatim[SF.text]);
801 :     clppDecl (CL.D_Verbatim[CLEigen2x2Frag.text]);
802 :     clppDecl (CL.D_Verbatim[CLEigen3x3Frag.text]);
803 :     clppDecl (genGlobalStruct (#gpuTy, !globals, RN.globalsTy));
804 :     clppDecl (genImageDataStruct(!imgGlobals, RN.imageDataType));
805 :     clppDecl (genStrandTyDef(#gpuTy, strand, tyName));
806 :     List.app clppDecl (!code);
807 :     clppDecl (genStrandCopy strand);
808 :     clppDecl (genUpdateMethod(strand, globals, imgGlobals));
809 :     (* Generate the Host C file *)
810 :     cppDecl (CL.D_Verbatim[
811 : jhr 1713 concat["#define " ^ TargetUtil.floatPrecisionDef tgt, "\n"],
812 :     concat["#define " ^ TargetUtil.intPrecisionDef tgt, "\n"],
813 :     concat["#define " ^ TargetUtil.targetDef tgt, "\n"],
814 : jhr 1671 "#include \"Diderot/diderot.h\"\n"
815 : jhr 1705 ]);
816 :     case !globals
817 :     of [] => cppDecl (CL.D_Verbatim[concat["typedef void ", RN.globalsTy, ";\n"] ])
818 :     | _ => ()
819 :     (* end case *);
820 : jhr 1671 cppDecl (CL.D_Var(["static"], CL.charPtr, "ProgramName",
821 : jhr 1713 SOME(CL.I_Exp(CL.mkStr(#srcFile tgt)))));
822 : jhr 1671 cppDecl (genGlobalStruct (#hostTy, !globals, RN.globalsTy));
823 :     cppDecl (genGlobalStruct (#shadowTy, !globals, RN.shadowGlobalsTy));
824 :     (* FIXME: does this really need to be a global? *)
825 :     cppDecl (CL.D_Var(["static"], globPtrTy, RN.globalsVarName, NONE));
826 :     cppDecl (genStrandTyDef (#hostTy, strand, tyName));
827 :     cppDecl (genStrandTyDef (#shadowTy, strand, RN.strandShadowTy tyName));
828 :     cppDecl (genConvertShadowTypes strand);
829 :     cppDecl (!init_code);
830 :     cppDecl (genStrandPrint strand);
831 :     cppDecl (genOutputFun strand);
832 :     List.app cppDecl (List.rev (!topDecls));
833 :     cppDecl (genGlobalBuffersArgs (!globals,imgGlobals));
834 :     List.app (fn strand => cppDecl (genStrandDesc (outFn,strand))) strands;
835 :     genStrandTable (cppDecl, strands);
836 :     cppDecl (!initially);
837 :     PrintAsC.close cppStrm;
838 :     PrintAsCL.close clppStrm;
839 :     TextIO.closeOut cOutS;
840 :     TextIO.closeOut clOutS
841 :     end
842 :    
843 :     (* output the code to the filesystem. The string is the basename of the source file *)
844 : jhr 1705 fun generate (prog as Prog{tgt, ...}) = let
845 :     val {outDir, outBase, exec, double, parallel, debug, ...} = tgt
846 : jhr 1671 fun condCons (true, x, xs) = x::xs
847 :     | condCons (false, _, xs) = xs
848 :     (* generate the C compiler flags *)
849 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
850 : jhr 1843 val cflags = condCons (#cl Paths.cflags <> "", #cl Paths.cflags, cflags)
851 : jhr 1671 val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
852 :     val cflags = if debug
853 :     then #debug Paths.cflags :: cflags
854 :     else #ndebug Paths.cflags :: cflags
855 :     val cflags = #base Paths.cflags :: cflags
856 :     (* generate the loader flags *)
857 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
858 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
859 :     val extraLibs = #cl Paths.extraLibs :: extraLibs
860 : jhr 1706 val rtLib = TargetUtil.runtimeName tgt
861 : jhr 1671 val ldOpts = rtLib :: extraLibs
862 : jhr 1705 val basename = OS.Path.joinDirFile{dir=outDir, file=outBase}
863 : jhr 1671 in
864 :     genSrc (basename, prog);
865 :     RunCC.compile (basename, cflags);
866 : jhr 1714 RunCC.linkExec (basename, ldOpts)
867 : jhr 1671 end
868 :    
869 :     end (* Program *)
870 :    
871 :     end
872 :    
873 :     structure CLBackEnd = CodeGenFn(CLTarget)

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