Debian Codegraph @

src/ArithmeticCPS/Core.v

raw
1 (* Following http://adam.chlipala.net/theses/andreser.pdf chapter 3 *)
2 From Coq Require Import ZArith Lia.
3 From Coq Require Import Orders.
4 From Coq Require Import List.
5 Require Import Crypto.Algebra.Nsatz.
6 Require Import Crypto.Arithmetic.ModularArithmeticTheorems.
7 Require Import Crypto.Util.Decidable.
8 Require Import Crypto.Util.LetIn.
9 Require Import Crypto.Util.ListUtil.
10 Require Import Crypto.Util.NatUtil.
11 Require Import Crypto.Util.Prod.
12 Require Import Crypto.Util.Decidable.Bool2Prop.
13 Require Import Crypto.Util.Tactics.SpecializeBy.
14 Require Import Crypto.Util.Tactics.UniquePose.
15 Require Import Crypto.Util.CPSUtil.
16 Require Import Crypto.Util.CPSNotations.
17 Require Import Crypto.Util.ZUtil.Definitions.
18 Require Import Crypto.Util.ZUtil.EquivModulo.
19 Require Import Crypto.Util.ZUtil.Modulo Crypto.Util.ZUtil.Div.
20 Require Import Crypto.Util.ZUtil.Zselect.
21 Require Import Crypto.Util.ZUtil.Hints.Core.
22 Require Import Crypto.Util.ZUtil.Modulo.PullPush.
23 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
24 Require Import Crypto.Util.ZUtil.Tactics.DivModToQuotRem.
25 Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.
26 Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
27 Require Import Crypto.Util.Notations.
28 Import ListNotations. Local Open Scope Z_scope.
29
30
31 Reserved Notation "'dlet_list_pair_only_snd' x := v 'in' f"
32 (at level 200, f at level 200, format "'dlet_list_pair_only_snd' x := v 'in' '//' f").
33 Reserved Notation "'dlet_list_pair' x := v 'in' f"
34 (at level 200, f at level 200, format "'dlet_list_pair' x := v 'in' '//' f").
35 Reserved Notation "'dlet_list' x := v 'in' f"
36 (at level 200, f at level 200, format "'dlet_list' x := v 'in' '//' f").
37 Declare Scope runtime_scope.
38 Delimit Scope runtime_scope with RT.
39 Import CPSBindNotations.
40 Local Open Scope cps_scope.
41
42 Module Type Runtime.
43 Parameter Let_In : forall {A P} (x : A) (f : forall a : A, P a), P x.
44 Parameter runtime_nth_default : forall {A}, A -> list A -> nat -> A.
45 Parameter runtime_add : Z -> Z -> Z.
46 Parameter runtime_sub : Z -> Z -> Z.
47 Parameter runtime_mul : Z -> Z -> Z.
48 Parameter runtime_div : Z -> Z -> Z.
49 Parameter runtime_modulo : Z -> Z -> Z.
50 Parameter runtime_opp : Z -> Z.
51 Arguments runtime_add (_ _)%RT.
52 Arguments runtime_sub (_ _)%RT.
53 Arguments runtime_mul (_ _)%RT.
54 Arguments runtime_div _%RT _%Z.
55 Arguments runtime_modulo _%RT _%Z.
56 Arguments runtime_opp _%RT.
57 Infix "*" := runtime_mul : runtime_scope.
58 Infix "+" := runtime_add : runtime_scope.
59 Infix "-" := runtime_sub : runtime_scope.
60 Infix "/" := runtime_div : runtime_scope.
61 Notation "x 'mod' y" := (runtime_modulo x y) : runtime_scope.
62 Notation "- x" := (runtime_opp x) : runtime_scope.
63 Notation "'dlet_nd' x .. y := v 'in' f" := (Let_In (P:=fun _ => _) v (fun x => .. (fun y => f) .. )) (only parsing).
64 Notation "'dlet' x .. y := v 'in' f" := (Let_In v (fun x => .. (fun y => f) .. )).
65
66 Module RT_Z.
67 Parameter zselect : Z -> Z -> Z -> Z.
68 Parameter add_get_carry_full : Z -> Z -> Z -> Z * Z.
69 Parameter add_with_get_carry_full : Z -> Z -> Z -> Z -> Z * Z.
70 Parameter mul_split : Z -> Z -> Z -> Z * Z.
71 Parameter land : Z -> Z -> Z.
72 End RT_Z.
73 End Runtime.
74
75 Module RuntimeDefinitions <: Runtime.
76 Definition Let_In := @LetIn.Let_In.
77 Definition runtime_nth_default := List.nth_default.
78 Definition runtime_add := Z.add.
79 Definition runtime_sub := Z.sub.
80 Definition runtime_mul := Z.mul.
81 Definition runtime_opp := Z.opp.
82 Definition runtime_div := Z.div.
83 Definition runtime_modulo := Z.modulo.
84 Module RT_Z.
85 Definition zselect := Z.zselect.
86 Definition add_get_carry_full := Z.add_get_carry_full.
87 Definition add_with_get_carry_full := Z.add_with_get_carry_full.
88 Definition mul_split := Z.mul_split.
89 Definition land := Z.land.
90 End RT_Z.
91 End RuntimeDefinitions.
92
93 Module RuntimeAxioms : Runtime.
94 Include RuntimeDefinitions.
95 End RuntimeAxioms.
96
97 Module Export RuntimeDefinitionsCbv.
98 Import RuntimeDefinitions.
99 Declare Reduction cbv_no_rt
100 := cbv -[Let_In
101 runtime_nth_default
102 runtime_add
103 runtime_sub
104 runtime_mul
105 runtime_opp
106 runtime_div
107 runtime_modulo
108 RT_Z.add_get_carry_full
109 RT_Z.add_with_get_carry_full
110 RT_Z.mul_split].
111 Declare Reduction lazy_no_rt
112 := lazy -[Let_In
113 runtime_nth_default
114 runtime_add
115 runtime_sub
116 runtime_mul
117 runtime_opp
118 runtime_div
119 runtime_modulo
120 RT_Z.add_get_carry_full
121 RT_Z.add_with_get_carry_full
122 RT_Z.mul_split].
123 Declare Reduction pattern_rt
124 := pattern Let_In,
125 runtime_nth_default,
126 runtime_add,
127 runtime_sub,
128 runtime_mul,
129 runtime_opp,
130 runtime_div,
131 runtime_modulo,
132 RT_Z.add_get_carry_full,
133 RT_Z.add_with_get_carry_full,
134 RT_Z.mul_split.
135
136 Import RuntimeAxioms.
137 Declare Reduction pattern_ax_rt
138 := pattern (@Let_In),
139 (@runtime_nth_default),
140 runtime_add,
141 runtime_sub,
142 runtime_mul,
143 runtime_opp,
144 runtime_div,
145 runtime_modulo,
146 RT_Z.add_get_carry_full,
147 RT_Z.add_with_get_carry_full,
148 RT_Z.mul_split.
149 End RuntimeDefinitionsCbv.
150
151 Module RT_Extra (Import RT : Runtime).
152 Fixpoint dlet_nd_list_pair {A B} (ls : list (A * B)) {T} (f : list (A * B) -> T) : T
153 := match ls with
154 | nil => f nil
155 | cons x xs
156 => dlet_nd x1 := fst x in dlet_nd x2 := snd x in @dlet_nd_list_pair A B xs T (fun xs => f ((x1, x2) :: xs))
157 end.
158
159 Fixpoint dlet_nd_list {A} (ls : list A) {T} (f : list A -> T) : T
160 := match ls with
161 | nil => f nil
162 | cons x xs
163 => dlet_nd x := x in @dlet_nd_list A xs T (fun xs => f (x :: xs))
164 end.
165
166 Fixpoint dlet_nd_list_pair_only_snd {A B} (ls : list (A * B)) {T} (f : list (A * B) -> T) : T
167 := match ls with
168 | nil => f nil
169 | cons x xs
170 => dlet_nd x2 := snd x in @dlet_nd_list_pair_only_snd A B xs T (fun xs => f ((fst x, x2) :: xs))
171 end.
172
173 Notation "'dlet_list_pair_only_snd' x := v 'in' f" := (dlet_nd_list_pair_only_snd v (fun x => f)).
174 Notation "'dlet_list_pair' x := v 'in' f" := (dlet_nd_list_pair v (fun x => f)).
175 Notation "'dlet_list' x := v 'in' f" := (dlet_nd_list v (fun x => f)).
176
177
178 Definition expand_list_helper {A} (default : A) (ls : list A) (n : nat) (idx : nat) : list A
179 := nat_rect
180 (fun _ => nat -> list A)
181 (fun _ => nil)
182 (fun n' rec_call idx
183 => cons (runtime_nth_default default ls idx) (rec_call (S idx)))
184 n
185 idx.
186 Definition expand_list {A} (default : A) (ls : list A) (n : nat) : list A
187 := expand_list_helper default ls n 0.
188 End RT_Extra.
189
190 Module Associational (Import RT : Runtime).
191 Module Import Deps.
192 Module Export RT_Extra := RT_Extra RT.
193 End Deps.
194 Definition eval (p:list (Z*Z)) : Z :=
195 fold_right (fun x y => x + y) 0%Z (map (fun t => fst t * snd t) p).
196
197 Definition mul (p q:list (Z*Z)) : list (Z*Z) :=
198 flat_map (fun t =>
199 map (fun t' =>
200 (fst t * fst t', (snd t * snd t')%RT))
201 q) p.
202
203 Definition square_cps (p:list (Z*Z)) : ~> list (Z*Z) :=
204 list_rect
205 _
206 (return nil)
207 (fun t ts acc T k
208 => (dlet two_t2 := (2 * snd t)%RT in
209 acc
210 _
211 (fun acc
212 => k (((fst t * fst t, (snd t * snd t)%RT)
213 :: (map (fun t'
214 => (fst t * fst t', (two_t2 * snd t')%RT))
215 ts))
216 ++ acc))))
217 p.
218
219 Definition negate_snd (p:list (Z*Z)) : list (Z*Z) :=
220 map (fun cx => (fst cx, (-snd cx)%RT)) p.
221
222 Definition split (s:Z) (p:list (Z*Z)) : list (Z*Z) * list (Z*Z)
223 := let hi_lo := partition (fun t => fst t mod s =? 0) p in
224 (snd hi_lo, map (fun t => (fst t / s, snd t)) (fst hi_lo)).
225
226 Definition reduce (s:Z) (c:list _) (p:list _) : list (Z*Z) :=
227 let lo_hi := split s p in fst lo_hi ++ mul c (snd lo_hi).
228
229 (* reduce at most [n] times, stopping early if the high list is nil at any point *)
230 Definition repeat_reduce (n : nat) (s:Z) (c:list _) (p:list _) : list (Z * Z)
231 := nat_rect
232 _
233 (fun p => p)
234 (fun n' repeat_reduce_n' p
235 => let lo_hi := split s p in
236 if (length (snd lo_hi) =? 0)%nat
237 then p
238 else let p := fst lo_hi ++ mul c (snd lo_hi) in
239 repeat_reduce_n' p)
240 n
241 p.
242
243 (* rough template (we actually have to do things a bit differently to account for duplicate weights):
244 [ dlet fi_c := c * fi in
245 let (fj_high, fj_low) := split fj at s/fi.weight in
246 dlet fi_2 := 2 * fi in
247 dlet fi_2_c := 2 * fi_c in
248 (if fi.weight^2 >= s then fi_c * fi else fi * fi)
249 ++ fi_2_c * fj_high
250 ++ fi_2 * fj_low
251 | fi <- f , fj := (f weight less than i) ]
252 *)
253 (** N.B. We take advantage of dead code elimination to allow us to
254 let-bind partial products that we don't end up using *)
255 (** [v] -> [(v, v*c, v*c*2, v*2)] *)
256 Definition let_bind_for_reduce_square_cps (c:list (Z*Z)) (p:list (Z*Z)) : ~> list ((Z*Z) * list(Z*Z) * list(Z*Z) * list(Z*Z)) :=
257 fun T
258 => let two := [(1,2)] (* (weight, value) *) in
259 map_cps2 (fun t T k => dlet_list_pair_only_snd c_t := mul [t] c in dlet_list_pair_only_snd two_c_t := mul c_t two in dlet_list_pair_only_snd two_t := mul [t] two in k (t, c_t, two_c_t, two_t)) p.
260 Definition reduce_square_cps (s:Z) (c:list (Z*Z)) (p:list (Z*Z)) : ~>list (Z*Z) :=
261 (p <- let_bind_for_reduce_square_cps c p;
262 let div_s := map (fun t => (fst t / s, snd t)) in
263 return (list_rect
264 _
265 nil
266 (fun t ts acc
267 => (let '(t, c_t, two_c_t, two_t) := t in
268 (if ((fst t * fst t) mod s =? 0)
269 then div_s (mul [t] c_t)
270 else mul [t] [t])
271 ++ (flat_map
272 (fun '(t', c_t', two_c_t', two_t')
273 => if ((fst t * fst t') mod s =? 0)
274 then div_s
275 (if fst t' <=? fst t
276 then mul [t'] two_c_t
277 else mul [t] two_c_t')
278 else (if fst t' <=? fst t
279 then mul [t'] two_t
280 else mul [t] two_t'))
281 ts))
282 ++ acc)
283 p)).
284
285 Definition bind_snd_cps (p : list (Z*Z)) : ~>list (Z * Z) :=
286 @dlet_nd_list_pair_only_snd _ _ p.
287
288 Section Carries.
289 Definition carryterm_cps (w fw:Z) (t:Z * Z) : ~> list (Z * Z) :=
290 fun T k
291 => if (Z.eqb (fst t) w)
292 then dlet_nd t2 := snd t in
293 dlet_nd d2 := (t2 / fw)%RT in
294 dlet_nd m2 := (t2 mod fw)%RT in
295 k [(w * fw, d2);(w,m2)]
296 else k [t].
297
298 Definition carry_cps (w fw:Z) (p:list (Z * Z)) : ~> list (Z * Z):=
299 fun T => flat_map_cps (carryterm_cps w fw) p.
300 End Carries.
301 End Associational.
302
303 Module Positional (Import RT : Runtime).
304 Module Import Deps.
305 Module Associational := Associational RT.
306 End Deps.
307 Section Positional.
308 Context (weight : nat -> Z).
309
310 Definition to_associational (n:nat) (xs:list Z) : list (Z*Z)
311 := combine (map weight (List.seq 0 n)) xs.
312 Definition eval n x := Associational.eval (@to_associational n x).
313 Definition zeros n : list Z := repeat 0 n.
314 Definition add_to_nth i x (ls : list Z) : list Z
315 := ListUtil.update_nth i (fun y => (x + y)%RT) ls.
316
317 Definition place (t:Z*Z) (i:nat) : nat * Z :=
318 nat_rect
319 (fun _ => unit -> (nat * Z)%type)
320 (fun _ => (O, if fst t =? 1 then snd t else (fst t * snd t)%RT))
321 (fun i' place_i' _
322 => let i := S i' in
323 if (fst t mod weight i =? 0)
324 then (i, let c := fst t / weight i in if c =? 1 then snd t else (c * snd t)%RT)
325 else place_i' tt)
326 i
327 tt.
328
329 Definition from_associational_cps n (p:list (Z*Z)) : ~> list Z :=
330 fun T => fold_right_cps2 (fun t ls T k =>
331 let '(p1, p2) := place t (pred n) in
332 dlet_nd p2 := p2 in
333 k (add_to_nth p1 p2 ls)) (zeros n) p.
334
335 Definition extend_to_length (n_in n_out : nat) (p:list Z) : list Z :=
336 p ++ zeros (n_out - n_in).
337
338 Definition drop_high_to_length (n : nat) (p:list Z) : list Z :=
339 firstn n p.
340
341 Section mulmod.
342 Context (s:Z)
343 (c:list (Z*Z)).
344 Definition mulmod_cps (n:nat) (a b:list Z) : ~> list Z
345 := let a_a := to_associational n a in
346 let b_a := to_associational n b in
347 let ab_a := Associational.mul a_a b_a in
348 let abm_a := Associational.repeat_reduce n s c ab_a in
349 from_associational_cps n abm_a.
350
351 Definition squaremod_cps (n:nat) (a:list Z) : ~> list Z
352 := (let a_a := to_associational n a in
353 aa_a <- Associational.reduce_square_cps s c a_a;
354 let aam_a := Associational.repeat_reduce (pred n) s c aa_a in
355 from_associational_cps n aam_a).
356 End mulmod.
357
358 Definition add_cps (n:nat) (a b:list Z) : ~> list Z
359 := let a_a := to_associational n a in
360 let b_a := to_associational n b in
361 from_associational_cps n (a_a ++ b_a).
362
363 Section Carries.
364 Definition carry_cps n m (index:nat) (p:list Z) : ~> list Z :=
365 (p <- @Associational.carry_cps (weight index)
366 (weight (S index) / weight index)
367 (to_associational n p);
368 from_associational_cps
369 m p).
370
371 Definition carry_reduce_cps n (s:Z) (c:list (Z * Z))
372 (index:nat) (p : list Z) : ~> list Z :=
373 (p <- @carry_cps n (S n) index p;
374 p <- from_associational_cps
375 n (Associational.reduce
376 s c (to_associational (S n) p));
377 return p).
378
379 (* N.B. It is important to reverse [idxs] here, because fold_right is
380 written such that the first terms in the list are actually used
381 last in the computation. For example, running:
382
383 `Eval cbv - [Z.add] in (fun a b c d => fold_right Z.add d [a;b;c]).`
384
385 will produce [fun a b c d => (a + (b + (c + d)))].*)
386 Definition chained_carries_cps n s c p (idxs : list nat) : ~> _ :=
387 fun T => fold_right_cps2 (fun a b => carry_reduce_cps n s c a b) p (rev idxs).
388
389 (* carries without modular reduction; useful for converting between bases *)
390 Definition chained_carries_no_reduce_cps n p (idxs : list nat) : ~> _ :=
391 fun T => fold_right_cps2 (fun a b => carry_cps n n a b) p (rev idxs).
392
393 (* Reverse of [eval]; translate from Z to basesystem by putting
394 everything in first digit and then carrying. *)
395 Definition encode_cps n s c (x : Z) : ~> list Z :=
396 (p <- from_associational_cps n [(1,x)]; chained_carries_cps n s c p (seq 0 n)).
397
398 (* Reverse of [eval]; translate from Z to basesystem by putting
399 everything in first digit and then carrying, but without reduction. *)
400 Definition encode_no_reduce_cps n (x : Z) : ~> list Z :=
401 (p <- from_associational_cps n [(1,x)]; chained_carries_no_reduce_cps n p (seq 0 n)).
402 End Carries.
403
404 Section sub.
405 Context (n:nat)
406 (s:Z)
407 (c:list (Z * Z))
408 (coef:Z).
409
410 Definition negate_snd_cps (a:list Z) : ~> list Z
411 := let A := to_associational n a in
412 let negA := Associational.negate_snd A in
413 from_associational_cps n negA.
414
415 Definition scmul_cps (x:Z) (a:list Z) : ~> list Z
416 := let A := to_associational n a in
417 let R := Associational.mul A [(1, x)] in
418 from_associational_cps n R.
419
420 Definition balance_cps : ~> list Z
421 := (sc <- encode_cps n s c (s - Associational.eval c); v <- scmul_cps coef sc; return v).
422
423 Definition sub_cps (a b:list Z) : ~> list Z
424 := (balance <- balance_cps;
425 ca <- add_cps n balance a;
426 _b <- negate_snd_cps b;
427 camb <- add_cps n ca _b;
428 return camb).
429
430 Definition opp_cps (a:list Z) : ~> list Z
431 := sub_cps (zeros n) a.
432 End sub.
433
434 Section select.
435 Definition zselect_cps (mask cond:Z) (p:list Z) : ~> _ :=
436 fun T k => dlet t := RT_Z.zselect cond 0 mask in k (List.map (RT_Z.land t) p).
437
438 Definition select (cond:Z) (if_zero if_nonzero:list Z) :=
439 List.map (fun '(p, q) => RT_Z.zselect cond p q) (List.combine if_zero if_nonzero).
440 End select.
441 End Positional.
442 End Positional.