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

SCM Repository

[diderot] Annotation of /branches/charisee/src/compiler/c-target/c-target.sml
ViewVC logotype

Annotation of /branches/charisee/src/compiler/c-target/c-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1444 - (view) (download)
Original Path: trunk/src/compiler/c-target/c-target.sml

1 : jhr 1115 (* 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 CTarget : TARGET =
8 :     struct
9 :    
10 :     structure IL = TreeIL
11 :     structure V = IL.Var
12 :     structure Ty = IL.Ty
13 :     structure CL = CLang
14 : jhr 1376 structure N = CNames
15 : jhr 1115 structure ToC = TreeToC
16 :    
17 :     type var = ToC.var
18 :     type exp = CL.exp
19 :     type stm = CL.stm
20 :    
21 :     datatype strand = Strand of {
22 : jhr 1375 name : string,
23 :     tyName : string,
24 :     state : var list ref,
25 :     output : (Ty.ty * CL.var) option ref, (* the strand's output variable (only one for now) *)
26 :     code : CL.decl list ref
27 : jhr 1115 }
28 :    
29 :     datatype program = Prog of {
30 : jhr 1375 name : string, (* stem of source file *)
31 :     double : bool, (* true for double-precision support *)
32 :     parallel : bool, (* true for multithreaded (or multi-GPU) target *)
33 :     debug : bool, (* true for debug support in executable *)
34 :     globals : CL.decl list ref,
35 :     topDecls : CL.decl list ref,
36 :     strands : strand AtomTable.hash_table,
37 :     initially : CL.decl ref
38 : jhr 1115 }
39 :    
40 :     datatype env = ENV of {
41 : jhr 1375 info : env_info,
42 :     vMap : var V.Map.map,
43 :     scope : scope
44 : jhr 1115 }
45 :    
46 :     and env_info = INFO of {
47 : jhr 1375 prog : program
48 : jhr 1115 }
49 :    
50 :     and scope
51 :     = NoScope
52 :     | GlobalScope
53 :     | InitiallyScope
54 : jhr 1375 | StrandScope of TreeIL.var list (* strand initialization *)
55 :     | MethodScope of TreeIL.var list (* method body; vars are state variables *)
56 : jhr 1115
57 :     (* the supprted widths of vectors of reals on the target. For the GNU vector extensions,
58 :     * the supported sizes are powers of two, but float2 is broken.
59 :     * NOTE: we should also consider the AVX vector hardware, which has 256-bit registers.
60 :     *)
61 : jhr 1376 fun vectorWidths () = if !N.doublePrecision
62 : jhr 1375 then [2, 4, 8]
63 :     else [4, 8]
64 : jhr 1115
65 :     (* tests for whether various expression forms can appear inline *)
66 : jhr 1375 fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
67 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
68 : jhr 1115
69 :     (* TreeIL to target translations *)
70 :     structure Tr =
71 :     struct
72 : jhr 1375 fun fragment (ENV{info, vMap, scope}, blk) = let
73 :     val (vMap, stms) = ToC.trFragment (vMap, blk)
74 :     in
75 :     (ENV{info=info, vMap=vMap, scope=scope}, stms)
76 :     end
77 :     fun saveState cxt stateVars (env, args, stm) = (
78 :     ListPair.foldrEq
79 :     (fn (x, e, stms) => ToC.trAssign(env, x, e)@stms)
80 :     [stm]
81 :     (stateVars, args)
82 :     ) handle ListPair.UnequalLengths => (
83 :     print(concat["saveState ", cxt, ": length mismatch; ", Int.toString(List.length args), " args\n"]);
84 :     raise Fail(concat["saveState ", cxt, ": length mismatch"]))
85 :     fun block (ENV{vMap, scope, ...}, blk) = (case scope
86 :     of StrandScope stateVars => ToC.trBlock (vMap, saveState "StrandScope" stateVars, blk)
87 :     | MethodScope stateVars => ToC.trBlock (vMap, saveState "MethodScope" stateVars, blk)
88 :     | _ => ToC.trBlock (vMap, fn (_, _, stm) => [stm], blk)
89 :     (* end case *))
90 :     fun exp (ENV{vMap, ...}, e) = ToC.trExp(vMap, e)
91 : jhr 1115 end
92 :    
93 :     (* variables *)
94 :     structure Var =
95 :     struct
96 : jhr 1375 fun name (ToC.V(_, name)) = name
97 :     fun global (Prog{globals, ...}, name, ty) = let
98 :     val ty' = ToC.trType ty
99 :     in
100 :     globals := CL.D_Var([], ty', name, NONE) :: !globals;
101 :     ToC.V(ty', name)
102 :     end
103 :     fun param x = ToC.V(ToC.trType(V.ty x), V.name x)
104 :     fun state (Strand{state, ...}, x) = let
105 :     val ty' = ToC.trType(V.ty x)
106 :     val x' = ToC.V(ty', V.name x)
107 :     in
108 :     state := x' :: !state;
109 :     x'
110 :     end
111 : jhr 1115 end
112 :    
113 :     (* environments *)
114 :     structure Env =
115 :     struct
116 :     (* create a new environment *)
117 : jhr 1375 fun new prog = ENV{
118 :     info=INFO{prog = prog},
119 :     vMap = V.Map.empty,
120 :     scope = NoScope
121 :     }
122 : jhr 1115 (* define the current translation context *)
123 : jhr 1375 fun setScope scope (ENV{info, vMap, ...}) = ENV{info=info, vMap=vMap, scope=scope}
124 :     val scopeGlobal = setScope GlobalScope
125 :     val scopeInitially = setScope InitiallyScope
126 :     fun scopeStrand (env, svars) = setScope (StrandScope svars) env
127 :     fun scopeMethod (env, svars) = setScope (MethodScope svars) env
128 : jhr 1115 (* bind a TreeIL varaiable to a target variable *)
129 : jhr 1375 fun bind (ENV{info, vMap, scope}, x, x') = ENV{
130 :     info = info,
131 :     vMap = V.Map.insert(vMap, x, x'),
132 :     scope = scope
133 :     }
134 : jhr 1115 end
135 :    
136 :     (* programs *)
137 :     structure Program =
138 :     struct
139 : jhr 1375 fun new {name, double, parallel, debug} = (
140 : jhr 1376 N.initTargetSpec double;
141 : jhr 1375 Prog{
142 :     name = name,
143 :     double = double, parallel = parallel, debug = debug,
144 :     globals = ref [ (* NOTE: in reverse order! *)
145 : jhr 1301 CL.D_Var(["static"], CL.charPtr, "ProgramName",
146 :     SOME(CL.I_Exp(CL.mkStr name))),
147 :     CL.D_Verbatim[
148 :     if double
149 :     then "#define DIDEROT_DOUBLE_PRECISION"
150 :     else "#define DIDEROT_SINGLE_PRECISION",
151 : jhr 1375 if parallel
152 :     then "#define DIDEROT_TARGET_PARALLEL"
153 :     else "#define DIDEROT_TARGET_C",
154 : jhr 1301 "#include \"Diderot/diderot.h\""
155 :     ]
156 : jhr 1375 ],
157 :     topDecls = ref [],
158 :     strands = AtomTable.mkTable (16, Fail "strand table"),
159 :     initially = ref(CL.D_Comment["missing initially"])
160 :     })
161 : jhr 1301 (* register the code that is used to register command-line options for input variables *)
162 : jhr 1375 fun inputs (Prog{topDecls, ...}, stm) = let
163 :     val inputsFn = CL.D_Func(
164 : jhr 1376 [], CL.voidTy, N.registerOpts,
165 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named N.optionsTy), "opts")],
166 : jhr 1375 stm)
167 :     in
168 :     topDecls := inputsFn :: !topDecls
169 :     end
170 : jhr 1115 (* register the global initialization part of a program *)
171 : jhr 1375 fun init (Prog{topDecls, ...}, init) = let
172 : jhr 1376 val initFn = CL.D_Func([], CL.voidTy, N.initGlobals, [], init)
173 : jhr 1375 val shutdownFn = CL.D_Func(
174 : jhr 1376 [], CL.voidTy, N.shutdown,
175 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named N.worldTy), "wrld")],
176 : jhr 1375 CL.S_Block[])
177 :     in
178 :     topDecls := shutdownFn :: initFn :: !topDecls
179 :     end
180 : jhr 1115 (* create and register the initially function for a program *)
181 : jhr 1375 fun initially {
182 :     prog = Prog{name=progName, strands, initially, ...},
183 :     isArray : bool,
184 :     iterPrefix : stm list,
185 :     iters : (var * exp * exp) list,
186 :     createPrefix : stm list,
187 :     strand : Atom.atom,
188 :     args : exp list
189 :     } = let
190 :     val name = Atom.toString strand
191 :     val nDims = List.length iters
192 : jhr 1376 val worldTy = CL.T_Ptr(CL.T_Named N.worldTy)
193 : jhr 1375 fun mapi f xs = let
194 :     fun mapf (_, []) = []
195 :     | mapf (i, x::xs) = f(i, x) :: mapf(i+1, xs)
196 :     in
197 :     mapf (0, xs)
198 :     end
199 :     val baseInit = mapi (fn (i, (_, e, _)) => (i, CL.I_Exp e)) iters
200 :     val sizeInit = mapi
201 :     (fn (i, (ToC.V(ty, _), lo, hi)) =>
202 :     (i, CL.I_Exp(CL.mkBinOp(CL.mkBinOp(hi, CL.#-, lo), CL.#+, CL.E_Int(1, ty))))
203 :     ) iters
204 :     (* code to allocate the world and initial strands *)
205 :     val wrld = "wrld"
206 :     val allocCode = [
207 :     CL.mkComment["allocate initial block of strands"],
208 :     CL.mkDecl(CL.T_Array(CL.int32, SOME nDims), "base", SOME(CL.I_Array baseInit)),
209 :     CL.mkDecl(CL.T_Array(CL.uint32, SOME nDims), "size", SOME(CL.I_Array sizeInit)),
210 :     CL.mkDecl(worldTy, wrld,
211 : jhr 1376 SOME(CL.I_Exp(CL.E_Apply(N.allocInitially, [
212 : jhr 1375 CL.mkVar "ProgramName",
213 : jhr 1376 CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)),
214 : jhr 1375 CL.E_Bool isArray,
215 :     CL.E_Int(IntInf.fromInt nDims, CL.int32),
216 :     CL.E_Var "base",
217 :     CL.E_Var "size"
218 :     ]))))
219 :     ]
220 :     (* create the loop nest for the initially iterations *)
221 :     val indexVar = "ix"
222 : jhr 1376 val strandTy = CL.T_Ptr(CL.T_Named(N.strandTy name))
223 : jhr 1375 fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
224 :     CL.mkDecl(strandTy, "sp",
225 :     SOME(CL.I_Exp(
226 :     CL.E_Cast(strandTy,
227 : jhr 1376 CL.E_Apply(N.inState, [CL.E_Var "wrld", CL.E_Var indexVar]))))),
228 :     CL.mkCall(N.strandInit name, CL.E_Var "sp" :: args),
229 : jhr 1375 CL.mkAssign(CL.E_Var indexVar, CL.mkBinOp(CL.E_Var indexVar, CL.#+, CL.E_Int(1, CL.uint32)))
230 :     ])
231 :     | mkLoopNest ((ToC.V(ty, param), lo, hi)::iters) = let
232 :     val body = mkLoopNest iters
233 :     in
234 :     CL.mkFor(
235 :     [(ty, param, lo)],
236 :     CL.mkBinOp(CL.E_Var param, CL.#<=, hi),
237 :     [CL.mkPostOp(CL.E_Var param, CL.^++)],
238 :     body)
239 :     end
240 :     val iterCode = [
241 :     CL.mkComment["initially"],
242 :     CL.mkDecl(CL.uint32, indexVar, SOME(CL.I_Exp(CL.E_Int(0, CL.uint32)))),
243 :     mkLoopNest iters
244 :     ]
245 :     val body = CL.mkBlock(
246 : jhr 1301 iterPrefix @
247 :     allocCode @
248 :     iterCode @
249 :     [CL.mkReturn(SOME(CL.E_Var "wrld"))])
250 : jhr 1376 val initFn = CL.D_Func([], worldTy, N.initially, [], body)
251 : jhr 1375 in
252 :     initially := initFn
253 :     end
254 : jhr 1115
255 :     (***** OUTPUT *****)
256 : jhr 1375 fun genStrand (Strand{name, tyName, state, output, code}) = let
257 :     (* the type declaration for the strand's state struct *)
258 :     val selfTyDef = CL.D_StructDef(
259 :     List.rev (List.map (fn ToC.V(ty, x) => (ty, x)) (!state)),
260 :     tyName)
261 :     (* the print function *)
262 :     val prFnName = concat[name, "_print"]
263 :     val prFn = let
264 :     val params = [
265 :     CL.PARAM([], CL.T_Ptr(CL.T_Named "FILE"), "outS"),
266 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "self")
267 :     ]
268 :     val SOME(ty, x) = !output
269 :     val outState = CL.mkIndirect(CL.mkVar "self", x)
270 :     val prArgs = (case ty
271 : jhr 1376 of Ty.IVecTy 1 => [CL.E_Str(!N.gIntFormat ^ "\n"), outState]
272 : jhr 1375 | Ty.IVecTy d => let
273 :     val fmt = CL.E_Str(
274 : jhr 1376 String.concatWith " " (List.tabulate(d, fn _ => !N.gIntFormat))
275 : jhr 1375 ^ "\n")
276 :     val args = List.tabulate (d, fn i => ToC.ivecIndex(outState, d, i))
277 :     in
278 :     fmt :: args
279 :     end
280 :     | Ty.TensorTy[] => [CL.E_Str "%f\n", outState]
281 :     | Ty.TensorTy[d] => let
282 :     val fmt = CL.E_Str(
283 :     String.concatWith " " (List.tabulate(d, fn _ => "%f"))
284 :     ^ "\n")
285 :     val args = List.tabulate (d, fn i => ToC.vecIndex(outState, d, i))
286 :     in
287 :     fmt :: args
288 :     end
289 :     | _ => raise Fail("genStrand: unsupported output type " ^ Ty.toString ty)
290 :     (* end case *))
291 :     in
292 :     CL.D_Func(["static"], CL.voidTy, prFnName, params,
293 :     CL.mkCall("fprintf", CL.mkVar "outS" :: prArgs))
294 :     end
295 :     (* the strand's descriptor object *)
296 :     val descI = let
297 :     fun fnPtr (ty, f) = CL.I_Exp(CL.mkCast(CL.T_Named ty, CL.mkVar f))
298 : jhr 1376 val SOME(outTy, _) = !output
299 : jhr 1375 in
300 :     CL.I_Struct[
301 :     ("name", CL.I_Exp(CL.mkStr name)),
302 : jhr 1376 ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(N.strandTy name)))),
303 :     (*
304 :     ("outputSzb", CL.I_Exp(CL.mkSizeof(ToC.trTy outTy))),
305 :     *)
306 : jhr 1375 ("update", fnPtr("update_method_t", name ^ "_update")),
307 :     ("print", fnPtr("print_method_t", prFnName))
308 :     ]
309 :     end
310 : jhr 1376 val desc = CL.D_Var([], CL.T_Named N.strandDescTy, N.strandDesc name, SOME descI)
311 : jhr 1375 in
312 :     selfTyDef :: List.rev (desc :: prFn :: !code)
313 :     end
314 : jhr 1115
315 :     (* generate the table of strand descriptors *)
316 : jhr 1375 fun genStrandTable (ppStrm, strands) = let
317 :     val nStrands = length strands
318 : jhr 1376 fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.E_Var(N.strandDesc name)))
319 : jhr 1375 fun genInits (_, []) = []
320 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
321 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
322 :     in
323 : jhr 1376 ppDecl (CL.D_Var([], CL.int32, N.numStrands,
324 : jhr 1375 SOME(CL.I_Exp(CL.E_Int(IntInf.fromInt nStrands, CL.int32)))));
325 :     ppDecl (CL.D_Var([],
326 : jhr 1376 CL.T_Array(CL.T_Ptr(CL.T_Named N.strandDescTy), SOME nStrands),
327 :     N.strands,
328 : jhr 1375 SOME(CL.I_Array(genInits (0, strands)))))
329 :     end
330 : jhr 1115
331 : jhr 1375 fun genSrc (baseName, prog) = let
332 :     val Prog{name, globals, topDecls, strands, initially, ...} = prog
333 :     val fileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
334 :     val outS = TextIO.openOut fileName
335 :     val ppStrm = PrintAsC.new outS
336 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
337 :     val strands = AtomTable.listItems strands
338 :     in
339 :     List.app ppDecl (List.rev (!globals));
340 :     List.app ppDecl (List.rev (!topDecls));
341 :     List.app (fn strand => List.app ppDecl (genStrand strand)) strands;
342 :     genStrandTable (ppStrm, strands);
343 :     ppDecl (!initially);
344 :     PrintAsC.close ppStrm;
345 :     TextIO.closeOut outS
346 :     end
347 : jhr 1115
348 :     (* output the code to a file. The string is the basename of the file, the extension
349 :     * is provided by the target.
350 :     *)
351 : jhr 1375 fun generate (basename, prog as Prog{name, double, parallel, debug, ...}) = let
352 :     fun condCons (true, x, xs) = x::xs
353 :     | condCons (false, _, xs) = xs
354 :     (* generate the C compiler flags *)
355 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
356 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
357 :     val cflags = if debug
358 :     then #debug Paths.cflags :: cflags
359 :     else #ndebug Paths.cflags :: cflags
360 :     val cflags = #base Paths.cflags :: cflags
361 :     (* generate the loader flags *)
362 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
363 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
364 :     val rtLib = TargetUtil.runtimeName {
365 :     target = TargetUtil.TARGET_C,
366 :     parallel = parallel, double = double, debug = debug
367 :     }
368 :     val ldOpts = rtLib :: extraLibs
369 :     in
370 :     genSrc (basename, prog);
371 :     RunCC.compile (basename, cflags);
372 :     RunCC.link (basename, ldOpts)
373 :     end
374 : jhr 1115
375 :     end
376 :    
377 :     (* strands *)
378 :     structure Strand =
379 :     struct
380 : jhr 1375 fun define (Prog{strands, ...}, strandId) = let
381 :     val name = Atom.toString strandId
382 :     val strand = Strand{
383 :     name = name,
384 : jhr 1376 tyName = N.strandTy name,
385 : jhr 1375 state = ref [],
386 :     output = ref NONE,
387 :     code = ref []
388 :     }
389 :     in
390 :     AtomTable.insert strands (strandId, strand);
391 :     strand
392 :     end
393 : jhr 1115
394 :     (* return the strand with the given name *)
395 : jhr 1375 fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
396 : jhr 1115
397 :     (* register the strand-state initialization code. The variables are the strand
398 :     * parameters.
399 :     *)
400 : jhr 1375 fun init (Strand{name, tyName, code, ...}, params, init) = let
401 : jhr 1376 val fName = N.strandInit name
402 : jhr 1375 val params =
403 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
404 :     List.map (fn (ToC.V(ty, x)) => CL.PARAM([], ty, x)) params
405 :     val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
406 :     in
407 :     code := initFn :: !code
408 :     end
409 : jhr 1115
410 :     (* register a strand method *)
411 : jhr 1375 fun method (Strand{name, tyName, code, ...}, methName, body) = let
412 : jhr 1444 val fName = concat[name, "_", MethodName.toString methName]
413 : jhr 1375 val params = [
414 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
415 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut")
416 :     ]
417 : jhr 1444 val resTy = (case methName
418 :     of MethodName.Update => CL.T_Named "StrandStatus_t"
419 :     | MethodName.Stabilize => CL.voidTy
420 :     (* end case *))
421 :     val methFn = CL.D_Func(["static"], resTy, fName, params, body)
422 : jhr 1375 in
423 :     code := methFn :: !code
424 :     end
425 : jhr 1115
426 : jhr 1375 fun output (Strand{output, ...}, ty, ToC.V(_, x)) = output := SOME(ty, x)
427 : jhr 1115
428 :     end
429 :    
430 :     end
431 :    
432 :     structure CBackEnd = CodeGenFn(CTarget)

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