forked from HaxeFoundation/haxe
-
Notifications
You must be signed in to change notification settings - Fork 5
/
analyzer.ml
1715 lines (1633 loc) · 50.8 KB
/
analyzer.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
(*
The Haxe Compiler
Copyright (C) 2005-2015 Haxe Foundation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*)
open Ast
open Type
open Common
open Typecore
let s_expr = s_expr (s_type (print_context()))
let s_expr_pretty = s_expr_pretty "" (s_type (print_context()))
let debug e = print_endline (s_expr e)
let debug_pretty s e = Printf.printf "%s %s\n" s (s_expr_pretty e)
let flag_no_check = "no_check"
let flag_check = "check"
let flag_no_const_propagation = "no_const_propagation"
let flag_const_propagation = "const_propagation"
let flag_no_local_dce = "no_local_dce"
let flag_local_dce = "local_dce"
let flag_ignore = "ignore"
let flag_no_simplification = "no_simplification"
let flag_check_has_effect = "check_has_effect"
let flag_no_check_has_effect = "no_check_has_effect"
let has_analyzer_option meta s =
try
let rec loop ml = match ml with
| (Meta.Analyzer,el,_) :: ml ->
if List.exists (fun (e,p) ->
match e with
| EConst(Ident s2) when s = s2 -> true
| _ -> false
) el then
true
else
loop ml
| _ :: ml ->
loop ml
| [] ->
false
in
loop meta
with Not_found ->
false
let is_ignored meta =
try
let rec loop ml = match ml with
| (Meta.Analyzer,el,_) :: ml ->
if List.exists (fun (e,p) ->
match e with
| EConst(Ident s2) when flag_ignore = s2 -> true
| _ -> false
) el then
true
else
loop ml
| (Meta.HasUntyped,_,_) :: _ ->
true
| _ :: ml ->
loop ml
| [] ->
false
in
loop meta
with Not_found ->
false
let rec get_type_meta t = match t with
| TMono r ->
begin match !r with
| None -> raise Not_found
| Some t -> get_type_meta t
end
| TLazy f ->
get_type_meta (!f())
| TInst(c,_) ->
c.cl_meta
| TEnum(en,_) ->
en.e_meta
| TAbstract(a,_) ->
a.a_meta
| TType(t,_) ->
t.t_meta
| TAnon _ | TFun _ | TDynamic _ ->
raise Not_found
let type_has_analyzer_option t s =
try
has_analyzer_option (get_type_meta t) s
with Not_found ->
false
let is_enum_type t = match follow t with
| TEnum(_) -> true
| _ -> false
let rec awkward_get_enum_index com e = match e.eexpr with
| TArray(e1,{eexpr = TConst(TInt i)}) when com.platform = Js && Int32.to_int i = 1 && is_enum_type e1.etype ->
e1
| TCall({eexpr = TField(e1, FDynamic "__Index")},[]) when com.platform = Cpp && is_enum_type e1.etype ->
e1
| TField(e1,FDynamic "index") when com.platform = Neko && is_enum_type e1.etype ->
e1
| TParenthesis e1 | TCast(e1,None) | TMeta(_,e1) ->
awkward_get_enum_index com e1
| _ ->
raise Not_found
(*
This module simplifies the AST by introducing temporary variables for complex expressions in many places.
In particular, it ensures that no branching can occur in value-places so that we can later insert SSA PHI
nodes without worrying about their placement.
*)
module Simplifier = struct
let mk_block_context com =
let block_el = ref [] in
let push e = block_el := e :: !block_el in
let assign ev e =
let mk_assign e2 = match e2.eexpr with
| TBreak | TContinue | TThrow _ | TReturn _ -> e2
| _ -> mk (TBinop(OpAssign,ev,e2)) e2.etype e2.epos
in
let rec loop e = match e.eexpr with
| TBlock el ->
begin match List.rev el with
| e1 :: el ->
let el = List.rev ((loop e1) :: el) in
{e with eexpr = TBlock el}
| _ ->
mk_assign e
end
| TIf(e1,e2,eo) ->
let e2 = loop e2 in
let eo = match eo with None -> None | Some e3 -> Some (loop e3) in
{e with eexpr = TIf(e1,e2,eo)}
| TSwitch(e1,cases,edef) ->
let cases = List.map (fun (el,e) ->
let e = loop e in
el,e
) cases in
let edef = match edef with None -> None | Some edef -> Some (loop edef) in
{e with eexpr = TSwitch(e1,cases,edef)}
| TTry(e1,catches) ->
let e1 = loop e1 in
let catches = List.map (fun (v,e) ->
let e = loop e in
v,e
) catches in
{e with eexpr = TTry(e1,catches)}
| TParenthesis e1 | TMeta(_,e1) ->
loop e1 (* this is still weird, have to review *)
(* | TBinop(OpAssign,({eexpr = TLocal _} as e1),e2) ->
push e;
mk_assign e1 *)
(* | TBinop(OpAssignOp op,({eexpr = TLocal _} as e1),e2) ->
push e;
mk_assign e1 *)
| _ ->
mk_assign e
in
loop e
in
let declare_temp t eo p =
let v = alloc_var "tmp" t in
v.v_meta <- [Meta.CompilerGenerated,[],p];
let e_v = mk (TLocal v) t p in
let declare e_init =
let e = mk (TVar (v,e_init)) com.basic.tvoid p in
push e;
in
let e_v = match eo with
| None ->
declare None;
e_v
| Some e1 ->
begin match e1.eexpr with
| TThrow _ | TReturn _ | TBreak | TContinue ->
e1
| _ ->
let rec loop e_v e = match e.eexpr with
| TParenthesis e1 ->
loop {e_v with eexpr = TParenthesis e_v} e1
| TMeta(m,e1) ->
loop {e_v with eexpr = TMeta(m,e_v)} e1
| _ ->
e_v,e
in
let e_v',e1 = loop e_v e1 in
let e1 = assign e_v e1 in
begin match e1.eexpr with
| TBinop(OpAssign,{eexpr = TLocal v1},e2) when v == v1 ->
declare (Some e2)
| _ ->
declare None;
push e1
end;
e_v'
end
in
e_v
in
let rec push_block () =
let cur = !block_el in
block_el := [];
fun () ->
let added = !block_el in
block_el := cur;
List.rev added
and block f el =
let close = push_block() in
List.iter (fun e ->
push (f e)
) el;
close()
in
block,declare_temp,fun () -> !block_el
let apply com e =
let block,declare_temp,close_block = mk_block_context com in
let skip_binding ?(allow_tlocal=false) e =
let rec loop e =
match e.eexpr with
| TConst _ | TTypeExpr _ | TFunction _ -> ()
| TLocal _ when allow_tlocal -> ()
| TParenthesis e1 | TCast(e1,None) -> Type.iter loop e
| TField(_,(FStatic(c,cf) | FInstance(c,_,cf))) when has_analyzer_option cf.cf_meta flag_no_simplification || has_analyzer_option c.cl_meta flag_no_simplification -> ()
| TField({eexpr = TLocal _},_) when allow_tlocal -> ()
| TCall({eexpr = TField(_,(FStatic(c,cf) | FInstance(c,_,cf)))},el) when has_analyzer_option cf.cf_meta flag_no_simplification || has_analyzer_option c.cl_meta flag_no_simplification -> ()
| TCall({eexpr = TLocal { v_name = "__cpp__" } },_) -> ()
| TField(_,FEnum _) -> ()
| TField(_,FDynamic _) -> ()
| _ when (try ignore(awkward_get_enum_index com e); true with Not_found -> false) -> ()
| _ -> raise Exit
in
try
loop e;
true
with Exit ->
begin match follow e.etype with
| TAbstract({a_path = [],"Void"},_) -> true
(* | TInst ({ cl_path = [],"Array" }, _) when com.platform = Cpp -> true *)
| _ -> false
end
in
let has_unbound = ref false in
let rec loop e = match e.eexpr with
| TCall({eexpr = TLocal v | TField({eexpr = TLocal v},_)},_) | TField({eexpr = TLocal v},_) | TLocal v when Meta.has Meta.Unbound v.v_meta && v.v_name <> "`trace" ->
has_unbound := true;
e
| TBlock el ->
{e with eexpr = TBlock (block loop el)}
| TCall({eexpr = TField(_,(FStatic(c,cf) | FInstance(c,_,cf)))},el) when has_analyzer_option cf.cf_meta flag_no_simplification || has_analyzer_option c.cl_meta flag_no_simplification ->
e
| TField(_,(FStatic(c,cf) | FInstance(c,_,cf))) when has_analyzer_option cf.cf_meta flag_no_simplification || has_analyzer_option c.cl_meta flag_no_simplification ->
e
| TCall(e1,el) ->
let rec is_valid_call_target e = match e.eexpr with
| TFunction _ | TField _ | TLocal _ | TConst (TSuper) ->
true
| TParenthesis e1 | TCast(e1,None) | TMeta(_,e1) ->
is_valid_call_target e1
| _ ->
false
in
let e1 = if is_valid_call_target e1 then
loop e1
else
bind e1
in
let check e t =
if type_has_analyzer_option t flag_no_simplification then e
else bind e
in
let el = match e1.eexpr,follow e1.etype with
| TConst TSuper,_ when com.platform = Java || com.platform = Cs ->
(* they hate you if you mess up the super call *)
el
| _,TFun _ | TConst TSuper,_ ->
Codegen.UnificationCallback.check_call check el e1.etype
| _ ->
(* too dangerous *)
List.map loop el
in
{e with eexpr = TCall(e1,el)}
| TNew(c,tl,el) ->
{e with eexpr = TNew(c,tl,ordered_list el)}
| TArrayDecl el ->
{e with eexpr = TArrayDecl (ordered_list el)}
| TObjectDecl fl ->
let el = ordered_list (List.map snd fl) in
{e with eexpr = TObjectDecl (List.map2 (fun (n,_) e -> n,e) fl el)}
| TBinop(OpBoolAnd | OpBoolOr as op,e1,e2) ->
let e1 = loop e1 in
let e_then = mk (TBlock (block loop [e2])) e2.etype e2.epos in
let e_if,e_else = if op = OpBoolOr then
mk (TUnop(Not,Prefix,e1)) com.basic.tbool e.epos,mk (TConst (TBool(true))) com.basic.tbool e.epos
else
e1,mk (TConst (TBool(false))) com.basic.tbool e.epos
in
loop (mk (TIf(e_if,e_then,Some e_else)) com.basic.tbool e.epos)
| TBinop((OpAssign | OpAssignOp _) as op,{eexpr = TArray(e11,e12)},e2) ->
let e1 = match ordered_list [e11;e12] with
| [e1;e2] ->
{e with eexpr = TArray(e1,e2)}
| _ ->
assert false
in
let e2 = bind e2 in
{e with eexpr = TBinop(op,e1,e2)}
| TBinop((OpAssign | OpAssignOp _) as op,e1,e2) ->
let e2 = bind ~allow_tlocal:true e2 in
let e1 = loop e1 in
{e with eexpr = TBinop(op,e1,e2)}
| TBinop(op,e1,e2) ->
begin match ordered_list [e1;e2] with
| [e1;e2] ->
{e with eexpr = TBinop(op,e1,e2)}
| _ ->
assert false
end
| TArray(e1,e2) ->
begin match ordered_list [e1;e2] with
| [e1;e2] ->
{e with eexpr = TArray(e1,e2)}
| _ ->
assert false
end
| TWhile(e1,e2,flag) when (match e1.eexpr with TConst(TBool true) | TParenthesis {eexpr = TConst(TBool true)} -> false | _ -> true) ->
let p = e.epos in
let e_break = mk TBreak t_dynamic p in
let e_not = mk (TUnop(Not,Prefix,Codegen.mk_parent e1)) e1.etype e1.epos in
let e_if eo = mk (TIf(e_not,e_break,eo)) com.basic.tvoid p in
let rec map_continue e = match e.eexpr with
| TContinue ->
(e_if (Some e))
| TWhile _ | TFor _ ->
e
| _ ->
Type.map_expr map_continue e
in
let e2 = if flag = NormalWhile then e2 else map_continue e2 in
let e_if = e_if None in
let e_if = mk (TMeta((Meta.Custom ":whileCond",[],e_if.epos), e_if)) e_if.etype e_if.epos in
let e_block = if flag = NormalWhile then Type.concat e_if e2 else Type.concat e2 e_if in
let e_true = mk (TConst (TBool true)) com.basic.tbool p in
let e = mk (TWhile(Codegen.mk_parent e_true,e_block,NormalWhile)) e.etype p in
loop e
| TFor(v,e1,e2) ->
let e1 = bind e1 in
let e2 = loop e2 in
{e with eexpr = TFor(v,e1,e2)}
| TIf(e1,e2,eo) ->
let e1 = bind e1 in
let e2 = loop e2 in
let eo = match eo with None -> None | Some e -> Some (loop e) in
{e with eexpr = TIf(e1,e2,eo)}
| TSwitch (e1,cases,eo) ->
let e1 = bind e1 in
let cases = List.map (fun (el,e) ->
let el = List.map loop el in
let e = loop e in
el,e
) cases in
let eo = match eo with None -> None | Some e -> Some (loop e) in
{e with eexpr = TSwitch(e1,cases,eo)}
| TVar(v,Some e1) ->
let e1 = match e1.eexpr with
| TFunction _ -> loop e1
| TArrayDecl [{eexpr = TFunction _}] -> loop e1
| TNew(_,_,el) when not (List.exists Optimizer.has_side_effect el) -> loop e1 (* issue #4322 *)
| _ -> bind ~allow_tlocal:true e1
in
{e with eexpr = TVar(v,Some e1)}
| TUnop((Neg | NegBits | Not) as op,flag,e1) ->
let e1 = bind e1 in
{e with eexpr = TUnop(op,flag,e1)}
| TField(e1,fa) ->
let e1 = bind ~allow_tlocal:true e1 in
{e with eexpr = TField(e1,fa)}
| TReturn (Some ({eexpr = TThrow _ | TReturn _} as e1)) ->
loop e1 (* this is a bit hackish *)
| TReturn (Some e1) ->
let e1 = bind e1 in
{e with eexpr = TReturn (Some e1)}
| TThrow e1 ->
let e1 = bind e1 in
{e with eexpr = TThrow e1}
| TCast(e1,mto) ->
let e1 = bind ~allow_tlocal:true e1 in
{e with eexpr = TCast(e1,mto)}
| _ ->
Type.map_expr loop e
and bind ?(allow_tlocal=false) e =
let e = loop e in
if skip_binding ~allow_tlocal e then
e
else
declare_temp e.etype (Some e) e.epos
and ordered_list el =
if List.for_all (skip_binding ~allow_tlocal:true) el then
List.map loop el
else
List.map bind el
in
let e = loop e in
!has_unbound,match close_block() with
| [] ->
e
| el ->
mk (TBlock (List.rev (e :: el))) e.etype e.epos
let unapply com e =
let var_map = ref IntMap.empty in
let rec get_assignment_to v e = match e.eexpr with
| TBinop(OpAssign,{eexpr = TLocal v2},e2) when v == v2 -> Some e2
| TBlock [e] -> get_assignment_to v e
| TIf(e1,e2,Some e3) ->
begin match get_assignment_to v e2,get_assignment_to v e3 with
| Some e2,Some e3 -> Some ({e with eexpr = TIf(e1,e2,Some e3)})
| _ -> None
end
| _ -> None
in
let if_or_op e e1 e2 e3 = match e1.eexpr,e3.eexpr with
| TUnop(Not,Prefix,e1),TConst (TBool true) -> {e with eexpr = TBinop(OpBoolOr,e1,e2)}
| _,TConst (TBool false) -> {e with eexpr = TBinop(OpBoolAnd,e1,e2)}
| _ -> {e with eexpr = TIf(e1,e2,Some e3)}
in
let rec loop e = match e.eexpr with
| TBlock el ->
let rec loop2 el = match el with
| e :: el ->
begin match e.eexpr with
| TVar(v,Some e1) when Meta.has Meta.CompilerGenerated v.v_meta ->
if el = [] then
[loop e1]
else begin
var_map := IntMap.add v.v_id (loop e1) !var_map;
loop2 el
end
| TVar(v,None) when not (com.platform = Php) ->
begin match el with
| {eexpr = TBinop(OpAssign,{eexpr = TLocal v2},e2)} :: el when v == v2 ->
let e = {e with eexpr = TVar(v,Some e2)} in
loop2 (e :: el)
| ({eexpr = TIf(e1,e2,Some e3)} as e_if) :: el ->
let e1 = loop e1 in
let e2 = loop e2 in
let e3 = loop e3 in
begin match get_assignment_to v e2,get_assignment_to v e3 with
| Some e2,Some e3 ->
let e_if = if_or_op e_if (loop e1) (loop e2) (loop e3) in
let e = {e with eexpr = TVar(v,Some e_if)} in
loop2 (e :: el)
| _ ->
let e_if = {e_if with eexpr = TIf(e1,e2,Some e3)} in
e :: e_if :: loop2 el
end
| _ ->
let e = loop e in
e :: loop2 el
end
| TReturn (Some e1) when (match follow e1.etype with TAbstract({a_path=[],"Void"},_) -> true | _ -> false) ->
[(loop e1);{e with eexpr = TReturn None}]
| _ ->
let e = loop e in
e :: loop2 el
end
| [] ->
[]
in
let el = loop2 el in
{e with eexpr = TBlock el}
| TLocal v when Meta.has Meta.CompilerGenerated v.v_meta ->
begin try IntMap.find v.v_id !var_map
with Not_found -> e end
| TWhile(e1,e2,flag) ->
let e1 = loop e1 in
let e2 = loop e2 in
let extract_cond e = match e.eexpr with
| TIf({eexpr = TUnop(Not,_,e1)},_,_) -> e1
| TBreak -> raise Exit (* can happen due to optimization, not so easy to deal with because there might be other breaks/continues *)
| _ -> assert false
in
let e1,e2,flag = try
begin match e2.eexpr with
| TBlock el ->
begin match el with
| {eexpr = TMeta((Meta.Custom ":whileCond",_,_),e1)} :: el ->
let e1 = extract_cond e1 in
e1,{e2 with eexpr = TBlock el},NormalWhile
| _ ->
e1,e2,flag
(* issue 3844 *)
(* begin match List.rev el with
| {eexpr = TMeta((Meta.Custom ":whileCond",_,_),e1)} :: el ->
let e1 = extract_cond e1 in
e1,{e2 with eexpr = TBlock (List.rev el)},DoWhile
| _ ->
e1,e2,flag
end *)
end
| _ ->
e1,e2,flag
end with Exit ->
e1,e2,flag
in
{e with eexpr = TWhile(e1,e2,flag)}
| TIf(e1,e2,Some e3) ->
let e1 = loop e1 in
let e2 = loop e2 in
let e3 = loop e3 in
if_or_op e e1 e2 e3
| _ ->
Type.map_expr loop e
in
loop e
end
module Ssa = struct
type var_map = tvar IntMap.t
type condition =
| Equal of tvar * texpr
| NotEqual of tvar * texpr
type node_data = {
nd_pos: pos;
mutable nd_var_map : var_map;
mutable nd_terminates : bool;
}
type join_node = {
mutable branches : node_data list;
}
type ssa_context = {
com : Common.context;
mutable cleanup : (unit -> unit) list;
mutable cur_data : node_data;
mutable var_conds : (condition list) IntMap.t;
mutable loop_stack : (join_node * join_node) list;
mutable exception_stack : join_node list;
mutable block_depth : int;
}
let s_cond = function
| Equal(v,e) -> Printf.sprintf "%s == %s" v.v_name (s_expr_pretty e)
| NotEqual(v,e) -> Printf.sprintf "%s != %s" v.v_name (s_expr_pretty e)
let s_conds conds =
String.concat " && " (List.map s_cond conds)
let mk_loc v p = mk (TLocal v) v.v_type p
let mk_phi =
let v_phi = alloc_var "__ssa_phi__" t_dynamic in
(fun vl p ->
let e = mk (TCall(mk_loc v_phi p,(List.map (fun (v,p) -> mk_loc v p) vl))) t_dynamic p in
e
)
(* TODO: make sure this is conservative *)
let can_throw e =
let rec loop e = match e.eexpr with
| TConst _ | TLocal _ | TTypeExpr _ | TFunction _ | TBlock _ -> ()
| TCall _ | TNew _ | TThrow _ | TCast(_,Some _) -> raise Exit
| _ -> Type.iter loop e
in
try
loop e; false
with Exit ->
true
let mk_join_node() = {
branches = []
}
let mk_node_data p = {
nd_pos = p;
nd_var_map = IntMap.empty;
nd_terminates = false;
}
let add_branch join branch p =
join.branches <- {branch with nd_pos = p} :: join.branches
let branch ctx p =
let old_map = ctx.cur_data.nd_var_map in
let old_term = ctx.cur_data.nd_terminates in
ctx.cur_data.nd_terminates <- false;
(fun join ->
add_branch join ctx.cur_data p;
ctx.cur_data.nd_var_map <- old_map;
ctx.cur_data.nd_terminates <- old_term;
)
let terminate ctx =
ctx.cur_data.nd_terminates <- true
let set_loop_join ctx join_top join_bottom =
ctx.loop_stack <- (join_top,join_bottom) :: ctx.loop_stack;
(fun () ->
ctx.loop_stack <- List.tl ctx.loop_stack
)
let set_exception_join ctx join =
ctx.exception_stack <- join :: ctx.exception_stack;
(fun () ->
ctx.exception_stack <- List.tl ctx.exception_stack;
)
let create_v_extra v =
match v.v_extra with
| Some (_,Some _) ->
()
| Some (tl,None) ->
let e_extra = mk (TObjectDecl []) t_dynamic null_pos in
v.v_extra <- Some (tl,Some e_extra)
| None ->
let e_extra = mk (TObjectDecl []) t_dynamic null_pos in
v.v_extra <- Some ([],Some e_extra)
let set_v_extra_value v s e = match v.v_extra with
| Some (tl, Some {eexpr = TObjectDecl fl}) ->
let rec loop fl = match fl with
| (s',_) :: fl when s' = s ->
(s,e) :: fl
| f1 :: fl ->
f1 :: loop fl
| [] ->
[s,e]
in
let e_extra = mk (TObjectDecl (loop fl)) t_dynamic null_pos in
v.v_extra <- Some (tl, Some e_extra)
| _ ->
assert false
let get_origin_var v = match v.v_extra with
| Some (_,Some {eexpr = TObjectDecl fl}) ->
begin match List.assoc "origin_var" fl with
| {eexpr = TLocal v'} -> v'
| _ -> raise Not_found
end
| _ ->
raise Not_found
let set_origin_var v v_origin p =
let ev = mk_loc v_origin p in
set_v_extra_value v "origin_var" ev
let get_var_value v = match v.v_extra with
| Some (_,Some {eexpr = TObjectDecl fl}) ->
List.assoc "var_value" fl
| _ ->
raise Not_found
let set_var_value v e =
set_v_extra_value v "var_value" e
let get_var_usage_count v = match v.v_extra with
| Some (_,Some {eexpr = TObjectDecl fl}) ->
begin try
begin match List.assoc "usage_count" fl with
| {eexpr = TConst (TInt i32)} -> Int32.to_int i32
| _ -> 0
end
with Not_found ->
0
end
| _ ->
raise Not_found
let set_var_usage_count v i =
let e = mk (TConst (TInt (Int32.of_int i))) t_dynamic null_pos in
set_v_extra_value v "usage_count" e
let declare_var ctx v p =
let old = v.v_extra in
ctx.cleanup <- (fun () ->
v.v_extra <- old
) :: ctx.cleanup;
ctx.cur_data.nd_var_map <- IntMap.add v.v_id v ctx.cur_data.nd_var_map;
v.v_meta <- ((Meta.Custom ":blockDepth",[EConst (Int (string_of_int ctx.block_depth)),p],p)) :: v.v_meta;
v.v_extra <- None;
create_v_extra v;
set_origin_var v v p
let assign_var ctx v e p =
if v.v_capture then
v
else begin
let i = match v.v_extra with
| Some (l,eo) ->
v.v_extra <- Some (("",t_dynamic) :: l,eo);
List.length l + 1
| _ ->
error "Something went wrong" p
in
let v' = alloc_var (Printf.sprintf "%s<%i>" v.v_name i) v.v_type in
create_v_extra v';
v'.v_meta <- [(Meta.Custom ":ssa"),[],p];
set_origin_var v' v p;
ctx.cur_data.nd_var_map <- IntMap.add v.v_id v' ctx.cur_data.nd_var_map;
set_var_value v' e;
v'
end
let get_var ctx v p =
try
IntMap.find v.v_id ctx.cur_data.nd_var_map
with Not_found ->
if not (has_meta Meta.Unbound v.v_meta) then
error (Printf.sprintf "Unbound variable %s" v.v_name) p;
v
let close_join_node ctx node p =
let terminates = ref true in
let branches = List.filter (fun branch ->
if branch.nd_terminates then false
else begin
terminates := false;
true
end
) node.branches in
match branches with
| [] ->
()
| branch :: branches ->
let vars = ref (IntMap.map (fun v -> [v,branch.nd_pos]) branch.nd_var_map) in
let rec handle_branch branch =
IntMap.iter (fun i v ->
try
let vl = IntMap.find i !vars in
if not (List.exists (fun (v',_) -> v == v') vl) then
vars := IntMap.add i ((v,p) :: vl) !vars
with Not_found ->
()
) branch.nd_var_map;
in
List.iter handle_branch branches;
ctx.cur_data.nd_terminates <- !terminates;
IntMap.iter (fun i vl -> match vl with
| [v,p] ->
ctx.cur_data.nd_var_map <- IntMap.add i v ctx.cur_data.nd_var_map;
| (v',_) :: _ ->
let v = get_origin_var v' in
ignore(assign_var ctx v (mk_phi vl p) p)
| _ ->
assert false
) !vars
let invert_cond = function
| Equal(v,e) -> NotEqual(v,e)
| NotEqual(v,e) -> Equal(v,e)
let invert_conds =
List.map invert_cond
let rec eval_cond ctx e = match e.eexpr with
| TBinop(OpNotEq,{eexpr = TLocal v},e1) ->
[NotEqual(v,e1)]
| TBinop(OpEq,{eexpr = TLocal v},e1) ->
[Equal(v,e1)]
| TUnop(Not,_,e1) ->
invert_conds (eval_cond ctx e1)
| TLocal v ->
begin try eval_cond ctx (get_var_value v)
with Not_found -> [] end
| TParenthesis e1 | TMeta(_,e1) | TCast(e1,None) ->
eval_cond ctx e1
| _ ->
[]
let append_cond ctx v cond p =
begin try
let conds = IntMap.find v.v_id ctx.var_conds in
ctx.var_conds <- IntMap.add v.v_id (cond :: conds) ctx.var_conds
with Not_found ->
ctx.var_conds <- IntMap.add v.v_id [cond] ctx.var_conds
end
let apply_cond ctx = function
| Equal(v,e1) ->
(* let v' = assign_var ctx (get_origin_var v) (mk_loc v e1.epos) e1.epos in
append_cond ctx v' (Equal(v',e1)) e1.epos *)
()
| NotEqual(v,e1) ->
(* let v' = assign_var ctx (get_origin_var v) (mk_loc v e1.epos) e1.epos in
append_cond ctx v' (NotEqual(v',e1)) e1.epos *)
()
let apply_not_null_cond ctx v p =
apply_cond ctx (NotEqual(v,(mk (TConst TNull) t_dynamic p)))
let apply com e =
let rec handle_if ctx f econd eif eelse =
let econd = loop ctx econd in
let cond = eval_cond ctx econd in
let join = mk_join_node() in
let close = branch ctx eif.epos in
List.iter (apply_cond ctx) cond;
let eif = loop ctx eif in
close join;
let eelse = match eelse with
| None ->
let cond = invert_conds cond in
List.iter (apply_cond ctx) cond;
add_branch join ctx.cur_data e.epos;
None
| Some e ->
let close = branch ctx e.epos in
let cond = invert_conds cond in
List.iter (apply_cond ctx) cond;
let eelse = loop ctx e in
close join;
Some eelse
in
close_join_node ctx join e.epos;
f econd eif eelse
and handle_loop_body ctx e =
let join_top = mk_join_node() in
let join_bottom = mk_join_node() in
let unset = set_loop_join ctx join_top join_bottom in
let close = branch ctx e.epos in
ignore(loop ctx e); (* TODO: I don't know if this is sane. *)
close join_top;
add_branch join_top ctx.cur_data e.epos;
close_join_node ctx join_top e.epos;
let ebody = loop ctx e in
ctx.cur_data.nd_terminates <- false;
unset();
close_join_node ctx join_bottom e.epos;
ebody
and loop ctx e = match e.eexpr with
(* var declarations *)
| TVar(v,eo) ->
declare_var ctx v e.epos;
let eo = match eo with
| None -> None
| Some e ->
let e = loop ctx e in
set_var_value v e;
Some e
in
{e with eexpr = TVar(v,eo)}
| TFunction tf ->
let close = branch ctx e.epos in
List.iter (fun (v,co) ->
declare_var ctx v e.epos;
match co with
| Some TNull when (match v.v_type with TType({t_path=["haxe"],"PosInfos"},_) -> false | _ -> true) -> ()
| _ -> apply_not_null_cond ctx v e.epos
) tf.tf_args;
let e' = loop ctx tf.tf_expr in
close (mk_join_node());
{e with eexpr = TFunction {tf with tf_expr = e'}}
(* var modifications *)
| TBinop(OpAssign,({eexpr = TLocal v} as e1),e2) ->
let e2 = loop ctx e2 in
let _ = assign_var ctx v e2 e1.epos in
{e with eexpr = TBinop(OpAssign,e1,e2)}
| TBinop(OpAssignOp op,({eexpr = TLocal v} as e1),e2) ->
let e1 = loop ctx e1 in
let e2 = loop ctx e2 in
let e_op = mk (TBinop(op,e1,e2)) e.etype e.epos in
let _ = assign_var ctx v e_op e1.epos in
{e with eexpr = TBinop(OpAssignOp op,e1,e2)}
| TUnop((Increment | Decrement as op),flag,({eexpr = TLocal v} as e1)) ->
let op = match op with Increment -> OpAdd | Decrement -> OpSub | _ -> assert false in
let e_one = mk (TConst (TInt (Int32.of_int 1))) com.basic.tint e.epos in
let e1 = loop ctx e1 in
let e_op = mk (TBinop(op,e1,e_one)) e.etype e.epos in
let _ = assign_var ctx v e_op e1.epos in
e
(* var user *)
| TLocal v ->
let v = get_var ctx v e.epos in
{e with eexpr = TLocal v}
(* control flow *)
| TIf(econd,eif,eelse) ->
let f econd eif eelse = {e with eexpr = TIf(econd,eif,eelse)} in
handle_if ctx f econd eif eelse
| TSwitch(e1,cases,edef) ->
let e1 = loop ctx e1 in
let join = mk_join_node() in
let cases = List.map (fun (el,e) ->
let close = branch ctx e.epos in
let el = List.map (loop ctx) el in
let e = loop ctx e in
close join;
el,e
) cases in
let edef = match edef with
| Some e ->
let close = branch ctx e.epos in
let e = loop ctx e in
close join;
Some e
| None ->
if not (Optimizer.is_exhaustive e1) then
add_branch join ctx.cur_data e.epos;
None
in
close_join_node ctx join e.epos;
let e = {e with eexpr = TSwitch(e1,cases,edef)} in
e
| TWhile(econd,ebody,mode) ->
let econd = loop ctx econd in
let ebody = handle_loop_body ctx ebody in
let e = {e with eexpr = TWhile(econd,ebody,mode)} in
e
| TFor(v,e1,ebody) ->
declare_var ctx v e.epos;
apply_not_null_cond ctx v e1.epos;
let v' = IntMap.find v.v_id ctx.cur_data.nd_var_map in
let e1 = loop ctx e1 in
let ebody = handle_loop_body ctx ebody in
let e = {e with eexpr = TFor(v',e1,ebody)} in
e
| TTry(e1,catches) ->
let join_ex = mk_join_node() in
let join_bottom = mk_join_node() in
let unset = set_exception_join ctx join_ex in
let e1 = loop ctx e1 in
unset();
add_branch join_bottom ctx.cur_data e.epos;
close_join_node ctx join_ex e.epos;
let catches = List.map (fun (v,e) ->
declare_var ctx v e.epos;
apply_not_null_cond ctx v e.epos;
let close = branch ctx e.epos in
let e = loop ctx e in
close join_bottom;
v,e
) catches in
close_join_node ctx join_bottom e.epos;
let e = {e with eexpr = TTry(e1,catches)} in
e
| TBreak ->
begin match ctx.loop_stack with
| [] -> error "Break outside loop" e.epos
| (_,join) :: _ -> add_branch join ctx.cur_data e.epos
end;
terminate ctx;
e
| TContinue ->
begin match ctx.loop_stack with
| [] -> error "Continue outside loop" e.epos
| (join,_) :: _ -> add_branch join ctx.cur_data e.epos
end;
terminate ctx;
e
| TThrow e1 ->
let e1 = loop ctx e1 in
begin match ctx.exception_stack with
| join :: _ -> add_branch join ctx.cur_data e.epos
| _ -> ()
end;
terminate ctx;
{e with eexpr = TThrow e1}
| TReturn eo ->
let eo = match eo with None -> None | Some e -> Some (loop ctx e) in
terminate ctx;
{e with eexpr = TReturn eo}
| TBlock el ->
let rec loop2 el = match el with
| [] ->
[]
| e :: el ->
if ctx.cur_data.nd_terminates then begin
(* ctx.com.warning (Printf.sprintf "Unreachable code: %s" (s_expr_pretty e)) e.epos; *)
[]
end else
let e = loop ctx e in
e :: (loop2 el)
in
ctx.block_depth <- ctx.block_depth + 1;
let el = loop2 el in
ctx.block_depth <- ctx.block_depth - 1;
{e with eexpr = TBlock(el)}
| _ ->