Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

lustrec / src / main_lustre_compiler.ml @ 76c7023b

History | View | Annotate | Download (15.5 KB)

1
(********************************************************************)
2
(*                                                                  *)
3
(*  The LustreC compiler toolset   /  The LustreC Development Team  *)
4
(*  Copyright 2012 -    --   ONERA - CNRS - INPT                    *)
5
(*                                                                  *)
6
(*  LustreC is free software, distributed WITHOUT ANY WARRANTY      *)
7
(*  under the terms of the GNU Lesser General Public License        *)
8
(*  version 2.1.                                                    *)
9
(*                                                                  *)
10
(********************************************************************)
11

    
12
open Format
13
open Log
14

    
15
open Utils
16
open LustreSpec
17
open Compiler_common
18
 
19
exception StopPhase1 of program
20

    
21
let usage = "Usage: lustrec [options] \x1b[4msource-file\x1b[0m"
22

    
23
let extensions = [".ec"; ".lus"; ".lusi"]
24

    
25
(* print a .lusi header file from a source prog *)
26
let print_lusi prog dirname basename extension =
27
  let header = Lusic.extract_header dirname basename prog in
28
  let header_name = dirname ^ "/" ^ basename ^ extension in
29
  let h_out = open_out header_name in
30
  let h_fmt = formatter_of_out_channel h_out in
31
  begin
32
    Typing.uneval_prog_generics header;
33
    Clock_calculus.uneval_prog_generics header;
34
    Printers.pp_lusi_header h_fmt basename header;
35
    close_out h_out
36
  end
37

    
38
(* compile a .lusi header file *)
39
let compile_header dirname basename extension =
40
  let destname = !Options.dest_dir ^ "/" ^ basename in
41
  let header_name = basename ^ extension in
42
  let lusic_ext = extension ^ "c" in
43
  begin
44
    Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v>");
45
    let header = parse_header true (dirname ^ "/" ^ header_name) in
46
    ignore (Modules.load_header ISet.empty header);
47
    ignore (check_top_decls header);
48
    create_dest_dir ();
49
    Log.report ~level:1
50
      (fun fmt -> fprintf fmt ".. generating compiled header file %sc@," (destname ^ extension));
51
    Lusic.write_lusic true header destname lusic_ext;
52
    Lusic.print_lusic_to_h destname lusic_ext;
53
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.")
54
  end
55

    
56
(* check whether a source file has a compiled header,
57
   if not, generate the compiled header *)
58
let compile_source_to_header prog computed_types_env computed_clocks_env dirname basename extension =
59
  let destname = !Options.dest_dir ^ "/" ^ basename in
60
  let lusic_ext = extension ^ "c" in
61
  let header_name = destname ^ lusic_ext in
62
  begin
63
    if not (Sys.file_exists header_name) then
64
      begin
65
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating compiled header file %s@," header_name);
66
	Lusic.write_lusic false (Lusic.extract_header dirname basename prog) destname lusic_ext;
67
	Lusic.print_lusic_to_h destname lusic_ext
68
      end
69
    else
70
      let lusic = Lusic.read_lusic destname lusic_ext in
71
      if not lusic.Lusic.from_lusi then
72
	begin
73
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating compiled header file %s@," header_name);
74
       	  Lusic.write_lusic false (Lusic.extract_header dirname basename prog) destname lusic_ext;
75
(*List.iter (fun top_decl -> Format.eprintf "lusic: %a@." Printers.pp_decl top_decl) lusic.Lusic.contents;*)
76
	  Lusic.print_lusic_to_h destname lusic_ext
77
	end
78
      else
79
	begin
80
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. loading compiled header file %s@," header_name);
81
	  Modules.check_dependency lusic destname;
82
	  let header = lusic.Lusic.contents in
83
	  let (declared_types_env, declared_clocks_env) = get_envs_from_top_decls header in
84
	  check_compatibility
85
	    (prog, computed_types_env, computed_clocks_env)
86
	    (header, declared_types_env, declared_clocks_env)
87
	end
88
  end
89

    
90

    
91

    
92
(* From prog to prog *)
93
let stage1 prog dirname basename =
94
  (* Removing automata *) 
95
  let prog = Automata.expand_decls prog in
96

    
97
  (* Importing source *)
98
  let _ = Modules.load_program ISet.empty prog in
99

    
100
  (* Extracting dependencies *)
101
  let dependencies, type_env, clock_env = import_dependencies prog in
102

    
103
  (* Sorting nodes *)
104
  let prog = SortProg.sort prog in
105

    
106
  (* Perform inlining before any analysis *)
107
  let orig, prog =
108
    if !Options.global_inline && !Options.main_node <> "" then
109
      (if !Options.witnesses then prog else []),
110
      Inliner.global_inline basename prog type_env clock_env
111
    else (* if !Option.has_local_inline *)
112
      [],
113
      Inliner.local_inline basename prog type_env clock_env
114
  in
115

    
116
  (* Checking stateless/stateful status *)
117
  if Plugins.check_force_stateful () then
118
    force_stateful_decls prog
119
  else
120
    check_stateless_decls prog;
121

    
122
  (* Typing *)
123
  let computed_types_env = type_decls type_env prog in
124

    
125
  (* Clock calculus *)
126
  let computed_clocks_env = clock_decls clock_env prog in
127

    
128
  (* Generating a .lusi header file only *)
129
  if !Options.lusi then
130
    (* We stop here the processing and produce the current prog. It will be
131
       exported as a lusi *)
132
    raise (StopPhase1 prog);
133

    
134
  (* Delay calculus *)
135
  (* TO BE DONE LATER (Xavier)
136
    if(!Options.delay_calculus)
137
    then
138
    begin
139
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. initialisation analysis@?");
140
    try
141
    Delay_calculus.delay_prog Basic_library.delay_env prog
142
    with (Delay.Error (loc,err)) as exc ->
143
    Location.print loc;
144
    eprintf "%a" Delay.pp_error err;
145
    Utils.track_exception ();
146
    raise exc
147
    end;
148
  *)
149

    
150
  (* Creating destination directory if needed *)
151
  create_dest_dir ();
152

    
153
  (* Compatibility with Lusi *)
154
  (* Checking the existence of a lusi (Lustre Interface file) *)
155
  let extension = ".lusi" in
156
  compile_source_to_header prog computed_types_env computed_clocks_env dirname basename extension;
157

    
158
  Typing.uneval_prog_generics prog;
159
  Clock_calculus.uneval_prog_generics prog;
160

    
161
  if !Options.global_inline && !Options.main_node <> "" && !Options.witnesses then
162
    begin
163
      let orig = Corelang.copy_prog orig in
164
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating witness file@,");
165
      check_stateless_decls orig;
166
      let _ = Typing.type_prog type_env orig in
167
      let _ = Clock_calculus.clock_prog clock_env orig in
168
      Typing.uneval_prog_generics orig;
169
      Clock_calculus.uneval_prog_generics orig;
170
      Inliner.witness
171
	basename
172
	!Options.main_node
173
	orig prog type_env clock_env
174
    end;
175

    
176
  (* Computes and stores generic calls for each node,
177
     only useful for ANSI C90 compliant generic node compilation *)
178
  if !Options.ansi then Causality.NodeDep.compute_generic_calls prog;
179
  (*Hashtbl.iter (fun id td -> match td.Corelang.top_decl_desc with
180
    Corelang.Node nd -> Format.eprintf "%s calls %a" id
181
    Causality.NodeDep.pp_generic_calls nd | _ -> ()) Corelang.node_table;*)
182

    
183
  (* Optimization of prog: 
184
     - Unfold consts 
185
     - eliminate trivial expressions
186
  *)
187
  let prog = 
188
    if !Options.const_unfold || !Options.optimization >= 4 then 
189
      Optimize_prog.prog_unfold_consts prog 
190
    else
191
      prog
192
  in
193

    
194
  (* Normalization phase *)
195
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. normalization@,");
196
  (* Special treatment of arrows in lustre backend. We want to keep them *)
197
  if !Options.output = "lustre" then
198
    Normalization.unfold_arrow_active := false;
199
  let prog = Normalization.normalize_prog prog in
200
  Log.report ~level:2 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
201

    
202
  let prog =
203
    if !Options.mpfr
204
    then
205
      begin
206
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. targetting MPFR library@,");
207
	Mpfr.inject_prog prog
208
      end
209
    else
210
      begin
211
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. keeping FP numbers@,");
212
	prog
213
      end in
214
  Log.report ~level:2 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
215

    
216
  (* Checking array accesses *)
217
  if !Options.check then
218
    begin
219
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. array access checks@,");
220
      Access.check_prog prog;
221
    end;
222

    
223
  prog, dependencies
224

    
225
(* prog -> machine *)
226

    
227
let stage2 prog =    
228

    
229
  (* Computation of node equation scheduling. It also breaks dependency cycles
230
     and warns about unused input or memory variables *)
231
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. scheduling@,");
232
  let prog, node_schs = Scheduling.schedule_prog prog in
233
  Log.report ~level:1 (fun fmt -> fprintf fmt "%a"              Scheduling.pp_warning_unused node_schs);
234
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Scheduling.pp_schedule node_schs);
235
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Scheduling.pp_fanin_table node_schs);
236
  Log.report ~level:5 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Scheduling.pp_dep_graph node_schs);
237
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
238

    
239
 (* Optimization of prog:
240
    - Unfold consts
241
    - eliminate trivial expressions
242
	TODO (PL): should we keep this phase or just remove it 
243
 *)
244
  let prog =
245
    if !Options.optimization >= 5 then
246
      begin
247
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. constants elimination@,");
248
	Optimize_prog.prog_unfold_consts prog
249
      end
250
    else
251
      prog
252
  in
253

    
254
  (* TODO Salsa optimize prog: 
255
     - emits warning for programs with pre inside expressions
256
     - make sure each node arguments and memory is bounded by a local annotation
257
     - introduce fresh local variables for each real pure subexpression
258
  *)
259
 (*  let prog =  *)
260
 (*    if true then *)
261
 (*      Salsa.Prog.normalize prog *)
262
 (*    else *)
263
 (*      prog *)
264
 (* in *)
265

    
266
  (* DFS with modular code generation *)
267
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. machines generation@ ");
268
  let machine_code = Machine_code.translate_prog prog node_schs in
269

    
270
   (* Optimize machine code *)
271
  let machine_code =
272
    if !Options.optimization >= 4 (* && !Options.output <> "horn" *) then
273
      begin
274
	Log.report ~level:1 
275
	  (fun fmt -> fprintf fmt ".. machines optimization: sub-expression elimination@,");
276
	Optimize_machine.machines_cse machine_code
277
      end
278
    else
279
      machine_code
280
  in
281
  
282
  (* Optimize machine code *)
283
  let machine_code, removed_table = 
284
    if !Options.optimization >= 2 (*&& !Options.output <> "horn"*) then
285
      begin
286
	Log.report ~level:1 (fun fmt -> fprintf fmt 
287
    ".. machines optimization: const. inlining (partial eval. with const)@,");
288
	Optimize_machine.machines_unfold (Corelang.get_consts prog) node_schs machine_code
289
      end
290
    else
291
      machine_code, IMap.empty
292
  in  
293
  (* Optimize machine code *)
294
  let machine_code =  (* TODO reactivate. I disabled it because output variables were removed *)
295
    if false && !Options.optimization >= 3 && not (Corelang.functional_backend ()) then
296
      begin
297
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. machines optimization: minimize heap alloc by reusing vars@,");
298
	let node_schs    = Scheduling.remove_prog_inlined_locals removed_table node_schs in
299
	let reuse_tables = Scheduling.compute_prog_reuse_table node_schs in
300
	Optimize_machine.machines_fusion (Optimize_machine.machines_reuse_variables machine_code reuse_tables)
301
      end
302
    else
303
      machine_code
304
  in
305
  
306
  (* Salsa optimize machine code *)
307
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@ "
308
    (Utils.fprintf_list ~sep:"@ " Machine_code.pp_machine)
309
    machine_code);
310

    
311
  machine_code
312

    
313

    
314
let stage3 prog machine_code dependencies basename =
315
  (* Printing code *)
316
  let basename    =  Filename.basename basename in
317
  let destname = !Options.dest_dir ^ "/" ^ basename in
318
  match !Options.output with
319
      "C" -> 
320
	begin
321
	  let alloc_header_file = destname ^ "_alloc.h" in (* Could be changed *)
322
	  let source_lib_file = destname ^ ".c" in (* Could be changed *)
323
	  let source_main_file = destname ^ "_main.c" in (* Could be changed *)
324
	  let makefile_file = destname ^ ".makefile" in (* Could be changed *)
325
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. C code generation@,");
326
	  C_backend.translate_to_c
327
	    alloc_header_file source_lib_file source_main_file makefile_file
328
	    basename prog machine_code dependencies
329
	end
330
    | "java" ->
331
      begin
332
	failwith "Sorry, but not yet supported !"
333
    (*let source_file = basename ^ ".java" in
334
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. opening file %s@,@?" source_file);
335
      let source_out = open_out source_file in
336
      let source_fmt = formatter_of_out_channel source_out in
337
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. java code generation@,@?");
338
      Java_backend.translate_to_java source_fmt basename normalized_prog machine_code;*)
339
      end
340
    | "horn" ->
341
      begin
342
	let source_file = destname ^ ".smt2" in (* Could be changed *)
343
	let source_out = open_out source_file in
344
	let fmt = formatter_of_out_channel source_out in
345
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. hornification@,");
346
        Horn_backend.translate fmt basename prog (Machine_code.arrow_machine::machine_code);
347
	(* Tracability file if option is activated *)
348
	if !Options.horntraces then (
349
	let traces_file = destname ^ ".traces.xml" in (* Could be changed *)
350
	let traces_out = open_out traces_file in
351
	let fmt = formatter_of_out_channel traces_out in
352
        Log.report ~level:1 (fun fmt -> fprintf fmt ".. tracing info@,");
353
	Horn_backend_traces.traces_file fmt basename prog machine_code;
354
	)
355
      end
356
    | "lustre" ->
357
      begin
358
	let source_file = destname ^ ".lustrec.lus" in (* Could be changed *)
359
	let source_out = open_out source_file in
360
	let fmt = formatter_of_out_channel source_out in
361
	Printers.pp_prog fmt prog;
362
(*	Lustre_backend.translate fmt basename normalized_prog machine_code *)
363
	()
364
      end
365

    
366
    | _ -> assert false
367

    
368
(* compile a .lus source file *)
369
let compile_source dirname basename extension =
370

    
371
  Log.report ~level:1 (fun fmt -> fprintf fmt "@[<v>");
372

    
373
  (* Parsing source *)
374
  let prog = parse_source (dirname ^ "/" ^ basename ^ extension) in
375

    
376
  let prog =
377
    if !Options.mpfr then
378
      Mpfr.mpfr_module::prog
379
    else
380
      prog
381
  in
382
  let prog, dependencies = 
383
    try 
384
      stage1 prog dirname basename
385
    with StopPhase1 prog -> (
386
      if !Options.lusi then
387
	begin
388
	  let lusi_ext = ".lusi" (* extension ^ "i" *) in
389
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating interface file %s@," (dirname ^ "/" ^ basename ^ lusi_ext));
390
	  print_lusi prog dirname basename lusi_ext;
391
	  Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.");
392
	  exit 0
393
	end
394
      else
395
        assert false
396
    )
397
  in
398

    
399
  let machine_code = 
400
    stage2 prog 
401
  in
402

    
403
  let machine_code = Plugins.refine_machine_code prog machine_code in
404
  
405
  stage3 prog machine_code dependencies basename;
406
  begin
407
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.");
408
    (* We stop the process here *)
409
    exit 0
410
  end
411

    
412
let compile dirname basename extension =
413
  match extension with
414
  | ".lusi"  -> compile_header dirname basename extension
415
  | ".lus"   -> compile_source dirname basename extension
416
  | _        -> assert false
417

    
418
let anonymous filename =
419
  let ok_ext, ext = List.fold_left
420
    (fun (ok, ext) ext' ->
421
      if not ok && Filename.check_suffix filename ext' then
422
	true, ext'
423
      else
424
	ok, ext)
425
    (false, "") extensions in
426
  if ok_ext then
427
    let dirname = Filename.dirname filename in
428
    let basename = Filename.chop_suffix (Filename.basename filename) ext in
429
    compile dirname basename ext
430
  else
431
    raise (Arg.Bad ("Can only compile *.lusi, *.lus or *.ec files"))
432

    
433
let _ =
434
  Global.initialize ();
435
  Corelang.add_internal_funs ();
436
  try
437
    Printexc.record_backtrace true;
438

    
439
    let options = Options.options @ (Plugins.options ()) in
440
    
441
    Arg.parse options anonymous usage
442
  with
443
  | Parse.Syntax_err _ | Lexer_lustre.Error _
444
  | Types.Error (_,_) | Clocks.Error (_,_)
445
  | Corelang.Error _ (*| Task_set.Error _*)
446
  | Causality.Cycle _ -> exit 1
447
  | Sys_error msg -> (eprintf "Failure: %s@." msg)
448
  | exc -> (Utils.track_exception (); raise exc)
449

    
450
(* Local Variables: *)
451
(* compile-command:"make -C .." *)
452
(* End: *)