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

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