Project

General

Profile

Download (16 KB) Statistics
| Branch: | Tag: | Revision:
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 = expand_automata prog in
96

    
97
  Log.report ~level:4 (fun fmt -> fprintf fmt ".. after automata expansion:@.@[<v 2>@ %a@]@," Printers.pp_prog prog);
98

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

    
102
  (* Extracting dependencies *)
103
  let dependencies, type_env, clock_env = import_dependencies prog in
104

    
105
  (* Sorting nodes *)
106
  let prog = SortProg.sort prog in
107

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

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

    
124
  (* Typing *)
125
  let computed_types_env = type_decls type_env prog in
126

    
127
  (* Clock calculus *)
128
  let computed_clocks_env = clock_decls clock_env prog in
129

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

    
136
 (* Optimization of prog: 
137
     - Unfold consts 
138
     - eliminate trivial expressions
139
 *)
140
  (*
141
  let prog = 
142
    if !Options.const_unfold || !Options.optimization >= 5 then
143
      begin
144
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. eliminating constants and aliases@,");
145
	Optimize_prog.prog_unfold_consts prog
146
      end
147
    else
148
      prog
149
  in
150
  *)
151
  (* Delay calculus *)
152
  (* TO BE DONE LATER (Xavier)
153
    if(!Options.delay_calculus)
154
    then
155
    begin
156
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. initialisation analysis@?");
157
    try
158
    Delay_calculus.delay_prog Basic_library.delay_env prog
159
    with (Delay.Error (loc,err)) as exc ->
160
    Location.print loc;
161
    eprintf "%a" Delay.pp_error err;
162
    Utils.track_exception ();
163
    raise exc
164
    end;
165
  *)
166

    
167
  (* Creating destination directory if needed *)
168
  create_dest_dir ();
169

    
170
  (* Compatibility with Lusi *)
171
  (* Checking the existence of a lusi (Lustre Interface file) *)
172
  let extension = ".lusi" in
173
  compile_source_to_header prog computed_types_env computed_clocks_env dirname basename extension;
174

    
175
  Typing.uneval_prog_generics prog;
176
  Clock_calculus.uneval_prog_generics prog;
177

    
178
  if !Options.global_inline && !Options.main_node <> "" && !Options.witnesses then
179
    begin
180
      let orig = Corelang.copy_prog orig in
181
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. generating witness file@,");
182
      check_stateless_decls orig;
183
      let _ = Typing.type_prog type_env orig in
184
      let _ = Clock_calculus.clock_prog clock_env orig in
185
      Typing.uneval_prog_generics orig;
186
      Clock_calculus.uneval_prog_generics orig;
187
      Inliner.witness
188
	basename
189
	!Options.main_node
190
	orig prog type_env clock_env
191
    end;
192
  
193
  (* Computes and stores generic calls for each node,
194
     only useful for ANSI C90 compliant generic node compilation *)
195
  if !Options.ansi then Causality.NodeDep.compute_generic_calls prog;
196
  (*Hashtbl.iter (fun id td -> match td.Corelang.top_decl_desc with
197
    Corelang.Node nd -> Format.eprintf "%s calls %a" id
198
    Causality.NodeDep.pp_generic_calls nd | _ -> ()) Corelang.node_table;*)
199

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

    
208
  let prog =
209
    if !Options.mpfr
210
    then
211
      begin
212
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. targetting MPFR library@,");
213
	Mpfr.inject_prog prog
214
      end
215
    else
216
      begin
217
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. keeping floating-point numbers@,");
218
	prog
219
      end in
220
  Log.report ~level:2 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@," Printers.pp_prog prog);
221

    
222
  (* Checking array accesses *)
223
  if !Options.check then
224
    begin
225
      Log.report ~level:1 (fun fmt -> fprintf fmt ".. checking array accesses@,");
226
      Access.check_prog prog;
227
    end;
228

    
229
  prog, dependencies
230

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

    
243

    
244
  (* TODO Salsa optimize prog: 
245
     - emits warning for programs with pre inside expressions
246
     - make sure each node arguments and memory is bounded by a local annotation
247
     - introduce fresh local variables for each real pure subexpression
248
  *)
249
  (* DFS with modular code generation *)
250
  Log.report ~level:1 (fun fmt -> fprintf fmt ".. machines generation@ ");
251
  let machine_code = Machine_code.translate_prog prog node_schs in
252

    
253
   (* Optimize machine code *)
254
  let machine_code =
255
    if !Options.optimization >= 4 (* && !Options.output <> "horn" *) then
256
      begin
257
	Log.report ~level:1 
258
	  (fun fmt -> fprintf fmt ".. machines optimization: sub-expression elimination@,");
259
	Optimize_machine.machines_cse machine_code
260
      end
261
    else
262
      machine_code
263
  in
264
  (* Optimize machine code *)
265
  let machine_code, removed_table = 
266
    if !Options.optimization >= 2 (*&& !Options.output <> "horn"*) then
267
      begin
268
	Log.report ~level:1 (fun fmt -> fprintf fmt 
269
    ".. machines optimization: const. inlining (partial eval. with const)@,");
270
	Optimize_machine.machines_unfold (Corelang.get_consts prog) node_schs machine_code
271
      end
272
    else
273
      machine_code, IMap.empty
274
  in  
275
  (* Optimize machine code *)
276
  let machine_code =
277
    if !Options.optimization >= 3 && not (Corelang.functional_backend ()) then
278
      begin
279
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. machines optimization: minimize stack usage by reusing variables@,");
280
	let node_schs    = Scheduling.remove_prog_inlined_locals removed_table node_schs in
281
	let reuse_tables = Scheduling.compute_prog_reuse_table node_schs in
282
	Optimize_machine.machines_fusion (Optimize_machine.machines_reuse_variables machine_code reuse_tables)
283
      end
284
    else
285
      machine_code
286
  in
287
  
288
  (* Salsa optimize machine code *)
289
  (*
290
  let machine_code = 
291
    if !Options.salsa_enabled then
292
      begin
293
	check_main ();
294
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. salsa machines optimization: optimizing floating-point accuracy with Salsa@,");
295
	(* Selecting float constants for Salsa *)
296
	let constEnv = List.fold_left (
297
	  fun accu c_topdecl ->
298
	    match c_topdecl.top_decl_desc with
299
	    | Const c when Types.is_real_type c.const_type  ->
300
	      (c.const_id, c.const_value) :: accu
301
	    | _ -> accu
302
	) [] (Corelang.get_consts prog) 
303
	in
304
	List.map 
305
	  (Machine_salsa_opt.machine_t2machine_t_optimized_by_salsa constEnv) 
306
	  machine_code 
307
      end
308
    else
309
      machine_code
310
  in
311
  Log.report ~level:3 (fun fmt -> fprintf fmt "@[<v 2>@ %a@]@ "
312
    (Utils.fprintf_list ~sep:"@ " Machine_code.pp_machine)
313
    machine_code);
314
  *)
315
  machine_code
316

    
317

    
318
(* printing code *)
319
let stage3 prog machine_code dependencies basename =
320
  let basename    =  Filename.basename basename in
321
  match !Options.output with
322
    "C" -> 
323
      begin
324
	Log.report ~level:1 (fun fmt -> fprintf fmt ".. C code generation@,");
325
	C_backend.translate_to_c
326
	  (* alloc_header_file source_lib_file source_main_file makefile_file *)
327
	  basename prog machine_code dependencies
328
      end
329
  | "java" ->
330
     begin
331
       (Format.eprintf "internal error: sorry, but not yet supported !"; assert false)
332
     (*let source_file = basename ^ ".java" in
333
       Log.report ~level:1 (fun fmt -> fprintf fmt ".. opening file %s@,@?" source_file);
334
       let source_out = open_out source_file in
335
       let source_fmt = formatter_of_out_channel source_out in
336
       Log.report ~level:1 (fun fmt -> fprintf fmt ".. java code generation@,@?");
337
       Java_backend.translate_to_java source_fmt basename normalized_prog machine_code;*)
338
     end
339
  | "horn" ->
340
     begin
341
       let destname = !Options.dest_dir ^ "/" ^ basename in
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.traces 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 destname = !Options.dest_dir ^ "/" ^ basename in
359
       let source_file = destname ^ ".lustrec.lus" in (* Could be changed *)
360
       let source_out = open_out source_file in
361
       let fmt = formatter_of_out_channel source_out in
362
       Printers.pp_prog fmt prog;
363
       (*	Lustre_backend.translate fmt basename normalized_prog machine_code *)
364
       ()
365
     end
366

    
367
  | _ -> assert false
368

    
369
(* compile a .lus source file *)
370
let rec compile_source dirname basename extension =
371
  let source_name = dirname ^ "/" ^ basename ^ extension in
372

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

    
375
  (* Parsing source *)
376
  let prog = parse_source source_name in
377

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

    
401
  let machine_code = 
402
    stage2 prog 
403
  in
404
  if Scopes.Plugin.show_scopes () then
405
    begin
406
      let all_scopes = Scopes.compute_scopes prog !Options.main_node in
407
      (* Printing scopes *)
408
      if !Options.verbose_level >= 1 then
409
	Format.printf "Possible scopes are:@   ";
410
      Format.printf "@[<v>%a@ @]@.@?" Scopes.print_scopes all_scopes;
411
      exit 0
412
	
413
    end;
414

    
415
  let machine_code = Plugins.refine_machine_code prog machine_code in
416
  
417
  stage3 prog machine_code dependencies basename;
418
  begin
419
    Log.report ~level:1 (fun fmt -> fprintf fmt ".. done !@ @]@.");
420
    (* We stop the process here *)
421
    exit 0
422
  end
423

    
424
let compile dirname basename extension =
425
  match extension with
426
  | ".lusi"  -> compile_header dirname basename extension
427
  | ".lus"   -> compile_source dirname basename extension
428
  | _        -> assert false
429

    
430
let anonymous filename =
431
  let ok_ext, ext = List.fold_left
432
    (fun (ok, ext) ext' ->
433
      if not ok && Filename.check_suffix filename ext' then
434
	true, ext'
435
      else
436
	ok, ext)
437
    (false, "") extensions in
438
  if ok_ext then
439
    let dirname = Filename.dirname filename in
440
    let basename = Filename.chop_suffix (Filename.basename filename) ext in
441
    compile dirname basename ext
442
  else
443
    raise (Arg.Bad ("Can only compile *.lusi, *.lus or *.ec files"))
444

    
445
let _ =
446
  Global.initialize ();
447
  Corelang.add_internal_funs ();
448
  try
449
    Printexc.record_backtrace true;
450

    
451
    let options = Options.lustrec_options @ (Plugins.options ()) in
452
    
453
    Arg.parse options anonymous usage
454
  with
455
  | Parse.Error _
456
  | Types.Error (_,_) | Clocks.Error (_,_)
457
  | Corelang.Error _ (*| Task_set.Error _*)
458
  | Causality.Error _ -> exit 1
459
  | Sys_error msg -> (eprintf "Failure: %s@." msg)
460
  | exc -> (Utils.track_exception (); raise exc)
461

    
462
(* Local Variables: *)
463
(* compile-command:"make -C .." *)
464
(* End: *)
(34-34/60)