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 1372 - (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 1372 structure RN = 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 :     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 :     }
28 :    
29 :     datatype program = Prog of {
30 : jhr 1301 name : string, (* stem of source file *)
31 : jhr 1232 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 : jhr 1115 globals : CL.decl list ref,
35 :     topDecls : CL.decl list ref,
36 :     strands : strand AtomTable.hash_table,
37 :     initially : CL.decl ref
38 :     }
39 :    
40 :     datatype env = ENV of {
41 :     info : env_info,
42 :     vMap : var V.Map.map,
43 :     scope : scope
44 :     }
45 :    
46 :     and env_info = INFO of {
47 :     prog : program
48 :     }
49 :    
50 :     and scope
51 :     = NoScope
52 :     | GlobalScope
53 :     | InitiallyScope
54 :     | StrandScope of TreeIL.var list (* strand initialization *)
55 :     | MethodScope of TreeIL.var list (* method body; vars are state variables *)
56 :    
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 1372 fun vectorWidths () = if !RN.doublePrecision
62 : jhr 1115 then [2, 4, 8]
63 :     else [4, 8]
64 :    
65 :     (* tests for whether various expression forms can appear inline *)
66 :     fun inlineCons n = (n < 2) (* vectors are inline, but not matrices *)
67 :     val inlineMatrixExp = false (* can matrix-valued expressions appear inline? *)
68 :    
69 :     (* TreeIL to target translations *)
70 :     structure Tr =
71 :     struct
72 : jhr 1232 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 : jhr 1115 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 : jhr 1232 ) 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 : jhr 1115 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 :     end
92 :    
93 :     (* variables *)
94 :     structure Var =
95 :     struct
96 :     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 :     end
112 :    
113 :     (* environments *)
114 :     structure Env =
115 :     struct
116 :     (* create a new environment *)
117 :     fun new prog = ENV{
118 :     info=INFO{prog = prog},
119 :     vMap = V.Map.empty,
120 :     scope = NoScope
121 :     }
122 :     (* define the current translation context *)
123 :     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 :     (* bind a TreeIL varaiable to a target variable *)
129 :     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 :     end
135 :    
136 :     (* programs *)
137 :     structure Program =
138 :     struct
139 : jhr 1301 fun new {name, double, parallel, debug} = (
140 : jhr 1232 RN.initTargetSpec double;
141 : jhr 1115 Prog{
142 : jhr 1301 name = name,
143 : jhr 1232 double = double, parallel = parallel, debug = debug,
144 : jhr 1301 globals = ref [ (* NOTE: in reverse order! *)
145 :     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 :     if parallel
152 :     then "#define DIDEROT_TARGET_PARALLEL"
153 :     else "#define DIDEROT_TARGET_C",
154 :     "#include \"Diderot/diderot.h\""
155 :     ]
156 :     ],
157 : jhr 1115 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 :     fun inputs (Prog{topDecls, ...}, stm) = let
163 :     val inputsFn = CL.D_Func(
164 :     [], CL.voidTy, RN.registerOpts,
165 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.optionsTy), "opts")],
166 :     stm)
167 :     in
168 :     topDecls := inputsFn :: !topDecls
169 :     end
170 : jhr 1115 (* register the global initialization part of a program *)
171 :     fun init (Prog{topDecls, ...}, init) = let
172 : jhr 1301 val initFn = CL.D_Func([], CL.voidTy, RN.initGlobals, [], init)
173 : jhr 1232 val shutdownFn = CL.D_Func(
174 :     [], CL.voidTy, RN.shutdown,
175 :     [CL.PARAM([], CL.T_Ptr(CL.T_Named RN.worldTy), "wrld")],
176 :     CL.S_Block[])
177 : jhr 1115 in
178 : jhr 1232 topDecls := shutdownFn :: initFn :: !topDecls
179 : jhr 1115 end
180 :     (* create and register the initially function for a program *)
181 :     fun initially {
182 : jhr 1301 prog = Prog{name=progName, strands, initially, ...},
183 : jhr 1115 isArray : bool,
184 : jhr 1232 iterPrefix : stm list,
185 : jhr 1115 iters : (var * exp * exp) list,
186 : jhr 1232 createPrefix : stm list,
187 : jhr 1115 strand : Atom.atom,
188 :     args : exp list
189 :     } = let
190 :     val name = Atom.toString strand
191 :     val nDims = List.length iters
192 :     val worldTy = CL.T_Ptr(CL.T_Named RN.worldTy)
193 :     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 : jhr 1301 (* code to allocate the world and initial strands *)
205 :     val wrld = "wrld"
206 : jhr 1115 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 : jhr 1301 CL.mkDecl(worldTy, wrld,
211 : jhr 1115 SOME(CL.I_Exp(CL.E_Apply(RN.allocInitially, [
212 : jhr 1301 CL.mkVar "ProgramName",
213 : jhr 1115 CL.mkUnOp(CL.%&, CL.E_Var(RN.strandDesc name)),
214 :     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 :     val strandTy = CL.T_Ptr(CL.T_Named(RN.strandTy name))
223 :     fun mkLoopNest [] = CL.mkBlock(createPrefix @ [
224 :     CL.mkDecl(strandTy, "sp",
225 :     SOME(CL.I_Exp(
226 :     CL.E_Cast(strandTy,
227 :     CL.E_Apply(RN.inState, [CL.E_Var "wrld", CL.E_Var indexVar]))))),
228 :     CL.mkCall(RN.strandInit name, CL.E_Var "sp" :: args),
229 :     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 : jhr 1301 val body = CL.mkBlock(
246 :     iterPrefix @
247 :     allocCode @
248 :     iterCode @
249 :     [CL.mkReturn(SOME(CL.E_Var "wrld"))])
250 : jhr 1115 val initFn = CL.D_Func([], worldTy, RN.initially, [], body)
251 :     in
252 :     initially := initFn
253 :     end
254 :    
255 :     (***** OUTPUT *****)
256 :     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 :     of Ty.IVecTy 1 => [CL.E_Str(!RN.gIntFormat ^ "\n"), outState]
272 :     | Ty.IVecTy d => let
273 :     val fmt = CL.E_Str(
274 :     String.concatWith " " (List.tabulate(d, fn _ => !RN.gIntFormat))
275 :     ^ "\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 :     in
299 :     CL.I_Struct[
300 : jhr 1301 ("name", CL.I_Exp(CL.mkStr name)),
301 : jhr 1115 ("stateSzb", CL.I_Exp(CL.mkSizeof(CL.T_Named(RN.strandTy name)))),
302 :     ("update", fnPtr("update_method_t", name ^ "_update")),
303 :     ("print", fnPtr("print_method_t", prFnName))
304 :     ]
305 :     end
306 :     val desc = CL.D_Var([], CL.T_Named RN.strandDescTy, RN.strandDesc name, SOME descI)
307 :     in
308 :     selfTyDef :: List.rev (desc :: prFn :: !code)
309 :     end
310 :    
311 :     (* generate the table of strand descriptors *)
312 :     fun genStrandTable (ppStrm, strands) = let
313 :     val nStrands = length strands
314 :     fun genInit (Strand{name, ...}) = CL.I_Exp(CL.mkUnOp(CL.%&, CL.E_Var(RN.strandDesc name)))
315 :     fun genInits (_, []) = []
316 :     | genInits (i, s::ss) = (i, genInit s) :: genInits(i+1, ss)
317 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
318 :     in
319 :     ppDecl (CL.D_Var([], CL.int32, RN.numStrands,
320 :     SOME(CL.I_Exp(CL.E_Int(IntInf.fromInt nStrands, CL.int32)))));
321 :     ppDecl (CL.D_Var([],
322 :     CL.T_Array(CL.T_Ptr(CL.T_Named RN.strandDescTy), SOME nStrands),
323 :     RN.strands,
324 :     SOME(CL.I_Array(genInits (0, strands)))))
325 :     end
326 :    
327 : jhr 1301 fun genSrc (baseName, prog) = let
328 :     val Prog{name, globals, topDecls, strands, initially, ...} = prog
329 : jhr 1115 val fileName = OS.Path.joinBaseExt{base=baseName, ext=SOME "c"}
330 :     val outS = TextIO.openOut fileName
331 :     val ppStrm = PrintAsC.new outS
332 :     fun ppDecl dcl = PrintAsC.output(ppStrm, dcl)
333 :     val strands = AtomTable.listItems strands
334 :     in
335 :     List.app ppDecl (List.rev (!globals));
336 :     List.app ppDecl (List.rev (!topDecls));
337 :     List.app (fn strand => List.app ppDecl (genStrand strand)) strands;
338 :     genStrandTable (ppStrm, strands);
339 :     ppDecl (!initially);
340 :     PrintAsC.close ppStrm;
341 :     TextIO.closeOut outS
342 :     end
343 :    
344 :     (* output the code to a file. The string is the basename of the file, the extension
345 :     * is provided by the target.
346 :     *)
347 : jhr 1301 fun generate (basename, prog as Prog{name, double, parallel, debug, ...}) = let
348 : jhr 1232 fun condCons (true, x, xs) = x::xs
349 :     | condCons (false, _, xs) = xs
350 :     (* generate the C compiler flags *)
351 :     val cflags = ["-I" ^ Paths.diderotInclude, "-I" ^ Paths.teemInclude]
352 :     val cflags = condCons (parallel, #pthread Paths.cflags, cflags)
353 :     val cflags = if debug
354 :     then #debug Paths.cflags :: cflags
355 :     else #ndebug Paths.cflags :: cflags
356 :     val cflags = #base Paths.cflags :: cflags
357 :     (* generate the loader flags *)
358 :     val extraLibs = condCons (parallel, #pthread Paths.extraLibs, [])
359 :     val extraLibs = Paths.teemLinkFlags @ #base Paths.extraLibs :: extraLibs
360 :     val rtLib = TargetUtil.runtimeName {
361 :     target = TargetUtil.TARGET_C,
362 :     parallel = parallel, double = double, debug = debug
363 :     }
364 :     val ldOpts = rtLib :: extraLibs
365 :     in
366 :     genSrc (basename, prog);
367 :     RunCC.compile (basename, cflags);
368 :     RunCC.link (basename, ldOpts)
369 :     end
370 : jhr 1115
371 :     end
372 :    
373 :     (* strands *)
374 :     structure Strand =
375 :     struct
376 :     fun define (Prog{strands, ...}, strandId) = let
377 :     val name = Atom.toString strandId
378 :     val strand = Strand{
379 :     name = name,
380 :     tyName = RN.strandTy name,
381 :     state = ref [],
382 :     output = ref NONE,
383 :     code = ref []
384 :     }
385 :     in
386 :     AtomTable.insert strands (strandId, strand);
387 :     strand
388 :     end
389 :    
390 :     (* return the strand with the given name *)
391 :     fun lookup (Prog{strands, ...}, strandId) = AtomTable.lookup strands strandId
392 :    
393 :     (* register the strand-state initialization code. The variables are the strand
394 :     * parameters.
395 :     *)
396 :     fun init (Strand{name, tyName, code, ...}, params, init) = let
397 :     val fName = RN.strandInit name
398 :     val params =
399 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut") ::
400 :     List.map (fn (ToC.V(ty, x)) => CL.PARAM([], ty, x)) params
401 :     val initFn = CL.D_Func([], CL.voidTy, fName, params, init)
402 :     in
403 :     code := initFn :: !code
404 :     end
405 :    
406 :     (* register a strand method *)
407 :     fun method (Strand{name, tyName, code, ...}, methName, body) = let
408 :     val fName = concat[name, "_", methName]
409 :     val params = [
410 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfIn"),
411 :     CL.PARAM([], CL.T_Ptr(CL.T_Named tyName), "selfOut")
412 :     ]
413 :     val methFn = CL.D_Func(["static"], CL.int32, fName, params, body)
414 :     in
415 :     code := methFn :: !code
416 :     end
417 :    
418 :     fun output (Strand{output, ...}, ty, ToC.V(_, x)) = output := SOME(ty, x)
419 :    
420 :     end
421 :    
422 :     end
423 :    
424 :     structure CBackEnd = CodeGenFn(CTarget)

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