Project

General

Profile

Revision cd670fe1 src/backends/C/c_backend.ml

View differences:

src/backends/C/c_backend.ml
23 23

  
24 24
(* This module is used for the lustre to C compiler *)
25 25

  
26
open Format
27
open LustreSpec
28
open Corelang
29
open Machine_code
30
open C_backend_common
31

  
32

  
33
let print_machine_decl_prefix = ref (fun fmt x -> ())
34
(********************************************************************************************)
35
(*                     Basic      Printing functions                                        *)
36
(********************************************************************************************)
37

  
38
let print_version fmt =
39
  Format.fprintf fmt 
40
    "/* @[<v>C code generated by %s@,SVN version number %s@,Code is %s compliant */@,@]@."
41
    (Filename.basename Sys.executable_name) 
42
    Version.number 
43
    (if !Options.ansi then "ANSI C90" else "C99")
44

  
45

  
46
(********************************************************************************************)
47
(*                    Instruction Printing functions                                        *)
48
(********************************************************************************************)
49

  
50
(* Computes the depth to which multi-dimension array assignments should be expanded.
51
   It equals the maximum number of nested static array constructions accessible from root [v].
52
*)
53
let rec expansion_depth v =
54
 match v with
55
 | Cst (Const_array cl) -> 1 + List.fold_right (fun c -> max (expansion_depth (Cst c))) cl 0
56
 | Cst _
57
 | LocalVar _
58
 | StateVar _  -> 0
59
 | Fun (_, vl) -> List.fold_right (fun v -> max (expansion_depth v)) vl 0
60
 | Array vl    -> 1 + List.fold_right (fun v -> max (expansion_depth v)) vl 0
61
 | Access (v, i) -> max 0 (expansion_depth v - 1)
62
 | Power (v, n)  -> 0 (*1 + expansion_depth v*)
63

  
64
type loop_index = LVar of ident | LInt of int ref
65

  
66
(* Computes the list of nested loop variables together with their dimension bounds.
67
   - LInt r stands for loop expansion (no loop variable, but int loop index)
68
   - LVar v stands for loop variable v
69
*)
70
let rec mk_loop_variables m ty depth =
71
 match (Types.repr ty).Types.tdesc, depth with
72
 | Types.Tarray (d, ty'), 0       ->
73
   let v = mk_loop_var m () in
74
   (d, LVar v) :: mk_loop_variables m ty' 0
75
 | Types.Tarray (d, ty'), _       ->
76
   let r = ref (-1) in
77
   (d, LInt r) :: mk_loop_variables m ty' (depth - 1)
78
 | _                    , 0       -> []
79
 | _                              -> assert false
80

  
81
let reorder_loop_variables loop_vars =
82
  let (int_loops, var_loops) = 
83
    List.partition (function (d, LInt _) -> true | _ -> false) loop_vars 
84
  in
85
  var_loops @ int_loops
86
    
87
(* Prints a one loop variable suffix for arrays *)
88
let pp_loop_var fmt lv =
89
 match snd lv with
90
 | LVar v -> fprintf fmt "[%s]" v
91
 | LInt r -> fprintf fmt "[%d]" !r
92

  
93
(* Prints a suffix of loop variables for arrays *)
94
let pp_suffix fmt loop_vars =
95
 Utils.fprintf_list ~sep:"" pp_loop_var fmt loop_vars
96

  
97
(* Prints a [value] indexed by the suffix list [loop_vars] *)
98
let rec pp_value_suffix self loop_vars pp_value fmt value =
99
 match loop_vars, value with
100
 | (_, LInt r) :: q, Array vl     ->
101
   pp_value_suffix self q pp_value fmt (List.nth vl !r)
102
 | _           :: q, Power (v, n) ->
103
   pp_value_suffix self loop_vars pp_value fmt v
104
 | _               , Fun (n, vl)  ->
105
   Basic_library.pp_c n (pp_value_suffix self loop_vars pp_value) fmt vl
106
 | _               , _            ->
107
   let pp_var_suffix fmt v = fprintf fmt "%a%a" pp_value v pp_suffix loop_vars in
108
   pp_c_val self pp_var_suffix fmt value
109

  
110
(* type_directed assignment: array vs. statically sized type
111
   - [var_type]: type of variable to be assigned
112
   - [var_name]: name of variable to be assigned
113
   - [value]: assigned value
114
   - [pp_var]: printer for variables
115
*)
116
let pp_assign m self pp_var fmt var_type var_name value =
117
  let depth = expansion_depth value in
118
(*eprintf "pp_assign %a %a %d@." Types.print_ty var_type pp_val value depth;*)
119
  let loop_vars = mk_loop_variables m var_type depth in
120
  let reordered_loop_vars = reorder_loop_variables loop_vars in
121
  let rec aux fmt vars =
122
    match vars with
123
    | [] ->
124
      fprintf fmt "%a = %a;" 
125
	(pp_value_suffix self loop_vars pp_var) var_name
126
	(pp_value_suffix self loop_vars pp_var) value
127
    | (d, LVar i) :: q ->
128
(*eprintf "pp_aux %a %s@." Dimension.pp_dimension d i;*)
129
      fprintf fmt "@[<v 2>{@,int %s;@,for(%s=0;%s<%a;%s++)@,%a @]@,}"
130
	i i i Dimension.pp_dimension d i
131
	aux q
132
    | (d, LInt r) :: q ->
133
(*eprintf "pp_aux %a %d@." Dimension.pp_dimension d (!r);*)
134
      let szl = Utils.enumerate (Dimension.size_const_dimension d) in
135
      fprintf fmt "@[<v 2>{@,%a@]@,}"
136
	(Utils.fprintf_list ~sep:"@," (fun fmt i -> r := i; aux fmt q)) szl
137
  in
138
  begin
139
    reset_loop_counter ();
140
    (*reset_addr_counter ();*)
141
    aux fmt reordered_loop_vars
142
  end
143

  
144
let pp_instance_call m self fmt i (inputs: value_t list) (outputs: var_decl list) =
145
 try (* stateful node instance *)
146
   let (n,_) = List.assoc i m.minstances in
147
   fprintf fmt "%a (%a%t%a%t%s->%s);"
148
     pp_machine_step_name (node_name n)
149
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
150
     (Utils.pp_final_char_if_non_empty ", " inputs) 
151
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs
152
     (Utils.pp_final_char_if_non_empty ", " outputs)
153
     self
154
     i
155
 with Not_found -> (* stateless node instance *)
156
   let (n,_) = List.assoc i m.mcalls in
157
   fprintf fmt "%a (%a%t%a);"
158
     pp_machine_step_name (node_name n)
159
     (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) inputs
160
     (Utils.pp_final_char_if_non_empty ", " inputs) 
161
     (Utils.fprintf_list ~sep:", " (pp_c_var_write m)) outputs 
162

  
163
let pp_machine_reset (m: machine_t) self fmt inst =
164
  let (node, static) = List.assoc inst m.minstances in
165
  fprintf fmt "%a(%a%t%s->%s);"
166
    pp_machine_reset_name (node_name node)
167
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
168
    (Utils.pp_final_char_if_non_empty ", " static)
169
    self inst
170

  
171
let has_c_prototype funname dependencies =
172
  let imported_node_opt = (* We select the last imported node with the name funname.
173
			       The order of evaluation of dependencies should be
174
			       compatible with overloading. (Not checked yet) *) 
175
      List.fold_left
176
	(fun res (_, _, decls) -> 
177
	  match res with
178
	  | Some _ -> res
179
	  | None -> 
180
	    let matched = fun t -> match t.top_decl_desc with 
181
	      | ImportedNode nd -> nd.nodei_id = funname 
182
	      | _ -> false
183
	    in
184
	    if List.exists matched decls then (
185
	      match (List.find matched decls).top_decl_desc with
186
	      | ImportedNode nd -> Some nd
187
	      | _ -> assert false
188
	    )
189
	    else
190
	      None
191
	) None dependencies in
192
    match imported_node_opt with
193
    | None -> false
194
    | Some nd -> (match nd.nodei_prototype with Some "C" -> true | _ -> false)
195

  
196
let rec pp_conditional dependencies (m: machine_t) self fmt c tl el =
197
  fprintf fmt "@[<v 2>if (%a) {%t%a@]@,@[<v 2>} else {%t%a@]@,}"
198
    (pp_c_val self (pp_c_var_read m)) c
199
    (Utils.pp_newline_if_non_empty tl)
200
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) tl
201
    (Utils.pp_newline_if_non_empty el)
202
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) el
203

  
204
and pp_machine_instr dependencies (m: machine_t) self fmt instr =
205
  match instr with 
206
  | MReset i ->
207
    pp_machine_reset m self fmt i
208
  | MLocalAssign (i,v) ->
209
    pp_assign
210
      m self (pp_c_var_read m) fmt
211
      i.var_type (LocalVar i) v
212
  | MStateAssign (i,v) ->
213
    pp_assign
214
      m self (pp_c_var_read m) fmt
215
      i.var_type (StateVar i) v
216
  | MStep ([i0], i, vl) when Basic_library.is_internal_fun i  ->
217
    pp_machine_instr dependencies m self fmt (MLocalAssign (i0, Fun (i, vl)))
218
  | MStep ([i0], i, vl) when has_c_prototype i dependencies -> 
219
    fprintf fmt "%a = %s(%a);" 
220
      (pp_c_val self (pp_c_var_read m)) (LocalVar i0) 
221
      i
222
      (Utils.fprintf_list ~sep:", " (pp_c_val self (pp_c_var_read m))) vl
223
  | MStep (il, i, vl) ->
224
    pp_instance_call m self fmt i vl il
225
  | MBranch (g,hl) ->
226
    if hl <> [] && let t = fst (List.hd hl) in t = tag_true || t = tag_false
227
    then (* boolean case, needs special treatment in C because truth value is not unique *)
228
	 (* may disappear if we optimize code by replacing last branch test with default *)
229
      let tl = try List.assoc tag_true  hl with Not_found -> [] in
230
      let el = try List.assoc tag_false hl with Not_found -> [] in
231
      pp_conditional dependencies m self fmt g tl el
232
    else (* enum type case *)
233
      fprintf fmt "@[<v 2>switch(%a) {@,%a@,}@]"
234
	(pp_c_val self (pp_c_var_read m)) g
235
	(Utils.fprintf_list ~sep:"@," (pp_machine_branch dependencies m self)) hl
236

  
237
and pp_machine_branch dependencies m self fmt (t, h) =
238
  fprintf fmt "@[<v 2>case %a:@,%a@,break;@]" pp_c_tag t (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) h
239

  
240

  
241

  
242
(********************************************************************************************)
243
(*                      Prototype Printing functions                                        *)
244
(********************************************************************************************)
245

  
246
let print_alloc_prototype fmt (name, static) =
247
  fprintf fmt "%a * %a (%a)"
248
    pp_machine_memtype_name name
249
    pp_machine_alloc_name name
250
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) static
251

  
252
let print_reset_prototype self fmt (name, static) =
253
  fprintf fmt "void %a (@[<v>%a%t%a *%s@])"
254
    pp_machine_reset_name name
255
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) static
256
    (Utils.pp_final_char_if_non_empty ",@," static) 
257
    pp_machine_memtype_name name
258
    self
259

  
260
let print_stateless_prototype fmt (name, inputs, outputs) =
261
  fprintf fmt "void %a (@[<v>@[%a%t@]@,@[%a@]@,@])"
262
    pp_machine_step_name name
263
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) inputs
264
    (Utils.pp_final_char_if_non_empty ",@ " inputs) 
265
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_output_var) outputs
266

  
267
let print_step_prototype self fmt (name, inputs, outputs) =
268
  fprintf fmt "void %a (@[<v>@[%a%t@]@,@[%a@]%t@[%a *%s@]@])"
269
    pp_machine_step_name name
270
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_input_var) inputs
271
    (Utils.pp_final_char_if_non_empty ",@ " inputs) 
272
    (Utils.fprintf_list ~sep:",@ " pp_c_decl_output_var) outputs
273
    (Utils.pp_final_char_if_non_empty ",@," outputs) 
274
    pp_machine_memtype_name name
275
    self
276

  
277
(********************************************************************************************)
278
(*                         Header Printing functions                                        *)
279
(********************************************************************************************)
280

  
281

  
282
let print_import_standard fmt =
283
  fprintf fmt "#include \"%s/include/lustrec/arrow.h\"@.@." Version.prefix
284

  
285
let print_import_prototype fmt (s, _, _) =
286
  fprintf fmt "#include \"%s.h\"@," s
287
    
288
let pp_registers_struct fmt m =
289
  if m.mmemory <> []
290
  then
291
    fprintf fmt "@[%a {@[%a; @]}@] _reg; "
292
      pp_machine_regtype_name m.mname.node_id
293
      (Utils.fprintf_list ~sep:"; " pp_c_decl_struct_var) m.mmemory
294
  else
295
    ()
296

  
297
let print_machine_struct fmt m =
298
  if fst (get_stateless_status m) then
299
    begin
300
    end
301
  else
302
    begin
303
      (* Define struct *)
304
      fprintf fmt "@[%a {@[%a%a%t@]};@]@."
305
	pp_machine_memtype_name m.mname.node_id
306
	pp_registers_struct m
307
	(Utils.fprintf_list ~sep:"; " pp_c_decl_instance_var) m.minstances
308
	(Utils.pp_final_char_if_non_empty "; " m.minstances)
309
    end
310

  
311
let print_static_declare_instance attr fmt (i, (m, static)) =
312
  fprintf fmt "%a(%s, %a%t%s)"
313
    pp_machine_static_declare_name (node_name m)
314
    attr
315
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
316
    (Utils.pp_final_char_if_non_empty ", " static)
317
    i
318

  
319
let print_static_declare_macro fmt m =
320
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
321
  let inst = mk_instance m in
322
  let attr = mk_attribute m in
323
  fprintf fmt "@[<v 2>#define %a(%s, %a%t%s)\\@,%s %a %s;\\@,%a%t%a;@,@]"
324
    pp_machine_static_declare_name m.mname.node_id
325
    attr
326
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
327
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
328
    inst
329
    attr
330
    pp_machine_memtype_name m.mname.node_id
331
    inst
332
    (Utils.fprintf_list ~sep:";\\@," pp_c_decl_local_var) array_mem
333
    (Utils.pp_final_char_if_non_empty ";\\@," array_mem)
334
    (Utils.fprintf_list ~sep:";\\@,"
335
       (fun fmt (i',m') ->
336
	 let path = sprintf "inst ## _%s" i' in
337
	 fprintf fmt "%a"
338
	   (print_static_declare_instance attr) (path,m')
339
       )) m.minstances
340

  
341
      
342
let print_static_link_instance fmt (i, (m, _)) =
343
 fprintf fmt "%a(%s)" pp_machine_static_link_name (node_name m) i
344

  
345
(* Allocation of a node struct:
346
   - if node memory is an array/matrix/etc, we cast it to a pointer (see pp_registers_struct)
347
*)
348
let print_static_link_macro fmt m =
349
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
350
  fprintf fmt "@[<v>@[<v 2>#define %a(inst) do {\\@,%a%t%a;\\@]@,} while (0)@.@]"
351
    pp_machine_static_link_name m.mname.node_id
352
    (Utils.fprintf_list ~sep:";\\@,"
353
       (fun fmt v ->
354
	 fprintf fmt "inst._reg.%s = (%a*) &%s"
355
	   v.var_id
356
           (fun fmt v -> pp_c_type "" fmt (Types.array_base_type v.var_type)) v
357
	   v.var_id
358
       )) array_mem
359
    (Utils.pp_final_char_if_non_empty ";\\@," array_mem)
360
    (Utils.fprintf_list ~sep:";\\@,"
361
       (fun fmt (i',m') ->
362
	 let path = sprintf "inst ## _%s" i' in
363
	 fprintf fmt "%a;\\@,inst.%s = &%s"
364
	   print_static_link_instance (path,m')
365
	   i'
366
	   path
367
       )) m.minstances
368
      
369
let print_static_alloc_macro fmt m =
370
  fprintf fmt "@[<v>@[<v 2>#define %a(attr,%a%tinst)\\@,%a(attr,%a%tinst);\\@,%a(inst);@]@,@]@."
371
    pp_machine_static_alloc_name m.mname.node_id
372
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
373
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
374
    pp_machine_static_declare_name m.mname.node_id
375
    (Utils.fprintf_list ~sep:", " (pp_c_var_read m)) m.mstatic
376
    (Utils.pp_final_char_if_non_empty ", " m.mstatic)
377
    pp_machine_static_link_name m.mname.node_id
378

  
379
 
380
let print_machine_decl fmt m =
381
  !print_machine_decl_prefix fmt m;
382
  if fst (get_stateless_status m) then
383
    begin
384
      fprintf fmt "extern %a;@.@."
385
	print_stateless_prototype
386
	(m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
387
    end
388
  else
389
    begin
390
      (* Static allocation *)
391
      if !Options.static_mem
392
      then (
393
	fprintf fmt "%a@.%a@.%a@."
394
	  print_static_declare_macro m
395
	  print_static_link_macro m
396
	  print_static_alloc_macro m
397
      )
398
      else ( 
399
        (* Dynamic allocation *)
400
	fprintf fmt "extern %a;@.@."
401
	  print_alloc_prototype (m.mname.node_id, m.mstatic)
402
      );
403
      let self = mk_self m in
404
      fprintf fmt "extern %a;@.@."
405
	(print_reset_prototype self) (m.mname.node_id, m.mstatic);
406

  
407
      fprintf fmt "extern %a;@.@."
408
	(print_step_prototype self)
409
	(m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
410
    end
411

  
412

  
413
(********************************************************************************************)
414
(*                         C file Printing functions                                        *)
415
(********************************************************************************************)
416

  
417
let print_const_def fmt cdecl =
418
  fprintf fmt "%a = %a;@." 
419
    (pp_c_type cdecl.const_id) cdecl.const_type
420
    pp_c_const cdecl.const_value 
421

  
422
let print_const_decl fmt cdecl =
423
  fprintf fmt "extern %a;@." 
424
    (pp_c_type cdecl.const_id) cdecl.const_type
425

  
426
let print_alloc_instance fmt (i, (m, static)) =
427
  fprintf fmt "_alloc->%s = %a (%a);@,"
428
    i
429
    pp_machine_alloc_name (node_name m)
430
    (Utils.fprintf_list ~sep:", " Dimension.pp_dimension) static
431

  
432
let print_alloc_array fmt vdecl =
433
  let base_type = Types.array_base_type vdecl.var_type in
434
  let size_types = Types.array_type_multi_dimension vdecl.var_type in
435
  let size_type = Dimension.multi_dimension_product vdecl.var_loc size_types in
436
  fprintf fmt "_alloc->_reg.%s = (%a*) malloc((%a)*sizeof(%a));@,assert(_alloc->%s);@,"
437
    vdecl.var_id
438
    (pp_c_type "") base_type
439
    Dimension.pp_dimension size_type
440
    (pp_c_type "") base_type
441
    vdecl.var_id
442

  
443
let print_alloc_code fmt m =
444
  let array_mem = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
445
  fprintf fmt "%a *_alloc;@,_alloc = (%a *) malloc(sizeof(%a));@,assert(_alloc);@,%a%areturn _alloc;"
446
    pp_machine_memtype_name m.mname.node_id
447
    pp_machine_memtype_name m.mname.node_id
448
    pp_machine_memtype_name m.mname.node_id
449
    (Utils.fprintf_list ~sep:"" print_alloc_array) array_mem
450
    (Utils.fprintf_list ~sep:"" print_alloc_instance) m.minstances
451

  
452
let print_stateless_code dependencies fmt m =
453
  let self = "__ERROR__" in
454
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
455
  then
456
    (* C99 code *)
457
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
458
      print_stateless_prototype (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
459
      (* locals *)
460
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
461
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
462
      (* check assertions *)
463
      (pp_c_checks self) m
464
      (* instrs *)
465
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
466
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
467
      (fun fmt -> fprintf fmt "return;")
468
  else
469
    (* C90 code *)
470
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
471
    let gen_calls = List.map (fun e -> let (id, _, _) = call_of_expr e in mk_call_var_decl e.expr_loc id) m.mname.node_gencalls in
472
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
473
      print_stateless_prototype (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
474
      (* locals *)
475
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
476
      (Utils.pp_final_char_if_non_empty ";" base_locals)
477
      (* check assertions *)
478
      (pp_c_checks self) m
479
      (* instrs *)
480
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
481
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
482
      (fun fmt -> fprintf fmt "return;")
483

  
484
let print_reset_code dependencies fmt m self =
485
  fprintf fmt "@[<v 2>%a {@,%a%treturn;@]@,}@.@."
486
    (print_reset_prototype self) (m.mname.node_id, m.mstatic)
487
    (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.minit
488
    (Utils.pp_newline_if_non_empty m.minit)
489

  
490
let print_step_code dependencies fmt m self =
491
  if not (!Options.ansi && is_generic_node { top_decl_desc = Node m.mname; top_decl_loc = Location.dummy_loc })
492
  then
493
    (* C99 code *)
494
    let array_mems = List.filter (fun v -> Types.is_array_type v.var_type) m.mmemory in
495
    fprintf fmt "@[<v 2>%a {@,%a%t%a%t@,%a%a%t%t@]@,}@.@."
496
      (print_step_prototype self) (m.mname.node_id, m.mstep.step_inputs, m.mstep.step_outputs)
497
      (* locals *)
498
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) m.mstep.step_locals
499
      (Utils.pp_final_char_if_non_empty ";@," m.mstep.step_locals)
500
      (* array mems *)
501
      (Utils.fprintf_list ~sep:";@," (pp_c_decl_array_mem self)) array_mems
502
      (Utils.pp_final_char_if_non_empty ";@," array_mems)
503
      (* check assertions *)
504
      (pp_c_checks self) m
505
      (* instrs *)
506
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
507
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
508
      (fun fmt -> fprintf fmt "return;")
509
  else
510
    (* C90 code *)
511
    let (gen_locals, base_locals) = List.partition (fun v -> Types.is_generic_type v.var_type) m.mstep.step_locals in
512
    let gen_calls = List.map (fun e -> let (id, _, _) = call_of_expr e in mk_call_var_decl e.expr_loc id) m.mname.node_gencalls in
513
    fprintf fmt "@[<v 2>%a {@,%a%t@,%a%a%t%t@]@,}@.@."
514
      (print_step_prototype self) (m.mname.node_id, (m.mstep.step_inputs@gen_locals@gen_calls), m.mstep.step_outputs)
515
      (* locals *)
516
      (Utils.fprintf_list ~sep:";@," pp_c_decl_local_var) base_locals
517
      (Utils.pp_final_char_if_non_empty ";" base_locals)
518
      (* check assertions *)
519
      (pp_c_checks self) m
520
      (* instrs *)
521
      (Utils.fprintf_list ~sep:"@," (pp_machine_instr dependencies m self)) m.mstep.step_instrs
522
      (Utils.pp_newline_if_non_empty m.mstep.step_instrs)
523
      (fun fmt -> fprintf fmt "return;")
524

  
525
let print_machine dependencies fmt m =
526
  if fst (get_stateless_status m) then
527
    begin
528
      (* Step function *)
529
      print_stateless_code dependencies fmt m
530
    end
531
  else
532
    begin
533
      (* Alloc function, only if non static mode *)
534
      if (not !Options.static_mem) then  
535
	(
536
	  fprintf fmt "@[<v 2>%a {@,%a@]@,}@.@."
537
	    print_alloc_prototype (m.mname.node_id, m.mstatic)
538
	    print_alloc_code m;
539
	);
540
      let self = mk_self m in
541
      (* Reset function *)
542
      print_reset_code dependencies fmt m self;
543
      (* Step function *)
544
      print_step_code dependencies fmt m self
545
    end
546

  
547

  
548

  
549
let header_has_code header =
550
  List.exists 
551
    (fun top -> 
552
      match top.top_decl_desc with
553
      | Consts _ -> true 
554
      | ImportedNode nd -> nd.nodei_in_lib = None
555
      | _ -> false
556
    )
557
    header
558

  
559
let header_libs header =
560
  List.fold_left (fun accu top ->
561
    match top.top_decl_desc with
562
      | ImportedNode nd -> (match nd.nodei_in_lib with 
563
	| None -> accu 
564
	| Some lib -> Utils.list_union [lib] accu)
565
      | _ -> accu 
566
  ) [] header 
567
    
568
let print_makefile basename nodename dependencies fmt =
569
  let compiled_dependencies = 
570
    List.filter (fun (_, _, header) -> header_has_code header) dependencies
571
  in
572
  let lib_dependencies = 
573
    List.fold_left 
574
      (fun accu (_, _, header) -> Utils.list_union (header_libs header) accu) [] dependencies 
575
  in
576
  fprintf fmt "GCC=gcc@.";
577
  fprintf fmt "LUSTREC=%s@." Sys.executable_name;
578
  fprintf fmt "LUSTREC_BASE=%s@." (Filename.dirname (Filename.dirname Sys.executable_name));
579
  fprintf fmt "INC=${LUSTREC_BASE}/include/lustrec@.";
580
  fprintf fmt "@.";
581
  fprintf fmt "%s_%s:@." basename nodename;
582
  fprintf fmt "\t${GCC} -I${INC} -I. -c %s.c@." basename;    
583
  List.iter (fun s -> (* Format.eprintf "Adding dependency: %s@." s;  *)
584
    fprintf fmt "\t${GCC} -I${INC} -c %s@." s)
585
    (("${INC}/io_frontend.c"):: (* IO functions when a main function is computed *)
586
	(List.map 
587
	   (fun (s, local, _) -> 
588
	     (if local then s else Version.prefix ^ "/include/lustrec/" ^ s) ^ ".c")
589
	   compiled_dependencies));    
590
  fprintf fmt "\t${GCC} -o %s_%s io_frontend.o %a %s.o %a@." basename nodename 
591
    (Utils.fprintf_list ~sep:" " (fun fmt (s, _, _) -> Format.fprintf fmt "%s.o" s)) compiled_dependencies 
592
    basename
593
    (Utils.fprintf_list ~sep:" " (fun fmt lib -> fprintf fmt "-l%s" lib)) lib_dependencies
594
    ;
595
 fprintf fmt "@.";
596
 fprintf fmt "clean:@.";
597
 fprintf fmt "\t\\rm -f *.o %s_%s@." basename nodename
598

  
599

  
600
let rec pp_c_struct_type_field filename cpt fmt (label, tdesc) =
601
  fprintf fmt "%a;" (pp_c_type_decl filename cpt label) tdesc
602
and pp_c_type_decl filename cpt var fmt tdecl =
603
  match tdecl with
604
  | Tydec_any           -> assert false
605
  | Tydec_int           -> fprintf fmt "int %s" var
606
  | Tydec_real          -> fprintf fmt "double %s" var
607
  | Tydec_float         -> fprintf fmt "float %s" var
608
  | Tydec_bool          -> fprintf fmt "_Bool %s" var
609
  | Tydec_clock ty      -> pp_c_type_decl filename cpt var fmt ty
610
  | Tydec_const c       -> fprintf fmt "%s %s" c var
611
  | Tydec_array (d, ty) -> fprintf fmt "%a[%a]" (pp_c_type_decl filename cpt var) ty pp_c_dimension d
612
  | Tydec_enum tl ->
613
    begin
614
      incr cpt;
615
      fprintf fmt "enum _enum_%s_%d { %a } %s" filename !cpt (Utils.fprintf_list ~sep:", " pp_print_string) tl var
616
    end
617
  | Tydec_struct fl ->
618
    begin
619
      incr cpt;
620
      fprintf fmt "struct _struct_%s_%d { %a } %s" filename !cpt (Utils.fprintf_list ~sep:" " (pp_c_struct_type_field filename cpt)) fl var
621
    end
622

  
623
let print_type_definitions fmt filename =
624
  let cpt_type = ref 0 in
625
  Hashtbl.iter (fun typ def ->
626
    match typ with
627
    | Tydec_const var ->
628
      fprintf fmt "typedef %a;@.@."
629
	(pp_c_type_decl filename cpt_type var) def
630
    | _        -> ()) type_table
631

  
632

  
633 26

  
634 27
(********************************************************************************************)
635 28
(*                         Translation function                                             *)
636 29
(********************************************************************************************)
637
let print_header header_fmt basename prog machines =
638
  (* Include once: start *)
639
  let baseNAME = String.uppercase basename in
640
  let baseNAME = Str.global_replace (Str.regexp "\\.\\|\\ ") "_" baseNAME in
641
  (* Print the svn version number and the supported C standard (C90 or C99) *)
642
  print_version header_fmt;
643
  fprintf header_fmt "#ifndef _%s@.#define _%s@." baseNAME baseNAME;
644
  pp_print_newline header_fmt ();
645
  fprintf header_fmt "/* Imports standard library */@.";
646
  (* imports standard library definitions (arrow) *)
647
  print_import_standard header_fmt;
648
  pp_print_newline header_fmt ();
649
  fprintf header_fmt "/* Types definitions */@.";
650
  (* Print the type definitions from the type table *)
651
  print_type_definitions header_fmt basename;
652
  pp_print_newline header_fmt ();
653
  (* Print the global constant declarations. *)
654
  fprintf header_fmt "/* Global constant (declarations, definitions are in C file) */@.";
655
  List.iter (fun c -> print_const_decl header_fmt c) (get_consts prog);
656
  pp_print_newline header_fmt ();
657
  (* Print the struct declarations of all machines. *)
658
  fprintf header_fmt "/* Struct declarations */@.";
659
  List.iter (print_machine_struct header_fmt) machines;
660
  pp_print_newline header_fmt ();
661
  (* Print the prototypes of all machines *)
662
  fprintf header_fmt "/* Nodes declarations */@.";
663
  List.iter (print_machine_decl header_fmt) machines;
664
  pp_print_newline header_fmt ();
665
  (* Include once: end *)
666
  fprintf header_fmt "#endif@.";
667
  pp_print_newline header_fmt ()
668

  
669
let print_c source_fmt basename prog machines dependencies =
670

  
671
  (* If a main node is identified, generate a main function for it *)
672
  let main_include, main_print, main_makefile =
673
    match !Options.main_node with
674
      | "" -> (fun _ -> ()), (fun _ -> ()), (fun _ -> ())
675
      | main_node -> (
676
	match Machine_code.get_machine_opt main_node machines with
677
	| None -> eprintf "Unable to find a main node named %s@.@?" main_node; (fun _ -> ()), (fun _ -> ()), (fun _ -> ())
678
	| Some m -> C_backend_main.print_main_header, C_backend_main.print_main_fun machines m, print_makefile basename !Options.main_node dependencies
679
      )
680
  in
681
  main_include source_fmt;
682
  fprintf source_fmt "#include <stdlib.h>@.#include <assert.h>@.#include \"%s\"@.@." (basename^".h");
683
  (* Print the svn version number and the supported C standard (C90 or C99) *)
684
  print_version source_fmt;
685
  (* Print the prototype of imported nodes *)
686
  fprintf source_fmt "/* Imported nodes declarations */@.";
687
  fprintf source_fmt "@[<v>";
688
  List.iter (print_import_prototype source_fmt) dependencies;
689
  fprintf source_fmt "@]@.";
690
  (* Print consts *)
691
  fprintf source_fmt "/* Global constants (definitions) */@.";
692
  List.iter (fun c -> print_const_def source_fmt c) (get_consts prog);
693
  pp_print_newline source_fmt ();
694
  (* Print nodes one by one (in the previous order) *)
695
  List.iter (print_machine dependencies source_fmt) machines;
696
  main_print source_fmt
697 30

  
698 31
let translate_to_c header_fmt source_fmt makefile_fmt spec_fmt_opt 
699 32
                   basename prog machines dependencies =
700 33

  
701 34
  (* Generating H file *)
702
  print_header header_fmt basename prog machines;
35
  C_backend_header.print_header header_fmt basename prog machines;
703 36

  
704 37
  (* Generating C file *)
705
  print_c source_fmt basename prog machines dependencies;
38
  C_backend_src.print_c source_fmt basename prog machines dependencies;
706 39

  
707 40
  (* Generating Makefile *)
708 41
  (* If a main node is identified, generate a main target for it *)
......
710 43
      | "" ->  ()
711 44
      | main_node -> (
712 45
	match Machine_code.get_machine_opt main_node machines with
713
	| None -> eprintf "Unable to find a main node named %s@.@?" main_node; 
46
	| None -> Format.eprintf "Unable to find a main node named %s@.@?" main_node; 
714 47
	  ()
715
	| Some m -> print_makefile basename !Options.main_node dependencies makefile_fmt
48
	| Some _ -> C_backend_makefile.print_makefile basename !Options.main_node dependencies makefile_fmt
716 49
      )
717 50

  
718 51
(* Local Variables: *)
719
(* compile-command:"make -C .." *)
52
(* compile-command:"make -C ../../.." *)
720 53
(* End: *)

Also available in: Unified diff