diff --git a/README.md b/README.md index 82648c062..434685bc2 100644 --- a/README.md +++ b/README.md @@ -57,6 +57,10 @@ Progress so far: - [x] Load-op memory operands on x86, opt-in `-fload-op`. This is the first approved trusted-base change ([#5](https://github.com/AananthV/CompCert/issues/5), [ledger](faster-compcert/TRUSTED_BASE.md)). +- [x] Model x86 shift-count masking (approved trusted-base change, opt-in + `-fshift-mask`; [#11](https://github.com/AananthV/CompCert/issues/11)). +- [x] Retroactive review of the round-1 trusted-base changes + ([#10](https://github.com/AananthV/CompCert/issues/10)). - [ ] Opt-in libm builtins (`sqrt`, `floor`) and unaligned 64-bit accesses: these need changes to the trusted model. - [x] Fix the Loadfwd compile-time/memory blow-up on large functions (65 GB → diff --git a/driver/Clflags.ml b/driver/Clflags.ml index a2aa5304f..c9511ef26 100644 --- a/driver/Clflags.ml +++ b/driver/Clflags.ml @@ -34,6 +34,7 @@ let option_flooprotate = ref true let option_flicm = ref true let option_fivwiden = ref true let option_floadop = ref false +let option_fshiftmask = ref false let option_fifconversion = ref true let option_Obranchless = ref false let option_falignfunctions = ref (None: int option) diff --git a/driver/Compopts.v b/driver/Compopts.v index a35d93759..ea2d5aa13 100644 --- a/driver/Compopts.v +++ b/driver/Compopts.v @@ -51,6 +51,10 @@ Parameter optim_ivwiden: unit -> bool. (** Flag -fload-op. For memory operands in arithmetic instructions. *) Parameter optim_loadop: unit -> bool. +(** Flag -fshift-mask. For dropping the masking of the count of + variable shifts, which the x86 hardware performs. *) +Parameter optim_shiftmask: unit -> bool. + (** Flag -fredundancy. For dead code elimination. *) Parameter optim_redundancy: unit -> bool. diff --git a/driver/Driver.ml b/driver/Driver.ml index c389a41ff..42ca72876 100644 --- a/driver/Driver.ml +++ b/driver/Driver.ml @@ -200,6 +200,7 @@ Processing options: -floadfwd Perform global forwarding of stored and loaded values [on] -fredundancy Perform redundancy elimination [on] -fload-op Use memory operands in arithmetic instructions [off] + -fshift-mask Rely on the hardware masking of variable shift counts [off] -finline Perform inlining of functions [on] -finline-functions-called-once Integrate functions only required by their single caller [on] @@ -399,6 +400,7 @@ let cmdline_actions = @ f_opt "licm" option_flicm @ f_opt "iv-widen" option_fivwiden @ f_opt "load-op" option_floadop + @ f_opt "shift-mask" option_fshiftmask @ f_opt "redundancy" option_fredundancy @ f_opt "inline" option_finline @ f_opt "inline-functions-called-once" option_finline_functions_called_once diff --git a/extraction/extraction.v b/extraction/extraction.v index 42831490a..b3d1c8f14 100644 --- a/extraction/extraction.v +++ b/extraction/extraction.v @@ -111,6 +111,8 @@ Extract Constant Compopts.optim_loadfwd => "fun _ -> !Clflags.option_floadfwd". Extract Constant Compopts.optim_loadop => "fun _ -> !Clflags.option_floadop". +Extract Constant Compopts.optim_shiftmask => + "fun _ -> !Clflags.option_fshiftmask". Extract Constant Compopts.optim_redundancy => "fun _ -> !Clflags.option_fredundancy". Extract Constant Compopts.thumb => diff --git a/faster-compcert/README.md b/faster-compcert/README.md index 267013059..df6ca2865 100644 --- a/faster-compcert/README.md +++ b/faster-compcert/README.md @@ -35,6 +35,8 @@ Changes, each fully proved: | new pass `Loadop`: x86 arithmetic with memory operands (#5; **trusted-base change**, see [TRUSTED_BASE.md](TRUSTED_BASE.md)) | `-fload-op` (off by default) | gemm 0.91x, nbody 0.96x, spectral 0.97x | +| x86 shift-count masking in the Asm model, plus masked-shift selection (#11; **trusted-base change**) | `-fshift-mask` (off by default) | nsievebits 0.94x | + Verification: - No new axioms. The only new entries in `Print Assumptions` are three flags diff --git a/faster-compcert/REPORT.md b/faster-compcert/REPORT.md index 8cab1d07b..a63e99e06 100644 --- a/faster-compcert/REPORT.md +++ b/faster-compcert/REPORT.md @@ -1147,3 +1147,30 @@ nearly every candidate unsafe: nbody had 1 fusion instead of 9. one instruction in between, including gemm's `A[i][k]`. - Commuted operands and accumulators (`t = load; t = t + x`) are not handled. + +--- + +## 17. Second trusted-base change: x86 shift-count masking (issue #11) + +**Trusted part.** The six variable-count shifts in `x86/Asm.v` now mask their +count to 5 or 6 bits, as the hardware does (ledger entry 4). The new semantics +is a strict refinement of the old one, which was undefined for large counts. +The differential test against the extracted new semantics gives 0 mismatches +and is defined on 100% of the tests (previously 6-13%). The approval and the +exact text were checked character for character against the proposal. + +**Verified part.** +- New masked-shift operators, plus a selection rule behind `-fshift-mask` + (off by default). It turns `x << (y & 31)`, and the low word of a 64-bit + `y & 31`, into the masked operator. The second form is what nsievebits + has: `1 << i % NBITS` with a `size_t` `NBITS`. +- Asmgen emits the plain `%cl` shift. +- Existing shifts use the refined instructions through a lemma that the masked + result is at least as defined as the unmasked one. + +**Results.** +- Without the flag, the generated code is byte-identical on all 136 files. +- With the flag, only nsievebits changes: both `andq $31,%rcx` instructions + are gone. It runs **−6.3%** (interleaved timing, 94.1 → 88.2 ms). +- 154 tests pass with and without the flag. +- Proofs check on all six targets. diff --git a/faster-compcert/TRUSTED_BASE.md b/faster-compcert/TRUSTED_BASE.md index ff0033839..76573ee9a 100644 --- a/faster-compcert/TRUSTED_BASE.md +++ b/faster-compcert/TRUSTED_BASE.md @@ -99,3 +99,34 @@ sequence with 3 seeds: **Revert.** Remove the xor-emitting lines in `TargetPrinter.ml` and `Asmexpand.ml`. + +## 4. x86 shift-count masking (#11) + +- **Approved:** by the owner, 2026-10-22, for exactly the proposal on #11. +- **Merged in:** "x86: model shift-count masking; optional masked-shift selection". +- **Flag:** the semantic refinement is unconditional. The optimization that + uses it is behind `-fshift-mask`, off by default. + +**Assumption.** In `x86/Asm.v`, the variable-count shifts mask their count: +```coq + | Psall_rcl rd => Next (nextinstr_nf (rs#rd <- (Val.shl rs#rd (Val.and rs#RCX (Vint (Int.repr 31)))))) m + (* likewise Pshrl_rcl (Val.shru) and Psarl_rcl (Val.shr) with 31; + Psalq_rcl (Val.shll), Pshrq_rcl (Val.shrlu) and Psarq_rcl (Val.shrl) with 63 *) +``` +Before this change these shifts were `Val.shl rs#rd rs#RCX` etc., which is +undefined for counts of 32 (or 64) and above. + +**Justification.** Intel SDM Vol. 2, SAL/SAR/SHL/SHR: the count is masked to +5 bits (6 with REX.W). This is a refinement: for counts that were defined +before, the new semantics agrees with the old. + +**Validation.** `harness/asm_difftest/` group `shift`, against the extracted new +semantics: +- all counts 0..255, with garbage in bits 8..63 of `%rcx`; +- about 20,000 tests per instruction, 3 seeds; +- 0 mismatches, and defined in 100% of the tests. Under the old semantics, only + 6-13% were defined. + +**Revert.** Restore the six cases. Then remove the masked operators +(`Oshlmask`, …), their selection rules and the `-fshift-mask` flag. + diff --git a/faster-compcert/harness/asm_difftest/Extract.v b/faster-compcert/harness/asm_difftest/Extract.v index 1588849d7..3f11d043f 100644 --- a/faster-compcert/harness/asm_difftest/Extract.v +++ b/faster-compcert/harness/asm_difftest/Extract.v @@ -1,4 +1,4 @@ -From compcert Require Import Coqlib Values. +From compcert Require Import Coqlib. From Coq Require Import ExtrOcamlBasic ExtrOcamlNativeString. Require Import Semantics. Extraction Inline Coqlib.proj_sumbool. @@ -9,6 +9,4 @@ Extraction "difftest_sem.ml" sem_addsd sem_subsd sem_mulsd sem_divsd sem_addl sem_xorl sem_andl sem_orl (* register instructions (#10, #11) *) run_regs sem_fsqrt vint vlong vfloat_bits vsingle_bits res_of_val - (* used by the proposed shift semantics of #11 in check_regs.ml *) - Val.and Val.shl Val.shru Val.shr Val.shll Val.shrlu Val.shrl int64_of_Z Z_of_int64 int_of_Z Z_of_int. diff --git a/faster-compcert/harness/asm_difftest/README.md b/faster-compcert/harness/asm_difftest/README.md index 529c7fdb2..46d4edc74 100644 --- a/faster-compcert/harness/asm_difftest/README.md +++ b/faster-compcert/harness/asm_difftest/README.md @@ -11,7 +11,7 @@ semantics extracted to OCaml. The tree must be built (`make proof`). | `loadop` | #5 | `Paddd_fm Psubd_fm Pmuld_fm Pdivd_fm Paddl_rm Pxorl_rm Pandl_rm Porl_rm` | | `zx` | #10 | `Psallzx_ri Pshrlzx_ri Pandlzx_ri` | | `cvt` | #10 | `Pcvtsi2sd_fr Pcvtsi2ss_fr Pcvtsl2sd_fr Pcvtsl2ss_fr Pcvtss2sd_ff Pcvtsd2ss_ff`, and `sqrtsd` (from `__builtin_fsqrt`), with the `xorpd`/`xorps` printed before them | -| `shift` | #11 | `Psall_rcl Pshrl_rcl Psarl_rcl Psalq_rcl Pshrq_rcl Psarq_rcl`, against both `Asm.v` and the masked semantics proposed in #11 | +| `shift` | #11 | `Psall_rcl Pshrl_rcl Psarl_rcl Psalq_rcl Pshrq_rcl Psarq_rcl`, whose count is masked in `Asm.v` since #11 | For example, `run.sh . 20000 0x1 shift` runs only the shifts. The script exits 1 if any group fails. Scratch files go to @@ -63,10 +63,9 @@ The reference is always the extracted Coq semantics (`Asm.exec_instr`, (failure); - **undef**: the model gives `Vundef`, so there is no constraint. - For `shift`, the same is done with `proposed_rcl`, the semantics - proposed in #11 (`Val.shl rd (Val.and rcx 31)`, ...). It is written - in OCaml from the extracted `Val` operations, and `Asm.v` is not - changed. + For `shift`, `Asm.v` masks the count since #11 + (`Val.shl rd (Val.and rcx 31)`, ...), so the model must be defined on + every test: an undef result is a failure there. A test also fails (`regs` column) if any register other than the destination changed. For `cvt`, whose semantics uses `nextinstr`, it also fails if a flag changed. The `wrong-kind:undef` column runs the diff --git a/faster-compcert/harness/asm_difftest/check_regs.ml b/faster-compcert/harness/asm_difftest/check_regs.ml index 1389a1bf9..c45f7637f 100644 --- a/faster-compcert/harness/asm_difftest/check_regs.ml +++ b/faster-compcert/harness/asm_difftest/check_regs.ml @@ -10,8 +10,9 @@ match the model is defined and equals the hardware bit for bit, MISMATCH the model is defined and differs from the hardware, undef the model gives [Vundef] (no constraint on the hardware). - For the shifts by %cl, the same is done for the masked semantics - proposed in #11 ([proposed_rcl] below; Asm.v is not changed). + Since #11, Asm.v masks the count of the shifts by %cl as the hardware + does, so for them the model must be defined on every test: an undef + result is a failure. Independently of the model, the test fails if a register other than the destination changed, and, for the conversions (whose semantics @@ -37,22 +38,6 @@ let lo32 x = Stdlib.Int64.logand x 0xffffffffL let hi32 x = Stdlib.Int64.shift_right_logical x 32 let z = z_of_uint64 -(* The proposed semantics of #11, written with the extracted [Val] - operations exactly as in the proposal: - Psall_rcl rd => rs#rd <- Val.shl rs#rd (Val.and rs#RCX (Vint (Int.repr 31))) - etc., with 63 for the 64-bit forms. *) -let proposed_rcl name (vrd: val0) (vrcx: val0) : val0 = - let m31 = Val.coq_and vrcx (vint (z 31L)) - and m63 = Val.coq_and vrcx (vint (z 63L)) in - match name with - | "sall_rcl" -> Val.shl vrd m31 - | "shrl_rcl" -> Val.shru vrd m31 - | "sarl_rcl" -> Val.shr vrd m31 - | "salq_rcl" -> Val.shll vrd m63 - | "shrq_rcl" -> Val.shrlu vrd m63 - | "sarq_rcl" -> Val.shrl vrd m63 - | s -> failwith s - (* The instruction of Asm.v, with its source operand in [src]. *) let instr name imm src = let n = int_of_Z (z imm) in @@ -126,14 +111,13 @@ let classify kind r (v: val0 option) = type stats = { mutable tests: int; mutable ok: int; mutable bad: int; mutable undef: int; (* Asm.v *) - mutable pok: int; mutable pbad: int; mutable pundef: int; (* #11 proposal *) mutable regs: int; (* other registers or flags changed *) mutable other_in: int; (* wrong-kind inputs giving Vundef / tested *) mutable other_undef: int; mutable info: int; (* see [info] below *) mutable info_of: int; } -let new_stats () = { tests = 0; ok = 0; bad = 0; undef = 0; pok = 0; pbad = 0; pundef = 0; +let new_stats () = { tests = 0; ok = 0; bad = 0; undef = 0; regs = 0; other_in = 0; other_undef = 0; info = 0; info_of = 0 } (* Inputs of a kind the compiler never produces for this instruction: @@ -176,14 +160,9 @@ let () = let where = Printf.sprintf "[%s] a=%Lx b=%Lx hw=%Lx" text a b r in (match classify kind r (run_model name imm same vd vs) with | Match -> s.ok <- s.ok + 1 - | Undef -> s.undef <- s.undef + 1 + | Undef -> s.undef <- s.undef + 1; + if g = Shift then report "UNDEF %s %s\n" name where | Mismatch m -> s.bad <- s.bad + 1; report "MISMATCH %s %s model=%s\n" name where m); - if g = Shift then - (match classify kind r (Some (proposed_rcl name vd vs)) with - | Match -> s.pok <- s.pok + 1 - | Undef -> s.pundef <- s.pundef + 1 - | Mismatch m -> s.pbad <- s.pbad + 1; - report "MISMATCH(#11 proposal) %s %s model=%s\n" name where m); if others_kept = 0 || (g = Cvt && flags_kept = 0) then begin s.regs <- s.regs + 1; report "REGS %s %s: other registers kept=%d, flags kept=%d\n" @@ -212,20 +191,18 @@ let () = | _ -> ())) done with End_of_file -> ()); - Printf.printf "%-9s %7s | %-27s | %-27s | %5s | %-15s | %s\n" "instr" "tests" - "Asm.v: match MISMATCH undef" "#11 prop.: match MISM undef" "regs" "wrong-kind:undef" "info"; + Printf.printf "%-9s %7s | %-27s | %5s | %-15s | %s\n" "instr" "tests" + "Asm.v: match MISMATCH undef" "regs" "wrong-kind:undef" "info"; List.iter (fun k -> match Hashtbl.find_opt tbl k with | None -> () | Some s -> - let prop = if group_of k = Shift - then Printf.sprintf "%9d %6d %6d" s.pok s.pbad s.pundef else "" in let info = match group_of k with | Zx -> Printf.sprintf "upper 32 zeroed %d/%d" s.info s.info_of | Shift when not (is_q k) -> Printf.sprintf "upper 32 zeroed %d/%d" s.info s.info_of | Cvt -> Printf.sprintf "upper lanes zero after xor %d/%d" s.info s.info_of | _ -> "" in - Printf.printf "%-9s %7d | %8d %8d %8d | %-27s | %5d | %7d/%-7d | %s\n" k s.tests - s.ok s.bad s.undef prop s.regs s.other_undef s.other_in info) + Printf.printf "%-9s %7d | %8d %8d %8d | %5d | %7d/%-7d | %s\n" k s.tests + s.ok s.bad s.undef s.regs s.other_undef s.other_in info) names; exit (if !failures = 0 then 0 else 1) diff --git a/faster-compcert/results/axioms-faster-compcert.txt b/faster-compcert/results/axioms-faster-compcert.txt index a71e4862a..26e9d5913 100644 --- a/faster-compcert/results/axioms-faster-compcert.txt +++ b/faster-compcert/results/axioms-faster-compcert.txt @@ -15,6 +15,7 @@ Compopts.optim_loadfwd Compopts.optim_loadop Compopts.optim_looprot Compopts.optim_redundancy +Compopts.optim_shiftmask Compopts.optim_tailcalls Compopts.propagate_float_constants Compopts.va_strict diff --git a/x86/Asm.v b/x86/Asm.v index 058febdd6..6c77aedb8 100644 --- a/x86/Asm.v +++ b/x86/Asm.v @@ -824,25 +824,25 @@ Definition exec_instr (f: function) (i: instruction) (rs: regset) (m: mem) : out | Pnotq rd => Next (nextinstr_nf (rs#rd <- (Val.notl rs#rd))) m | Psall_rcl rd => - Next (nextinstr_nf (rs#rd <- (Val.shl rs#rd rs#RCX))) m + Next (nextinstr_nf (rs#rd <- (Val.shl rs#rd (Val.and rs#RCX (Vint (Int.repr 31)))))) m | Psalq_rcl rd => - Next (nextinstr_nf (rs#rd <- (Val.shll rs#rd rs#RCX))) m + Next (nextinstr_nf (rs#rd <- (Val.shll rs#rd (Val.and rs#RCX (Vint (Int.repr 63)))))) m | Psall_ri rd n => Next (nextinstr_nf (rs#rd <- (Val.shl rs#rd (Vint n)))) m | Psalq_ri rd n => Next (nextinstr_nf (rs#rd <- (Val.shll rs#rd (Vint n)))) m | Pshrl_rcl rd => - Next (nextinstr_nf (rs#rd <- (Val.shru rs#rd rs#RCX))) m + Next (nextinstr_nf (rs#rd <- (Val.shru rs#rd (Val.and rs#RCX (Vint (Int.repr 31)))))) m | Pshrq_rcl rd => - Next (nextinstr_nf (rs#rd <- (Val.shrlu rs#rd rs#RCX))) m + Next (nextinstr_nf (rs#rd <- (Val.shrlu rs#rd (Val.and rs#RCX (Vint (Int.repr 63)))))) m | Pshrl_ri rd n => Next (nextinstr_nf (rs#rd <- (Val.shru rs#rd (Vint n)))) m | Pshrq_ri rd n => Next (nextinstr_nf (rs#rd <- (Val.shrlu rs#rd (Vint n)))) m | Psarl_rcl rd => - Next (nextinstr_nf (rs#rd <- (Val.shr rs#rd rs#RCX))) m + Next (nextinstr_nf (rs#rd <- (Val.shr rs#rd (Val.and rs#RCX (Vint (Int.repr 31)))))) m | Psarq_rcl rd => - Next (nextinstr_nf (rs#rd <- (Val.shrl rs#rd rs#RCX))) m + Next (nextinstr_nf (rs#rd <- (Val.shrl rs#rd (Val.and rs#RCX (Vint (Int.repr 63)))))) m | Psarl_ri rd n => Next (nextinstr_nf (rs#rd <- (Val.shr rs#rd (Vint n)))) m | Psarq_ri rd n => diff --git a/x86/Asmgen.v b/x86/Asmgen.v index 87656e730..2557d5b5f 100644 --- a/x86/Asmgen.v +++ b/x86/Asmgen.v @@ -652,6 +652,32 @@ Definition transl_op assertion (mreg_eq a1 res); do r <- ireg_of res; do r2 <- ireg_of a2; transl_sel c args r r2 k +(* The hardware masks the count of a shift by [%cl], so the masked + shifts are plain shifts by [%cl]. *) + | Oshlmask, a1 :: a2 :: nil => + assertion (mreg_eq a1 res); + assertion (mreg_eq a2 CX); + do r <- ireg_of res; OK (Psall_rcl r :: k) + | Oshrmask, a1 :: a2 :: nil => + assertion (mreg_eq a1 res); + assertion (mreg_eq a2 CX); + do r <- ireg_of res; OK (Psarl_rcl r :: k) + | Oshrumask, a1 :: a2 :: nil => + assertion (mreg_eq a1 res); + assertion (mreg_eq a2 CX); + do r <- ireg_of res; OK (Pshrl_rcl r :: k) + | Oshllmask, a1 :: a2 :: nil => + assertion (mreg_eq a1 res); + assertion (mreg_eq a2 CX); + do r <- ireg_of res; OK (Psalq_rcl r :: k) + | Oshrlmask, a1 :: a2 :: nil => + assertion (mreg_eq a1 res); + assertion (mreg_eq a2 CX); + do r <- ireg_of res; OK (Psarq_rcl r :: k) + | Oshrlumask, a1 :: a2 :: nil => + assertion (mreg_eq a1 res); + assertion (mreg_eq a2 CX); + do r <- ireg_of res; OK (Pshrq_rcl r :: k) | _, _ => Error(msg "Asmgen.transl_op") end. diff --git a/x86/Asmgenproof1.v b/x86/Asmgenproof1.v index 24d1f460e..2f109fe37 100644 --- a/x86/Asmgenproof1.v +++ b/x86/Asmgenproof1.v @@ -1305,6 +1305,57 @@ Ltac TranslOp := [ apply exec_straight_one; [ simpl; eauto | auto ] | split; [ Simplifs | intros; Simplifs ]]. +(** Shifts by [%cl]: the count is masked as by the hardware. This + refines the unmasked shifts of [Op], and is the semantics of the + masked shifts of [Op]. *) + +Remark mask_small: + forall i n logn, Int.is_power2 n = Some logn -> + Int.ltu i n = true -> Int.and i (Int.sub n Int.one) = i. +Proof. + intros. rewrite <- (Int.modu_and i n logn) by auto. + unfold Int.ltu in H0. destruct (zlt (Int.unsigned i) (Int.unsigned n)); try discriminate. + unfold Int.modu. rewrite Z.mod_small. apply Int.repr_unsigned. + generalize (Int.unsigned_range i); lia. +Qed. + +Remark mask31_small: + forall i, Int.ltu i Int.iwordsize = true -> Int.and i (Int.repr 31) = i. +Proof. + intros. exact (mask_small i Int.iwordsize (Int.repr 5) (eq_refl _) H). +Qed. + +Remark mask63_small: + forall i, Int.ltu i Int64.iwordsize' = true -> Int.and i (Int.repr 63) = i. +Proof. + intros. exact (mask_small i Int64.iwordsize' (Int.repr 6) (eq_refl _) H). +Qed. + +Lemma shift_mask_lessdef: + forall x y, + Val.lessdef (Val.shl x y) (Val.shl x (Val.and y (Vint (Int.repr 31)))) + /\ Val.lessdef (Val.shr x y) (Val.shr x (Val.and y (Vint (Int.repr 31)))) + /\ Val.lessdef (Val.shru x y) (Val.shru x (Val.and y (Vint (Int.repr 31)))) + /\ Val.lessdef (Val.shll x y) (Val.shll x (Val.and y (Vint (Int.repr 63)))) + /\ Val.lessdef (Val.shrl x y) (Val.shrl x (Val.and y (Vint (Int.repr 63)))) + /\ Val.lessdef (Val.shrlu x y) (Val.shrlu x (Val.and y (Vint (Int.repr 63)))). +Proof. + intros. destruct x; destruct y; simpl; intuition auto. +- destruct (Int.ltu i0 Int.iwordsize) eqn:L; auto. rewrite mask31_small, L by auto; auto. +- destruct (Int.ltu i0 Int.iwordsize) eqn:L; auto. rewrite mask31_small, L by auto; auto. +- destruct (Int.ltu i0 Int.iwordsize) eqn:L; auto. rewrite mask31_small, L by auto; auto. +- destruct (Int.ltu i0 Int64.iwordsize') eqn:L; auto. rewrite mask63_small, L by auto; auto. +- destruct (Int.ltu i0 Int64.iwordsize') eqn:L; auto. rewrite mask63_small, L by auto; auto. +- destruct (Int.ltu i0 Int64.iwordsize') eqn:L; auto. rewrite mask63_small, L by auto; auto. +Qed. + +Ltac TranslShift := + econstructor; split; + [ apply exec_straight_one; [ simpl; eauto | auto ] + | split; [ rewrite nextinstr_nf_inv by auto with asmgen; rewrite Pregmap.gss; + edestruct shift_mask_lessdef as (? & ? & ? & ? & ? & ?); eassumption + | intros; Simplifs ]]. + Lemma transl_op_correct: forall op args res k c (rs: regset) m v, transl_op op args res k = OK c -> @@ -1329,7 +1380,7 @@ Transparent destroyed_by_op. intros [rs' [A [B C]]]. subst v. exists rs'; auto. } - destruct op; simpl in TR; ArgsInv; simpl in EV; try (inv EV); try (apply SAME; TranslOp; fail). + destruct op; simpl in TR; ArgsInv; simpl in EV; try (inv EV); try (apply SAME; TranslOp; fail); try (TranslShift; fail). (* move *) exploit mk_mov_correct; eauto. intros [rs2 [A [B C]]]. apply SAME. exists rs2. eauto. diff --git a/x86/LICMop.v b/x86/LICMop.v index 0ef9d2ba0..01a71873a 100644 --- a/x86/LICMop.v +++ b/x86/LICMop.v @@ -57,6 +57,7 @@ Definition op_safe (op: operation) (n: nat) : bool := | Oshl | Oshr | Oshru | Oshldimm _ | Omakelong | Osubl | Omull | Omullhs | Omullhu | Oandl | Oorl | Oxorl | Oshll | Oshrl | Oshrlu + | Oshlmask | Oshrmask | Oshrumask | Oshllmask | Oshrlmask | Oshrlumask | Oaddf | Osubf | Omulf | Odivf | Omaxf | Ominf | Oaddfs | Osubfs | Omulfs | Odivfs), 2%nat => true | Olea a, _ => addressing32_safe a n diff --git a/x86/Machregs.v b/x86/Machregs.v index 0eb0df50d..a6ede141b 100644 --- a/x86/Machregs.v +++ b/x86/Machregs.v @@ -219,6 +219,8 @@ Definition mregs_for_operation (op: operation): list (option mreg) * option mreg | Oshrl => (None :: Some CX :: nil, None) | Oshrlu => (None :: Some CX :: nil, None) | Oshrxlimm _ => (Some AX :: nil, Some AX) + | Oshlmask | Oshrmask | Oshrumask + | Oshllmask | Oshrlmask | Oshrlumask => (None :: Some CX :: nil, None) | _ => (nil, None) end. @@ -353,6 +355,8 @@ Definition two_address_op (op: operation) : bool := | Osingleoflong => false | Ocmp c => false | Osel c op => true + | Oshlmask | Oshrmask | Oshrumask => true + | Oshllmask | Oshrlmask | Oshrlumask => true end. (* Constraints on constant propagation for builtins *) diff --git a/x86/NeedOp.v b/x86/NeedOp.v index 171a341eb..a27f6671b 100644 --- a/x86/NeedOp.v +++ b/x86/NeedOp.v @@ -110,6 +110,8 @@ Definition needs_of_operation (op: operation) (nv: nval): list nval := | Olongoffloat | Ofloatoflong | Olongofsingle | Osingleoflong => op1 (default nv) | Ocmp c => needs_of_condition c | Osel c ty => nv :: nv :: needs_of_condition c + | Oshlmask | Oshrmask | Oshrumask + | Oshllmask | Oshrlmask | Oshrlumask => op2 (default nv) end. Definition operation_is_redundant (op: operation) (nv: nval): bool := diff --git a/x86/Op.v b/x86/Op.v index 98053e7a4..c850a6ad9 100644 --- a/x86/Op.v +++ b/x86/Op.v @@ -173,8 +173,16 @@ Inductive operation : Type := | Osingleoflong (**r [rd = float32_of_signed_long(r1)] *) (*c Boolean tests: *) | Ocmp (cond: condition) (**r [rd = 1] if condition holds, [rd = 0] otherwise. *) - | Osel: condition -> typ -> operation. + | Osel: condition -> typ -> operation (**r [rd = rs1] if condition holds, [rd = rs2] otherwise. *) +(*c Shifts whose count is masked to 5 bits (32-bit) or 6 bits (64-bit), + as the hardware does for shifts by [%cl]: *) + | Oshlmask (**r [rd = r1 << (r2 & 31)] *) + | Oshrmask (**r [rd = r1 >> (r2 & 31)] (signed) *) + | Oshrumask (**r [rd = r1 >> (r2 & 31)] (unsigned) *) + | Oshllmask (**r [rd = r1 << (r2 & 63)] *) + | Oshrlmask (**r [rd = r1 >> (r2 & 63)] (signed) *) + | Oshrlumask. (**r [rd = r1 >> (r2 & 63)] (unsigned) *) (** Comparison functions (used in modules [CSE] and [Allocation]). *) @@ -446,6 +454,12 @@ Definition eval_operation | Osingleoflong, v1::nil => Val.singleoflong v1 | Ocmp c, _ => Some(Val.of_optbool (eval_condition c vl m)) | Osel c ty, v1::v2::vl => Some(Val.select (eval_condition c vl m) v1 v2 ty) + | Oshlmask, v1::v2::nil => Some (Val.shl v1 (Val.and v2 (Vint (Int.repr 31)))) + | Oshrmask, v1::v2::nil => Some (Val.shr v1 (Val.and v2 (Vint (Int.repr 31)))) + | Oshrumask, v1::v2::nil => Some (Val.shru v1 (Val.and v2 (Vint (Int.repr 31)))) + | Oshllmask, v1::v2::nil => Some (Val.shll v1 (Val.and v2 (Vint (Int.repr 63)))) + | Oshrlmask, v1::v2::nil => Some (Val.shrl v1 (Val.and v2 (Vint (Int.repr 63)))) + | Oshrlumask, v1::v2::nil => Some (Val.shrlu v1 (Val.and v2 (Vint (Int.repr 63)))) | _, _ => None end. @@ -623,6 +637,8 @@ Definition type_of_operation (op: operation) : list typ * typ := | Osingleoflong => (Tlong :: nil, Tsingle) | Ocmp c => (type_of_condition c, Tint) | Osel c ty => (ty :: ty :: type_of_condition c, ty) + | Oshlmask | Oshrmask | Oshrumask => (Tint :: Tint :: nil, Tint) + | Oshllmask | Oshrlmask | Oshrlumask => (Tlong :: Tint :: nil, Tlong) end. (** Weak type soundness results for [eval_operation]: @@ -786,6 +802,8 @@ Proof with (try exact I; try reflexivity). destruct v0; simpl in H0; inv H0... destruct (eval_condition cond vl m); simpl... destruct b... unfold Val.select. destruct (eval_condition c vl m). apply Val.normalize_type. exact I. + all: destruct v0; destruct v1; simpl; trivial; + match goal with |- context [if ?c then _ else _] => destruct c end... Qed. End SOUNDNESS. @@ -1368,6 +1386,8 @@ Proof. apply Val.select_inject; auto. destruct (eval_condition c vl1 m1) eqn:?; auto. right; symmetry; eapply eval_condition_inj; eauto. + all: inv H4; inv H2; simpl; auto; + match goal with |- context [if ?c then _ else _] => destruct c end; auto. Qed. End EVAL_COMPAT. diff --git a/x86/PrintOp.ml b/x86/PrintOp.ml index 6c97beeb6..6d7bc64ab 100644 --- a/x86/PrintOp.ml +++ b/x86/PrintOp.ml @@ -173,6 +173,12 @@ let print_operation reg pp = function fprintf pp "%a ?%s %a : %a" (print_condition reg) (c, args) (PrintAST.name_of_type ty) reg r1 reg r2 + | Oshlmask, [r1;r2] -> fprintf pp "%a << (%a & 31)" reg r1 reg r2 + | Oshrmask, [r1;r2] -> fprintf pp "%a >>s (%a & 31)" reg r1 reg r2 + | Oshrumask, [r1;r2] -> fprintf pp "%a >>u (%a & 31)" reg r1 reg r2 + | Oshllmask, [r1;r2] -> fprintf pp "%a < fprintf pp "%a >>ls (%a & 63)" reg r1 reg r2 + | Oshrlumask, [r1;r2] -> fprintf pp "%a >>lu (%a & 63)" reg r1 reg r2 | _ -> fprintf pp "" diff --git a/x86/SelectLong.vp b/x86/SelectLong.vp index ca75d1f69..c328e9eaf 100644 --- a/x86/SelectLong.vp +++ b/x86/SelectLong.vp @@ -254,21 +254,33 @@ Definition shll (e1: expr) (e2: expr) := if Archi.splitlong then SplitLong.shll e1 e2 else match is_intconst e2 with | Some n2 => shllimm e1 n2 - | None => Eop Oshll (e1:::e2:::Enil) + | None => + match masked_count (Int.repr 63) e2 with + | Some t2 => Eop Oshllmask (e1:::t2:::Enil) + | None => Eop Oshll (e1:::e2:::Enil) + end end. Definition shrl (e1: expr) (e2: expr) := if Archi.splitlong then SplitLong.shrl e1 e2 else match is_intconst e2 with | Some n2 => shrlimm e1 n2 - | None => Eop Oshrl (e1:::e2:::Enil) + | None => + match masked_count (Int.repr 63) e2 with + | Some t2 => Eop Oshrlmask (e1:::t2:::Enil) + | None => Eop Oshrl (e1:::e2:::Enil) + end end. Definition shrlu (e1: expr) (e2: expr) := if Archi.splitlong then SplitLong.shrlu e1 e2 else match is_intconst e2 with | Some n2 => shrluimm e1 n2 - | _ => Eop Oshrlu (e1:::e2:::Enil) + | None => + match masked_count (Int.repr 63) e2 with + | Some t2 => Eop Oshrlumask (e1:::t2:::Enil) + | None => Eop Oshrlu (e1:::e2:::Enil) + end end. Nondetfunction addlimm (n: int64) (e: expr) := diff --git a/x86/SelectLongproof.v b/x86/SelectLongproof.v index 05ed2b36b..5328d59c0 100644 --- a/x86/SelectLongproof.v +++ b/x86/SelectLongproof.v @@ -385,7 +385,11 @@ Proof. unfold shll. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shll; auto. red; intros. destruct (is_intconst b) as [n2|] eqn:C. - exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shllimm; auto. -- TrivialExists. +- destruct (masked_count (Int.repr 63) b) as [t|] eqn:M. ++ exploit eval_masked_count; eauto. intros (v & A & B). + exists (Val.shll x (Val.and v (Vint (Int.repr 63)))); split. EvalOp. + inv B; auto. destruct x; auto. ++ TrivialExists. Qed. Theorem eval_shrlu: binary_constructor_sound shrlu Val.shrlu. @@ -393,7 +397,11 @@ Proof. unfold shrlu. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrlu; auto. red; intros. destruct (is_intconst b) as [n2|] eqn:C. - exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrluimm; auto. -- TrivialExists. +- destruct (masked_count (Int.repr 63) b) as [t|] eqn:M. ++ exploit eval_masked_count; eauto. intros (v & A & B). + exists (Val.shrlu x (Val.and v (Vint (Int.repr 63)))); split. EvalOp. + inv B; auto. destruct x; auto. ++ TrivialExists. Qed. Theorem eval_shrl: binary_constructor_sound shrl Val.shrl. @@ -401,7 +409,11 @@ Proof. unfold shrl. destruct Archi.splitlong eqn:SL. apply SplitLongproof.eval_shrl; auto. red; intros. destruct (is_intconst b) as [n2|] eqn:C. - exploit is_intconst_sound; eauto. intros EQ; subst y. apply eval_shrlimm; auto. -- TrivialExists. +- destruct (masked_count (Int.repr 63) b) as [t|] eqn:M. ++ exploit eval_masked_count; eauto. intros (v & A & B). + exists (Val.shrl x (Val.and v (Vint (Int.repr 63)))); split. EvalOp. + inv B; auto. destruct x; auto. ++ TrivialExists. Qed. Theorem eval_negl: unary_constructor_sound negl Val.negl. diff --git a/x86/SelectOp.vp b/x86/SelectOp.vp index 353b2d5a4..6f04b9c05 100644 --- a/x86/SelectOp.vp +++ b/x86/SelectOp.vp @@ -346,24 +346,62 @@ Definition shrximm (e1: expr) (n2: int) := (** ** General shifts *) -Nondetfunction shl (e1: expr) (e2: expr) := +Nondetfunction shl_base (e1: expr) (e2: expr) := match e2 with | Eop (Ointconst n2) Enil => shlimm e1 n2 | _ => Eop Oshl (e1:::e2:::Enil) end. -Nondetfunction shr (e1: expr) (e2: expr) := +Nondetfunction shr_base (e1: expr) (e2: expr) := match e2 with | Eop (Ointconst n2) Enil => shrimm e1 n2 | _ => Eop Oshr (e1:::e2:::Enil) end. -Nondetfunction shru (e1: expr) (e2: expr) := +Nondetfunction shru_base (e1: expr) (e2: expr) := match e2 with | Eop (Ointconst n2) Enil => shruimm e1 n2 | _ => Eop Oshru (e1:::e2:::Enil) end. +(** With [-fshift-mask], a shift whose count is explicitly masked, + as in [x << (y & 31)], uses a masked shift operator. The hardware + masks the count of a shift by [%cl] itself, so the [and] disappears. + [masked_count n e] returns [t] if [e] is [t & n], or the low word of + a 64-bit [t & n], as for [x << (i % 32)] with [i] of type [size_t]. *) + +Nondetfunction masked_count_base (n: int) (e: expr) := + match e with + | Eop (Oandimm m) (t:::Enil) => + if Int.eq m n then Some t else None + | Eop Olowlong (Eop (Oandlimm m) (Eop Ocast32unsigned (t:::Enil):::Enil):::Enil) => + if Int64.eq m (Int64.repr (Int.unsigned n)) then Some t else None + | Eop Olowlong (Eop (Oandlimm m) (t:::Enil):::Enil) => + if Int64.eq m (Int64.repr (Int.unsigned n)) then Some (Eop Olowlong (t:::Enil)) else None + | _ => None + end. + +Definition masked_count (n: int) (e: expr) : option expr := + if Compopts.optim_shiftmask tt then masked_count_base n e else None. + +Definition shl (e1: expr) (e2: expr) := + match masked_count (Int.repr 31) e2 with + | Some t2 => Eop Oshlmask (e1:::t2:::Enil) + | None => shl_base e1 e2 + end. + +Definition shr (e1: expr) (e2: expr) := + match masked_count (Int.repr 31) e2 with + | Some t2 => Eop Oshrmask (e1:::t2:::Enil) + | None => shr_base e1 e2 + end. + +Definition shru (e1: expr) (e2: expr) := + match masked_count (Int.repr 31) e2 with + | Some t2 => Eop Oshrumask (e1:::t2:::Enil) + | None => shru_base e1 e2 + end. + (** ** Floating-point arithmetic *) Definition negf (e: expr) := Eop Onegf (e ::: Enil). diff --git a/x86/SelectOpproof.v b/x86/SelectOpproof.v index b49b15e67..89dfefeb3 100644 --- a/x86/SelectOpproof.v +++ b/x86/SelectOpproof.v @@ -583,25 +583,92 @@ Proof. econstructor; split. EvalOp. auto. Qed. +(** Shifts with a masked count ([-fshift-mask]). *) + +Remark loword_and: + forall a b, Int64.loword (Int64.and a b) = Int.and (Int64.loword a) (Int64.loword b). +Proof. + intros. apply Int.same_bits_eq; intros. unfold Int64.loword. + change Int.zwordsize with 32 in H. + rewrite Int.bits_and by (change Int.zwordsize with 32; lia). + rewrite !Int.testbit_repr by (change Int.zwordsize with 32; lia). + change (Z.testbit (Int64.unsigned (Int64.and a b)) i) with (Int64.testbit (Int64.and a b) i). + rewrite Int64.bits_and by (change Int64.zwordsize with 64; lia). auto. +Qed. + +Remark loword_repr_unsigned: + forall n, Int64.loword (Int64.repr (Int.unsigned n)) = n. +Proof. + intros. unfold Int64.loword. rewrite Int64.unsigned_repr. apply Int.repr_unsigned. + generalize (Int.unsigned_range n). unfold Int.modulus, Int64.max_unsigned, Int64.modulus. + change (two_power_nat Int.wordsize) with 4294967296. + change (two_power_nat Int64.wordsize) with 18446744073709551616. lia. +Qed. + +Ltac InvEvalAll := + repeat match goal with + | [ H: eval_expr _ _ _ _ _ (Eop _ _) _ |- _ ] => inv H + | [ H: eval_exprlist _ _ _ _ _ Enil _ |- _ ] => inv H + | [ H: eval_exprlist _ _ _ _ _ (_ ::: _) _ |- _ ] => inv H + | [ H: eval_operation _ _ _ _ _ = Some _ |- _ ] => simpl in H; inv H + end. + +Lemma eval_masked_count: + forall le n b t y, + masked_count n b = Some t -> + eval_expr ge sp e m le b y -> + exists v, eval_expr ge sp e m le t v /\ Val.lessdef y (Val.and v (Vint n)). +Proof. + unfold masked_count; intros until y. + destruct (Compopts.optim_shiftmask tt); try discriminate. + unfold masked_count_base; case (masked_count_base_match b); intros; try discriminate. +- destruct (Int.eq m0 n) eqn:E; inv H. + apply Int.same_if_eq in E; subst m0. InvEval. eauto. +- destruct (Int64.eq m0 (Int64.repr (Int.unsigned n))) eqn:E; inv H. + apply Int64.same_if_eq in E; subst m0. InvEvalAll. eexists; split; [eassumption|]. + match goal with |- Val.lessdef _ (Val.and ?v _) => destruct v end; simpl; auto. + rewrite loword_and, !loword_repr_unsigned; auto. +- destruct (Int64.eq m0 (Int64.repr (Int.unsigned n))) eqn:E; inv H. + apply Int64.same_if_eq in E; subst m0. InvEvalAll. + match goal with H: eval_expr _ _ _ _ _ _ ?v |- _ => exists (Val.loword v); split; [EvalOp|destruct v] end; + simpl; auto. rewrite loword_and, loword_repr_unsigned; auto. +Qed. + + Theorem eval_shl: binary_constructor_sound shl Val.shl. Proof. - red; intros until y; unfold shl; case (shl_match b); intros. -- InvEval. apply eval_shlimm; auto. -- TrivialExists. + red; intros until y; intros EA EB; unfold shl. + destruct (masked_count (Int.repr 31) b) as [t|] eqn:M. +- exploit eval_masked_count; eauto. intros (v & A & B). + exists (Val.shl x (Val.and v (Vint (Int.repr 31)))); split. EvalOp. + inv B; auto. destruct x; auto. +- revert EA EB. unfold shl_base; case (shl_base_match b); intros. ++ InvEval. apply eval_shlimm; auto. ++ TrivialExists. Qed. Theorem eval_shr: binary_constructor_sound shr Val.shr. Proof. - red; intros until y; unfold shr; case (shr_match b); intros. -- InvEval. apply eval_shrimm; auto. -- TrivialExists. + red; intros until y; intros EA EB; unfold shr. + destruct (masked_count (Int.repr 31) b) as [t|] eqn:M. +- exploit eval_masked_count; eauto. intros (v & A & B). + exists (Val.shr x (Val.and v (Vint (Int.repr 31)))); split. EvalOp. + inv B; auto. destruct x; auto. +- revert EA EB. unfold shr_base; case (shr_base_match b); intros. ++ InvEval. apply eval_shrimm; auto. ++ TrivialExists. Qed. Theorem eval_shru: binary_constructor_sound shru Val.shru. Proof. - red; intros until y; unfold shru; case (shru_match b); intros. -- InvEval. apply eval_shruimm; auto. -- TrivialExists. + red; intros until y; intros EA EB; unfold shru. + destruct (masked_count (Int.repr 31) b) as [t|] eqn:M. +- exploit eval_masked_count; eauto. intros (v & A & B). + exists (Val.shru x (Val.and v (Vint (Int.repr 31)))); split. EvalOp. + inv B; auto. destruct x; auto. +- revert EA EB. unfold shru_base; case (shru_base_match b); intros. ++ InvEval. apply eval_shruimm; auto. ++ TrivialExists. Qed. Theorem eval_negf: unary_constructor_sound negf Val.negf. diff --git a/x86/ValueAOp.v b/x86/ValueAOp.v index 3740f40fb..7ceb3ed64 100644 --- a/x86/ValueAOp.v +++ b/x86/ValueAOp.v @@ -166,6 +166,12 @@ Definition eval_static_operation (op: operation) (vl: list aval): aval := | Osingleoflong, v1::nil => singleoflong v1 | Ocmp c, _ => of_optbool (eval_static_condition c vl) | Osel c ty, v1::v2::vl => select (eval_static_condition c vl) v1 v2 ty + | Oshlmask, v1::v2::nil => shl v1 (and v2 (I (Int.repr 31))) + | Oshrmask, v1::v2::nil => shr v1 (and v2 (I (Int.repr 31))) + | Oshrumask, v1::v2::nil => shru v1 (and v2 (I (Int.repr 31))) + | Oshllmask, v1::v2::nil => shll v1 (and v2 (I (Int.repr 63))) + | Oshrlmask, v1::v2::nil => shrl v1 (and v2 (I (Int.repr 63))) + | Oshrlumask, v1::v2::nil => shrlu v1 (and v2 (I (Int.repr 63))) | _, _ => Vbot end.