| 1 |
From Coq Require Import Bool. |
| 2 |
From Coq Require Import ZArith. |
| 3 |
From Coq Require Import Lia. |
| 4 |
|
| 5 |
Require Import Crypto.Util.ZUtil.Definitions. |
| 6 |
Require Import Crypto.Util.ZUtil.Notations. |
| 7 |
Require Import Crypto.Util.ZUtil.Land. |
| 8 |
Require Import Crypto.Util.ZUtil.Testbit. |
| 9 |
Require Import Crypto.Util.ZUtil.TwosComplement. |
| 10 |
|
| 11 |
Require Import Crypto.Util.ZUtil.Tactics.SolveRange. |
| 12 |
|
| 13 |
Import Notations. |
| 14 |
|
| 15 |
Local Open Scope Z_scope. |
| 16 |
|
| 17 |
Module Z. |
| 18 |
Lemma sign_bit_0_land_pow2 a m : |
| 19 |
Z.sign_bit m a = 0 -> a &' 2 ^ (m - 1) = 0. |
| 20 |
Proof. |
| 21 |
intros H; apply Z.shiftr_eq_0_iff in H; destruct H as [? |[? ?] ]; subst. |
| 22 |
- rewrite Z.land_0_l; reflexivity. |
| 23 |
- rewrite Z.land_pow2_testbit, Z.bits_above_log2; lia. Qed. |
| 24 |
|
| 25 |
Lemma sign_bit_testbit a m |
| 26 |
(Hm : 0 < m) |
| 27 |
(H : 0 <= a < 2 ^ m) : |
| 28 |
Z.sign_bit m a = Z.b2z (Z.testbit a (m - 1)). |
| 29 |
Proof. |
| 30 |
rewrite Z.testbit_spec', Z.mod_small, <- Z.shiftr_div_pow2 by Z.solve_range. |
| 31 |
reflexivity. Qed. |
| 32 |
|
| 33 |
Lemma sign_bit_equiv a m |
| 34 |
(Hm : 0 < m) |
| 35 |
(Ha : 0 <= a < 2 ^ m) : |
| 36 |
Z.sign_bit m a = Z.b2z (negb (a <? 2 ^ (m - 1))). |
| 37 |
Proof. rewrite <- (Z.mod_small _ _ Ha) at 2. |
| 38 |
rewrite Z.twos_complement_cond_equiv, sign_bit_testbit, negb_involutive; lia. Qed. |
| 39 |
|
| 40 |
Lemma sign_bit_1_land_pow2 a m |
| 41 |
(Hm : 0 < m) |
| 42 |
(Ha : 0 <= a < 2 ^ m) : |
| 43 |
Z.sign_bit m a <> 0 -> a &' 2 ^ (m - 1) = 2 ^ (m - 1). |
| 44 |
Proof. |
| 45 |
intros H. rewrite Z.land_pow2_testbit, Z.testbit_b2z, <- sign_bit_testbit by assumption. |
| 46 |
apply Z.eqb_neq in H; rewrite H; reflexivity. Qed. |
| 47 |
|
| 48 |
Lemma sign_bit_0_testbit a m |
| 49 |
(Hm : 0 < m) : |
| 50 |
Z.sign_bit m a = 0 -> Z.testbit a (m - 1) = false. |
| 51 |
Proof. |
| 52 |
assert (Hnz : 2 ^ (m - 1) <> 0) by (apply Z.pow_nonzero; lia). |
| 53 |
intro H; apply sign_bit_0_land_pow2 in H. rewrite Z.land_pow2_testbit in H; |
| 54 |
destruct (Z.testbit a (m - 1)); |
| 55 |
[contradiction|reflexivity]. Qed. |
| 56 |
|
| 57 |
Lemma sign_bit_1_testbit a m |
| 58 |
(Hm : 0 < m) |
| 59 |
(Ha : 0 <= a < 2 ^ m) : |
| 60 |
Z.sign_bit m a <> 0 -> Z.testbit a (m - 1) = true. |
| 61 |
Proof. |
| 62 |
rewrite Z.testbit_b2z, <- sign_bit_testbit by lia; intro H. |
| 63 |
apply Z.eqb_neq in H; rewrite H; reflexivity. Qed. |
| 64 |
End Z. |