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

SCM Repository

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

Annotation of /branches/pure-cfg/src/compiler/c-target/c-target.sml

Parent Directory Parent Directory | Revision Log Revision Log


Revision 1285 - (view) (download)

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

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