-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathgenerate.ml
2281 lines (2128 loc) · 79.3 KB
/
generate.ml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(* Js_of_ocaml compiler
* http://www.ocsigen.org/js_of_ocaml/
* Copyright (C) 2010 Jérôme Vouillon
* Laboratoire PPS - CNRS Université Paris Diderot
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, with linking exception;
* either version 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*)
open! Stdlib
let debug = Debug.find "gen"
let times = Debug.find "times"
let cps_transform () =
match Config.effects () with
| `Cps | `Double_translation -> true
| `Disabled -> false
| `Jspi -> assert false
open Code
module J = Javascript
(****)
let string_of_set s =
String.concat ~sep:", " (List.map ~f:Addr.to_string (Addr.Set.elements s))
let rec list_group_rec ~equal f g l b m n =
match l with
| [] -> List.rev ((b, List.rev m) :: n)
| a :: r ->
let fa = f a in
if equal fa b
then list_group_rec ~equal f g r b (g a :: m) n
else list_group_rec ~equal f g r fa [ g a ] ((b, List.rev m) :: n)
let list_group ~equal f g l =
match l with
| [] -> []
| a :: r -> list_group_rec ~equal f g r (f a) [ g a ] []
(****)
type fall_through =
| Block of Addr.t
| Return
type application_description =
{ arity : int
; exact : bool
; trampolined : bool
; in_cps : bool
}
module Share = struct
module AppMap = Map.Make (struct
type t = application_description
let compare = Poly.compare
end)
type 'a aux =
{ byte_strings : 'a StringMap.t
; utf_strings : 'a StringMap.t
; applies : 'a AppMap.t
; prims : 'a StringMap.t
}
let empty_aux =
{ prims = StringMap.empty
; byte_strings = StringMap.empty
; utf_strings = StringMap.empty
; applies = AppMap.empty
}
type t =
{ count : int aux
; mutable vars : J.ident aux
; alias_prims : bool
; alias_strings : bool
; alias_apply : bool
}
let add_byte_string s t =
let n = try StringMap.find s t.byte_strings with Not_found -> 0 in
{ t with byte_strings = StringMap.add s (n + 1) t.byte_strings }
let add_utf_string s t =
let n = try StringMap.find s t.utf_strings with Not_found -> 0 in
{ t with utf_strings = StringMap.add s (n + 1) t.utf_strings }
let add_prim s t =
let n = try StringMap.find s t.prims with Not_found -> 0 in
if n < 0 then t else { t with prims = StringMap.add s (n + 1) t.prims }
let add_special_prim_if_exists s t =
if Primitive.exists s then { t with prims = StringMap.add s (-1) t.prims } else t
let add_apply i t =
let n = try AppMap.find i t.applies with Not_found -> 0 in
{ t with applies = AppMap.add i (n + 1) t.applies }
let add_code_string s share =
let share =
if String.is_ascii s then add_utf_string s share else add_byte_string s share
in
if Config.Flag.use_js_string ()
then share
else add_prim "caml_string_of_jsbytes" share
let add_code_native_string (s : Code.Native_string.t) share =
match s with
| Utf (Utf8 s) -> add_utf_string s share
| Byte s -> add_byte_string s share
let rec get_constant c t =
match c with
| String s -> add_code_string s t
| NativeString s -> add_code_native_string s t
| Tuple (_, args, _) -> Array.fold_left args ~init:t ~f:(fun t c -> get_constant c t)
| _ -> t
let add_args args t =
List.fold_left args ~init:t ~f:(fun t a ->
match a with
| Pc c -> get_constant c t
| _ -> t)
let get
~trampolined_calls
~in_cps
?alias_strings
?(alias_prims = false)
?(alias_apply = true)
{ blocks; _ } : t =
let alias_strings =
match alias_strings with
| None -> Config.Flag.use_js_string () && not (Config.Flag.share_constant ())
| Some x -> x
in
let count =
Addr.Map.fold
(fun _ block share ->
List.fold_left block.body ~init:share ~f:(fun share i ->
match i with
| Let (_, Constant c) -> get_constant c share
| Let (x, Apply { args; exact; _ }) ->
let trampolined = Var.Set.mem x trampolined_calls in
let in_cps = Var.Set.mem x in_cps in
if (not exact) || trampolined
then
add_apply
{ arity = List.length args; exact; trampolined; in_cps }
share
else share
| Let (_, Special (Alias_prim name)) ->
let name = Primitive.resolve name in
let share =
if Primitive.exists name then add_prim name share else share
in
share
| Let (_, Prim (Extern name, args)) ->
let name = Primitive.resolve name in
let share =
if Primitive.exists name then add_prim name share else share
in
add_args args share
| Let (_, Prim (_, args)) -> add_args args share
| _ -> share))
blocks
empty_aux
in
let count =
List.fold_left
[ "caml_trampoline"
; "caml_trampoline_return"
; "caml_wrap_exception"
; "caml_list_of_js_array"
; "caml_maybe_attach_backtrace"
; "jsoo_effect_not_supported"
]
~init:count
~f:(fun acc x -> add_special_prim_if_exists x acc)
in
{ count; vars = empty_aux; alias_strings; alias_prims; alias_apply }
let get_byte_string gen s t =
if not t.alias_strings
then gen s
else
try
let c = StringMap.find s t.count.byte_strings in
if c > 1
then (
try J.EVar (StringMap.find s t.vars.byte_strings)
with Not_found ->
let x = Var.fresh_n (Printf.sprintf "cst_%s" s) in
let v = J.V x in
t.vars <- { t.vars with byte_strings = StringMap.add s v t.vars.byte_strings };
J.EVar v)
else gen s
with Not_found -> gen s
let get_utf_string gen s t =
if not t.alias_strings
then gen s
else
try
let c = StringMap.find s t.count.utf_strings in
if c > 1
then (
try J.EVar (StringMap.find s t.vars.utf_strings)
with Not_found ->
let x = Var.fresh_n (Printf.sprintf "cst_%s" s) in
let v = J.V x in
t.vars <- { t.vars with utf_strings = StringMap.add s v t.vars.utf_strings };
J.EVar v)
else gen s
with Not_found -> gen s
let get_prim gen s t =
let s = Primitive.resolve s in
if not t.alias_prims
then gen s
else
try
let c = StringMap.find s t.count.prims in
if c > 1 || c = -1
then (
try J.EVar (StringMap.find s t.vars.prims)
with Not_found ->
let x = Var.fresh_n s in
let v = J.V x in
t.vars <- { t.vars with prims = StringMap.add s v t.vars.prims };
J.EVar v)
else gen s
with Not_found -> gen s
let get_apply gen desc t =
if not t.alias_apply
then gen desc
else
try J.EVar (AppMap.find desc t.vars.applies)
with Not_found ->
let x =
let { arity; exact; trampolined; in_cps } = desc in
Var.fresh_n
(Printf.sprintf
"caml_%scall%d"
(match exact, trampolined, in_cps with
| true, false, false -> assert false (* inlined *)
| true, false, true -> "exact_cps_"
| true, true, false -> "exact_trampoline_"
| false, false, true ->
assert false (* CPS functions are always trampolined *)
| false, false, false -> ""
| false, true, false -> "trampoline_"
| false, true, true -> "trampoline_cps_"
| true, true, true -> "exact_trampoline_cps_")
arity)
in
let v = J.V x in
t.vars <- { t.vars with applies = AppMap.add desc v t.vars.applies };
J.EVar v
end
module Ctx = struct
type t =
{ blocks : block Addr.Map.t
; live : Deadcode.variable_uses
; share : Share.t
; debug : Parse_bytecode.Debug.t
; exported_runtime : (Code.Var.t * bool ref) option
; should_export : bool
; effect_warning : bool ref
; trampolined_calls : Effects.trampolined_calls
; deadcode_sentinal : Var.t
; mutated_vars : Code.Var.Set.t Code.Addr.Map.t
; freevars : Code.Var.Set.t Code.Addr.Map.t
; in_cps : Effects.in_cps
}
let initial
~warn_on_unhandled_effect
~exported_runtime
~should_export
~deadcode_sentinal
~mutated_vars
~freevars
~in_cps
blocks
live
trampolined_calls
share
debug =
{ blocks
; live
; share
; debug
; exported_runtime
; should_export
; effect_warning = ref (not warn_on_unhandled_effect)
; trampolined_calls
; deadcode_sentinal
; mutated_vars
; freevars
; in_cps
}
end
type edge_kind =
| Loop
| Exit_loop of bool ref
| Exit_switch of bool ref
| Forward
let var x = J.EVar (J.V x)
let int n = J.ENum (J.Num.of_targetint (Targetint.of_int_exn n))
let targetint n = J.ENum (J.Num.of_targetint n)
let to_int cx = J.EBin (J.Bor, cx, int 0)
let unsigned' x = J.EBin (J.Lsr, x, int 0)
let unsigned x =
let x =
match x with
| J.EBin (J.Bor, x, J.ENum maybe_zero) when J.Num.is_zero maybe_zero -> x
| _ -> x
in
let pos_int32 =
match x with
| J.ENum num -> ( try Targetint.(J.Num.to_targetint num >= zero) with _ -> false)
| _ -> false
in
if pos_int32 then x else unsigned' x
let one = J.ENum (J.Num.of_targetint Targetint.one)
let zero = J.ENum (J.Num.of_targetint Targetint.zero)
let plus_int x y =
match x, y with
| J.ENum y, x when J.Num.is_zero y -> x
| x, J.ENum y when J.Num.is_zero y -> x
| J.ENum x, J.ENum y -> J.ENum (J.Num.add x y)
| x, y -> J.EBin (J.Plus, x, y)
let bool e = J.ECond (e, one, zero)
(****)
let source_location ctx position pc =
match Parse_bytecode.Debug.find_loc ctx.Ctx.debug ~position pc with
| Some pi -> J.Pi pi
| None -> J.N
(****)
let float_const f = J.ENum (J.Num.of_float f)
let s_var name = J.EVar (J.ident (Utf8_string.of_string_exn name))
let runtime_fun ctx name =
match ctx.Ctx.exported_runtime with
| Some (runtime, runtime_needed) ->
runtime_needed := true;
let name = Utf8_string.of_string_exn name in
J.dot (J.EVar (J.V runtime)) name
| None -> s_var name
let str_js_byte s =
let b = Buffer.create (String.length s) in
String.iter s ~f:(function
| '\\' -> Buffer.add_string b "\\\\"
| '\128' .. '\255' as c ->
Buffer.add_string b "\\x";
Buffer.add_char_hex b c
| c -> Buffer.add_char b c);
let s = Buffer.contents b in
J.EStr (Utf8_string.of_string_exn s)
let str_js_utf8 s =
let b = Buffer.create (String.length s) in
String.iter s ~f:(function
| '\\' -> Buffer.add_string b "\\\\"
| c -> Buffer.add_char b c);
let s = Buffer.contents b in
J.EStr (Utf8_string.of_string_exn s)
(****)
(*
Some variables are constant: x = 1
Some may change after effectful operations : x = y[z]
There can be at most one effectful operations in the queue at once
let (e, expr_queue) = ... in
flush_queue expr_queue e
*)
let const_p = 0, Var.Set.empty
let mutable_p = 1, Var.Set.empty
let mutator_p = 2, Var.Set.empty
let flush_p = 3, Var.Set.empty
let or_p (p, s1) (q, s2) = max p q, Var.Set.union s1 s2
let is_mutable (p, _) = p >= fst mutable_p
let kind k =
match k with
| `Pure -> const_p
| `Mutable -> mutable_p
| `Mutator -> mutator_p
let ocaml_string ~ctx ~loc s =
if Config.Flag.use_js_string ()
then s
else
let p = Share.get_prim (runtime_fun ctx) "caml_string_of_jsbytes" ctx.Ctx.share in
J.call p [ s ] loc
let rec constant_rec ~ctx x level instrs =
match x with
| String s ->
let e =
if String.is_ascii s
then Share.get_utf_string str_js_byte s ctx.Ctx.share
else Share.get_byte_string str_js_byte s ctx.Ctx.share
in
let e = ocaml_string ~ctx ~loc:J.N e in
e, instrs
| NativeString s -> (
match s with
| Byte x -> Share.get_byte_string str_js_byte x ctx.Ctx.share, instrs
| Utf (Utf8 x) -> Share.get_utf_string str_js_utf8 x ctx.Ctx.share, instrs)
| Float f -> float_const f, instrs
| Float_array a ->
( Mlvalue.Array.make
~tag:Obj.double_array_tag
~args:(Array.to_list (Array.map a ~f:(fun x -> J.Element (float_const x))))
, instrs )
| Int64 i ->
let p =
Share.get_prim (runtime_fun ctx) "caml_int64_create_lo_mi_hi" ctx.Ctx.share
in
let lo = int (Int64.to_int i land 0xffffff)
and mi = int (Int64.to_int (Int64.shift_right i 24) land 0xffffff)
and hi = int (Int64.to_int (Int64.shift_right i 48) land 0xffff) in
J.call p [ lo; mi; hi ] J.N, instrs
| Tuple (tag, a, _) -> (
let constant_max_depth = Config.Param.constant_max_depth () in
let rec detect_list n acc = function
| Tuple (0, [| x; l |], _) -> detect_list (succ n) (x :: acc) l
| Int maybe_zero when Targetint.is_zero maybe_zero ->
if n > constant_max_depth then Some acc else None
| _ -> None
in
match detect_list 0 [] x with
| Some elts_rev ->
let elements, instrs =
List.fold_left elts_rev ~init:([], instrs) ~f:(fun (arr, instrs) elt ->
let js, instrs = constant_rec ~ctx elt level instrs in
js :: arr, instrs)
in
let p =
Share.get_prim (runtime_fun ctx) "caml_list_of_js_array" ctx.Ctx.share
in
J.call p [ J.array elements ] J.N, instrs
| None ->
let split = level = constant_max_depth in
let level = if split then 0 else level + 1 in
let l, instrs =
List.fold_left (Array.to_list a) ~init:([], instrs) ~f:(fun (l, instrs) cc ->
let js, instrs = constant_rec ~ctx cc level instrs in
js :: l, instrs)
in
let l, instrs =
if split
then
List.fold_left l ~init:([], instrs) ~f:(fun (acc, instrs) js ->
match js with
| J.EArr _ ->
let v = Code.Var.fresh_n "partial" in
let instrs =
(J.variable_declaration [ J.V v, (js, J.N) ], J.N) :: instrs
in
J.Element (J.EVar (J.V v)) :: acc, instrs
| _ -> J.Element js :: acc, instrs)
else List.map ~f:(fun x -> J.Element x) (List.rev l), instrs
in
Mlvalue.Block.make ~tag ~args:l, instrs)
| Int i -> targetint i, instrs
| Int32 _ | NativeInt _ ->
assert false (* Should not be produced when compiling to Javascript *)
let constant ~ctx x level =
let expr, instr = constant_rec ~ctx x level [] in
expr, List.rev instr
type queue_elt =
{ prop : int
; ce : J.expression
; loc : J.location option
; deps : Code.Var.Set.t
}
let access_queue queue x =
try
let elt = List.assoc x queue in
((elt.prop, elt.deps), elt.ce, elt.loc), List.remove_assoc x queue
with Not_found -> ((fst const_p, Code.Var.Set.singleton x), var x, None), queue
let access_queue_loc queue loc' x =
let (prop, c, loc), queue = access_queue queue x in
(prop, c, Option.value ~default:loc' loc), queue
let should_flush (cond, _) prop = cond <> fst const_p && cond + prop >= fst flush_p
let flush_queue expr_queue prop loc (l : J.statement_list) =
let instrs, expr_queue =
if fst prop >= fst flush_p
then expr_queue, []
else List.partition ~f:(fun (_, elt) -> should_flush prop elt.prop) expr_queue
in
let instrs =
List.map instrs ~f:(fun (x, elt) ->
let loc = Option.value ~default:loc elt.loc in
J.variable_declaration [ J.V x, (elt.ce, loc) ], loc)
in
List.rev_append instrs l, expr_queue
let flush_all expr_queue loc l = fst (flush_queue expr_queue flush_p loc l)
let enqueue expr_queue prop x ce flush_loc expr_loc acc =
let instrs, expr_queue =
if Config.Flag.compact ()
then
if is_mutable prop
then flush_queue expr_queue prop flush_loc acc
else acc, expr_queue
else flush_queue expr_queue flush_p flush_loc acc
in
let prop, deps = prop in
instrs, (x, { prop; deps; ce; loc = expr_loc }) :: expr_queue
type queue = (Var.t * queue_elt) list
type prop = int * Code.Var.Set.t
module Expr_builder : sig
type 'a t
val ( let* ) : 'a t -> ('a -> 'b t) -> 'b t
val return : 'a -> 'a t
val access : Var.t -> J.expression t
val access' : ctx:Ctx.t -> prim_arg -> J.expression t
val info : ?need_loc:bool -> prop -> unit t
val statement_loc : J.location -> J.location t
val flush_all : queue -> J.location -> J.statement_list t -> J.statement_list
val flush_queue : queue -> J.location -> J.statement_list t -> J.statement_list * queue
val enqueue :
queue
-> Var.t
-> J.location
-> (J.expression * J.statement_list) t
-> J.statement_list * queue
val get : queue -> J.location -> 'a t -> 'a * J.location * queue
val list_map : ('a -> 'b t) -> 'a list -> 'b list t
end = struct
type state =
{ queue : queue
; prop : prop
; need_loc : bool
; loc : J.location option
}
type 'a t = state -> 'a * state
let ( let* ) (type a b) (e : a t) (f : a -> b t) : b t =
fun st ->
let v, st = e st in
f v st
let return x st = x, st
let info ?(need_loc = false) prop st =
(), { st with prop = or_p st.prop prop; need_loc = need_loc || st.need_loc }
let access x st =
let (prop, c, loc), queue = access_queue st.queue x in
( c
, { st with
prop = or_p st.prop prop
; queue
; loc =
(match st.loc with
| None -> loc
| _ -> st.loc)
} )
let access' ~ctx x =
match x with
| Pc c ->
let js, instrs = constant ~ctx c (Config.Param.constant_max_depth ()) in
assert (List.is_empty instrs);
(* We only have simple constants here *)
fun st -> js, st
| Pv x -> access x
let statement_loc loc st =
( (match st.loc with
| None -> loc
| Some loc -> loc)
, st )
let initial_state queue = { queue; prop = const_p; loc = None; need_loc = false }
let flush_queue queue loc instrs =
let v, { queue; prop; _ } = instrs (initial_state queue) in
flush_queue queue prop loc v
let flush_all queue loc instrs =
let v, { queue; _ } = instrs (initial_state queue) in
flush_all queue loc v
let enqueue queue x flush_loc expr =
let (ce, instrs), { queue; prop; loc; need_loc } = expr (initial_state queue) in
let expr_loc =
match loc with
| None when need_loc -> Some flush_loc
| _ -> loc
in
enqueue queue prop x ce flush_loc expr_loc instrs
let get queue loc' x =
let x, { queue; loc; _ } = x (initial_state queue) in
let loc =
match loc with
| None -> loc'
| Some loc -> loc
in
x, loc, queue
let rec list_map f l st =
match l with
| [] -> [], st
| x :: r ->
let x', st = f x st in
let r', st = list_map f r st in
x' :: r', st
end
(****)
type state =
{ structure : Structure.t
; dom : Structure.graph
; visited_blocks : Addr.Set.t ref
; ctx : Ctx.t
; pc : Addr.t
}
module DTree = struct
(* This has to be kept in sync with the way we build conditionals
and switches! *)
type cond =
| IsTrue
| CEq of Targetint.t
| CLt of Targetint.t
| CLe of Targetint.t
type 'a branch = int list * 'a
type 'a t =
| If of cond * 'a t * 'a t
| Switch of 'a branch array
| Branch of 'a branch
let normalize a =
a
|> Array.to_list
|> List.sort ~cmp:(fun (cont1, _) (cont2, _) -> Poly.compare cont1 cont2)
|> list_group ~equal:Poly.equal fst snd
|> List.map ~f:(fun (cont1, l1) -> cont1, List.flatten l1)
|> List.sort ~cmp:(fun (_, l1) (_, l2) -> compare (List.length l1) (List.length l2))
|> Array.of_list
let build_if b1 b2 = If (IsTrue, Branch ([ 1 ], b1), Branch ([ 0 ], b2))
let build_switch (a : cont array) : cont t =
let m = Config.Param.switch_max_case () in
let ai = Array.mapi a ~f:(fun i x -> x, i) in
(* group the contiguous cases with the same continuation *)
let ai : (Code.cont * int list) array =
Array.of_list (list_group ~equal:Poly.equal fst snd (Array.to_list ai))
in
let rec loop low up =
let array_norm : (Code.cont * int list) array =
normalize (Array.sub ai ~pos:low ~len:(up - low + 1))
in
let array_len = Array.length array_norm in
if array_len = 1 (* remaining cases all jump to the same branch *)
then Branch (snd array_norm.(0), fst array_norm.(0))
else
try
(* try to optimize when there are only 2 branch *)
match array_norm with
| [| (b1, ([ i1 ] as l1)); (b2, l2) |] ->
If (CEq (Targetint.of_int_exn i1), Branch (l1, b1), Branch (l2, b2))
| [| (b1, l1); (b2, ([ i2 ] as l2)) |] ->
If (CEq (Targetint.of_int_exn i2), Branch (l2, b2), Branch (l1, b1))
| [| (b1, l1); (b2, l2) |] ->
let bound l1 =
match l1, List.rev l1 with
| min :: _, max :: _ -> min, max
| _ -> assert false
in
let min1, max1 = bound l1 in
let min2, max2 = bound l2 in
if max1 < min2
then If (CLt (Targetint.of_int_exn max1), Branch (l2, b2), Branch (l1, b1))
else if max2 < min1
then If (CLt (Targetint.of_int_exn max2), Branch (l1, b1), Branch (l2, b2))
else raise Not_found
| _ -> raise Not_found
with Not_found -> (
(* do we have to split again ? *)
(* we count the number of cases, default/last case count for one *)
let nbcases =
ref 1
(* default case *)
in
for i = 0 to array_len - 2 do
nbcases := !nbcases + List.length (snd array_norm.(i))
done;
if !nbcases <= m
then Switch (Array.map array_norm ~f:(fun (x, l) -> l, x))
else
let h = (up + low) / 2 in
let b1 = loop low h and b2 = loop (succ h) up in
let range1 = snd ai.(h) and range2 = snd ai.(succ h) in
match range1, range2 with
| [], _ | _, [] -> assert false
| _, lower_bound2 :: _ -> If (CLe (Targetint.of_int_exn lower_bound2), b2, b1))
in
let len = Array.length ai in
assert (len > 0);
loop 0 (len - 1)
let nbbranch (a : cont t) pc =
let rec loop c : cont t -> int = function
| Branch (_, (pc', _)) -> if pc' = pc then succ c else c
| If (_, a, b) ->
let c = loop c a in
let c = loop c b in
c
| Switch a ->
Array.fold_left a ~init:c ~f:(fun acc (_, (pc', _)) ->
if pc' = pc then succ acc else acc)
in
loop 0 a
let nbcomp a =
let rec loop c = function
| Branch _ -> c
| If (_, a, b) ->
let c = succ c in
let c = loop c a in
let c = loop c b in
c
| Switch _ ->
let c = succ c in
c
in
loop 0 a
end
let build_graph ctx pc =
let visited_blocks = ref Addr.Set.empty in
let structure = Structure.build_graph ctx.Ctx.blocks pc in
let dom = Structure.dominator_tree structure in
{ visited_blocks; structure; dom; ctx; pc }
(****)
let rec visit visited prev s m x l =
if not (Var.Set.mem x visited)
then
let visited = Var.Set.add x visited in
let y = Var.Map.find x m in
if Code.Var.compare x y = 0
then visited, None, l
else if Var.Set.mem y prev
then
let t = Code.Var.fresh () in
visited, Some (y, t), (x, t) :: l
else if Var.Set.mem y s
then
let visited, aliases, l = visit visited (Var.Set.add x prev) s m y l in
match aliases with
| Some (a, b) when Code.Var.compare a x = 0 -> visited, None, (b, a) :: (x, y) :: l
| _ -> visited, aliases, (x, y) :: l
else visited, None, (x, y) :: l
else visited, None, l
let visit_all params args =
let m = Subst.build_mapping params args in
let s = List.fold_left params ~init:Var.Set.empty ~f:(fun s x -> Var.Set.add x s) in
let _, l =
Var.Set.fold
(fun x (visited, l) ->
let visited, _, l = visit visited Var.Set.empty s m x l in
visited, l)
s
(Var.Set.empty, [])
in
l
let parallel_renaming loc back_edge params args continuation queue =
if
back_edge && Config.Flag.es6 ()
(* This is likely slower than using explicit temp variable
but let's experiment with es6 a bit *)
then
let args, params =
List.map2 args params ~f:(fun a p -> if Var.equal a p then None else Some (a, p))
|> List.filter_map ~f:(fun x -> x)
|> List.split
in
let open Expr_builder in
let args, loc, queue =
get
queue
loc
(List.fold_left args ~init:(return []) ~f:(fun acc a ->
let* acc = acc in
let* cx = access a in
return (cx :: acc)))
in
let never, code = continuation queue in
match params, args with
| [ p ], [ a ] ->
never, (J.Expression_statement (J.EBin (J.Eq, J.EVar (J.V p), a)), loc) :: code
| params, args ->
let lhs =
J.EAssignTarget
(J.ArrayTarget (List.map params ~f:(fun p -> J.TargetElementId (J.V p, None))))
in
let rhs = J.EArr (List.rev_map args ~f:(fun x -> J.Element x)) in
never, (J.Expression_statement (J.EBin (J.Eq, lhs, rhs)), loc) :: code
else
let l = visit_all params args in
(* if not back_edge
* then assert (Poly.( = ) l (List.rev_map2 params args ~f:(fun a b -> a, b))); *)
let queue, before, renaming, _ =
List.fold_left
l
~init:(queue, [], [], Code.Var.Set.empty)
~f:(fun (queue, before, renaming, seen) (y, x) ->
let ((_, deps_x), cx, locx), queue = access_queue_loc queue loc x in
let seen' = Code.Var.Set.add y seen in
if not Code.Var.Set.(is_empty (inter seen deps_x))
then
let () = assert back_edge in
let before = (J.variable_declaration [ J.V x, (cx, locx) ], locx) :: before in
let renaming = (y, J.EVar (J.V x)) :: renaming in
queue, before, renaming, seen'
else
let renaming = (y, cx) :: renaming in
queue, before, renaming, seen')
in
let renaming =
if back_edge
then
List.map renaming ~f:(fun (t, e) ->
J.Expression_statement (J.EBin (J.Eq, J.EVar (J.V t), e)), loc)
else
List.map renaming ~f:(fun (t, e) ->
J.variable_declaration [ J.V t, (e, loc) ], loc)
in
let never, code = continuation queue in
never, List.rev_append before (List.rev_append renaming code)
(****)
let apply_fun_raw =
let cps_field = Utf8_string.of_string_exn "cps" in
fun ctx f params exact trampolined cps loc ->
let apply_directly f params =
(* Make sure we are performing a regular call, not a (slower)
method call *)
match f with
| J.EAccess _ | J.EDot _ ->
J.call (J.dot f (Utf8_string.of_string_exn "call")) (s_var "null" :: params) loc
| _ -> J.call f params loc
in
let apply ~cps f params =
(* Adapt if [f] is a (direct-style, CPS) closure pair *)
let real_closure =
match Config.effects () with
| `Double_translation when cps ->
(* Effects enabled, CPS version, not single-version *)
J.EDot (f, J.ANormal, cps_field)
| `Cps | `Double_translation | `Disabled -> f
| `Jspi -> assert false
in
(* We skip the arity check when we know that we have the right
number of parameters, since this test is expensive. *)
if exact
then apply_directly real_closure params
else
let l = Utf8_string.of_string_exn "l" in
J.ECond
( J.EBin
( J.EqEqEq
, J.ECond
( J.EBin (J.Ge, J.dot real_closure l, int 0)
, J.dot real_closure l
, J.EBin
( J.Eq
, J.dot real_closure l
, J.dot real_closure (Utf8_string.of_string_exn "length") ) )
, int (List.length params) )
, apply_directly real_closure params
, J.call
(* Note: when double translation is enabled, [caml_call_gen*] functions takes a two-version function *)
(runtime_fun
ctx
(match Config.effects () with
| `Double_translation when cps -> "caml_call_gen_cps"
| `Double_translation | `Cps | `Disabled -> "caml_call_gen"
| `Jspi -> assert false))
[ f; J.array params ]
J.N )
in
let apply =
match Config.effects () with
| `Double_translation when cps ->
let n = List.length params in
J.ECond
( J.EDot (f, J.ANormal, cps_field)
, apply ~cps:true f params
, J.call
(List.nth params (n - 1))
[ apply ~cps:false f (fst (List.take (n - 1) params)) ]
J.N )
| `Double_translation | `Cps | `Disabled -> apply ~cps f params
| `Jspi -> assert false
in
if trampolined
then (
assert (cps_transform ());
(* When supporting effect, we systematically perform tailcall
optimization. To implement it, we check the stack depth and
bounce to a trampoline if needed, to avoid a stack overflow.
The trampoline then performs the call in an shorter stack. *)
J.ECond
( J.call (runtime_fun ctx "caml_stack_check_depth") [] loc
, apply
, J.call
(runtime_fun ctx "caml_trampoline_return")
[ f; J.array params; (if cps then zero else one) ]
loc ))
else apply
let generate_apply_fun ctx { arity; exact; trampolined; in_cps } =
let f' = Var.fresh_n "f" in