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

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