/
Symbolic.v
1879 lines (1729 loc) · 75.7 KB
/
Symbolic.v
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
Require Crypto.Assembly.Parse.
Require Import Coq.Lists.List.
Require Import Coq.micromega.Lia.
Require Import Coq.ZArith.ZArith.
Require Crypto.Util.Tuple.
Require Import Util.OptionList.
Require Import Crypto.Util.ErrorT.
Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
Require Import Crypto.Util.ZUtil.Testbit.
Require Import Crypto.Util.ZUtil.Hints.ZArith.
Require Import Crypto.Util.ZUtil.Land.
Require Import Crypto.Util.ZUtil.Ones.
Require Import Crypto.Util.Bool.Reflect.
Require Import Crypto.Util.ListUtil.
Require Import Crypto.Util.ListUtil.FoldMap. Import FoldMap.List.
Require Import Crypto.Util.ListUtil.IndexOf. Import IndexOf.List.
Require Import Crypto.Util.ListUtil.Forall.
Require Import Crypto.Util.ListUtil.Permutation.
Require Import Crypto.Util.NUtil.Sorting.
Require Import Crypto.Util.NUtil.Testbit.
Require Import Crypto.Util.ListUtil.PermutationCompat.
Require Import Crypto.Util.Bool.LeCompat.
Require Import Crypto.Util.Tactics.DestructHead.
Require Import Crypto.Util.Prod.
Require Import Crypto.Util.Tactics.SplitInContext.
Require Import Crypto.Util.ZUtil.Lxor.
Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.
Require Import Crypto.Util.Bool.Reflect.
Require Import coqutil.Z.bitblast.
Require Import Coq.Strings.String Crypto.Util.Strings.Show.
Require Import Crypto.Assembly.Syntax.
Definition idx := N.
Local Set Decidable Equality Schemes.
Definition symbol := N.
Class OperationSize := operation_size : N.
Global Instance Show_OperationSize : Show OperationSize := show_N.
Section S.
Implicit Type s : OperationSize.
Variant op := old s (_:symbol) | const (_ : Z) | add s | addcarry s | subborrow s | addoverflow s | neg s | shl s | shr s | sar s | rcr s | and s | or s | xor s | slice (lo sz : N) | mul s | set_slice (lo sz : N) | selectznz | iszero (* | ... *)
| addZ | mulZ | negZ | shlZ | shrZ | andZ | orZ | xorZ | addcarryZ s | subborrowZ s.
Definition op_beq a b := if op_eq_dec a b then true else false.
End S.
Global Instance Show_op : Show op := fun o =>
match o with
| old s n => "old " ++ show s ++ " " ++ show n
| const n => "const " ++ show n
| add s => "add " ++ show s
| addcarry s => "addcarry " ++ show s
| subborrow s => "subborrow " ++ show s
| addoverflow s => "addoverflow " ++ show s
| neg s => "neg " ++ show s
| shl s => "shl " ++ show s
| shr s => "shr " ++ show s
| sar s => "sar " ++ show s
| rcr s => "rcr " ++ show s
| and s => "and " ++ show s
| or s => "or " ++ show s
| xor s => "xor " ++ show s
| slice lo sz => "slice " ++ show lo ++ " " ++ show sz
| mul s => "mul " ++ show s
| set_slice lo sz => "set_slice " ++ show lo ++ " " ++ show sz
| selectznz => "selectznz"
| iszero => "iszero"
| addZ => "addZ"
| mulZ => "mulZ"
| negZ => "negZ"
| shlZ => "shlZ"
| shrZ => "shrZ"
| andZ => "andZ"
| orZ => "orZ"
| xorZ => "xorZ"
| addcarryZ s => "addcarryZ " ++ show s
| subborrowZ s => "subborrowZ " ++ show s
end%string.
Definition associative o := match o with add _|mul _|mulZ|or _|and _|xor _|andZ|orZ|xorZ=> true | _ => false end.
Definition commutative o := match o with add _|addcarry _|addoverflow _|mul _|mulZ|or _|and _|xor _|andZ|orZ|xorZ => true | _ => false end.
Definition identity o := match o with mul N0 => Some 0%Z| mul _|mulZ=>Some 1%Z |add _|addZ|or _|orZ|xor _|xorZ => Some 0%Z | and s => Some (Z.ones (Z.of_N s))|andZ => Some (-1)%Z |_=> None end.
Definition unary_truncate_size o := match o with add s|and s|or s|xor s|mul s => Some (Z.of_N s) | addZ|mulZ|andZ|orZ|xorZ => Some (-1)%Z | _ => None end.
Definition node (A : Set) : Set := op * list A.
Global Instance Show_node {A : Set} {show_A : Show A} : Show (node A) := show_prod.
Local Unset Elimination Schemes.
Inductive expr : Set :=
| ExprRef (_ : idx)
| ExprApp (_ : node expr).
Local Set Elimination Schemes.
Section expr_ind.
Context (P : expr -> Prop)
(HRef : forall i, P (ExprRef i))
(HApp : forall n, Forall P (snd n) -> P (ExprApp n)).
Fixpoint expr_ind e {struct e} : P e :=
match e with
| ExprRef i => HRef i
| ExprApp n => HApp _ (list_rect _ (Forall_nil _) (fun e _ H => Forall_cons e (expr_ind e) H) (snd n))
end.
End expr_ind.
Definition invert_ExprRef (e : expr) : option idx :=
match e with ExprRef i => Some i | _ => None end.
Definition Show_expr_body (Show_expr : Show expr) : Show expr
:= Eval cbv -[String.append show_N concat List.map Show_op] in
fun e => match e with
| ExprRef i => "ExprRef " ++ show i
| ExprApp (o, e) => "ExprApp " ++ show (o, e)
end%string.
Definition Show_expr : Show expr
:= Eval cbv -[String.append show_N concat List.map Show_op] in
fix Show_expr e := Show_expr_body Show_expr e.
Global Existing Instance Show_expr.
Lemma op_beq_spec a b : BoolSpec (a=b) (a<>b) (op_beq a b).
Proof using Type. cbv [op_beq]; destruct (op_eq_dec a b); constructor; congruence. Qed.
Global Instance reflect_eq_op : reflect_rel eq op_beq | 10 := reflect_rel_of_BoolSpec op_beq_spec.
Fixpoint expr_beq (X Y : expr) {struct X} : bool :=
match X, Y with
| ExprRef x, ExprRef x0 => N.eqb x x0
| ExprApp x, ExprApp x0 =>
Prod.prod_beq _ _ op_beq (ListUtil.list_beq expr expr_beq) x x0
| _, _ => false
end.
Lemma expr_beq_spec a b : BoolSpec (a=b) (a<>b) (expr_beq a b).
Proof using Type.
revert b; induction a, b; cbn.
1: destruct (N.eqb_spec i i0); constructor; congruence.
1,2: constructor; congruence.
destruct n, n0; cbn.
destruct (op_beq_spec o o0); cbn in *; [subst|constructor; congruence].
revert l0; induction H, l0; cbn; try (constructor; congruence); [].
destruct (H e); cbn; try (constructor; congruence); []; subst.
destruct (IHForall l0); [left|right]; congruence.
Qed.
Global Instance reflect_eq_expr : reflect_rel eq expr_beq | 10 := reflect_rel_of_BoolSpec expr_beq_spec.
Lemma expr_beq_true a b : expr_beq a b = true -> a = b.
Proof using Type. destruct (expr_beq_spec a b); congruence. Qed.
Require Import Crypto.Util.Option Crypto.Util.Notations Coq.Lists.List.
Import ListNotations.
Section WithContext.
Context (ctx : symbol -> option Z).
Definition signed s n : Z := (Z.land (Z.shiftl 1 (Z.of_N s-1) + n) (Z.ones (Z.of_N s)) - Z.shiftl 1 (Z.of_N s-1))%Z.
Definition interp_op o (args : list Z) : option Z :=
let keep n x := Z.land x (Z.ones (Z.of_N n)) in
match o, args with
| old s x, nil => match ctx x with Some v => Some (keep s v) | None => None end
| const z, nil => Some z
| add s, args => Some (keep s (List.fold_right Z.add 0 args))
| addcarry s, args =>
Some (Z.shiftr (List.fold_right Z.add 0 args) (Z.of_N s) mod 2)
| subborrow s, cons a args' =>
Some ((- Z.shiftr (a - List.fold_right Z.add 0 args') (Z.of_N s)) mod 2)
| addoverflow s, args => Some (Z.b2z (negb (Z.eqb
(signed s (keep s (List.fold_right Z.add 0 args)))
(List.fold_right Z.add 0%Z (List.map (signed s) args)))))
| neg s, [a] => Some (keep s (- a))
| shl s, [a; b] => Some (keep s (Z.shiftl a b))
| shr s, [a; b] => Some (keep s (Z.shiftr a b))
| sar s, [a; b] => Some (keep s (Z.shiftr (signed s a) b))
| rcr s, [v1; cf; cnt] => Some (
let v1c := Z.lor v1 (Z.shiftl cf (Z.of_N s)) in
let l := Z.lor v1c (Z.shiftl v1 (1+Z.of_N s)) in
keep s (Z.shiftr l cnt))
| and s, args => Some (keep s (List.fold_right Z.land (-1) args))
| or s, args => Some (keep s (List.fold_right Z.lor 0 args))
| xor s, args => Some (keep s (List.fold_right Z.lxor 0 args))
| slice lo sz, [a] => Some (keep sz (Z.shiftr a (Z.of_N lo)))
| mul s, args => Some (keep s (List.fold_right Z.mul 1 args))
| set_slice lo sz, [a; b] =>
Some (Z.lor (Z.shiftl (keep sz b) (Z.of_N lo))
(Z.ldiff a (Z.shiftl (Z.ones (Z.of_N sz)) (Z.of_N lo))))
| selectznz, [c; a; b] => Some (if Z.eqb c 0 then a else b)
| iszero, [a] => Some (Z.b2z (Z.eqb a 0))
| addZ, args => Some (List.fold_right Z.add 0 args)
| mulZ, args => Some (List.fold_right Z.mul 1 args)
| negZ, [a] => Some (Z.opp a)
| shlZ, [a; b] => Some (Z.shiftl a b)
| shrZ, [a; b] => Some (Z.shiftr a b)
| andZ, args => Some (List.fold_right Z.land (-1) args)
| orZ, args => Some (List.fold_right Z.lor 0 args)
| xorZ, args => Some (List.fold_right Z.lxor 0 args)
| addcarryZ s, args => Some (Z.shiftr (List.fold_right Z.add 0 args) (Z.of_N s))
| subborrowZ s, cons a args' => Some (- Z.shiftr (a - List.fold_right Z.add 0 args') (Z.of_N s))
| _, _ => None
end%Z.
End WithContext.
Definition interp0_op := interp_op (fun _ => None).
Lemma interp_op_weaken_symbols G1 G2 o args
(H : forall (s:symbol) v, G1 s = Some v -> G2 s = Some v)
: forall v, interp_op G1 o args = Some v -> interp_op G2 o args = Some v.
Proof using Type.
cbv [interp_op option_map]; intros;
repeat (BreakMatch.break_match || BreakMatch.break_match_hyps);
inversion_option; subst;
try congruence.
all : eapply H in Heqo0; congruence.
Qed.
Lemma interp_op_interp0_op o a v (H : interp0_op o a = Some v)
: forall G, interp_op G o a = Some v.
Proof using Type. intros; eapply interp_op_weaken_symbols in H; eauto; discriminate. Qed.
Definition node_beq {A : Set} (arg_eqb : A -> A -> bool) : node A -> node A -> bool :=
Prod.prod_beq _ _ op_beq (ListUtil.list_beq _ arg_eqb).
Global Instance reflect_node_beq {A : Set} {arg_eqb} {H : reflect_rel (@eq A) arg_eqb}
: reflect_rel eq (@node_beq A arg_eqb) | 10 := _.
Definition dag := list (node idx).
Section WithDag.
Context (ctx : symbol -> option Z) (dag : dag).
Definition reveal_step reveal (i : idx) : expr :=
match List.nth_error dag (N.to_nat i) with
| None => (* undefined *) ExprRef i
| Some (op, args) => ExprApp (op, List.map reveal args)
end.
Fixpoint reveal (n : nat) (i : idx) :=
match n with
| O => ExprRef i
| S n => reveal_step (reveal n) i
end.
Definition reveal_node n '(op, args) :=
ExprApp (op, List.map (reveal n) args).
Local Unset Elimination Schemes.
Inductive eval : expr -> Z -> Prop :=
| ERef i op args args' n
(_:List.nth_error dag (N.to_nat i) = Some (op, args))
(_:List.Forall2 eval (map ExprRef args) args')
(_:interp_op ctx op args' = Some n)
: eval (ExprRef i) n
| EApp op args args' n
(_:List.Forall2 eval args args')
(_:interp_op ctx op args' = Some n)
: eval (ExprApp (op, args)) n.
Variant eval_node : node idx -> Z -> Prop :=
| ENod op args args' n
(_:List.Forall2 eval (map ExprRef args) args')
(_:interp_op ctx op args' = Some n)
: eval_node (op, args) n.
Section eval_ind.
Context (P : expr -> Z -> Prop)
(HRef : forall i op args args' n, nth_error dag (N.to_nat i) = Some (op, args) ->
Forall2 (fun e n => eval e n /\ P e n) (map ExprRef args) args' ->
interp_op ctx op args' = Some n ->
P (ExprRef i) n)
(HApp : forall op args args' n,
Forall2 (fun i e => eval i e /\ P i e) args args' ->
interp_op ctx op args' = Some n ->
P (ExprApp (op, args)) n).
Fixpoint eval_ind i n (pf : eval i n) {struct pf} : P i n :=
match pf with
| ERef _ _ _ _ _ A B C => HRef _ _ _ _ _ A (Forall2_weaken (fun _ _ D => conj D (eval_ind _ _ D)) _ _ B) C
| EApp _ _ _ _ A B => HApp _ _ _ _ (Forall2_weaken (fun _ _ C => conj C (eval_ind _ _ C)) _ _ A) B
end.
End eval_ind.
Lemma eval_eval : forall e v1, eval e v1 -> forall v2, eval e v2 -> v1=v2.
Proof using Type.
induction 1; inversion 1; subst;
enough (args' = args'0) by congruence;
try replace args0 with args in * by congruence.
{ eapply Forall2_map_l in H0.
eapply Forall2_flip in H0.
eapply (proj1 (Forall2_map_l _ _ _)) in H5.
epose proof Forall2_trans H0 H5 as HH.
eapply Forall2_eq, Forall2_weaken, HH; cbv beta; clear; firstorder. }
{ eapply Forall2_flip in H.
epose proof Forall2_trans H H4 as HH.
eapply Forall2_eq, Forall2_weaken, HH; cbv beta; clear; firstorder. }
Qed.
Lemma eval_eval_Forall2 xs vxs (_ : Forall2 eval xs vxs)
vys (_ : Forall2 eval xs vys) : vxs = vys.
Proof using Type.
revert dependent vys; induction H; inversion 1; subst;
eauto; eauto using f_equal2, IHForall2, eval_eval.
Qed.
Lemma eval_reveal : forall n i, forall v, eval (ExprRef i) v ->
forall e, reveal n i = e -> eval e v.
Proof using Type.
induction n; cbn [reveal]; cbv [reveal_step]; intros; subst; eauto; [].
inversion H; subst; clear H.
rewrite H1; econstructor; try eassumption; [].
eapply (proj1 (Forall2_map_l _ _ _)) in H2.
clear dependent i; clear dependent v.
induction H2; cbn; eauto.
Qed.
Lemma eval_node_reveal_node : forall n v, eval_node n v ->
forall f e, reveal_node f n = e -> eval e v.
Proof using Type.
cbv [reveal_node]; inversion 1; intros; subst.
econstructor; eauto.
eapply (proj1 (Forall2_map_l _ _ _)) in H0; eapply Forall2_map_l.
eapply Forall2_weaken; try eassumption; []; cbv beta; intros.
eapply eval_reveal; eauto.
Qed.
End WithDag.
Module dag.
Definition M T := dag -> T * dag.
Definition bind {A B} (v : M A) (f : A -> M B) : M B
:= fun d => let '(v, d) := v d in f v d.
Definition ret {A} (v : A) : M A
:= fun d => (v, d).
End dag.
Delimit Scope dagM_scope with dagM.
Bind Scope dagM_scope with dag.M.
Notation "x <- y ; f" := (dag.bind y (fun x => f%dagM)) : dagM_scope.
Definition merge_node (n : node idx) : dag.M idx :=
fun d => match List.indexof (node_beq N.eqb n) d with
| Some i => (N.of_nat i, d)
| None => (N.of_nat (length d), List.app d (cons n nil))
end.
Fixpoint merge (e : expr) (d : dag) : idx * dag :=
match e with
| ExprRef i => (i, d)
| ExprApp (op, args) =>
let idxs_d := List.foldmap merge args d in
let idxs := if commutative op
then N.sort (fst idxs_d)
else (fst idxs_d) in
merge_node (op, idxs) (snd idxs_d)
end.
Lemma node_beq_sound e x : node_beq N.eqb e x = true -> e = x.
Proof using Type.
eapply Prod.internal_prod_dec_bl.
{ intros X Y; destruct (op_beq_spec X Y); congruence. }
{ intros X Y. eapply ListUtil.internal_list_dec_bl, N.eqb_eq. }
Qed.
Lemma eval_weaken G d x e n : eval G d e n -> eval G (d ++ [x]) e n.
Proof using Type.
induction 1; subst; econstructor; eauto.
{ erewrite nth_error_app1; try eassumption; [].
eapply ListUtil.nth_error_value_length; eassumption. }
all : eapply Forall2_weaken; [|eassumption].
{ intuition eauto. eapply H2. }
{ intuition eauto. eapply H1. }
Qed.
Lemma eval_weaken_symbols G1 G2 d e n
(H : forall s v, G1 s = Some v -> G2 s = Some v)
: eval G1 d e n -> eval G2 d e n.
Proof using Type.
induction 1; subst; econstructor;
intuition eauto using interp_op_weaken_symbols.
{ eapply Forall2_weaken; [|eassumption]; intros ? ? (?&?); eauto. }
{ eapply Forall2_weaken; [|eassumption]; intros ? ? (?&?); eauto. }
Qed.
Lemma eval_eval0 d e n G : eval (fun _ => None) d e n -> eval G d e n.
Proof using Type. eapply eval_weaken_symbols; congruence. Qed.
Lemma permute_commutative G op args n : commutative op = true ->
interp_op G op args = Some n ->
forall args', Permutation.Permutation args args' ->
interp_op G op args' = Some n.
Proof using Type.
destruct op; inversion 1; cbn; intros ? ? Hp;
try (erewrite <- Z.fold_right_Proper_Permutation_add; eauto);
try (erewrite <- Z.fold_right_Proper_Permutation_mul; eauto);
try (erewrite <- Z.fold_right_Proper_Permutation_land; eauto);
try (erewrite <- Z.fold_right_Proper_Permutation_lor; eauto);
try (erewrite <- Z.fold_right_Proper_Permutation_lxor; eauto).
{ erewrite <-(Z.fold_right_Proper_Permutation_add _ _ eq_refl _ (map _ args'));
eauto using Permutation.Permutation_map. }
Qed.
(* fresh symbols must have value <= their index, so that fresh symbols are truly fresh *)
Definition node_ok (i : idx) (n : node idx) := forall w s args, n = (old w s, args) -> (s <= i)%N.
(* the gensym state cannot map anything past the end of the dag *)
Definition gensym_ok (G : symbol -> option Z) (d : dag) := forall s _v, G s = Some _v -> (s < N.of_nat (List.length d))%N.
Definition dag_ok G (d : dag) := forall i r, nth_error d (N.to_nat i) = Some r -> node_ok i r /\ exists v, eval G d (ExprRef i) v.
Definition gensym_dag_ok G d := gensym_ok G d /\ dag_ok G d.
Lemma gensym_ok_length_Proper G d1 d2
(H : List.length d1 <= List.length d2)
: gensym_ok G d1 -> gensym_ok G d2.
Proof using Type. cbv [gensym_ok]; firstorder lia. Qed.
Lemma gensym_ok_app G d1 d2
: gensym_ok G d1 -> gensym_ok G (d1 ++ d2).
Proof using Type. apply gensym_ok_length_Proper; rewrite app_length; lia. Qed.
Lemma eval_merge_node :
forall G d, gensym_dag_ok G d ->
forall op args n, let e := (op, args) in
eval G d (ExprApp (op, List.map ExprRef args)) n ->
eval G (snd (merge_node e d)) (ExprRef (fst (merge_node e d))) n /\
gensym_dag_ok G (snd (merge_node e d)) /\
forall i e', eval G d i e' -> eval G (snd (merge_node e d)) i e'.
Proof using Type.
intros.
cbv beta delta [merge_node].
inversion H0; subst.
case (indexof _ _) eqn:?; cbn; repeat split; try solve [ cbv [gensym_dag_ok dag_ok] in *; split_and; eauto ].
{ eapply indexof_Some in Heqo; case Heqo as (?&?&?).
replace x with e in * by (eauto using node_beq_sound); clear H2. (* node_beq -> eq *)
econstructor; rewrite ?Nnat.Nat2N.id; eauto. }
{ econstructor; eauto.
{ erewrite ?nth_error_app2, ?Nnat.Nat2N.id, Nat.sub_diag by Lia.lia.
exact eq_refl. }
eapply Forall2_weaken; [|eauto]; eauto using eval_weaken. }
{ cbv [gensym_dag_ok] in *; destruct_head'_and; now apply gensym_ok_app. }
{ cbv [gensym_dag_ok dag_ok gensym_ok] in *; split_and; eauto.
rewrite @nth_error_app in *; break_innermost_match_hyps; eauto.
destruct (_ - _)%nat as [| [|] ]; cbn [nth_error] in *; inversion_option; subst.
hnf; intros; subst e; inversion_prod; subst; cbn [interp_op] in *; break_innermost_match_hyps; inversion_option; subst.
firstorder lia. }
{ cbv [gensym_dag_ok dag_ok] in *; split_and; intros.
case (lt_dec (N.to_nat i) (length d)) as [?|?];
erewrite ?nth_error_app1, ?nth_error_app2 in H1 by Lia.lia.
{ match goal with
| [ H : forall i r, nth_error _ (N.to_nat i) = Some r -> exists v, eval _ _ _ _, H1 : nth_error _ _ = Some _ |- _ ]
=> case (H _ _ H1); eauto using eval_weaken
end. }
{ destruct (N.to_nat i - length d) as [| [|] ] eqn:?; cbn [nth_error] in *; inversion_option; subst.
eexists. econstructor.
replace (N.to_nat i) with (length d) by Lia.lia.
{ erewrite ?nth_error_app2, ?Nnat.Nat2N.id, Nat.sub_diag by Lia.lia.
exact eq_refl. }
{ eapply Forall2_weaken; [|eauto]; eauto using eval_weaken. }
eauto. } }
{ eauto using eval_weaken. }
Qed.
Require Import coqutil.Tactics.autoforward coqutil.Decidable coqutil.Tactics.Tactics.
Global Set Default Goal Selector "1".
Lemma eval_merge G :
forall e n,
forall d, gensym_dag_ok G d ->
eval G d e n ->
eval G (snd (merge e d)) (ExprRef (fst (merge e d))) n /\
gensym_dag_ok G (snd (merge e d)) /\
forall i e', eval G d i e' -> eval G (snd (merge e d)) i e'.
Proof using Type.
induction e; intros; eauto; [].
rename n0 into v.
set (merge _ _) as m; cbv beta iota delta [merge] in m; fold merge in m.
destruct n as (op&args).
repeat match goal with
m := let x := ?A in @?B x |- _ =>
let y := fresh x in
set A as y;
let m' := eval cbv beta in (B y) in
change m' in (value of m)
end.
inversion H1; clear H1 ; subst.
cbn [fst snd] in *.
assert (gensym_dag_ok G (snd idxs_d) /\
Forall2 (fun i v => eval G (snd idxs_d) (ExprRef i) v) (fst idxs_d) args' /\
forall i e', eval G d i e' -> eval G (snd idxs_d) i e'
) as HH; [|destruct HH as(?&?&?)].
{ clear m idxs H6 v op; revert dependent d; revert dependent args'.
induction H; cbn; intros; inversion H4; subst;
split_and; pose proof @Forall2_weaken; typeclasses eauto 8 with core. }
clearbody idxs_d.
enough (eval G (snd idxs_d) (ExprApp (op, map ExprRef idxs)) v) by
(unshelve edestruct ((eval_merge_node _ _ ltac:(eassumption) op) idxs v) as (?&?&?); eauto); clear m.
pose proof length_Forall2 H4; pose proof length_Forall2 H2.
cbn [fst snd] in *; destruct (commutative op) eqn:?; cycle 1; subst idxs.
{ econstructor; eauto.
eapply ListUtil.Forall2_forall_iff; rewrite map_length; try congruence; [].
intros i Hi.
unshelve (epose proof (proj1 (ListUtil.Forall2_forall_iff _ _ _ _ _ _) H2 i _));
shelve_unifiable; try congruence; [].
rewrite ListUtil.map_nth_default_always. eapply H8. }
pose proof N.Sort.Permuted_sort (fst idxs_d) as Hperm.
eapply (Permutation.Permutation_Forall2 Hperm) in H2.
case H2 as (argExprs&Hperm'&H2).
eapply permute_commutative in H6; try eassumption; [].
epose proof Permutation.Permutation_length Hperm.
epose proof Permutation.Permutation_length Hperm'.
{ econstructor; eauto.
eapply ListUtil.Forall2_forall_iff; rewrite map_length; try congruence; [|].
{ setoid_rewrite <-H8. setoid_rewrite <-H9. eassumption. }
intros i Hi.
unshelve (epose proof (proj1 (ListUtil.Forall2_forall_iff _ _ _ _ _ _) H2 i _));
shelve_unifiable; try trivial; [|].
{ setoid_rewrite <-H8. setoid_rewrite <-H9. eassumption. }
rewrite ListUtil.map_nth_default_always. eapply H10. }
Unshelve. all : constructor.
Qed.
Definition zconst s (z:Z) := const (Z.land z (Z.ones (Z.of_N s)))%Z.
Section WithContext.
Context (ctx : symbol -> option Z).
Fixpoint interp_expr (e : expr) : option Z :=
match e with
| ExprApp (o, arges) =>
args <- Option.List.lift (List.map interp_expr arges);
interp_op ctx o args
| _ => None
end%option.
End WithContext.
Definition interp0_expr := interp_expr (fun _ => None).
Lemma eval_interp_expr G e : forall d v, interp_expr G e = Some v -> eval G d e v.
Proof using Type.
induction e; cbn; try discriminate; intros.
case n in *; cbn [fst snd] in *.
destruct (Option.List.lift _) eqn:? in *; try discriminate.
econstructor; try eassumption; [].
clear dependent v.
revert dependent l0.
induction H; cbn in *.
{ inversion 1; subst; eauto. }
destruct (interp_expr _) eqn:? in *; cbn in *; try discriminate; [].
destruct (fold_right _ _ _) eqn:? in *; cbn in *; try discriminate; [].
specialize (fun d => H d _ eq_refl).
inversion 1; subst.
econstructor; trivial; [].
eapply IHForall; eassumption.
Qed.
Lemma eval_interp0_expr e v (H : interp0_expr e = Some v) : forall G d, eval G d e v.
Proof using Type.
cbv [interp0_expr]; intros.
eapply eval_interp_expr, eval_weaken_symbols in H; [eassumption|congruence].
Qed.
Local Open Scope Z_scope.
Fixpoint bound_expr e : option Z := (* e <= r *)
match e with
| ExprApp (const v, _) => if Z.leb 0 v then Some v else None
| ExprApp (add s, args) =>
Some match Option.List.lift (List.map bound_expr args) with
| Some bounds => Z.min (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s))
| None => Z.ones (Z.of_N s)
end
| ExprApp (selectznz, [c;a;b]) =>
match bound_expr a, bound_expr b with
| Some a, Some b => Some (Z.max a b)
| _, _ => None
end
| ExprApp (set_slice 0 w, [a;b]) =>
match bound_expr a, bound_expr b with
| Some a, Some b => Some (Z.lor
(Z.land (Z.ones (Z.succ (Z.log2 b))) (Z.ones (Z.of_N w)))
(Z.ldiff (Z.ones (Z.succ (Z.log2 a))) (Z.ones (Z.of_N w))))
| _, _ => None
end
| ExprApp ((old s _ | slice _ s | mul s | shl s | shr s | sar s | neg s | and s | or s | xor s), _) => Some (Z.ones (Z.of_N s))
| ExprApp ((addcarry _ | subborrow _ | addoverflow _ | iszero), _) => Some 1
| _ => None
end%Z.
Import coqutil.Tactics.Tactics.
Ltac t:= match goal with
| _ => progress intros
| H : eval _ _ (ExprApp _) _ |- _ => inversion H; clear H; subst
| H : Forall _ (cons _ _) |- _ => inversion H; clear H; subst
| H : Forall _ nil |- _ => inversion H; clear H; subst
| H : Forall2 _ (cons _ _) _ |- _ => inversion H; clear H; subst
| H : Forall2 _ nil _ |- _ => inversion H; clear H; subst
| H : Forall2 _ _ (cons _ _) |- _ => inversion H; clear H; subst
| H : Forall2 _ _ nil |- _ => inversion H; clear H; subst
| H : _ = true |- _ => autoforward with typeclass_instances in H
| H : forall b, _ |- _ => pose proof (H _ ltac:(eassumption) _ _ ltac:(eassumption)); clear H
| H : eval _ ?d ?e ?v1, G: eval _ ?d ?e ?v2 |- _ =>
assert_fails (constr_eq v1 v2);
eapply (eval_eval _ d e v1 H v2) in G
| _ => progress cbv [interp_op] in *
| _ => progress cbn [fst snd] in *
| _ => progress destruct_one_match
| _ => progress Option.inversion_option
| _ => progress subst
end.
Lemma bound_sum' G d
es (He : Forall (fun e => forall b, bound_expr e = Some b ->
forall (d : dag) (v : Z), eval G d e v -> (0 <= v <= b)%Z) es)
: forall
bs (Hb : Option.List.lift (map bound_expr es) = Some bs)
vs (Hv : Forall2 (eval G d) es vs)
, (0 <= fold_right Z.add 0 vs <= fold_right Z.add 0 bs)%Z.
Proof using Type.
induction He; cbn in *; repeat t.
{ cbv [fold_right]; Lia.lia. }
destruct (bound_expr _) eqn:? in *; cbn in *; repeat t.
destruct (fold_right (B:=option _) _) eqn:? in *; cbn in *; repeat t.
specialize (IHHe _ ltac:(eassumption) _ ltac:(eassumption)); cbn.
specialize (H _ ltac:(exact eq_refl) _ _ ltac:(eassumption)).
Lia.lia.
Qed.
Require Import Util.ZRange.LandLorBounds.
Lemma eval_bound_expr G e b : bound_expr e = Some b ->
forall d v, eval G d e v -> (0 <= v <= b)%Z.
Proof using Type.
revert b; induction e; simpl bound_expr; BreakMatch.break_match;
inversion 2; intros; inversion_option; subst;
try match goal with H : context [set_slice] |- _ => shelve end;
cbv [interp_op] in *;
BreakMatch.break_match_hyps; inversion_option; subst;
rewrite ?Z.ldiff_ones_r, ?Z.land_ones, ?Z.ones_equiv;
cbv [Z.b2z];
try match goal with |- context [(?a mod ?b)%Z] => unshelve epose proof Z.mod_pos_bound a b ltac:(eapply Z.pow_pos_nonneg; Lia.lia) end;
repeat t;
try (Z.div_mod_to_equations; Lia.lia).
{ clear dependent args'0.
epose proof bound_sum' _ ltac:(eassumption) _ ltac:(eassumption) _ ltac:(eassumption) _ ltac:(eassumption).
split; try Lia.lia.
eapply Z.min_glb_iff; split; try Lia.lia.
etransitivity. eapply Zmod_le.
all : try Lia.lia. }
Unshelve. {
repeat t.
pose proof Z.log2_nonneg z; pose proof Z.log2_nonneg z0.
rewrite !Z.shiftl_0_r.
split.
{ eapply Z.lor_nonneg; split; try eapply Z.land_nonneg; try eapply Z.ldiff_nonneg; Lia.lia. }
eapply Z.le_bitwise.
{ eapply Z.lor_nonneg; split; try eapply Z.land_nonneg; try eapply Z.ldiff_nonneg; Lia.lia. }
{ eapply Z.lor_nonneg; split; try eapply Z.land_nonneg; try eapply Z.ldiff_nonneg;
left; try eapply Z.ones_nonneg; Lia.lia. }
{ intros i Hi.
Z.rewrite_bitwise.
destr (i <? Z.of_N sz);
rewrite ?Bool.andb_false_r, ?Bool.andb_true_r, ?Bool.orb_false_l, ?Bool.orb_false_r.
{ clear -H Hi.
destr (i <? Z.succ (Z.log2 z0)).
{ eapply Bool.le_implb, Bool.implb_true_r. }
rewrite Z.bits_above_log2; cbn; trivial; try Lia.lia.
destruct H as [H' H]; eapply Z.log2_le_mono in H. Lia.lia. }
{ clear -H0 Hi.
destr (i <? Z.succ (Z.log2 z)).
{ eapply Bool.le_implb, Bool.implb_true_r. }
rewrite Z.bits_above_log2; cbn; trivial; try Lia.lia.
destruct H0 as [? H0]; eapply Z.log2_le_mono in H0. Lia.lia. } } }
Qed.
Lemma bound_sum G d es
bs (Hb : Option.List.lift (map bound_expr es) = Some bs)
vs (Hv : Forall2 (eval G d) es vs)
: (0 <= fold_right Z.add 0 vs <= fold_right Z.add 0 bs)%Z.
Proof using Type.
eapply bound_sum' in Hb; eauto.
eapply Forall_forall; intros.
eapply eval_bound_expr; eauto.
Qed.
Definition isCst (e : expr) :=
match e with ExprApp ((const _), _) => true | _ => false end.
Module Rewrite.
Class Ok r := rwok : forall G d e v, eval G d e v -> eval G d (r e) v.
Ltac resolve_match_using_hyp :=
match goal with |- context[match ?x with _ => _ end] =>
match goal with H : x = ?v |- _ =>
let h := Head.head v in
is_constructor h;
rewrite H
end end.
Ltac step := match goal with
| |- Ok ?r => cbv [Ok r]; intros
| _ => solve [trivial | contradiction]
| _ => resolve_match_using_hyp
| _ => inversion_option_step
| H : _ = ?v |- _ => is_var v; progress subst v
| H : ?v = _ |- _ => is_var v; progress subst v
| H : eval _ ?d ?e ?v1, G: eval _ ?d ?e ?v2 |- _ =>
assert_fails (constr_eq v1 v2);
eapply (eval_eval _ d e v1 H v2) in G
| |- eval _ ?d ?e ?v =>
match goal with
H : eval _ d e ?v' |- _ =>
let Heq := fresh in
enough (Heq : v = v') by (rewrite Heq; exact H);
try (clear H; clear e)
end
| H: interp_op _ (const _) nil = Some _ |- _ => inversion H; clear H; subst
| H: interp0_op _ _ = Some _ |- _ => eapply interp_op_interp0_op in H
| H: interp0_expr _ = Some _ |- _ => eapply eval_interp0_expr in H
| H: bound_expr _ = Some _ |- _ => eapply eval_bound_expr in H; eauto; [ ]
| H : (?x <=? ?y)%N = ?b |- _ => is_constructor b; destruct (N.leb_spec x y); (inversion H || clear H)
| H : andb _ _ = true |- _ => eapply Bool.andb_prop in H; case H as (?&?)
| H : N.eqb ?n _ = true |- _ => eapply N.eqb_eq in H; try subst n
| H : Z.eqb ?n _ = true |- _ => eapply Z.eqb_eq in H; try subst n
| H : expr_beq ?a ?b = true |- _ => replace a with b in * by (symmetry;exact (expr_beq_true a b H)); clear H
| _ => progress destruct_one_match_hyp
| _ => progress destruct_one_match
| H : eval _ _ ?e _ |- _ => assert_fails (is_var e); inversion H; clear H; subst
| H : Forall2 (eval _ _) (cons _ _) _ |- _ => inversion H; clear H; subst
| H : Forall2 (eval _ _) _ (cons _ _) |- _ => inversion H; clear H; subst
| H : Forall2 _ _ nil |- _ => inversion H; clear H; subst
| H : Forall2 _ nil _ |- _ => inversion H; clear H; subst
| _ => progress cbn [fst snd map option_map] in *
end.
Ltac Econstructor :=
match goal with
| |- Forall2 (eval _ _) _ _ => econstructor
| |- eval _ _ ?e _ => econstructor
end.
Ltac t := repeat (step || Econstructor || eauto || (progress cbn [interp0_op interp_op] in * ) ).
Definition slice0 :=
fun e => match e with
ExprApp (slice 0 s, [(ExprApp ((addZ|mulZ|negZ|shlZ|shrZ|andZ|orZ|xorZ) as o, args))]) =>
ExprApp ((match o with addZ=>add s|mulZ=>mul s|negZ=>neg s|shlZ=>shl s|shrZ => shr s|andZ => and s| orZ => or s|xorZ => xor s |_=>old 0%N 999999%N end), args)
| _ => e end.
Global Instance slice0_ok : Ok slice0. Proof using Type. t. Qed.
Definition slice01_addcarryZ :=
fun e => match e with
ExprApp (slice 0 1, [(ExprApp (addcarryZ s, args))]) =>
ExprApp (addcarry s, args)
| _ => e end.
Global Instance slice01_addcarryZ_ok : Ok slice01_addcarryZ.
Proof using Type. t; rewrite ?Z.shiftr_0_r, ?Z.land_ones, ?Z.shiftr_div_pow2; trivial; Lia.lia. Qed.
Definition slice01_subborrowZ :=
fun e => match e with
ExprApp (slice 0 1, [(ExprApp (subborrowZ s, args))]) =>
ExprApp (subborrow s, args)
| _ => e end.
Global Instance slice01_subborrowZ_ok : Ok slice01_subborrowZ.
Proof using Type. t; rewrite ?Z.shiftr_0_r, ?Z.land_ones, ?Z.shiftr_div_pow2; trivial; Lia.lia. Qed.
Definition slice_set_slice :=
fun e => match e with
ExprApp (slice 0 s1, [ExprApp (set_slice 0 s2, [_; e'])]) =>
if N.leb s1 s2 then ExprApp (slice 0 s1, [e']) else e | _ => e end.
Global Instance slice_set_slice_ok : Ok slice_set_slice.
Proof using Type. t. f_equal. Z.bitblast. Qed.
Definition set_slice_set_slice :=
fun e => match e with
ExprApp (set_slice lo1 s1, [ExprApp (set_slice lo2 s2, [x; e']); y]) =>
if andb (N.eqb lo1 lo2) (N.leb s2 s1) then ExprApp (set_slice lo1 s1, [x; y]) else e | _ => e end.
Global Instance set_slice_set_slice_ok : Ok set_slice_set_slice.
Proof using Type. t. f_equal. Z.bitblast. Qed.
Definition set_slice0_small :=
fun e => match e with
ExprApp (set_slice 0 s, [x; y]) =>
match bound_expr x, bound_expr y with Some a, Some b =>
if Z.leb a (Z.ones (Z.of_N s)) && Z.leb b (Z.ones (Z.of_N s)) then y
else e | _, _ => e end | _ => e end%bool.
Global Instance set_slice0_small_ok : Ok set_slice0_small.
Proof using Type.
t.
eapply Zle_bool_imp_le in H0; rewrite Z.ones_equiv in H0; eapply Z.lt_le_pred in H0.
eapply Zle_bool_imp_le in H1; rewrite Z.ones_equiv in H1; eapply Z.lt_le_pred in H1.
assert ((0 <= y < 2^Z.of_N sz)%Z) by Lia.lia; clear dependent z.
assert ((0 <= y0 < 2^Z.of_N sz)%Z) by Lia.lia; clear dependent z0.
rewrite ?Z.shiftl_0_r, Z.land_ones, Z.mod_small by Lia.lia.
destruct (Z.eq_dec y 0); subst.
{ rewrite Z.ldiff_0_l, Z.lor_0_r; trivial. }
rewrite Z.ldiff_ones_r_low, Z.lor_0_r; try Lia.lia.
eapply Z.log2_lt_pow2; Lia.lia.
Qed.
Definition truncate_small :=
fun e => match e with
ExprApp (slice 0%N s, [e']) =>
match bound_expr e' with Some b =>
if Z.leb b (Z.ones (Z.of_N s))
then e'
else e | _ => e end | _ => e end.
Global Instance truncate_small_ok : Ok truncate_small. Proof using Type. t; []. cbn in *; eapply Z.land_ones_low_alt_ones; eauto. firstorder. Lia.lia. Qed.
Definition addcarry_bit :=
fun e => match e with
ExprApp (addcarry s, ([ExprApp (const a, nil);b])) =>
if option_beq Z.eqb (bound_expr b) (Some 1) then
match interp0_op (addcarry s) [a; 0], interp0_op (addcarry s) [a; 1] with
| Some 0, Some 1 => b
| Some 0, Some 0 => ExprApp (const 0, nil)
| _, _ => e
end else e | _ => e end%Z%bool.
Global Instance addcarry_bit_ok : Ok addcarry_bit.
Proof using Type.
repeat step;
[instantiate (1:=G) in E0; instantiate (1:=G) in E1|];
destruct (Reflect.reflect_eq_option (eqA:=Z.eqb) (bound_expr e) (Some 1%Z)) in E;
try discriminate; repeat step;
assert (y0 = 0 \/ y0 = 1)%Z as HH by Lia.lia; case HH as [|];
subst; repeat step; repeat Econstructor; cbn; congruence.
Qed.
Definition addoverflow_bit :=
fun e => match e with
ExprApp (addoverflow s, ([ExprApp (const a, nil);b])) =>
if option_beq Z.eqb (bound_expr b) (Some 1%Z) then
match interp0_op (addoverflow s) [a; 0] , interp0_op (addoverflow s) [a; 1] with
| Some 0, Some 1 => b
| Some 0, Some 0 => ExprApp (const 0, nil)
| _, _ => e
end else e | _ => e end%Z%bool.
Global Instance addoverflow_bit_ok : Ok addoverflow_bit.
Proof using Type.
repeat step;
[instantiate (1:=G) in E0; instantiate (1:=G) in E1|];
destruct (Reflect.reflect_eq_option (eqA:=Z.eqb) (bound_expr e) (Some 1)%Z) in E;
try discriminate; repeat step;
assert (y0 = 0 \/ y0 = 1)%Z as HH by Lia.lia; case HH as [|];
subst; repeat step; repeat Econstructor; cbn; congruence.
Qed.
Definition addbyte_small :=
fun e => match e with
ExprApp (add (8%N as s), args) =>
match Option.List.lift (List.map bound_expr args) with
| Some bounds =>
if Z.leb (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s))
then ExprApp (add 64%N, args)
else e | _ => e end | _ => e end.
Global Instance addbyte_small_ok : Ok addbyte_small.
Proof using Type.
t; f_equal.
eapply bound_sum in H2; eauto.
rewrite Z.ones_equiv in E0; rewrite !Z.land_ones, !Z.mod_small; try Lia.lia;
replace (Z.of_N 8) with 8 in * by (vm_compute; reflexivity);
replace (Z.of_N 64) with 64 in * by (vm_compute; reflexivity); Lia.lia.
Qed.
Definition addcarry_small :=
fun e => match e with
ExprApp (addcarry s, args) =>
match Option.List.lift (List.map bound_expr args) with
| Some bounds =>
if Z.leb (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s))
then (ExprApp (const 0, nil))
else e | _ => e end | _ => e end.
Global Instance addcarry_small_ok : Ok addcarry_small.
Proof using Type.
t; f_equal.
eapply bound_sum in H2; eauto.
rewrite Z.ones_equiv in E0; rewrite Z.shiftr_div_pow2, Z.div_small; cbn; Lia.lia.
Qed.
Lemma signed_small s v (Hv : (0 <= v <= Z.ones (Z.of_N s-1))%Z) : signed s v = v.
Proof using Type.
destruct (N.eq_dec s 0); subst; cbv [signed].
{ rewrite Z.land_0_r. cbn in *; Lia.lia. }
rewrite !Z.land_ones, !Z.shiftl_mul_pow2, ?Z.add_0_r, ?Z.mul_1_l by Lia.lia.
rewrite Z.ones_equiv in Hv.
rewrite Z.mod_small; try ring.
enough (2 ^ Z.of_N s = 2 ^ (Z.of_N s - 1) + 2 ^ (Z.of_N s - 1))%Z; try Lia.lia.
replace (Z.of_N s) with (1+(Z.of_N s-1))%Z at 1 by Lia.lia.
rewrite Z.pow_add_r; try Lia.lia.
Qed.
Definition addoverflow_small :=
fun e => match e with
ExprApp (addoverflow s, ([_]|[_;_]|[_;_;_]) as args) =>
match Option.List.lift (List.map bound_expr args) with
| Some bounds =>
if Z.leb (List.fold_right Z.add 0%Z bounds) (Z.ones (Z.of_N s-1))
then (ExprApp (const 0, nil))
else e | _ => e end | _ => e end.
Global Instance addoverflow_small_ok : Ok addoverflow_small.
Proof using Type.
t; cbv [Option.List.lift Option.bind fold_right] in *;
BreakMatch.break_match_hyps; Option.inversion_option; t;
epose proof Z.ones_equiv (Z.of_N s -1).
all : rewrite Z.land_ones, !Z.mod_small, !signed_small, !Z.eqb_refl; trivial.
all : try split; try Lia.lia.
all : replace (Z.of_N s) with (1+(Z.of_N s-1))%Z at 1 by Lia.lia;
rewrite Z.pow_add_r; try Lia.lia.
all : destruct s; cbn in E0; Lia.lia.
Qed.
Definition constprop :=
fun e => match interp0_expr e with
| Some v => ExprApp (const v, nil)
| _ => e end.
Global Instance constprop_ok : Ok constprop.
Proof using Type. t. f_equal; eauto using eval_eval. Qed.
(* convert unary operations to slice *)
Definition unary_truncate :=
fun e => match e with
ExprApp (o, [x]) =>
match unary_truncate_size o with
| Some (-1)%Z => x
| Some 0%Z => ExprApp (const 0, nil)
| Some (Zpos p)
=> ExprApp (slice 0%N (Npos p), [x])
| _ => e end | _ => e end.
Global Instance unary_truncate_ok : Ok unary_truncate.
Proof using Type.
t.
all: repeat first [ progress cbv [unary_truncate_size] in *
| progress cbn [fold_right Z.of_N] in *
| progress change (Z.of_N 0) with 0 in *
| progress change (Z.ones 0) with 0 in *
| apply (f_equal (@Some _))
| lia
| progress autorewrite with zsimplify_const
| progress break_innermost_match_hyps
| match goal with
| [ H : Z.of_N ?s = 0 |- _ ] => is_var s; destruct s; try lia
| [ H : Z.of_N ?s = Z.pos _ |- _ ] => is_var s; destruct s; try lia
| [ H : Z.pos _ = Z.pos _ |- _ ] => inversion H; clear H
end
| progress t ].
Qed.
Lemma interp_op_drop_identity o id : identity o = Some id ->
forall G xs, interp_op G o xs = interp_op G o (List.filter (fun v => negb (Z.eqb v id)) xs).
Proof using Type.
destruct o; cbn [identity]; intro; inversion_option; subst; intros G xs; cbn [interp_op]; f_equal.
all: induction xs as [|x xs IHxs]; cbn [fold_right List.filter]; try reflexivity.
all: unfold negb at 1; break_innermost_match_step; reflect_hyps; subst; cbn [fold_right].
all: break_innermost_match_hyps; inversion_option; subst.
all: autorewrite with zsimplify_const.
all: try assumption.
all: rewrite ?(Z.land_comm (Z.ones _)).
all: try solve [ rewrite <- !Z.land_assoc; congruence ].
all: try solve [ rewrite ?Z.land_ones by lia; pull_Zmod; push_Zmod; rewrite <- ?Z.land_ones by lia; rewrite <- ?IHxs; try reflexivity ].
{ rewrite 2Z.land_lor_distr_l, IHxs; reflexivity. }
{ rewrite Z.land_lxor_distr_r, IHxs, <- Z.land_lxor_distr_r; reflexivity. }
Qed.
Lemma interp_op_nil_is_identity o i (Hi : identity o = Some i)
G : interp_op G o [] = Some i.
Proof using Type.
destruct o; cbn [identity] in *; break_innermost_match_hyps; inversion_option; subst; cbn [interp_op fold_right]; f_equal.
all: cbn [interp_op fold_right]; autorewrite with zsimplify_const; try reflexivity.
{ cbn [identity]; break_innermost_match; try reflexivity.
rewrite Z.land_ones by lia; Z.rewrite_mod_small; try reflexivity;
(* compat with older versions of Coq (needed for 8.11, not for 8.13) *)
rewrite Z.mod_small; rewrite ?Z.log2_lt_pow2; cbn [Z.log2]; try lia. }
Qed.
Lemma invert_interp_op_associative o : associative o = true ->
forall G x xs v, interp_op G o (x :: xs) = Some v ->
exists v', interp_op G o xs = Some v' /\
interp_op G o [x; v'] = Some v.
Proof using Type.
destruct o; inversion 1; intros * HH; inversion HH; clear HH; subst; cbn;
eexists; split; eauto; f_equal; try ring; try solve [Z.bitblast].
{ rewrite !Z.add_0_r, ?Z.land_ones; push_Zmod; pull_Zmod; Lia.lia. }
{ rewrite !Z.mul_1_r, ?Z.land_ones; push_Zmod; pull_Zmod; Lia.lia. }
Qed.
(** TODO: plausibly we want to define all associative operations in terms of some [make_associative_op] definition, so that we can separate out the binary operation reasoning from the fold and option reasoning *)
(* is it okay for associative to imply identity? *)
Lemma interp_op_associative_spec_fold o : associative o = true ->
forall G xs, interp_op G o xs = fold_right (fun v acc => acc <- acc; interp_op G o [v; acc])%option (interp_op G o []) xs.
Proof using Type.
intros H G; induction xs as [|x xs IHxs]; cbn [fold_right]; [ reflexivity | ].
rewrite <- IHxs; clear IHxs.
destruct o; inversion H; cbn [interp_op Option.bind fold_right]; f_equal.
all: autorewrite with zsimplify_const.
all: try solve [ Z.bitblast ].
all: try solve [ rewrite ?Z.land_ones in *; push_Zmod; pull_Zmod; Lia.lia ].
Qed.
Lemma interp_op_associative_spec_id o : associative o = true ->
forall G, interp_op G o [] = identity o.
Proof using Type.
intros H G.
pose proof (fun id H => interp_op_nil_is_identity o id H G) as H1.
destruct o; inversion H; cbn [identity] in *; break_innermost_match_hyps; erewrite H1; try reflexivity.
Qed.
Lemma interp_op_associative_identity_Some o : associative o = true ->
forall G xs vxs, interp_op G o xs = Some vxs -> Option.is_Some (identity o) = true.