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

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

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