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

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

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