forked from ocaml/ocaml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
translcore.ml
1406 lines (1340 loc) · 53.5 KB
/
translcore.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
(**************************************************************************)
(* *)
(* OCaml *)
(* *)
(* Xavier Leroy, projet Cristal, INRIA Rocquencourt *)
(* *)
(* Copyright 1996 Institut National de Recherche en Informatique et *)
(* en Automatique. *)
(* *)
(* All rights reserved. This file is distributed under the terms of *)
(* the GNU Lesser General Public License version 2.1, with the *)
(* special exception on linking described in the file LICENSE. *)
(* *)
(**************************************************************************)
(* Translation from typed abstract syntax to lambda terms,
for the core language *)
open Misc
open Asttypes
open Primitive
open Types
open Typedtree
open Typeopt
open Lambda
type error =
Free_super_var
| Unknown_builtin_primitive of string
| Unreachable_reached
exception Error of Location.t * error
let use_dup_for_constant_arrays_bigger_than = 4
(* Forward declaration -- to be filled in by Translmod.transl_module *)
let transl_module =
ref((fun _cc _rootpath _modl -> assert false) :
module_coercion -> Path.t option -> module_expr -> lambda)
let transl_object =
ref (fun _id _s _cl -> assert false :
Ident.t -> string list -> class_expr -> lambda)
(* Compile an exception/extension definition *)
let prim_fresh_oo_id =
Pccall (Primitive.simple ~name:"caml_fresh_oo_id" ~arity:1 ~alloc:false)
let transl_extension_constructor env path ext =
let name =
match path, !Clflags.for_package with
None, _ -> Ident.name ext.ext_id
| Some p, None -> Path.name p
| Some p, Some pack -> Printf.sprintf "%s.%s" pack (Path.name p)
in
let loc = ext.ext_loc in
match ext.ext_kind with
Text_decl _ ->
Lprim (Pmakeblock (Obj.object_tag, Immutable, None),
[Lconst (Const_base (Const_string (name, None)));
Lprim (prim_fresh_oo_id, [Lconst (Const_base (Const_int 0))], loc)],
loc)
| Text_rebind(path, _lid) ->
transl_extension_path ~loc env path
(* Translation of primitives *)
let comparisons_table = create_hashtable 11 [
"%equal",
(Pccall(Primitive.simple ~name:"caml_equal" ~arity:2 ~alloc:true),
Pintcomp Ceq,
Pfloatcomp Ceq,
Pccall(Primitive.simple ~name:"caml_string_equal" ~arity:2
~alloc:false),
Pccall(Primitive.simple ~name:"caml_bytes_equal" ~arity:2
~alloc:false),
Pbintcomp(Pnativeint, Ceq),
Pbintcomp(Pint32, Ceq),
Pbintcomp(Pint64, Ceq),
true);
"%notequal",
(Pccall(Primitive.simple ~name:"caml_notequal" ~arity:2 ~alloc:true),
Pintcomp Cneq,
Pfloatcomp Cneq,
Pccall(Primitive.simple ~name:"caml_string_notequal" ~arity:2
~alloc:false),
Pccall(Primitive.simple ~name:"caml_bytes_notequal" ~arity:2
~alloc:false),
Pbintcomp(Pnativeint, Cneq),
Pbintcomp(Pint32, Cneq),
Pbintcomp(Pint64, Cneq),
true);
"%lessthan",
(Pccall(Primitive.simple ~name:"caml_lessthan" ~arity:2 ~alloc:true),
Pintcomp Clt,
Pfloatcomp Clt,
Pccall(Primitive.simple ~name:"caml_string_lessthan" ~arity:2
~alloc:false),
Pccall(Primitive.simple ~name:"caml_bytes_lessthan" ~arity:2
~alloc:false),
Pbintcomp(Pnativeint, Clt),
Pbintcomp(Pint32, Clt),
Pbintcomp(Pint64, Clt),
false);
"%greaterthan",
(Pccall(Primitive.simple ~name:"caml_greaterthan" ~arity:2 ~alloc:true),
Pintcomp Cgt,
Pfloatcomp Cgt,
Pccall(Primitive.simple ~name:"caml_string_greaterthan" ~arity:2
~alloc: false),
Pccall(Primitive.simple ~name:"caml_bytes_greaterthan" ~arity:2
~alloc: false),
Pbintcomp(Pnativeint, Cgt),
Pbintcomp(Pint32, Cgt),
Pbintcomp(Pint64, Cgt),
false);
"%lessequal",
(Pccall(Primitive.simple ~name:"caml_lessequal" ~arity:2 ~alloc:true),
Pintcomp Cle,
Pfloatcomp Cle,
Pccall(Primitive.simple ~name:"caml_string_lessequal" ~arity:2
~alloc:false),
Pccall(Primitive.simple ~name:"caml_bytes_lessequal" ~arity:2
~alloc:false),
Pbintcomp(Pnativeint, Cle),
Pbintcomp(Pint32, Cle),
Pbintcomp(Pint64, Cle),
false);
"%greaterequal",
(Pccall(Primitive.simple ~name:"caml_greaterequal" ~arity:2 ~alloc:true),
Pintcomp Cge,
Pfloatcomp Cge,
Pccall(Primitive.simple ~name:"caml_string_greaterequal" ~arity:2
~alloc:false),
Pccall(Primitive.simple ~name:"caml_bytes_greaterequal" ~arity:2
~alloc:false),
Pbintcomp(Pnativeint, Cge),
Pbintcomp(Pint32, Cge),
Pbintcomp(Pint64, Cge),
false);
"%compare",
let unboxed_compare name native_repr =
Pccall( Primitive.make ~name ~alloc:false
~native_name:(name^"_unboxed")
~native_repr_args:[native_repr;native_repr]
~native_repr_res:Untagged_int
) in
(Pccall(Primitive.simple ~name:"caml_compare" ~arity:2 ~alloc:true),
(* Not unboxed since the comparison is done directly on tagged int *)
Pccall(Primitive.simple ~name:"caml_int_compare" ~arity:2 ~alloc:false),
unboxed_compare "caml_float_compare" Unboxed_float,
Pccall(Primitive.simple ~name:"caml_string_compare" ~arity:2
~alloc:false),
Pccall(Primitive.simple ~name:"caml_bytes_compare" ~arity:2
~alloc:false),
unboxed_compare "caml_nativeint_compare" (Unboxed_integer Pnativeint),
unboxed_compare "caml_int32_compare" (Unboxed_integer Pint32),
unboxed_compare "caml_int64_compare" (Unboxed_integer Pint64),
false)
]
let gen_array_kind =
if Config.flat_float_array then Pgenarray else Paddrarray
let primitives_table = create_hashtable 57 [
"%identity", Pidentity;
"%bytes_to_string", Pbytes_to_string;
"%bytes_of_string", Pbytes_of_string;
"%ignore", Pignore;
"%revapply", Prevapply;
"%apply", Pdirapply;
"%loc_LOC", Ploc Loc_LOC;
"%loc_FILE", Ploc Loc_FILE;
"%loc_LINE", Ploc Loc_LINE;
"%loc_POS", Ploc Loc_POS;
"%loc_MODULE", Ploc Loc_MODULE;
"%field0", Pfield 0;
"%field1", Pfield 1;
"%setfield0", Psetfield(0, Pointer, Assignment);
"%makeblock", Pmakeblock(0, Immutable, None);
"%makemutable", Pmakeblock(0, Mutable, None);
"%raise", Praise Raise_regular;
"%reraise", Praise Raise_reraise;
"%raise_notrace", Praise Raise_notrace;
"%sequand", Psequand;
"%sequor", Psequor;
"%boolnot", Pnot;
"%big_endian", Pctconst Big_endian;
"%backend_type", Pctconst Backend_type;
"%word_size", Pctconst Word_size;
"%int_size", Pctconst Int_size;
"%max_wosize", Pctconst Max_wosize;
"%ostype_unix", Pctconst Ostype_unix;
"%ostype_win32", Pctconst Ostype_win32;
"%ostype_cygwin", Pctconst Ostype_cygwin;
"%negint", Pnegint;
"%succint", Poffsetint 1;
"%predint", Poffsetint(-1);
"%addint", Paddint;
"%subint", Psubint;
"%mulint", Pmulint;
"%divint", Pdivint Safe;
"%modint", Pmodint Safe;
"%andint", Pandint;
"%orint", Porint;
"%xorint", Pxorint;
"%lslint", Plslint;
"%lsrint", Plsrint;
"%asrint", Pasrint;
"%eq", Pintcomp Ceq;
"%noteq", Pintcomp Cneq;
"%ltint", Pintcomp Clt;
"%leint", Pintcomp Cle;
"%gtint", Pintcomp Cgt;
"%geint", Pintcomp Cge;
"%incr", Poffsetref(1);
"%decr", Poffsetref(-1);
"%intoffloat", Pintoffloat;
"%floatofint", Pfloatofint;
"%negfloat", Pnegfloat;
"%absfloat", Pabsfloat;
"%addfloat", Paddfloat;
"%subfloat", Psubfloat;
"%mulfloat", Pmulfloat;
"%divfloat", Pdivfloat;
"%eqfloat", Pfloatcomp Ceq;
"%noteqfloat", Pfloatcomp Cneq;
"%ltfloat", Pfloatcomp Clt;
"%lefloat", Pfloatcomp Cle;
"%gtfloat", Pfloatcomp Cgt;
"%gefloat", Pfloatcomp Cge;
"%string_length", Pstringlength;
"%string_safe_get", Pstringrefs;
"%string_safe_set", Pbytessets;
"%string_unsafe_get", Pstringrefu;
"%string_unsafe_set", Pbytessetu;
"%bytes_length", Pbyteslength;
"%bytes_safe_get", Pbytesrefs;
"%bytes_safe_set", Pbytessets;
"%bytes_unsafe_get", Pbytesrefu;
"%bytes_unsafe_set", Pbytessetu;
"%array_length", Parraylength gen_array_kind;
"%array_safe_get", Parrayrefs gen_array_kind;
"%array_safe_set", Parraysets gen_array_kind;
"%array_unsafe_get", Parrayrefu gen_array_kind;
"%array_unsafe_set", Parraysetu gen_array_kind;
"%obj_size", Parraylength gen_array_kind;
"%obj_field", Parrayrefu gen_array_kind;
"%obj_set_field", Parraysetu gen_array_kind;
"%floatarray_length", Parraylength Pfloatarray;
"%floatarray_safe_get", Parrayrefs Pfloatarray;
"%floatarray_safe_set", Parraysets Pfloatarray;
"%floatarray_unsafe_get", Parrayrefu Pfloatarray;
"%floatarray_unsafe_set", Parraysetu Pfloatarray;
"%obj_is_int", Pisint;
"%lazy_force", Plazyforce;
"%nativeint_of_int", Pbintofint Pnativeint;
"%nativeint_to_int", Pintofbint Pnativeint;
"%nativeint_neg", Pnegbint Pnativeint;
"%nativeint_add", Paddbint Pnativeint;
"%nativeint_sub", Psubbint Pnativeint;
"%nativeint_mul", Pmulbint Pnativeint;
"%nativeint_div", Pdivbint { size = Pnativeint; is_safe = Safe };
"%nativeint_mod", Pmodbint { size = Pnativeint; is_safe = Safe };
"%nativeint_and", Pandbint Pnativeint;
"%nativeint_or", Porbint Pnativeint;
"%nativeint_xor", Pxorbint Pnativeint;
"%nativeint_lsl", Plslbint Pnativeint;
"%nativeint_lsr", Plsrbint Pnativeint;
"%nativeint_asr", Pasrbint Pnativeint;
"%int32_of_int", Pbintofint Pint32;
"%int32_to_int", Pintofbint Pint32;
"%int32_neg", Pnegbint Pint32;
"%int32_add", Paddbint Pint32;
"%int32_sub", Psubbint Pint32;
"%int32_mul", Pmulbint Pint32;
"%int32_div", Pdivbint { size = Pint32; is_safe = Safe };
"%int32_mod", Pmodbint { size = Pint32; is_safe = Safe };
"%int32_and", Pandbint Pint32;
"%int32_or", Porbint Pint32;
"%int32_xor", Pxorbint Pint32;
"%int32_lsl", Plslbint Pint32;
"%int32_lsr", Plsrbint Pint32;
"%int32_asr", Pasrbint Pint32;
"%int64_of_int", Pbintofint Pint64;
"%int64_to_int", Pintofbint Pint64;
"%int64_neg", Pnegbint Pint64;
"%int64_add", Paddbint Pint64;
"%int64_sub", Psubbint Pint64;
"%int64_mul", Pmulbint Pint64;
"%int64_div", Pdivbint { size = Pint64; is_safe = Safe };
"%int64_mod", Pmodbint { size = Pint64; is_safe = Safe };
"%int64_and", Pandbint Pint64;
"%int64_or", Porbint Pint64;
"%int64_xor", Pxorbint Pint64;
"%int64_lsl", Plslbint Pint64;
"%int64_lsr", Plsrbint Pint64;
"%int64_asr", Pasrbint Pint64;
"%nativeint_of_int32", Pcvtbint(Pint32, Pnativeint);
"%nativeint_to_int32", Pcvtbint(Pnativeint, Pint32);
"%int64_of_int32", Pcvtbint(Pint32, Pint64);
"%int64_to_int32", Pcvtbint(Pint64, Pint32);
"%int64_of_nativeint", Pcvtbint(Pnativeint, Pint64);
"%int64_to_nativeint", Pcvtbint(Pint64, Pnativeint);
"%caml_ba_ref_1",
Pbigarrayref(false, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_ref_2",
Pbigarrayref(false, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_ref_3",
Pbigarrayref(false, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_set_1",
Pbigarrayset(false, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_set_2",
Pbigarrayset(false, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_set_3",
Pbigarrayset(false, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_unsafe_ref_1",
Pbigarrayref(true, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_unsafe_ref_2",
Pbigarrayref(true, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_unsafe_ref_3",
Pbigarrayref(true, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_unsafe_set_1",
Pbigarrayset(true, 1, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_unsafe_set_2",
Pbigarrayset(true, 2, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_unsafe_set_3",
Pbigarrayset(true, 3, Pbigarray_unknown, Pbigarray_unknown_layout);
"%caml_ba_dim_1", Pbigarraydim(1);
"%caml_ba_dim_2", Pbigarraydim(2);
"%caml_ba_dim_3", Pbigarraydim(3);
"%caml_string_get16", Pstring_load_16(false);
"%caml_string_get16u", Pstring_load_16(true);
"%caml_string_get32", Pstring_load_32(false);
"%caml_string_get32u", Pstring_load_32(true);
"%caml_string_get64", Pstring_load_64(false);
"%caml_string_get64u", Pstring_load_64(true);
"%caml_string_set16", Pstring_set_16(false);
"%caml_string_set16u", Pstring_set_16(true);
"%caml_string_set32", Pstring_set_32(false);
"%caml_string_set32u", Pstring_set_32(true);
"%caml_string_set64", Pstring_set_64(false);
"%caml_string_set64u", Pstring_set_64(true);
"%caml_bigstring_get16", Pbigstring_load_16(false);
"%caml_bigstring_get16u", Pbigstring_load_16(true);
"%caml_bigstring_get32", Pbigstring_load_32(false);
"%caml_bigstring_get32u", Pbigstring_load_32(true);
"%caml_bigstring_get64", Pbigstring_load_64(false);
"%caml_bigstring_get64u", Pbigstring_load_64(true);
"%caml_bigstring_set16", Pbigstring_set_16(false);
"%caml_bigstring_set16u", Pbigstring_set_16(true);
"%caml_bigstring_set32", Pbigstring_set_32(false);
"%caml_bigstring_set32u", Pbigstring_set_32(true);
"%caml_bigstring_set64", Pbigstring_set_64(false);
"%caml_bigstring_set64u", Pbigstring_set_64(true);
"%bswap16", Pbswap16;
"%bswap_int32", Pbbswap(Pint32);
"%bswap_int64", Pbbswap(Pint64);
"%bswap_native", Pbbswap(Pnativeint);
"%int_as_pointer", Pint_as_pointer;
"%opaque", Popaque;
]
let find_primitive prim_name =
Hashtbl.find primitives_table prim_name
let prim_restore_raw_backtrace =
Primitive.simple ~name:"caml_restore_raw_backtrace" ~arity:2 ~alloc:false
let specialize_comparison table env ty =
let (gencomp, intcomp, floatcomp, stringcomp, bytescomp,
nativeintcomp, int32comp, int64comp, _) = table in
match () with
| () when is_base_type env ty Predef.path_int
|| is_base_type env ty Predef.path_char
|| (maybe_pointer_type env ty = Immediate) -> intcomp
| () when is_base_type env ty Predef.path_float -> floatcomp
| () when is_base_type env ty Predef.path_string -> stringcomp
| () when is_base_type env ty Predef.path_bytes -> bytescomp
| () when is_base_type env ty Predef.path_nativeint -> nativeintcomp
| () when is_base_type env ty Predef.path_int32 -> int32comp
| () when is_base_type env ty Predef.path_int64 -> int64comp
| () -> gencomp
(* The following function computes the greatest lower bound in the
semilattice of array kinds:
gen
/ \
addr float
|
int
Note that the GLB is not guaranteed to exist, in which case we return
our first argument instead of raising a fatal error because, although
it cannot happen in a well-typed program, (ab)use of Obj.magic can
probably trigger it.
*)
let glb_array_type t1 t2 =
match t1, t2 with
| Pfloatarray, (Paddrarray | Pintarray)
| (Paddrarray | Pintarray), Pfloatarray -> t1
| Pgenarray, x | x, Pgenarray -> x
| Paddrarray, x | x, Paddrarray -> x
| Pintarray, Pintarray -> Pintarray
| Pfloatarray, Pfloatarray -> Pfloatarray
(* Specialize a primitive from available type information,
raise Not_found if primitive is unknown *)
let specialize_primitive p env ty ~has_constant_constructor =
try
let table = Hashtbl.find comparisons_table p.prim_name in
let (gencomp, intcomp, _, _, _, _, _, _, simplify_constant_constructor) =
table in
if has_constant_constructor && simplify_constant_constructor then
intcomp
else
match is_function_type env ty with
| Some (lhs,_rhs) -> specialize_comparison table env lhs
| None -> gencomp
with Not_found ->
let p = find_primitive p.prim_name in
(* Try strength reduction based on the type of the argument *)
let params = match is_function_type env ty with
| None -> []
| Some (p1, rhs) -> match is_function_type env rhs with
| None -> [p1]
| Some (p2, _) -> [p1;p2]
in
match (p, params) with
(Psetfield(n, _, init), [_p1; p2]) ->
Psetfield(n, maybe_pointer_type env p2, init)
| (Parraylength t, [p]) ->
Parraylength(glb_array_type t (array_type_kind env p))
| (Parrayrefu t, p1 :: _) ->
Parrayrefu(glb_array_type t (array_type_kind env p1))
| (Parraysetu t, p1 :: _) ->
Parraysetu(glb_array_type t (array_type_kind env p1))
| (Parrayrefs t, p1 :: _) ->
Parrayrefs(glb_array_type t (array_type_kind env p1))
| (Parraysets t, p1 :: _) ->
Parraysets(glb_array_type t (array_type_kind env p1))
| (Pbigarrayref(unsafe, n, Pbigarray_unknown, Pbigarray_unknown_layout),
p1 :: _) ->
let (k, l) = bigarray_type_kind_and_layout env p1 in
Pbigarrayref(unsafe, n, k, l)
| (Pbigarrayset(unsafe, n, Pbigarray_unknown, Pbigarray_unknown_layout),
p1 :: _) ->
let (k, l) = bigarray_type_kind_and_layout env p1 in
Pbigarrayset(unsafe, n, k, l)
| (Pmakeblock(tag, mut, None), fields) ->
let shape = List.map (Typeopt.value_kind env) fields in
Pmakeblock(tag, mut, Some shape)
| _ -> p
(* Eta-expand a primitive *)
let used_primitives = Hashtbl.create 7
let add_used_primitive loc env path =
match path with
Some (Path.Pdot _ as path) ->
let path = Env.normalize_path (Some loc) env path in
let unit = Path.head path in
if Ident.global unit && not (Hashtbl.mem used_primitives path)
then Hashtbl.add used_primitives path loc
| _ -> ()
let transl_primitive loc p env ty path =
let prim =
try specialize_primitive p env ty ~has_constant_constructor:false
with Not_found ->
add_used_primitive loc env path;
Pccall p
in
match prim with
| Plazyforce ->
let parm = Ident.create "prim" in
Lfunction{kind = Curried; params = [parm];
body = Matching.inline_lazy_force (Lvar parm) Location.none;
loc = loc;
attr = default_stub_attribute }
| Ploc kind ->
let lam = lam_of_loc kind loc in
begin match p.prim_arity with
| 0 -> lam
| 1 -> (* TODO: we should issue a warning ? *)
let param = Ident.create "prim" in
Lfunction{kind = Curried; params = [param];
attr = default_stub_attribute;
loc = loc;
body = Lprim(Pmakeblock(0, Immutable, None),
[lam; Lvar param], loc)}
| _ -> assert false
end
| _ ->
let rec make_params n =
if n <= 0 then [] else Ident.create "prim" :: make_params (n-1) in
let params = make_params p.prim_arity in
Lfunction{ kind = Curried; params;
attr = default_stub_attribute;
loc = loc;
body = Lprim(prim, List.map (fun id -> Lvar id) params, loc) }
let transl_primitive_application loc prim env ty path args =
let prim_name = prim.prim_name in
try
let has_constant_constructor = match args with
[_; {exp_desc = Texp_construct(_, {cstr_tag = Cstr_constant _}, _)}]
| [{exp_desc = Texp_construct(_, {cstr_tag = Cstr_constant _}, _)}; _]
| [_; {exp_desc = Texp_variant(_, None)}]
| [{exp_desc = Texp_variant(_, None)}; _] -> true
| _ -> false
in
specialize_primitive prim env ty ~has_constant_constructor
with Not_found ->
if String.length prim_name > 0 && prim_name.[0] = '%' then
raise(Error(loc, Unknown_builtin_primitive prim_name));
add_used_primitive loc env path;
Pccall prim
(* To propagate structured constants *)
exception Not_constant
let extract_constant = function
Lconst sc -> sc
| _ -> raise Not_constant
let extract_float = function
Const_base(Const_float f) -> f
| _ -> fatal_error "Translcore.extract_float"
(* Push the default values under the functional abstractions *)
(* Also push bindings of module patterns, since this sound *)
type binding =
| Bind_value of value_binding list
| Bind_module of Ident.t * string loc * module_expr
let rec push_defaults loc bindings cases partial =
match cases with
[{c_lhs=pat; c_guard=None;
c_rhs={exp_desc = Texp_function { arg_label; param; cases; partial; } }
as exp}] ->
let cases = push_defaults exp.exp_loc bindings cases partial in
[{c_lhs=pat; c_guard=None;
c_rhs={exp with exp_desc = Texp_function { arg_label; param; cases;
partial; }}}]
| [{c_lhs=pat; c_guard=None;
c_rhs={exp_attributes=[{txt="#default"},_];
exp_desc = Texp_let
(Nonrecursive, binds, ({exp_desc = Texp_function _} as e2))}}] ->
push_defaults loc (Bind_value binds :: bindings)
[{c_lhs=pat;c_guard=None;c_rhs=e2}]
partial
| [{c_lhs=pat; c_guard=None;
c_rhs={exp_attributes=[{txt="#modulepat"},_];
exp_desc = Texp_letmodule
(id, name, mexpr, ({exp_desc = Texp_function _} as e2))}}] ->
push_defaults loc (Bind_module (id, name, mexpr) :: bindings)
[{c_lhs=pat;c_guard=None;c_rhs=e2}]
partial
| [case] ->
let exp =
List.fold_left
(fun exp binds ->
{exp with exp_desc =
match binds with
| Bind_value binds -> Texp_let(Nonrecursive, binds, exp)
| Bind_module (id, name, mexpr) ->
Texp_letmodule (id, name, mexpr, exp)})
case.c_rhs bindings
in
[{case with c_rhs=exp}]
| {c_lhs=pat; c_rhs=exp; c_guard=_} :: _ when bindings <> [] ->
let param = Typecore.name_pattern "param" cases in
let name = Ident.name param in
let exp =
{ exp with exp_loc = loc; exp_desc =
Texp_match
({exp with exp_type = pat.pat_type; exp_desc =
Texp_ident (Path.Pident param, mknoloc (Longident.Lident name),
{val_type = pat.pat_type; val_kind = Val_reg;
val_attributes = [];
Types.val_loc = Location.none;
})},
cases, [], partial) }
in
push_defaults loc bindings
[{c_lhs={pat with pat_desc = Tpat_var (param, mknoloc name)};
c_guard=None; c_rhs=exp}]
Total
| _ ->
cases
(* Insertion of debugging events *)
let event_before exp lam = match lam with
| Lstaticraise (_,_) -> lam
| _ ->
if !Clflags.debug && not !Clflags.native_code
then Levent(lam, {lev_loc = exp.exp_loc;
lev_kind = Lev_before;
lev_repr = None;
lev_env = Env.summary exp.exp_env})
else lam
let event_after exp lam =
if !Clflags.debug && not !Clflags.native_code
then Levent(lam, {lev_loc = exp.exp_loc;
lev_kind = Lev_after exp.exp_type;
lev_repr = None;
lev_env = Env.summary exp.exp_env})
else lam
let event_function exp lam =
if !Clflags.debug && not !Clflags.native_code then
let repr = Some (ref 0) in
let (info, body) = lam repr in
(info,
Levent(body, {lev_loc = exp.exp_loc;
lev_kind = Lev_function;
lev_repr = repr;
lev_env = Env.summary exp.exp_env}))
else
lam None
let primitive_is_ccall = function
(* Determine if a primitive is a Pccall or will be turned later into
a C function call that may raise an exception *)
| Pccall _ | Pstringrefs | Pbytesrefs | Pbytessets | Parrayrefs _ |
Parraysets _ | Pbigarrayref _ | Pbigarrayset _ | Pduprecord _ | Pdirapply |
Prevapply -> true
| _ -> false
(* Assertions *)
let assert_failed exp =
let (fname, line, char) =
Location.get_pos_info exp.exp_loc.Location.loc_start in
Lprim(Praise Raise_regular, [event_after exp
(Lprim(Pmakeblock(0, Immutable, None),
[transl_normal_path Predef.path_assert_failure;
Lconst(Const_block(0,
[Const_base(Const_string (fname, None));
Const_base(Const_int line);
Const_base(Const_int char)]))], exp.exp_loc))], exp.exp_loc)
;;
let rec cut n l =
if n = 0 then ([],l) else
match l with [] -> failwith "Translcore.cut"
| a::l -> let (l1,l2) = cut (n-1) l in (a::l1,l2)
(* Translation of expressions *)
let try_ids = Hashtbl.create 8
let rec transl_exp e =
List.iter (Translattribute.check_attribute e) e.exp_attributes;
let eval_once =
(* Whether classes for immediate objects must be cached *)
match e.exp_desc with
Texp_function _ | Texp_for _ | Texp_while _ -> false
| _ -> true
in
if eval_once then transl_exp0 e else
Translobj.oo_wrap e.exp_env true transl_exp0 e
and transl_exp0 e =
match e.exp_desc with
Texp_ident(path, _, {val_kind = Val_prim p}) ->
let public_send = p.prim_name = "%send" in
if public_send || p.prim_name = "%sendself" then
let kind = if public_send then Public else Self in
let obj = Ident.create "obj" and meth = Ident.create "meth" in
Lfunction{kind = Curried; params = [obj; meth];
attr = default_stub_attribute;
loc = e.exp_loc;
body = Lsend(kind, Lvar meth, Lvar obj, [], e.exp_loc)}
else if p.prim_name = "%sendcache" then
let obj = Ident.create "obj" and meth = Ident.create "meth" in
let cache = Ident.create "cache" and pos = Ident.create "pos" in
Lfunction{kind = Curried; params = [obj; meth; cache; pos];
attr = default_stub_attribute;
loc = e.exp_loc;
body = Lsend(Cached, Lvar meth, Lvar obj,
[Lvar cache; Lvar pos], e.exp_loc)}
else
transl_primitive e.exp_loc p e.exp_env e.exp_type (Some path)
| Texp_ident(_, _, {val_kind = Val_anc _}) ->
raise(Error(e.exp_loc, Free_super_var))
| Texp_ident(path, _, {val_kind = Val_reg | Val_self _}) ->
transl_value_path ~loc:e.exp_loc e.exp_env path
| Texp_ident _ -> fatal_error "Translcore.transl_exp: bad Texp_ident"
| Texp_constant cst ->
Lconst(Const_base cst)
| Texp_let(rec_flag, pat_expr_list, body) ->
transl_let rec_flag pat_expr_list (event_before body (transl_exp body))
| Texp_function { arg_label = _; param; cases; partial; } ->
let ((kind, params), body) =
event_function e
(function repr ->
let pl = push_defaults e.exp_loc [] cases partial in
transl_function e.exp_loc !Clflags.native_code repr partial
param pl)
in
let attr = {
default_function_attribute with
inline = Translattribute.get_inline_attribute e.exp_attributes;
specialise = Translattribute.get_specialise_attribute e.exp_attributes;
}
in
let loc = e.exp_loc in
Lfunction{kind; params; body; attr; loc}
| Texp_apply({ exp_desc = Texp_ident(path, _, {val_kind = Val_prim p});
exp_type = prim_type } as funct, oargs)
when List.length oargs >= p.prim_arity
&& List.for_all (fun (_, arg) -> arg <> None) oargs ->
let args, args' = cut p.prim_arity oargs in
let wrap f =
if args' = []
then event_after e f
else
let should_be_tailcall, funct =
Translattribute.get_tailcall_attribute funct
in
let inlined, funct =
Translattribute.get_and_remove_inlined_attribute funct
in
let specialised, funct =
Translattribute.get_and_remove_specialised_attribute funct
in
let e = { e with exp_desc = Texp_apply(funct, oargs) } in
event_after e
(transl_apply ~should_be_tailcall ~inlined ~specialised
f args' e.exp_loc)
in
let wrap0 f =
if args' = [] then f else wrap f in
let args =
List.map (function _, Some x -> x | _ -> assert false) args in
let argl = transl_list args in
let public_send = p.prim_name = "%send"
|| not !Clflags.native_code && p.prim_name = "%sendcache"in
if public_send || p.prim_name = "%sendself" then
let kind = if public_send then Public else Self in
let obj = List.hd argl in
wrap (Lsend (kind, List.nth argl 1, obj, [], e.exp_loc))
else if p.prim_name = "%sendcache" then
match argl with [obj; meth; cache; pos] ->
wrap (Lsend(Cached, meth, obj, [cache; pos], e.exp_loc))
| _ -> assert false
else if p.prim_name = "%raise_with_backtrace" then begin
let texn1 = List.hd args (* Should not fail by typing *) in
let texn2,bt = match argl with
| [a;b] -> a,b
| _ -> assert false (* idem *)
in
let vexn = Ident.create "exn" in
Llet(Strict, Pgenval, vexn, texn2,
event_before e begin
Lsequence(
wrap (Lprim (Pccall prim_restore_raw_backtrace,
[Lvar vexn;bt],
e.exp_loc)),
wrap0 (Lprim(Praise Raise_reraise,
[event_after texn1 (Lvar vexn)],
e.exp_loc))
)
end
)
end
else begin
let prim = transl_primitive_application
e.exp_loc p e.exp_env prim_type (Some path) args in
match (prim, args) with
(Praise k, [arg1]) ->
let targ = List.hd argl in
let k =
match k, targ with
| Raise_regular, Lvar id
when Hashtbl.mem try_ids id ->
Raise_reraise
| _ ->
k
in
wrap0 (Lprim(Praise k, [event_after arg1 targ], e.exp_loc))
| (Ploc kind, []) ->
lam_of_loc kind e.exp_loc
| (Ploc kind, [arg1]) ->
let lam = lam_of_loc kind arg1.exp_loc in
Lprim(Pmakeblock(0, Immutable, None), lam :: argl, e.exp_loc)
| (Ploc _, _) -> assert false
| (_, _) ->
begin match (prim, argl) with
| (Plazyforce, [a]) ->
wrap (Matching.inline_lazy_force a e.exp_loc)
| (Plazyforce, _) -> assert false
|_ -> let p = Lprim(prim, argl, e.exp_loc) in
if primitive_is_ccall prim then wrap p else wrap0 p
end
end
| Texp_apply(funct, oargs) ->
let should_be_tailcall, funct =
Translattribute.get_tailcall_attribute funct
in
let inlined, funct =
Translattribute.get_and_remove_inlined_attribute funct
in
let specialised, funct =
Translattribute.get_and_remove_specialised_attribute funct
in
let e = { e with exp_desc = Texp_apply(funct, oargs) } in
event_after e
(transl_apply ~should_be_tailcall ~inlined ~specialised
(transl_exp funct) oargs e.exp_loc)
| Texp_match(arg, pat_expr_list, exn_pat_expr_list, partial) ->
transl_match e arg pat_expr_list exn_pat_expr_list partial
| Texp_try(body, pat_expr_list) ->
let id = Typecore.name_pattern "exn" pat_expr_list in
Ltrywith(transl_exp body, id,
Matching.for_trywith (Lvar id) (transl_cases_try pat_expr_list))
| Texp_tuple el ->
let ll, shape = transl_list_with_shape el in
begin try
Lconst(Const_block(0, List.map extract_constant ll))
with Not_constant ->
Lprim(Pmakeblock(0, Immutable, Some shape), ll, e.exp_loc)
end
| Texp_construct(_, cstr, args) ->
let ll, shape = transl_list_with_shape args in
if cstr.cstr_inlined <> None then begin match ll with
| [x] -> x
| _ -> assert false
end else begin match cstr.cstr_tag with
Cstr_constant n ->
Lconst(Const_pointer n)
| Cstr_unboxed ->
(match ll with [v] -> v | _ -> assert false)
| Cstr_block n ->
begin try
Lconst(Const_block(n, List.map extract_constant ll))
with Not_constant ->
Lprim(Pmakeblock(n, Immutable, Some shape), ll, e.exp_loc)
end
| Cstr_extension(path, is_const) ->
if is_const then
transl_extension_path e.exp_env path
else
Lprim(Pmakeblock(0, Immutable, Some (Pgenval :: shape)),
transl_extension_path e.exp_env path :: ll, e.exp_loc)
end
| Texp_extension_constructor (_, path) ->
transl_extension_path e.exp_env path
| Texp_variant(l, arg) ->
let tag = Btype.hash_variant l in
begin match arg with
None -> Lconst(Const_pointer tag)
| Some arg ->
let lam = transl_exp arg in
try
Lconst(Const_block(0, [Const_base(Const_int tag);
extract_constant lam]))
with Not_constant ->
Lprim(Pmakeblock(0, Immutable, None),
[Lconst(Const_base(Const_int tag)); lam], e.exp_loc)
end
| Texp_record {fields; representation; extended_expression} ->
transl_record e.exp_loc e.exp_env fields representation
extended_expression
| Texp_field(arg, _, lbl) ->
let targ = transl_exp arg in
begin match lbl.lbl_repres with
Record_regular | Record_inlined _ ->
Lprim (Pfield lbl.lbl_pos, [targ], e.exp_loc)
| Record_unboxed _ -> targ
| Record_float -> Lprim (Pfloatfield lbl.lbl_pos, [targ], e.exp_loc)
| Record_extension ->
Lprim (Pfield (lbl.lbl_pos + 1), [targ], e.exp_loc)
end
| Texp_setfield(arg, _, lbl, newval) ->
let access =
match lbl.lbl_repres with
Record_regular
| Record_inlined _ ->
Psetfield(lbl.lbl_pos, maybe_pointer newval, Assignment)
| Record_unboxed _ -> assert false
| Record_float -> Psetfloatfield (lbl.lbl_pos, Assignment)
| Record_extension ->
Psetfield (lbl.lbl_pos + 1, maybe_pointer newval, Assignment)
in
Lprim(access, [transl_exp arg; transl_exp newval], e.exp_loc)
| Texp_array expr_list ->
let kind = array_kind e in
let ll = transl_list expr_list in
begin try
(* For native code the decision as to which compilation strategy to
use is made later. This enables the Flambda passes to lift certain
kinds of array definitions to symbols. *)
(* Deactivate constant optimization if array is small enough *)
if List.length ll <= use_dup_for_constant_arrays_bigger_than
then begin
raise Not_constant
end;
begin match List.map extract_constant ll with
| exception Not_constant when kind = Pfloatarray ->
(* We cannot currently lift [Pintarray] arrays safely in Flambda
because [caml_modify] might be called upon them (e.g. from
code operating on polymorphic arrays, or functions such as
[caml_array_blit].
To avoid having different Lambda code for
bytecode/Closure vs. Flambda, we always generate
[Pduparray] here, and deal with it in [Bytegen] (or in
the case of Closure, in [Cmmgen], which already has to
handle [Pduparray Pmakearray Pfloatarray] in the case
where the array turned out to be inconstant).
When not [Pfloatarray], the exception propagates to the handler
below. *)
let imm_array =
Lprim (Pmakearray (kind, Immutable), ll, e.exp_loc)
in
Lprim (Pduparray (kind, Mutable), [imm_array], e.exp_loc)
| cl ->
let imm_array =
match kind with
| Paddrarray | Pintarray ->
Lconst(Const_block(0, cl))
| Pfloatarray ->
Lconst(Const_float_array(List.map extract_float cl))
| Pgenarray ->
raise Not_constant (* can this really happen? *)
in
Lprim (Pduparray (kind, Mutable), [imm_array], e.exp_loc)
end
with Not_constant ->
Lprim(Pmakearray (kind, Mutable), ll, e.exp_loc)
end
| Texp_ifthenelse(cond, ifso, Some ifnot) ->
Lifthenelse(transl_exp cond,
event_before ifso (transl_exp ifso),
event_before ifnot (transl_exp ifnot))
| Texp_ifthenelse(cond, ifso, None) ->
Lifthenelse(transl_exp cond,
event_before ifso (transl_exp ifso),
lambda_unit)
| Texp_sequence(expr1, expr2) ->
Lsequence(transl_exp expr1, event_before expr2 (transl_exp expr2))
| Texp_while(cond, body) ->
Lwhile(transl_exp cond, event_before body (transl_exp body))
| Texp_for(param, _, low, high, dir, body) ->
Lfor(param, transl_exp low, transl_exp high, dir,
event_before body (transl_exp body))
| Texp_send(_, _, Some exp) -> transl_exp exp
| Texp_send(expr, met, None) ->
let obj = transl_exp expr in
let lam =
match met with
Tmeth_val id -> Lsend (Self, Lvar id, obj, [], e.exp_loc)
| Tmeth_name nm ->
let (tag, cache) = Translobj.meth obj nm in
let kind = if cache = [] then Public else Cached in
Lsend (kind, tag, obj, cache, e.exp_loc)
in
event_after e lam
| Texp_new (cl, {Location.loc=loc}, _) ->
Lapply{ap_should_be_tailcall=false;
ap_loc=loc;
ap_func=Lprim(Pfield 0, [transl_class_path ~loc e.exp_env cl], loc);
ap_args=[lambda_unit];
ap_inlined=Default_inline;
ap_specialised=Default_specialise}
| Texp_instvar(path_self, path, _) ->
Lprim(Pfield_computed,
[transl_normal_path path_self; transl_normal_path path], e.exp_loc)
| Texp_setinstvar(path_self, path, _, expr) ->
transl_setinstvar e.exp_loc (transl_normal_path path_self) path expr
| Texp_override(path_self, modifs) ->
let cpy = Ident.create "copy" in
Llet(Strict, Pgenval, cpy,
Lapply{ap_should_be_tailcall=false;
ap_loc=Location.none;
ap_func=Translobj.oo_prim "copy";
ap_args=[transl_normal_path path_self];
ap_inlined=Default_inline;
ap_specialised=Default_specialise},
List.fold_right
(fun (path, _, expr) rem ->
Lsequence(transl_setinstvar Location.none
(Lvar cpy) path expr, rem))
modifs
(Lvar cpy))
| Texp_letmodule(id, loc, modl, body) ->
let defining_expr =
Levent (!transl_module Tcoerce_none None modl, {
lev_loc = loc.loc;
lev_kind = Lev_module_definition id;
lev_repr = None;
lev_env = Env.summary Env.empty;