Debian Codegraph @

src/Assembly/Symbolic.v

raw
1 Require Crypto.Assembly.Parse.
2 From Coq.Program Require Import Tactics.
3 From Coq Require Import Derive.
4 From Coq Require Import List.
5 From Coq Require Import Lia.
6 From Coq Require Import ZArith.
7 From Coq Require Import NArith.
8 From Coq Require Import Permutation.
9 From Coq Require Import Equalities.
10 From Coq Require Import OrderedType.
11 From Coq Require Import Orders.
12 From Coq Require Import FMapInterface.
13 From Coq Require Import FMapPositive.
14 From Coq Require Import FMapFacts.
15 Require Crypto.Util.ZRange.
16 Require Crypto.Util.Tuple.
17 Require Import Util.OptionList.
18 Require Import Crypto.Util.ErrorT.
19 Require Import Crypto.Util.ZUtil.Tactics.PullPush.Modulo.
20 Require Import Crypto.Util.ZUtil.Tactics.LtbToLt.
21 Require Import Crypto.Util.ZUtil.Testbit.
22 Require Import Crypto.Util.ZUtil.Hints.ZArith.
23 Require Import Crypto.Util.ZUtil.Land.
24 Require Import Crypto.Util.ZUtil.Land.Fold.
25 Require Import Crypto.Util.ZUtil.Ones.
26 Require Import Crypto.Util.ZUtil.Definitions.
27 Require Import Crypto.Util.ZUtil.Signed.
28 Require Import Crypto.Util.Equality.
29 Require Import Crypto.Util.Bool.Reflect.
30 Require Import Crypto.Util.Option.
31 Require Import Crypto.Util.Strings.Subscript.
32 Require Import Crypto.Util.Structures.Orders.
33 Require Import Crypto.Util.Structures.Equalities.
34 Require Import Crypto.Util.Structures.Equalities.Iso.
35 Require Import Crypto.Util.Structures.Equalities.Prod.
36 Require Import Crypto.Util.Structures.Equalities.Option.
37 Require Import Crypto.Util.Structures.Orders.Iso.
38 Require Import Crypto.Util.Structures.Orders.Prod.
39 Require Import Crypto.Util.Structures.Orders.Option.
40 Require Import Crypto.Util.Structures.OrdersEx.
41 Require Import Crypto.Util.ListUtil.
42 Require Import Crypto.Util.ListUtil.Concat.
43 Require Import Crypto.Util.ListUtil.GroupAllBy.
44 Require Import Crypto.Util.ListUtil.FoldMap. Import FoldMap.List.
45 Require Import Crypto.Util.ListUtil.IndexOf. Import IndexOf.List.
46 Require Import Crypto.Util.ListUtil.Forall.
47 Require Import Crypto.Util.ListUtil.Permutation.
48 Require Import Crypto.Util.ListUtil.Partition.
49 Require Import Crypto.Util.ListUtil.Filter.
50 Require Import Crypto.Util.NUtil.Sorting.
51 Require Import Crypto.Util.NUtil.Testbit.
52 Require Import Crypto.Util.FSets.FMapOption.
53 Require Import Crypto.Util.FSets.FMapN.
54 Require Import Crypto.Util.FSets.FMapZ.
55 Require Import Crypto.Util.FSets.FMapProd.
56 Require Import Crypto.Util.FSets.FMapIso.
57 Require Import Crypto.Util.FSets.FMapSect.
58 Require Import Crypto.Util.FSets.FMapInterface.
59 Require Import Crypto.Util.FSets.FMapFacts.
60 Require Import Crypto.Util.FSets.FMapTrieEx.
61 Require Import Crypto.Util.MSets.MSetN.
62 Require Import Crypto.Util.Bool.LeCompat.
63 Require Import Crypto.Util.Tactics.DestructHead.
64 Require Import Crypto.Util.Tactics.SetEvars.
65 Require Import Crypto.Util.Prod.
66 Require Import Crypto.Util.Tactics.SplitInContext.
67 Require Import Crypto.Util.Tactics.SpecializeBy.
68 Require Import Crypto.Util.Tactics.SpecializeAllWays.
69 Require Import Crypto.Util.Tactics.SpecializeUnderBindersBy.
70 Require Import Crypto.Util.Tactics.InHypUnderBindersDo.
71 Require Import Crypto.Util.Tactics.Head.
72 Require Import Crypto.Util.Tactics.UniquePose.
73 Require Import Crypto.Util.ZUtil.Lxor.
74 Require Import Crypto.Util.ZUtil.Tactics.PeelLe.
75 Require Import Crypto.Util.ZUtil.Tactics.RewriteModSmall.
76 Require Import Crypto.Util.Listable.
77 Require Import Crypto.Util.Strings.Parse.Common.
78 Require Import Crypto.Util.Tactics.WarnIfGoalsRemain.
79 Require Import Crypto.Util.Bool.Reflect.
80 Require Import coqutil.Z.bitblast.
81 From Coq Require Import String.
82 Require Import Crypto.Util.Strings.Show.
83 Require Import Crypto.Util.Strings.Show.Enum.
84 Require Import Crypto.Assembly.Syntax.
85 Import ListNotations.
86 Definition idx := N.
87 Local Set Decidable Equality Schemes.
88 Definition symbol := N.
89
90 Class OperationSize := operation_size : N.
91 Global Instance Show_OperationSize : Show OperationSize := show_N.
92
93 Section S.
94 Implicit Type s : OperationSize.
95 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 (* | ... *)
96 | addZ | mulZ | negZ | shlZ | shrZ | andZ | orZ | xorZ | addcarryZ s | subborrowZ s.
97 Definition op_beq a b := if op_eq_dec a b then true else false.
98 End S.
99
100 Global Instance Show_op : Show op := fun o =>
101 match o with
102 | old s n => "old " ++ show s ++ " " ++ show n
103 | const n => "const " ++ show n
104 | add s => "add " ++ show s
105 | addcarry s => "addcarry " ++ show s
106 | subborrow s => "subborrow " ++ show s
107 | addoverflow s => "addoverflow " ++ show s
108 | neg s => "neg " ++ show s
109 | shl s => "shl " ++ show s
110 | shr s => "shr " ++ show s
111 | sar s => "sar " ++ show s
112 | rcr s => "rcr " ++ show s
113 | and s => "and " ++ show s
114 | or s => "or " ++ show s
115 | xor s => "xor " ++ show s
116 | slice lo sz => "slice " ++ show lo ++ " " ++ show sz
117 | mul s => "mul " ++ show s
118 | set_slice lo sz => "set_slice " ++ show lo ++ " " ++ show sz
119 | selectznz => "selectznz"
120 | iszero => "iszero"
121 | addZ => "addZ"
122 | mulZ => "mulZ"
123 | negZ => "negZ"
124 | shlZ => "shlZ"
125 | shrZ => "shrZ"
126 | andZ => "andZ"
127 | orZ => "orZ"
128 | xorZ => "xorZ"
129 | addcarryZ s => "addcarryZ " ++ show s
130 | subborrowZ s => "subborrowZ " ++ show s
131 end%string.
132
133 Definition show_op_subscript : Show op := fun o =>
134 match o with
135 | old s n => "old" ++ String.to_subscript (show s) ++ " " ++ show n
136 | const n => "const " ++ show n
137 | add s => "add" ++ String.to_subscript (show s)
138 | addcarry s => "addcarry" ++ String.to_subscript (show s)
139 | subborrow s => "subborrow" ++ String.to_subscript (show s)
140 | addoverflow s => "addoverflow" ++ String.to_subscript (show s)
141 | neg s => "neg" ++ String.to_subscript (show s)
142 | shl s => "shl" ++ String.to_subscript (show s)
143 | shr s => "shr" ++ String.to_subscript (show s)
144 | sar s => "sar" ++ String.to_subscript (show s)
145 | rcr s => "rcr" ++ String.to_subscript (show s)
146 | and s => "and" ++ String.to_subscript (show s)
147 | or s => "or" ++ String.to_subscript (show s)
148 | xor s => "xor" ++ String.to_subscript (show s)
149 | slice lo sz => "slice" ++ String.to_subscript (show lo) ++ "," ++ String.to_subscript (show sz)
150 | mul s => "mul" ++ String.to_subscript (show s)
151 | set_slice lo sz => "set_slice" ++ String.to_subscript (show lo) ++ "," ++ String.to_subscript (show sz)
152 | selectznz => "selectznz"
153 | iszero => "iszero"
154 | addZ => "addℤ"
155 | mulZ => "mulℤ"
156 | negZ => "negℤ"
157 | shlZ => "shlℤ"
158 | shrZ => "shrℤ"
159 | andZ => "andℤ"
160 | orZ => "orℤ"
161 | xorZ => "xorℤ"
162 | addcarryZ s => "addcarryℤ" ++ String.to_subscript (show s)
163 | subborrowZ s => "subborrowℤ" ++ String.to_subscript (show s)
164 end%string.
165
166 Module FMapOp.
167 Definition op_args : Set := (option OperationSize * (option symbol * (option Z * (option N * option N)))).
168 Definition op' : Set := N * op_args.
169 Definition eta_op_cps {T} (k : op -> T) (o : op) : T.
170 Proof.
171 pose o as o'.
172 destruct o.
173 all: let v := (eval cbv [o'] in o') in
174 exact (k v).
175 Defined.
176
177 Definition nat_of_op (o : op) : nat.
178 Proof.
179 evar (base : nat).
180 destruct o.
181 all: let rec peel_S val :=
182 lazymatch val with
183 | S ?val => apply S; peel_S val
184 | ?ev => is_evar ev;
185 let __ := open_constr:(eq_refl : ev = S _) in
186 exact O
187 end in
188 let v := (eval cbv [base] in base) in
189 peel_S v.
190 Unshelve.
191 exact O.
192 Defined.
193
194 Definition args_of_op (o : op) : op_args.
195 Proof.
196 destruct o; hnf.
197 all: repeat lazymatch reverse goal with
198 | [ H : ?T |- ?A * ?B ]
199 => lazymatch A with
200 | context[option T]
201 => split; [ | clear H ]
202 | _ => split; [ repeat apply pair; exact None | ]
203 end
204 | [ H : ?T |- _ ]
205 => lazymatch goal with
206 | [ |- option T ] => exact (Some H)
207 | [ |- _ ] => idtac "bad"
208 end
209 | [ |- _ * _ ] => split
210 | [ |- option _ ] => exact None
211 end.
212 Defined.
213
214 Definition op'_of_op : op -> op'
215 := Eval compute in eta_op_cps (fun o => (N.of_nat (nat_of_op o), args_of_op o)).
216
217 Derive op_of_op'_opt
218 SuchThat ((forall (o : op), op_of_op'_opt (op'_of_op o) = Some o)
219 /\ (forall (n n' : op'), option_map op'_of_op (op_of_op'_opt n) = Some n' -> n = n'))
220 As op_op'_correct.
221 Proof.
222 instantiate (1:=ltac:(intros [n v]; hnf in v; destruct_head'_prod; destruct n as [|n])) in (value of op_of_op'_opt).
223 subst op_of_op'_opt.
224 split.
225 { intro o; destruct o; cbv [op'_of_op].
226 all: [ > cbv beta iota;
227 lazymatch goal with
228 | [ |- ?ev = Some _ ]
229 => is_evar ev;
230 let H := fresh in
231 pose ev as H;
232 instantiate (1:=ltac:(lazymatch goal with
233 | [ n : positive |- _ ]
234 => destruct n
235 | _ => idtac
236 end)) in (value of H);
237 subst H; cbv beta iota
238 end .. ].
239 all: lazymatch goal with
240 | [ |- ?ev = Some ?v ]
241 => is_evar ev;
242 let h := head v in
243 let H := fresh in
244 pose ev as H;
245 instantiate (1:=ltac:(reverse)) in (value of H);
246 subst H;
247 repeat match goal with
248 | [ |- context[?ev ?x] ]
249 => is_evar ev;
250 let H := fresh in
251 pose ev as H;
252 lazymatch x with
253 | Some _
254 => instantiate (1:=ltac:(let x := fresh "x" in intro x; intros; destruct x; [ reverse | exact None ])) in (value of H)
255 | None
256 => instantiate (1:=ltac:(let x := fresh "x" in intro x; intros; destruct x; [ exact None | reverse ])) in (value of H)
257 | ?x
258 => tryif is_var x
259 then instantiate (1:=ltac:(intro)) in (value of H)
260 else idtac "unknown" x
261 end;
262 subst H; cbv beta iota
263 end;
264 reflexivity
265 end. }
266 { intros [n nargs] [n' nargs'].
267 set (f := option_map _).
268 break_innermost_match.
269 all: let G := lazymatch goal with |- ?G => G end in
270 tryif has_evar G then instantiate (1:=None) else idtac.
271 all: vm_compute.
272 all: lazymatch goal with
273 | [ |- Some _ = Some _ -> _ ] => intro; inversion_option; inversion_pair; subst; try reflexivity
274 | [ |- None = Some _ -> _ ] => let H := fresh in intro H; exfalso; clear -H; inversion_option
275 end. }
276 Qed.
277
278 Module OptionNMap <: S := OptionUsualMap NMap.
279 Module OptionZMap <: S := OptionUsualMap ZMap.
280 Module OptionSymbolMap <: S := OptionNMap.
281 Module OptionOperationSizeMap <: S := OptionNMap.
282 Module OpArgsMap0 <: S := OptionNMap.
283 Module OpArgsMap1 <: S := ProdUsualMap OptionNMap OpArgsMap0.
284 Module OpArgsMap2 <: S := ProdUsualMap OptionZMap OpArgsMap1.
285 Module OpArgsMap3 <: S := ProdUsualMap OptionSymbolMap OpArgsMap2.
286 Module OpArgsMap4 <: S := ProdUsualMap OptionOperationSizeMap OpArgsMap3.
287 Module OpArgsMap <: S := OpArgsMap4.
288 Module OpMap' <: S := ProdUsualMap NMap OpArgsMap.
289 Module OpSectOp' <: SectMiniOrderedType OpMap'.E.
290 Definition t := op.
291 Include HasUsualEq.
292 Include UsualIsEq.
293 Include UsualIsEqOrig.
294 Definition to_ : t -> OpMap'.E.t := Eval vm_compute in op'_of_op.
295 Definition of_ (v : OpMap'.E.t) : t
296 := Eval vm_compute in match op_of_op'_opt v with
297 | Some v => v
298 | None => old 0%N 0%N
299 end.
300 Global Instance Proper_to_ : Proper (Logic.eq ==> Logic.eq) to_ | 5.
301 Proof. repeat intro; subst; reflexivity. Qed.
302 Global Instance Proper_of_ : Proper (Logic.eq ==> Logic.eq) of_ | 5.
303 Proof. repeat intro; subst; reflexivity. Qed.
304 Lemma of_to : forall x, eq (of_ (to_ x)) x.
305 Proof.
306 intro x.
307 refine (_ : match op_of_op'_opt (op'_of_op x) with
308 | Some v => v
309 | None => _
310 end = x).
311 rewrite (proj1 op_op'_correct).
312 reflexivity.
313 Qed.
314 Include LiftIsoHasLt OpMap'.E.
315 Include LiftSectHasMiniOrderedType OpMap'.E.
316 Include LiftSectIsLt OpMap'.E.
317 End OpSectOp'.
318 Module OpMap <: UsualS := SectS OpMap' OpSectOp'.
319 End FMapOp.
320
321 Module OpMap := FMapOp.OpMap.
322
323 Module Export RewritePass.
324 Variant rewrite_pass :=
325 | addbyte_small
326 | addcarry_bit
327 | addcarry_small
328 | addoverflow_bit
329 | addoverflow_small
330 | combine_consts
331 | constprop
332 | consts_commutative
333 | drop_identity
334 | flatten_associative
335 | flatten_bounded_associative
336 | fold_consts_to_and
337 | set_slice0_small
338 | set_slice_set_slice
339 | shift_to_mul
340 | slice0
341 | slice01_addcarryZ
342 | slice01_subborrowZ
343 | slice_set_slice
344 | truncate_small
345 | unary_truncate
346 | xor_same
347 .
348 Definition rewrite_pass_beq (x y : rewrite_pass) : bool := if rewrite_pass_eq_dec x y then true else false.
349
350 Derive rewrite_pass_Listable SuchThat (@FinitelyListable rewrite_pass rewrite_pass_Listable) As rewrite_pass_FinitelyListable.
351 Proof. prove_ListableDerive. Qed.
352 Global Existing Instances rewrite_pass_Listable rewrite_pass_FinitelyListable.
353
354 Global Instance show_rewrite_pass : Show rewrite_pass.
355 Proof. prove_Show_enum (). Defined.
356 Global Instance show_lvl_rewrite_pass : ShowLevel rewrite_pass := show_rewrite_pass.
357
358 Definition parse_rewrite_pass_list : list (string * rewrite_pass)
359 := Eval vm_compute in
360 List.map
361 (fun r => (show r, r))
362 (list_all rewrite_pass).
363
364 Definition parse_rewrite_pass : ParserAction rewrite_pass
365 := parse_strs parse_rewrite_pass_list.
366
367 Definition default_rewrite_pass_order : list rewrite_pass
368 := [constprop
369 ;slice0
370 ;slice01_addcarryZ
371 ;slice01_subborrowZ
372 ;set_slice_set_slice
373 ;slice_set_slice
374 ;set_slice0_small
375 ;shift_to_mul
376 ;flatten_associative
377 ;consts_commutative
378 ;fold_consts_to_and
379 ;drop_identity
380 ;flatten_bounded_associative
381 ;unary_truncate
382 ;truncate_small
383 ;combine_consts
384 ;addoverflow_bit
385 ;addcarry_bit
386 ;addcarry_small
387 ;addoverflow_small
388 ;addbyte_small
389 ;xor_same
390 ].
391 End RewritePass.
392
393 Module Export Options.
394 (* Holds the order and multiplicity of passes *)
395 Class rewriting_pipeline_opt := rewriting_pipeline : list rewrite_pass.
396 (* Holds the passes that are enabled *)
397 Class rewriting_pass_filter_opt := rewriting_pass_filter : rewrite_pass -> bool.
398 (* Holds the actual list of passes that are used; we make this a
399 separate option so that it is computed once and for all rather
400 than every time, because it is (currently) quadratic to compute
401 in the number of passes *)
402 Class rewriting_passes_opt := rewriting_passes : list rewrite_pass.
403 (** Should we symex the assembly first, even though this may be more inefficient? *)
404 Class debug_symex_asm_first_opt := debug_symex_asm_first : bool.
405 (** How deep should we reveal nodes? *)
406 Class node_reveal_depth_opt := node_reveal_depth : nat.
407 Definition default_rewriting_passes
408 {rewriting_pipeline : rewriting_pipeline_opt}
409 {rewriting_pass_filter : rewriting_pass_filter_opt}
410 : rewriting_passes_opt
411 := List.filter rewriting_pass_filter rewriting_pipeline.
412
413 Class symbolic_options_opt :=
414 { asm_rewriting_pipeline : rewriting_pipeline_opt
415 ; asm_rewriting_pass_filter : rewriting_pass_filter_opt
416 ; asm_debug_symex_asm_first : debug_symex_asm_first_opt
417 ; asm_node_reveal_depth : node_reveal_depth_opt
418 }.
419
420 Definition default_node_reveal_depth := 3%nat.
421
422 (* This holds the list of computed options, which are passed around between methods *)
423 Class symbolic_options_computed_opt :=
424 { asm_rewriting_passes : rewriting_passes_opt
425 ; asm_debug_symex_asm_first_computed : debug_symex_asm_first_opt
426 ; asm_node_reveal_depth_computed : node_reveal_depth_opt
427 }.
428
429 (* N.B. The default rewriting pass filter should not be changed here, but instead changed in CLI.v where it is derived from a default string *)
430 Definition default_symbolic_options : symbolic_options_opt
431 := {| asm_rewriting_pipeline := default_rewrite_pass_order
432 ; asm_rewriting_pass_filter := fun _ => true
433 ; asm_debug_symex_asm_first := false
434 ; asm_node_reveal_depth := default_node_reveal_depth
435 |}.
436 End Options.
437 Module Export Hints.
438 Global Existing Instance default_rewriting_passes.
439 Global Existing Instances
440 Build_symbolic_options_opt
441 Build_symbolic_options_computed_opt
442 asm_rewriting_pipeline
443 asm_rewriting_pass_filter
444 asm_rewriting_passes
445 asm_debug_symex_asm_first
446 asm_debug_symex_asm_first_computed
447 asm_node_reveal_depth
448 asm_node_reveal_depth_computed
449 .
450 #[global]
451 Hint Cut [
452 ( _ * )
453 (asm_rewriting_pipeline
454 | asm_rewriting_pass_filter
455 | asm_rewriting_passes
456 | asm_debug_symex_asm_first
457 | asm_debug_symex_asm_first_computed
458 | asm_node_reveal_depth
459 | asm_node_reveal_depth_computed
460 ) ( _ * )
461 (Build_symbolic_options_opt
462 | Build_symbolic_options_computed_opt
463 )
464 ] : typeclass_instances.
465 End Hints.
466
467 Definition associative o := match o with add _|addZ|mul _|mulZ|or _|and _|xor _|andZ|orZ|xorZ=> true | _ => false end.
468 Definition commutative o := match o with add _|addZ|addcarry _|addoverflow _|mul _|mulZ|or _|and _|xor _|andZ|orZ|xorZ => true | _ => false end.
469 Definition identity o := match o with mul s => Some match s with N0 => 0%Z | _ => 1%Z end| mulZ=>Some 1%Z |add _|addZ|or _|orZ|xor _|xorZ|addcarry _|addcarryZ _|addoverflow _ => Some 0%Z | and s => Some (Z.ones (Z.of_N s))|andZ => Some (-1)%Z |_=> None end.
470 (* identity, but not in the first slot *)
471 Definition identity_after_0 o := match o with subborrow _|subborrowZ _ => Some 0%Z | _=> None end.
472 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.
473 Definition op_always_interps o := match o with add _|addcarry _|addoverflow _|and _|or _|xor _|mul _|addZ|mulZ|andZ|orZ|xorZ|addcarryZ _ => true | _ => false end.
474 Definition combines_to o := match o with add s => Some (mul s) | addZ => Some mulZ | _ => None end.
475 (* the inner operation can be dropped when replacing it with another operation results in a bounded output *)
476 Variant drop_kind := drop_always | drop_if_bounded (bound : ZRange.zrange) (rep_op : op).
477 Definition bounds_for_drop_inner_associative o_outer o_inner :=
478 match o_outer with addcarryZ s|addcarry s(*|addoverflow s*) =>
479 match o_inner with
480 | addZ => Some drop_always
481 | add _ => (s' <- unary_truncate_size o_inner; Some (drop_if_bounded (ZRange.Build_zrange 0 (Z.ones s')) addZ))
482 | _ => None end | _ => None end%option.
483
484 Definition node (A : Set) : Set := op * list A.
485 Global Instance Show_node {A : Set} {show_A : Show A} : Show (node A) := show_prod.
486
487 Local Unset Elimination Schemes.
488 Inductive expr : Set :=
489 | ExprRef (_ : idx)
490 | ExprApp (_ : node expr).
491 Local Set Elimination Schemes.
492 Section expr_ind.
493 Context (P : expr -> Prop)
494 (HRef : forall i, P (ExprRef i))
495 (HApp : forall n, Forall P (snd n) -> P (ExprApp n)).
496 Fixpoint expr_ind e {struct e} : P e :=
497 match e with
498 | ExprRef i => HRef i
499 | ExprApp n => HApp _ (list_rect _ (Forall_nil _) (fun e _ H => Forall_cons e (expr_ind e) H) (snd n))
500 end.
501 End expr_ind.
502 Definition invert_ExprRef (e : expr) : option idx :=
503 match e with ExprRef i => Some i | _ => None end.
504 Definition Show_expr_body (Show_expr : Show expr) : Show expr
505 := Eval cbv -[String.append show_N concat List.map Show_op] in
506 fun e => match e with
507 | ExprRef i => "ExprRef " ++ show i
508 | ExprApp (o, e) => "ExprApp " ++ show (o, e)
509 end%string.
510 Definition Show_expr : Show expr
511 := Eval cbv -[String.append show_N concat List.map Show_op] in
512 fix Show_expr e := Show_expr_body Show_expr e.
513 Global Existing Instance Show_expr.
514
515 Local Notation max_powers_of_two := 5%nat (only parsing).
516 Local Notation max_decimal := 256%Z (only parsing).
517
518 Definition show_infix_op (o : op) : option string
519 := match o with
520 | add s => Some ("+" ++ String.to_subscript (show s))
521 | shl s => Some (">>" ++ String.to_subscript (show s))
522 | shr s => Some (">>" ++ String.to_subscript (show s))
523 | and s => Some ("&" ++ String.to_subscript (show s))
524 | or s => Some ("|" ++ String.to_subscript (show s))
525 | xor s => Some ("^" ++ String.to_subscript (show s))
526 | mul s => Some ("*" ++ String.to_subscript (show s))
527 | sar s => Some (">>>" ++ String.to_subscript (show s))
528 | addZ => Some "+ℤ"
529 | mulZ => Some "*ℤ"
530 | shlZ => Some "<<ℤ"
531 | shrZ => Some ">>ℤ"
532 | andZ => Some "&ℤ"
533 | orZ => Some "|ℤ"
534 | xorZ => Some "^ℤ"
535 | _ => None
536 end%string.
537
538 Definition show_prefix_op (o : op) : option (string * Level)
539 := match o with
540 | neg s => Some ("-" ++ String.to_subscript (show s), opp_lvl)
541 | negZ => Some ("-ℤ", opp_lvl)
542 | _ => None
543 end%string.
544
545 Definition show_lvl_expr_pretty : ShowLevel expr
546 := fix show_lvl_pretty_expr (e : expr) : Level -> string
547 := let __ : ShowLevel expr := show_lvl_pretty_expr in
548 let __ : Show expr := @Show_of_ShowLevel _ show_lvl_pretty_expr in
549 let show_comment_args args
550 := match args with
551 | nil => ""
552 | _ => " (* " ++ show args ++ " *)"
553 end%string in
554 match e with
555 | ExprRef i => fun _ => "#" ++ show i
556 | ExprApp (old s x, args) => lvl_wrap_parens app_lvl ("old" ++ String.to_subscript (show s) ++ " " ++ show x ++ show_comment_args args)
557 | ExprApp (const x, args) => fun lvl => PowersOfTwo.show_lvl_Z_up_to max_powers_of_two max_decimal x lvl ++ show_comment_args args
558 | ExprApp ((add _|shl _|shr _|and _|or _|xor _|mul _|sar _|addZ|mulZ|shlZ|shrZ|andZ|orZ|xorZ) as o, args)
559 => let o : string := invert_Some (show_infix_op o) in
560 match args with
561 | nil => fun _ => o ++ "[]"
562 | x :: nil => fun _ => o ++ "[" ++ show x ++ "]"
563 | _ => fun _ => "(" ++ String.concat (" " ++ o ++ " ") (List.map show args) ++ ")"
564 end
565 | ExprApp ((neg _|negZ) as o, args)
566 => let '(o, lvl) := invert_Some (show_prefix_op o) in
567 match args with
568 | nil => fun _ => o ++ "[]"
569 | x :: nil => fun _ => o ++ show_lvl x lvl
570 | _ => fun _ => o ++ show args
571 end
572 | ExprApp (o, args)
573 => fun _ => "(" ++ show_op_subscript o ++ ", " ++ show args ++ ")"
574 end%string%list.
575
576 Definition show_expr_pretty : Show expr
577 := @Show_of_ShowLevel _ show_lvl_expr_pretty.
578
579 Lemma op_beq_spec a b : BoolSpec (a=b) (a<>b) (op_beq a b).
580 Proof using Type. cbv [op_beq]; destruct (op_eq_dec a b); constructor; congruence. Qed.
581 Global Instance reflect_eq_op : reflect_rel eq op_beq | 10 := reflect_rel_of_BoolSpec op_beq_spec.
582 Fixpoint expr_beq (X Y : expr) {struct X} : bool :=
583 match X, Y with
584 | ExprRef x, ExprRef x0 => N.eqb x x0
585 | ExprApp x, ExprApp x0 =>
586 Prod.prod_beq _ _ op_beq (ListUtil.list_beq expr expr_beq) x x0
587 | _, _ => false
588 end.
589 Lemma expr_beq_spec a b : BoolSpec (a=b) (a<>b) (expr_beq a b).
590 Proof using Type.
591 revert b; induction a, b; cbn.
592 1: destruct (N.eqb_spec i i0); constructor; congruence.
593 1,2: constructor; congruence.
594 destruct n, n0; cbn.
595 destruct (op_beq_spec o o0); cbn in *; [subst|constructor; congruence].
596 revert l0; induction H, l0; cbn; try (constructor; congruence); [].
597 destruct (H e); cbn; try (constructor; congruence); []; subst.
598 destruct (IHForall l0); [left|right]; congruence.
599 Qed.
600 Global Instance reflect_eq_expr : reflect_rel eq expr_beq | 10 := reflect_rel_of_BoolSpec expr_beq_spec.
601 Lemma expr_beq_true a b : expr_beq a b = true -> a = b.
602 Proof using Type. destruct (expr_beq_spec a b); congruence. Qed.
603
604 Require Import Crypto.Util.Option Crypto.Util.Notations Coq.Lists.List.
605 Import ListNotations.
606
607 Section WithContext.
608 Context (ctx : symbol -> option Z).
609 Definition op_to_Z_binop (o : op) : option _
610 := match o with
611 | add _ => Some Z.add
612 | shl _ => Some Z.shiftl
613 | shr _ => Some Z.shiftr
614 | and _ => Some Z.land
615 | or _ => Some Z.lor
616 | xor _ => Some Z.lxor
617 | mul _ => Some Z.mul
618 | addZ => Some Z.add
619 | mulZ => Some Z.mul
620 | shlZ => Some Z.shiftl
621 | shrZ => Some Z.shiftr
622 | andZ => Some Z.land
623 | orZ => Some Z.lor
624 | xorZ => Some Z.lxor
625 | _ => None
626 end.
627
628 Definition interp_op o (args : list Z) : option Z :=
629 Eval cbv [invert_Some identity op_to_Z_binop] in
630 let keep n x := Z.land x (Z.ones (Z.of_N n)) in
631 match o, args with
632 | old s x, nil => match ctx x with Some v => Some (keep s v) | None => None end
633 | const z, nil => Some z
634 | addcarry s, args =>
635 Some (Z.shiftr (List.fold_right Z.add 0 args) (Z.of_N s) mod 2)
636 | subborrow s, cons a args' =>
637 Some ((- Z.shiftr (a - List.fold_right Z.add 0 args') (Z.of_N s)) mod 2)
638 | addoverflow s, args => Some (Z.b2z (negb (Z.eqb
639 (Z.signed s (keep s (List.fold_right Z.add 0 args)))
640 (List.fold_right Z.add 0%Z (List.map (Z.signed s) args)))))
641 | neg s, [a] => Some (keep s (- a))
642 | shl s, [a; b] => Some (keep s (Z.shiftl a b))
643 | shr s, [a; b] => Some (keep s (Z.shiftr a b))
644 | sar s, [a; b] => Some (keep s (Z.shiftr (Z.signed s a) b))
645 | rcr s, [v1; cf; cnt] => Some (
646 let v1c := Z.lor v1 (Z.shiftl cf (Z.of_N s)) in
647 let l := Z.lor v1c (Z.shiftl v1 (1+Z.of_N s)) in
648 keep s (Z.shiftr l cnt))
649 | (add s|and s|or s|xor s|mul s) as o, args
650 => let id := invert_Some (identity o) in
651 let o := invert_Some (op_to_Z_binop o) in
652 Some (keep s (List.fold_right o id args))
653 | (addZ|mulZ|andZ|orZ|xorZ) as o, args
654 => let id := invert_Some (identity o) in
655 let o := invert_Some (op_to_Z_binop o) in
656 Some (List.fold_right o id args)
657 | slice lo sz, [a] => Some (keep sz (Z.shiftr a (Z.of_N lo)))
658 | set_slice lo sz, [a; b] =>
659 Some (Z.lor (Z.shiftl (keep sz b) (Z.of_N lo))
660 (Z.ldiff a (Z.shiftl (Z.ones (Z.of_N sz)) (Z.of_N lo))))
661 | selectznz, [c; a; b] => Some (if Z.eqb c 0 then a else b)
662 | iszero, [a] => Some (Z.b2z (Z.eqb a 0))
663 | negZ, [a] => Some (Z.opp a)
664 | shlZ, [a; b] => Some (Z.shiftl a b)
665 | shrZ, [a; b] => Some (Z.shiftr a b)
666 | addcarryZ s, args => Some (Z.shiftr (List.fold_right Z.add 0 args) (Z.of_N s))
667 | subborrowZ s, cons a args' => Some (- Z.shiftr (a - List.fold_right Z.add 0 args') (Z.of_N s))
668 | _, _ => None
669 end%Z.
670 End WithContext.
671 Definition interp0_op := interp_op (fun _ => None).
672
673 Lemma interp_op_weaken_symbols G1 G2 o args
674 (H : forall (s:symbol) v, G1 s = Some v -> G2 s = Some v)
675 : forall v, interp_op G1 o args = Some v -> interp_op G2 o args = Some v.
676 Proof using Type.
677 cbv [interp_op option_map]; intros;
678 repeat (BreakMatch.break_match || BreakMatch.break_match_hyps);
679 inversion_option; subst;
680 try congruence.
681 all : eapply H in Heqo0; congruence.
682 Qed.
683
684 Lemma interp_op_interp0_op o a v (H : interp0_op o a = Some v)
685 : forall G, interp_op G o a = Some v.
686 Proof using Type. intros; eapply interp_op_weaken_symbols in H; try eassumption; discriminate. Qed.
687
688 Definition node_beq {A : Set} (arg_eqb : A -> A -> bool) : node A -> node A -> bool :=
689 Prod.prod_beq _ _ op_beq (ListUtil.list_beq _ arg_eqb).
690 Global Instance reflect_node_beq {A : Set} {arg_eqb} {H : reflect_rel (@eq A) arg_eqb}
691 : reflect_rel eq (@node_beq A arg_eqb) | 10 := _.
692
693 Local Open Scope Z_scope.
694 Require Crypto.Language.API.
695 Require Crypto.AbstractInterpretation.ZRange.
696 Require Crypto.AbstractInterpretation.ZRangeProofs.
697 Require Import Crypto.CastLemmas.
698 Require Import Crypto.Language.PreExtra.
699 Require Import Crypto.Util.ZRange.LandLorBounds.
700 Require Import Crypto.Util.ZRange.BasicLemmas.
701 Require Import Crypto.Util.ZRange.Operations.
702 Require Import Crypto.Util.ZUtil.LandLorShiftBounds.
703 Require Import Crypto.Util.ZUtil.LandLorBounds.
704
705 Section bound_node_via_PHOAS.
706 Import Crypto.Util.ZRange.
707 Import API.Compilers.
708 Import AbstractInterpretation.ZRange.Compilers.
709 Import AbstractInterpretation.ZRangeProofs.Compilers.
710
711 Local Instance : shiftr_avoid_uint1_opt := false.
712 Local Notation interp_PHOAS_op := (ZRange.ident.option.interp true).
713
714 Definition op_to_PHOAS_binop (o : op) : option _
715 := match o with
716 | add _ => Some ident.Z_add
717 | shl _ => Some ident.Z_shiftl
718 | shr _ => Some ident.Z_shiftr
719 | and _ => Some ident.Z_land
720 | or _ => Some ident.Z_lor
721 | xor _ => Some ident.Z_lxor
722 | mul _ => Some ident.Z_mul
723 | addZ => Some ident.Z_add
724 | mulZ => Some ident.Z_mul
725 | shlZ => Some ident.Z_shiftl
726 | shrZ => Some ident.Z_shiftr
727 | andZ => Some ident.Z_land
728 | orZ => Some ident.Z_lor
729 | xorZ => Some ident.Z_lxor
730 | _ => None
731 end.
732 Definition op_to_PHOAS_unop (o : op) : option _
733 := match o with
734 | neg _ => Some ident.Z_opp
735 | negZ => Some ident.Z_opp
736 | _ => None
737 end.
738 Definition op_to_PHOAS_tritop (o : op) : option _
739 := match o with
740 | selectznz => Some ident.Z_zselect
741 | _ => None
742 end.
743 Definition op_to_bounds (o : op) : option _
744 := match o with
745 | add s
746 | shl s
747 | shr s
748 | and s
749 | or s
750 | xor s
751 | mul s
752 | neg s
753 => Some r[0~>Z.ones (Z.of_N s)]
754 | _ => None
755 end%zrange.
756
757 Definition op_to_PHOAS_bounds (o : op) : option (list (unit -> option zrange) -> option zrange)
758 := let unthunk := List.map (fun x => x tt) in
759 match o with
760 | old s _ => Some (fun _ => Some r[0~>Z.ones (Z.of_N s)])
761 | const x
762 => Some (fun _ => interp_PHOAS_op (ident.Literal (t:=base.type.Z) x))
763 | (add _|and _|or _|xor _|mul _) as o
764 => let b : zrange := invert_Some (op_to_bounds o) in
765 let id : Z := invert_Some (identity o) in
766 let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_binop o)) in
767 Some (fun args => interp_PHOAS_op ident.Z_cast (Some b) (fold_right o (Some r[id~>id]) (unthunk args)))
768 | (addcarry _ | subborrow _ | addoverflow _ | iszero)
769 => Some (fun _ => Some r[0~>1])
770 | (addZ|mulZ|andZ|orZ|xorZ) as o
771 => let id : Z := invert_Some (identity o) in
772 let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_binop o)) in
773 Some (fun args => fold_right o (Some r[id~>id]) (unthunk args))
774 | (shl _|shr _) as o
775 => let b : zrange := invert_Some (op_to_bounds o) in
776 let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_binop o)) in
777 Some (fun args
778 => match args with
779 | [x; y] => interp_PHOAS_op ident.Z_cast (Some b) (o (x tt) (y tt))
780 | _ => None
781 end)
782 | (shlZ|shrZ) as o
783 => let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_binop o)) in
784 Some (fun args
785 => match args with
786 | [x; y] => o (x tt) (y tt)
787 | _ => None
788 end)
789 | (neg _) as o
790 => let b : zrange := invert_Some (op_to_bounds o) in
791 let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_unop o)) in
792 Some (fun args
793 => match args with
794 | [x] => interp_PHOAS_op ident.Z_cast (Some b) (o (x tt))
795 | _ => None
796 end)
797 | (negZ) as o
798 => let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_unop o)) in
799 Some (fun args
800 => match args with
801 | [x] => o (x tt)
802 | _ => None
803 end)
804 | (selectznz) as o
805 => let o := interp_PHOAS_op (invert_Some (op_to_PHOAS_tritop o)) in
806 Some (fun args
807 => match args with
808 | [x; y; z] => o (x tt) (y tt) (z tt)
809 | _ => None
810 end)
811 | (slice _ s | sar s | rcr s) as o
812 => Some (fun _ => Some r[0~>Z.ones (Z.of_N s)])
813 | set_slice 0 w
814 => Some (fun args
815 => match unthunk args with
816 | [Some a; Some b]
817 => if ((lower a <? 0) || (lower b <? 0))%Z%bool
818 then None
819 else let a := upper a in
820 let b := upper b in
821 Some r[0~>(Z.lor
822 (Z.land (Z.ones (Z.succ (Z.log2 b))) (Z.ones (Z.of_N w)))
823 (Z.ldiff (Z.ones (Z.succ (Z.log2 a))) (Z.ones (Z.of_N w))))]
824 | _ => None
825 end)
826 | addcarryZ _
827 | subborrowZ _
828 | set_slice _ _
829 => None
830 end%zrange.
831
832 Local Coercion is_true : bool >-> Sortclass.
833
834 Lemma interp_op_op_to_PHOAS_bounds_set_slice_0 G o bf arg_bounds args v b
835 (H : op_to_PHOAS_bounds o = Some bf)
836 (Hargs : Forall2 (fun v b => match b with
837 | Some b => is_bounded_by_bool v b = true
838 | None => True
839 end)
840 args arg_bounds)
841 (Hop : interp_op G o args = Some v)
842 arg_bounds' (Hb : bf arg_bounds' = Some b)
843 (Ha : arg_bounds = List.map (fun x => x tt) arg_bounds')
844 w (Ho : set_slice 0 w = o)
845 : is_bounded_by_bool v b.
846 Proof.
847 subst o; cbv [op_to_PHOAS_bounds interp_op] in *; inversion_option; subst.
848 break_innermost_match_hyps; inversion_option; subst.
849 repeat (destruct_one_head list; inversion_list).
850 invlist Forall2.
851 break_innermost_match_hyps; inversion_option; subst.
852 apply unreflect_bool; reflect_hyps; cbn [upper lower].
853 autorewrite with zsimplify_const.
854 rewrite Z.land_ones_ones.
855 rewrite Z.lor_nonneg, Z.ldiff_nonneg, !Z.land_ones by lia.
856 repeat apply conj; auto with zarith.
857 match goal with
858 | [ H : ~(?x < 0 \/ ?y < 0) |- _ ] => assert (0 <= x /\ 0 <= y) by lia; clear H
859 end.
860 clear G; destruct_head zrange; destruct_head'_and.
861 pose proof Z.log2_le_mono; pose proof Z.log2_nonneg; specialize_all_ways.
862 repeat match goal with H : _ -> _ |- _ => clear H end.
863 break_innermost_match; reflect_hyps; destruct_head'_or; try lia.
864 apply Z.le_bitwise; rewrite ?Z.lor_nonneg, ?Z.ldiff_nonneg; auto with zarith.
865 intros; rewrite <- Z.land_ones by lia.
866 Z.bitblast_core; cbn.
867 all: repeat rewrite ?andb_true_r, ?andb_false_r, ?andb_false_l, ?andb_true_l, ?orb_false_r, ?orb_false_l, ?orb_true_l, ?orb_true_r.
868 all: cbv [Bool.le]; break_innermost_match; auto.
869 all: rewrite ?Z.min_le_iff in *.
870 all: destruct_head'_or.
871 all: rewrite Z.bits_above_log2 in * by lia.
872 all: congruence.
873 Qed.
874
875 Lemma interp_op_op_to_PHOAS_bounds_fold_right_helper G o arg_bounds args v
876 (Hargs : Forall2 (fun v b => match b with
877 | Some b => is_bounded_by_bool v b = true
878 | None => True
879 end)
880 args arg_bounds)
881 (Hop : interp_op G o args = Some v)
882 id (Hid : identity o = Some id)
883 bo (Hbo : op_to_PHOAS_binop o = Some bo)
884 (o' := interp_PHOAS_op bo)
885 (bf := fold_right o' (Some r[id~>id]%zrange))
886 b (Hb : bf arg_bounds = Some b)
887 : is_bounded_by_bool (fold_right (ident.interp bo) id args) b.
888 Proof.
889 subst o' bf; subst.
890 pose proof (@ZRange.ident.option.interp_related _ _ _ bo
891 : type.related_hetero _ (interp_PHOAS_op bo) (ident.interp bo)) as Hbounds.
892 cbn -[interp_PHOAS_op] in *.
893 cbv [Morphisms.respectful_hetero] in *.
894 revert dependent b.
895 clear Hop v.
896 induction Hargs; cbn [fold_right]; intros; inversion_option; subst.
897 { apply ZRange.is_bounded_by_bool_constant. }
898 let H := match goal with H : interp_PHOAS_op bo _ _ = Some _ |- _ => H end in
899 in_hyp_under_binders_do (fun H' => rewrite H in H').
900 apply Hbounds; clear Hbounds.
901 all: break_innermost_match; try reflexivity; specialize_under_binders_by reflexivity.
902 all: auto.
903 Qed.
904
905 Lemma interp_op_op_to_PHOAS_bounds G o bf arg_bounds args v b
906 (H : op_to_PHOAS_bounds o = Some bf)
907 (Hargs : Forall2 (fun v b => match b with
908 | Some b => is_bounded_by_bool v b = true
909 | None => True
910 end)
911 args arg_bounds)
912 (Hop : interp_op G o args = Some v)
913 arg_bounds' (Hb : bf arg_bounds' = Some b)
914 (Ha : arg_bounds = List.map (fun x => x tt) arg_bounds')
915 : is_bounded_by_bool v b.
916 Proof.
917 (* pose proof the lemmas that we needed extra insight to prove separately *)
918 pose proof (@interp_op_op_to_PHOAS_bounds_set_slice_0 G o bf arg_bounds args v b H Hargs Hop arg_bounds' Hb Ha) as Hslice.
919 pose proof (@interp_op_op_to_PHOAS_bounds_fold_right_helper G o arg_bounds args v Hargs Hop) as Hfold_right.
920 (* destruct the operation, do general cleanup *)
921 cbv [op_to_PHOAS_bounds] in *.
922 all: repeat first [ progress subst
923 | progress inversion_option
924 | progress cbn [interp_op] in *
925 | break_innermost_match_hyps_step ].
926 (* make use of the special-insight lemmas *)
927 all: first [ specialize (Hslice _ eq_refl) | clear Hslice ].
928 all: first [ specialize (Hfold_right _ eq_refl _ eq_refl) | clear Hfold_right ].
929 all: try assumption.
930 (* forward reasoning of destructing bounds interp things, so we can expose the PHOAS bounds lemmas *)
931 all: let rec do_on T :=
932 lazymatch T with
933 | ?F ?x
934 => let h := head x in
935 try (constr_eq h (@ZRange.ident.option.interp); destruct x eqn:?);
936 do_on F
937 | _ => idtac
938 end in
939 repeat match goal with
940 | [ H : ?T = Some _ |- _ ] => do_on T
941 end.
942 (* pose proof the bounds be get from PHOAS reasoning *)
943 all: repeat match goal with
944 | [ H : context[@ZRange.ident.option.interp ?a ?b ?t ?op] |- _ ]
945 => unique pose proof (@ZRange.ident.option.interp_related a b t op)
946 end.
947 (* various simplification and cleanup *)
948 all: cbn -[interp_PHOAS_op] in *.
949 all: cbv [Morphisms.respectful_hetero] in *.
950 all: invlist Forall2.
951 all: repeat first [ progress subst
952 | assumption
953 | progress cbn [List.map] in *
954 | inversion_list_step
955 | match goal with
956 | [ H : Forall2 _ nil _ |- _ ] => inversion H; clear H
957 | [ H : Forall2 _ (_ :: _) _ |- _ ] => inversion H; clear H
958 | [ H : ?x = Some _, H' : context[?x] |- _ ] => rewrite H in H'
959 | [ H : nil = List.map _ ?ls |- _ ] => is_var ls; destruct ls
960 | [ H : _ :: _ = List.map _ ?ls |- _ ] => is_var ls; destruct ls
961 end ].
962 all: break_innermost_match_hyps.
963 (* handle goals with relatively simple bounds that follow just from masking/casting/modulo *)
964 all: try change (Z.land ?x 0) with (Z.land x (Z.ones 0)).
965 all: repeat match goal with
966 | [ |- context[is_bounded_by_bool (Z.land ?x (Z.ones ?n)) _] ]
967 => rewrite (@Z.land_ones x n), ?(Z.ones_equiv n), <- ?Z.sub_1_r by lia
968 | [ |- is_true (is_bounded_by_bool (?y mod ?x) r[0~>?x-1]) ]
969 => apply unreflect_bool; cbn [lower upper]; generalize (Z.mod_pos_bound y x); try lia
970 | [ |- is_true (is_bounded_by_bool (?y mod ?x) r[0~>_]) ]
971 => try now apply unreflect_bool; cbn [lower upper]; generalize (Z.mod_pos_bound y x); lia
972 | [ |- is_true (is_bounded_by_bool (Z.b2z ?b) r[0~>1]) ]
973 => case b; vm_compute; reflexivity
974 end.
975 (* transform asm masking (Z.land _ (Z.ones _)) into PHOAS casting (ident.cast), so the bounds things line up *)
976 all: repeat first [ assumption
977 | solve [ auto ]
978 | match goal with
979 | [ |- context[is_bounded_by_bool (?x mod ?y) ?b] ]
980 => rewrite <- (Z.sub_add 1 y), (Z.sub_1_r y);
981 rewrite <- (@ident.cast_out_of_bounds_simple_0_mod (Z.pred y)) by auto with zarith;
982 rewrite <- ?Z.ones_equiv
983 end ].
984 all: rewrite ?Z.add_simpl_r. (* idk why we need this *)
985 (* start applying and specializing PHOAS bounds hypotheses *)
986 all: repeat first [ reflexivity
987 | assumption
988 | solve [ auto ]
989 | exactly_once (idtac; multimatch goal with
990 | [ H : _ |- _ ] => apply H; clear H
991 end)
992 | break_innermost_match_step
993 | progress specialize_under_binders_by reflexivity
994 | progress specialize_under_binders_by eapply zrange_lb ].
995 (* some PHOAS bounds hypotheses have a match in their conclusion; we rewrite away the match by autospecializing it with hypotheses in the context *)
996 all: repeat first [ match goal with
997 | [ H : ?x = _ |- _ ]
998 => let h := head x in
999 constr_eq h (@ZRange.ident.option.interp);
1000 progress in_hyp_under_binders_do (fun H' => rewrite H in H')
1001 end ].
1002 (* finish specializing PHOAS bounds hypotheses *)
1003 all: repeat first [ reflexivity
1004 | assumption
1005 | congruence
1006 | progress inversion_option
1007 | progress subst
1008 | solve [ auto ]
1009 | exactly_once (idtac; multimatch goal with
1010 | [ H : _ |- _ ] => apply H; clear H
1011 end)
1012 | break_innermost_match_step
1013 | apply zrange_lb
1014 | progress specialize_under_binders_by reflexivity
1015 | progress specialize_under_binders_by apply zrange_lb
1016 | break_innermost_match_hyps_step ].
1017 (* Somehow, Z.zselect gets unfolded in the goal and broken up by break_innermost_match above; so we must unfold it in the hyps *)
1018 all: cbv [Z.zselect] in *.
1019 all: repeat match goal with
1020 | [ H : (?x =? 0) = _ |- _ ] => in_hyp_under_binders_do (fun H' => rewrite H in H')
1021 end.
1022 all: try now cbv [is_true]; eauto with nocore.
1023 Qed.
1024
1025 Definition bound_node_idx_via_PHOAS (lookup_bounds : idx -> option zrange) (n : node idx) : option zrange
1026 := (let '(o, args) := n in
1027 b <- op_to_PHOAS_bounds o;
1028 b (List.map (fun idx 'tt => lookup_bounds idx) args))%option.
1029
1030 Lemma bound_node_idx_via_PHOAS_Forall2_ext lookup_bounds1 lookup_bounds2 n1 n2
1031 : fst n1 = fst n2 -> Forall2 (fun i1 i2 => lookup_bounds1 i1 = lookup_bounds2 i2) (snd n1) (snd n2) -> bound_node_idx_via_PHOAS lookup_bounds1 n1 = bound_node_idx_via_PHOAS lookup_bounds2 n2.
1032 Proof.
1033 destruct n1 as [o1 a1], n2 as [o2 a2]; cbn [fst snd]; intro; subst.
1034 cbv [bound_node_idx_via_PHOAS Crypto.Util.Option.bind]; break_innermost_match; try reflexivity.
1035 intro H; apply f_equal.
1036 induction H; cbn; f_equal; eauto.
1037 match goal with H : _ |- _ => now rewrite H end.
1038 Qed.
1039
1040 Lemma bound_node_idx_via_PHOAS_Forall_ext lookup_bounds1 lookup_bounds2 n
1041 : Forall (fun i => lookup_bounds1 i = lookup_bounds2 i) (snd n) -> bound_node_idx_via_PHOAS lookup_bounds1 n = bound_node_idx_via_PHOAS lookup_bounds2 n.
1042 Proof.
1043 intro H; apply bound_node_idx_via_PHOAS_Forall2_ext; cbn; try reflexivity.
1044 induction H; constructor; eauto.
1045 Qed.
1046
1047 Lemma interp_op_bound_node_idx_via_PHOAS lookup_bounds (evalGd : Symbolic.expr -> _ -> Prop) G o args argsZ bs v
1048 (H : bound_node_idx_via_PHOAS lookup_bounds (o, args) = Some bs)
1049 (Hargs : Forall (fun i => forall v b,
1050 evalGd (ExprRef i) v
1051 -> lookup_bounds i = Some b
1052 -> is_bounded_by_bool v b = true)
1053 args)
1054 (HargsZ : Forall2 evalGd (List.map ExprRef args) argsZ)
1055 (Hop : interp_op G o argsZ = Some v)
1056 : is_bounded_by_bool v bs.
1057 Proof.
1058 cbv [bound_node_idx_via_PHOAS Crypto.Util.Option.bind] in *; break_innermost_match_hyps; inversion_option; subst.
1059 eapply interp_op_op_to_PHOAS_bounds; try eassumption; try reflexivity.
1060 rewrite !Forall2_map_r_iff.
1061 rewrite Forall2_map_l_iff in HargsZ.
1062 clear dependent o.
1063 clear dependent bs.
1064 induction HargsZ; invlist Forall; constructor; break_innermost_match_hyps; break_innermost_match; inversion_option; subst; eauto.
1065 Qed.
1066 End bound_node_via_PHOAS.
1067
1068 Class description := descr : option ((unit -> string) * bool (* always show *)).
1069 #[global]
1070 Typeclasses Opaque description.
1071 Definition eager_description := option (string * bool).
1072 Notation Build_description descr always_show := (Some (fun 'tt => descr, always_show)) (only parsing).
1073 Notation no_description := None (only parsing).
1074
1075 (* all indices in the node must be already present in the dag *)
1076 Definition node_arg_ok (i : idx) (n : idx) := (n < i)%N.
1077 Definition node_args_ok (i : idx) (n : list idx) := Forall (node_arg_ok i) n.
1078 (* fresh symbols must have value <= their index, so that fresh symbols are truly fresh *)
1079 Definition node_ok (i : idx) (n : node idx) := (forall w s args, n = (old w s, args) -> (s <= i)%N) /\ node_args_ok i (snd n).
1080 Lemma new_node_ok n (pf : match n with (old _ _, _) => False | _ => True end) i (Hi : node_args_ok i (snd n)) : node_ok i n.
1081 Proof. split; repeat intro; subst; assumption. Qed.
1082 Existing Class node_ok.
1083 Existing Class node_arg_ok.
1084 Existing Class node_args_ok.
1085 #[global]
1086 Hint Extern 1 (node_ok ?i ?n) => exact (@new_node_ok n I i) : typeclass_instances.
1087 #[global] Instance node_args_ok_nil i : node_args_ok i nil.
1088 Proof. constructor. Qed.
1089 Lemma node_args_ok_cons i x xs : node_arg_ok i x -> node_args_ok i xs -> node_args_ok i (x :: xs).
1090 Proof. constructor; assumption. Qed.
1091 (* For @cons N and @cons idx *)
1092 #[global] Hint Extern 2 (node_args_ok ?i (@cons _ ?x ?xs)) => simple notypeclasses refine (@node_args_ok_cons i x xs) : typeclass_instances.
1093 Lemma relax_node_arg_ok i1 i2 n : (i1 < i2)%N -> node_arg_ok i1 n -> node_arg_ok i2 n.
1094 Proof. cbv [node_arg_ok idx] in *; lia. Qed.
1095 Lemma relax_node_args_ok i1 i2 n : (i1 < i2)%N -> node_args_ok i1 n -> node_args_ok i2 n.
1096 Proof. cbv [node_args_ok]; intro; apply Forall_impl; intro; apply relax_node_arg_ok; assumption. Qed.
1097 Lemma relax_node_ok i1 i2 n : (i1 < i2)%N -> node_ok i1 n -> node_ok i2 n.
1098 Proof.
1099 cbv [node_ok]; intro H; pose proof (@relax_node_args_ok i1 i2 (snd n) H).
1100 intuition (auto; subst).
1101 specialize_under_binders_by reflexivity.
1102 lia.
1103 Qed.
1104 Module Type DagDefinitions.
1105 Parameter t : Type.
1106 Parameter empty : t.
1107 Parameter size : t -> N.
1108 Parameter lookup : t -> idx -> option (node idx).
1109 Parameter lookup_bounds : t -> idx -> option ZRange.zrange.
1110 Parameter reverse_lookup : t -> node idx -> option idx.
1111 Axiom size_ok : t -> Prop.
1112 Axiom merge_node : forall {descr : description} (n : node idx) (d : t), idx * t.
1113 End DagDefinitions.
1114 Module DagExtraDefinitions (Import dag : DagDefinitions).
1115 Definition all_nodes_ok (d : t) : Prop
1116 := forall i r, lookup d i = Some r -> node_ok i r.
1117 Definition bounds_ok (d : t) : Prop
1118 := (forall i r, lookup d i = Some r -> lookup_bounds d i = bound_node_idx_via_PHOAS (lookup_bounds d) r)
1119 /\ (forall i, lookup d i = None -> lookup_bounds d i = None).
1120 (* We require that all ok nodes reference only other nodes in the dag; we can overapproximate this by requiring all indices <= size be present, which is tautological for assoc-list dags *)
1121 Definition ok (d : t) : Prop
1122 := size_ok d
1123 /\ bounds_ok d
1124 /\ (forall i n, reverse_lookup d n = Some i <-> lookup d i = Some n)
1125 /\ (forall i n, lookup d i = Some n -> (i < size d)%N)
1126 /\ (forall i, lookup d i = None -> (size d <= i)%N).
1127
1128 Definition gensym (s:OperationSize) (d : t) : node idx
1129 := (old s (size d), []).
1130 Existing Class ok.
1131 Existing Class all_nodes_ok.
1132
1133 Definition get_eager_description_description (d : eager_description) : option string
1134 := option_map fst d.
1135 Definition get_eager_description_always_show (d : eager_description) : bool
1136 := match d with Some (_, always_show) => always_show | None => false end.
1137 Definition force_description : description -> eager_description
1138 := option_map (fun '(descr, always_show) => (descr tt, always_show)).
1139
1140 Definition M T := t -> T * t.
1141 Definition bind {A B} (v : M A) (f : A -> M B) : M B
1142 := fun d => let '(v, d) := v d in f v d.
1143 Definition ret {A} (v : A) : M A
1144 := fun d => (v, d).
1145
1146 Module Type EagerDagDefinitions.
1147 Parameter t : Type.
1148 Parameter force : dag.t -> t.
1149 Parameter description_lookup : forall (d : t) (descr : string), list idx.
1150 Parameter elements : t -> list (idx * node idx * eager_description).
1151 End EagerDagDefinitions.
1152 End DagExtraDefinitions.
1153 Module Type DagExtraDefinitionsSig (dag : DagDefinitions).
1154 Include DagExtraDefinitions dag.
1155 End DagExtraDefinitionsSig.
1156 Module Type DagProperties (Import dag : DagDefinitions) (Import dag' : DagExtraDefinitionsSig dag).
1157 Axiom lookup_merge_node
1158 : forall {descr : description} (n : node idx) (d : t) i
1159 {ok : ok d},
1160 dag.lookup (snd (dag.merge_node n d)) i = match dag.lookup d i with
1161 | Some v => Some v
1162 | None
1163 => if (i =? size d)%N && Option.is_None (reverse_lookup d n)
1164 then Some n
1165 else None
1166 end.
1167
1168 Axiom reverse_lookup_merge_node
1169 : forall {d : t}
1170 {ok : ok d} {descr : description} (n n' : node idx),
1171 dag.reverse_lookup (snd (dag.merge_node n d)) n'
1172 = if node_beq N.eqb n' n
1173 then Some (fst (dag.merge_node n d))
1174 else dag.reverse_lookup d n'.
1175
1176 Axiom fst_merge_node
1177 : forall {descr : description} (n : node idx) (d : t),
1178 fst (dag.merge_node n d) = match reverse_lookup d n with
1179 | Some i => i
1180 | None => size d
1181 end.
1182
1183 Axiom lookup_bounds_merge_node
1184 : forall {descr : description} (n : node idx) (d : t) i
1185 {ok : ok d},
1186 dag.lookup_bounds (snd (dag.merge_node n d)) i = match dag.lookup_bounds d i with
1187 | Some v => Some v
1188 | None
1189 => if (i =? size d)%N && Option.is_None (reverse_lookup d n)
1190 then bound_node_idx_via_PHOAS (lookup_bounds d) n
1191 else None
1192 end.
1193
1194 Axiom lookup_empty : forall i, lookup empty i = None.
1195 Axiom reverse_lookup_empty : forall n, reverse_lookup empty n = None.
1196 Axiom lookup_bounds_empty : forall i, lookup_bounds empty i = None.
1197 Axiom size_empty : size empty = 0%N.
1198 Axiom size_ok_empty : size_ok empty.
1199
1200 Axiom size_merge_node
1201 : forall {descr:description} n (d:t),
1202 size (snd (merge_node n d)) = match reverse_lookup d n with Some _ => size d | None => N.succ (size d) end.
1203 Axiom size_ok_merge_node
1204 : forall {descr:description} n (d:t),
1205 ok d -> size_ok (snd (merge_node n d)).
1206 End DagProperties.
1207 Module DagExtraProperties (Import dag : DagDefinitions) (Import dag' : DagExtraDefinitionsSig dag) (Import dag'' : DagProperties dag dag').
1208 Lemma iff_reverse_lookup_lookup d {ok : ok d}
1209 : forall i n, reverse_lookup d n = Some i <-> lookup d i = Some n.
1210 Proof. apply ok. Qed.
1211
1212 Lemma lookup_value_size d {ok : ok d}
1213 : forall i n, lookup d i = Some n -> (i < size d)%N.
1214 Proof. apply ok. Qed.
1215
1216 Lemma lookup_size_error d {ok : ok d}
1217 : forall i, (size d <= i)%N -> lookup d i = None.
1218 Proof.
1219 intro i; generalize (lookup_value_size d i); destruct lookup; intuition.
1220 specialize_under_binders_by reflexivity.
1221 lia.
1222 Qed.
1223
1224 Lemma lookup_error_size d {ok : ok d}
1225 : forall i, lookup d i = None -> (size d <= i)%N.
1226 Proof. apply ok. Qed.
1227
1228 Lemma lookup_bounds_ok (d : t) {ok : ok d}
1229 : forall i r, dag.lookup d i = Some r -> dag.lookup_bounds d i = bound_node_idx_via_PHOAS (dag.lookup_bounds d) r.
1230 Proof. apply ok. Qed.
1231
1232 Lemma lookup_bounds_lookup (d : t) {ok : ok d}
1233 : forall i, dag.lookup_bounds d i = match dag.lookup d i with
1234 | None => None
1235 | Some r => bound_node_idx_via_PHOAS (dag.lookup_bounds d) r
1236 end.
1237 Proof.
1238 intro i.
1239 pose proof (lookup_bounds_ok d i).
1240 pose proof (lookup_error_size d i).
1241 pose proof (lookup_value_size d i).
1242 destruct ok; cbv [bounds_ok] in *; destruct_head'_and.
1243 destruct lookup_bounds eqn:?, lookup eqn:?.
1244 all: specialize_under_binders_by reflexivity.
1245 all: specialize_under_binders_by eassumption.
1246 all: auto.
1247 all: congruence.
1248 Qed.
1249
1250 Lemma all_nodes_idx_present (d : t)
1251 {ok : ok d}
1252 {all_ok : all_nodes_ok d}
1253 : forall i r, dag.lookup d i = Some r -> Forall (fun a => dag.lookup d a <> None) (snd r).
1254 Proof.
1255 cbv [all_nodes_ok] in *; destruct_head'_and.
1256 intros; specialize_under_binders_by eassumption.
1257 cbv [node_ok node_args_ok node_arg_ok] in *; destruct_head'_and.
1258 let H := match goal with H : Forall _ ?l |- Forall _ ?l => H end in
1259 induction H; constructor; try assumption.
1260 repeat match goal with
1261 | [ H : lookup _ _ = Some _ |- _ ] => apply lookup_value_size in H; [ | assumption .. ]
1262 | [ H : lookup _ _ = None |- _ ] => apply lookup_error_size in H; [ | assumption .. ]
1263 | [ |- None <> None ] => exfalso
1264 | [ |- Some _ <> None ] => congruence
1265 | [ |- ?x <> None ] => destruct x eqn:?
1266 | [ |- False ] => lia
1267 end.
1268 Qed.
1269
1270 Lemma reverse_lookup_gensym s (d : t)
1271 {ok : ok d}
1272 {all_nodes_ok : all_nodes_ok d}
1273 : dag.reverse_lookup d (gensym s d) = None.
1274 Proof.
1275 cbv [dag'.all_nodes_ok] in *.
1276 destruct (reverse_lookup d (gensym s d)) as [i|] eqn:H; [ | reflexivity ].
1277 rewrite iff_reverse_lookup_lookup in H by assumption.
1278 cbv [node_ok gensym] in *.
1279 repeat first [ progress destruct_head'_and
1280 | progress specialize_under_binders_by eassumption
1281 | progress specialize_under_binders_by reflexivity ].
1282 apply lookup_value_size in H; trivial.
1283 lia.
1284 Qed.
1285
1286 Lemma lookup_merge_node_gensym {descr : description} s (d : t) i
1287 {ok : ok d}
1288 {all_nodes_ok : all_nodes_ok d}
1289 : dag.lookup (snd (dag.merge_node (gensym s d) d)) i
1290 = if (i =? size d)%N
1291 then Some (gensym s d)
1292 else dag.lookup d i.
1293 Proof.
1294 rewrite lookup_merge_node, reverse_lookup_gensym by assumption.
1295 cbv [andb is_None].
1296 break_innermost_match; try reflexivity; reflect_hyps; subst; try tauto.
1297 rewrite lookup_size_error in * by first [ assumption | lia ].
1298 congruence.
1299 Qed.
1300
1301 Lemma fst_merge_node_gensym {descr : description} s (d : t)
1302 {ok : ok d}
1303 {all_nodes_ok : all_nodes_ok d}
1304 : fst (dag.merge_node (gensym s d) d) = size d.
1305 Proof.
1306 rewrite fst_merge_node, reverse_lookup_gensym by assumption; reflexivity.
1307 Qed.
1308
1309 Lemma bound_node_gensym s (d : t) {lookup_bounds}
1310 : bound_node_idx_via_PHOAS lookup_bounds (gensym s d) = Some {| ZRange.lower := 0; ZRange.upper := Z.ones (Z.of_N s) |}.
1311 Proof. reflexivity. Qed.
1312
1313 Lemma size_merge_node_le {descr:description} n (d:t)
1314 : (size d <= size (snd (merge_node n d)))%N.
1315 Proof.
1316 rewrite size_merge_node; break_innermost_match; lia.
1317 Qed.
1318
1319 Lemma size_merge_node_gensym {descr:description} s (d:t)
1320 {ok : ok d}
1321 {all_nodes_ok : all_nodes_ok d}
1322 : size (snd (merge_node (gensym s d) d)) = N.succ (size d).
1323 Proof. rewrite size_merge_node, reverse_lookup_gensym by assumption; reflexivity. Qed.
1324
1325 Global Instance empty_ok : ok empty | 10.
1326 Proof.
1327 repeat apply conj; intros *;
1328 cbv [bounds_ok]; intros *;
1329 rewrite ?lookup_empty, ?reverse_lookup_empty, ?size_empty, ?lookup_bounds_empty; try apply size_ok_empty;
1330 intuition first [ congruence | lia ].
1331 Qed.
1332 Global Instance empty_all_nodes_ok : all_nodes_ok empty | 10.
1333 Proof.
1334 repeat intro; subst; rewrite lookup_empty in *; congruence.
1335 Qed.
1336 Global Instance merge_node_ok {descr:description} {n:node idx} {d : t} {dok : ok d} {dnok : all_nodes_ok d} {nok : node_args_ok (size d) (snd n)} : ok (snd (merge_node n d)) | 10.
1337 Proof.
1338 destruct (dok).
1339 repeat apply conj; cbv [bounds_ok node_args_ok node_arg_ok all_nodes_ok node_ok] in *; intros *;
1340 rewrite Forall_forall_iff_nth_error in nok;
1341 setoid_rewrite Forall_forall_iff_nth_error in dnok.
1342 all: split_and.
1343 all: rewrite ?lookup_merge_node, ?reverse_lookup_merge_node, ?fst_merge_node, ?size_merge_node, ?lookup_bounds_merge_node by assumption.
1344 all: erewrite ?(@bound_node_idx_via_PHOAS_Forall_ext (lookup_bounds (snd (merge_node _ _))))
1345 by (rewrite Forall_forall_iff_nth_error; intros *; rewrite lookup_bounds_merge_node by assumption; reflexivity).
1346 all: let tac :=
1347 repeat first [ progress subst
1348 | progress intros
1349 | progress destruct_head'_and
1350 | progress reflect_hyps
1351 | break_innermost_match_step
1352 | break_innermost_match_hyps_step
1353 | apply size_ok_merge_node
1354 | lia
1355 | progress inversion_option
1356 | progress specialize_under_binders_by reflexivity
1357 | congruence
1358 | tauto
1359 | apply bound_node_idx_via_PHOAS_Forall_ext
1360 | rewrite Forall_forall_iff_nth_error
1361 | match goal with
1362 | [ H : lookup ?d (size ?d) = Some _ |- _ ] => apply lookup_value_size in H; [ | assumption .. ]
1363 | [ H : ?x = bound_node_idx_via_PHOAS _ _ |- ?y = bound_node_idx_via_PHOAS _ _ ]
1364 => replace y with x by congruence; rewrite H;
1365 apply bound_node_idx_via_PHOAS_Forall_ext
1366 end
1367 | split
1368 | progress split_iff ] in
1369 do 2 (tac;
1370 repeat match goal with
1371 | [ H : _ = Some _ |- _ ] => progress specialize_all_ways_under_binders_by rewrite H
1372 | [ H : _ = None |- _ ] => progress specialize_all_ways_under_binders_by exact H
1373 end;
1374 tac).
1375 Qed.
1376 Global Instance merge_node_all_nodes_ok {descr:description} {n:node idx} {d : t} {dok : ok d} {dnok : all_nodes_ok d} {nok : node_ok (size d) n}
1377 : all_nodes_ok (snd (merge_node n d)) | 10.
1378 Proof.
1379 cbv [all_nodes_ok] in *; intros i r; specialize (dnok i r).
1380 rewrite lookup_merge_node in * by assumption.
1381 cbv [andb is_None]; break_innermost_match; intros; inversion_option; reflect_hyps; subst; auto.
1382 Qed.
1383 Global Instance gensym_node_ok s d : node_ok (size d) (gensym s d) | 10.
1384 Proof.
1385 cbv [node_ok gensym]; split; cbn [snd]; try exact _.
1386 inversion 1; subst; reflexivity.
1387 Qed.
1388 Global Hint Extern 1 (node_ok (size _) (gensym _ _)) => exact (@gensym_node_ok _ _) : typeclass_instances.
1389
1390 Lemma eq_fst_merge_node_change_descr {descr1 descr2 : description} (n : node idx) (d : t)
1391 : fst (@merge_node descr1 n d) = fst (@merge_node descr2 n d).
1392 Proof.
1393 rewrite !fst_merge_node; reflexivity.
1394 Qed.
1395
1396 Lemma lookup_merge_node' {descr1 descr2 : description} (n : node idx) (d : t)
1397 {ok : ok d}
1398 : dag.lookup (snd (@dag.merge_node descr1 n d)) (fst (@dag.merge_node descr2 n d)) = Some n.
1399 Proof.
1400 rewrite lookup_merge_node, fst_merge_node by assumption.
1401 cbv [andb is_None].
1402 repeat first [ rewrite iff_reverse_lookup_lookup in * by assumption
1403 | rewrite lookup_size_error in * by first [ assumption | lia ]
1404 | progress inversion_option
1405 | progress subst
1406 | reflexivity
1407 | progress reflect_hyps
1408 | lia
1409 | break_innermost_match_step ].
1410 Qed.
1411
1412 Lemma lookup_None d {ok : ok d}
1413 : forall i, lookup d i = None <-> (size d <= i)%N.
1414 Proof.
1415 intro i.
1416 pose proof (lookup_value_size d i).
1417 pose proof (lookup_size_error d i).
1418 pose proof (lookup_error_size d i).
1419 split; intro; destruct (lookup d i);
1420 specialize_under_binders_by first [ reflexivity | lia | eassumption ];
1421 inversion_option; first [ lia | congruence | auto ].
1422 Qed.
1423
1424 Lemma lookup_Some d {ok : ok d}
1425 : forall i, lookup d i <> None <-> (i < size d)%N.
1426 Proof.
1427 intro i.
1428 pose proof (lookup_value_size d i).
1429 pose proof (lookup_size_error d i).
1430 pose proof (lookup_error_size d i).
1431 split; intro; destruct (lookup d i);
1432 specialize_under_binders_by first [ reflexivity | lia | eassumption ];
1433 inversion_option; first [ lia | congruence | auto ].
1434 Qed.
1435
1436 Lemma lookup_ind d {ok : ok d} {dnok : all_nodes_ok d}
1437 (P : option (node idx) -> Prop)
1438 (PNone : P None)
1439 (PSome : forall o args,
1440 (exists i, dag.lookup d i = Some (o, args) /\ node_ok i (o, args))
1441 -> Forall (fun a => P (dag.lookup d a)) args
1442 -> P (Some (o, args)))
1443 : forall i, P (dag.lookup d i).
1444 Proof.
1445 induction i using (well_founded_induction N.lt_wf_0).
1446 destruct (lookup d i) as [ [o args] |] eqn:H'; [ | assumption ].
1447 apply PSome.
1448 { eexists; split; try eapply dnok; eassumption. }
1449 { apply dnok in H'.
1450 cbv [node_ok node_args_ok node_arg_ok] in *; destruct_head'_and.
1451 cbn [snd] in *.
1452 let H := match goal with H : Forall _ _ |- _ => H end in
1453 revert H.
1454 apply Forall_impl; eauto. }
1455 Qed.
1456 End DagExtraProperties.
1457 Module Type DagExtraPropertiesSig (dag : DagDefinitions) (dag' : DagExtraDefinitionsSig dag) (dag'' : DagProperties dag dag').
1458 Include DagExtraProperties dag dag' dag''.
1459 End DagExtraPropertiesSig.
1460 Module Type Dag.
1461 Include DagDefinitions.
1462 Include DagExtraDefinitions.
1463 Declare Module eager : EagerDagDefinitions.
1464 Include DagProperties.
1465 Include DagExtraProperties.
1466 End Dag.
1467 Module Old.
1468 Module dag <: Dag.
1469 Definition t : Type := list (node idx * description * option ZRange.zrange).
1470 Definition empty : t := nil.
1471 Definition size (d : t) : N := N.of_nat (List.length d).
1472 Definition lookup (d : t) (i : idx) : option (node idx)
1473 := option_map (fun '(n, _d, _b) => n) (List.nth_error d (N.to_nat i)).
1474 Definition lookup_bounds (d : t) (i : idx) : option ZRange.zrange
1475 := (n <- List.nth_error d (N.to_nat i); let '(_n, _d, b) := n in b)%option.
1476 Definition reverse_lookup (d : t) (i : node idx) : option idx
1477 := option_map N.of_nat (List.indexof (fun '(n', _, _) => node_beq N.eqb i n') d).
1478 Definition size_ok (d : t) : Prop
1479 := True.
1480 Definition merge_node {descr : description} (n : node idx) (d : t) : idx * t
1481 := match reverse_lookup d n with
1482 | Some i => (i, d)
1483 | None
1484 => (size d, d ++ [(n, descr, bound_node_idx_via_PHOAS (lookup_bounds d) n)])
1485 end.
1486
1487 Include DagExtraDefinitions.
1488
1489 Module eager <: EagerDagDefinitions.
1490 Definition t := list (idx * node idx * eager_description).
1491 Definition force (d : dag.t) : eager.t
1492 := List.map (fun '(idx, (n, descr, _)) => (N.of_nat idx, n, force_description descr))
1493 (List.enumerate d).
1494 Definition description_lookup (d : eager.t) (descr : string) : list idx
1495 := List.map (fun '(idx, _, _) => idx) (List.filter (fun '(_, _, descr') => match get_eager_description_description descr' with Some descr' => String.eqb descr descr' | _ => false end) d).
1496 Definition elements (d : t) : list (idx * node idx * eager_description) := d.
1497 End eager.
1498
1499 Lemma lookup_merge_node {descr : description} (n : node idx) (d : t) i
1500 {ok : ok d}
1501 : dag.lookup (snd (dag.merge_node n d)) i = match dag.lookup d i with
1502 | Some v => Some v
1503 | None
1504 => if (i =? size d)%N && Option.is_None (reverse_lookup d n)
1505 then Some n
1506 else None
1507 end.
1508 Proof.
1509 cbv [dag.merge_node andb is_None lookup dag.ok size] in *;
1510 repeat first [ assumption
1511 | reflexivity
1512 | lia
1513 | progress specialize_under_binders_by eassumption
1514 | progress subst
1515 | progress destruct_head'_and
1516 | progress reflect_hyps
1517 | progress cbn [fst snd option_map List.nth_error] in *
1518 | progress cbv [option_map] in *
1519 | rewrite Nat2N.id in *
1520 | rewrite nth_error_app in *
1521 | rewrite Nat.sub_diag in *
1522 | rewrite nth_error_length_error in * by lia
1523 | rewrite @nth_error_nil_error in *
1524 | congruence
1525 | break_innermost_match_step
1526 | match goal with
1527 | [ H : nth_error (_ :: _) ?x = _ |- _ ] => destruct x eqn:?; cbn [nth_error] in H
1528 end ].
1529 Qed.
1530
1531 Lemma reverse_lookup_merge_node {d : t}
1532 {ok : ok d} {descr : description} (n n' : node idx)
1533 : dag.reverse_lookup (snd (dag.merge_node n d)) n'
1534 = if node_beq N.eqb n' n
1535 then Some (fst (dag.merge_node n d))
1536 else dag.reverse_lookup d n'.
1537 Proof.
1538 cbv [dag.merge_node andb is_None reverse_lookup dag.ok size] in *;
1539 repeat first [ assumption
1540 | reflexivity
1541 | lia
1542 | congruence
1543 | progress inversion_option
1544 | progress specialize_under_binders_by eassumption
1545 | progress subst
1546 | progress destruct_head'_and
1547 | progress reflect_hyps
1548 | rewrite @indexof_app in *
1549 | progress cbv [option_map Crypto.Util.Option.value Crypto.Util.Option.sequence idx] in *
1550 | progress cbn [fst snd option_map indexof] in *
1551 | rewrite Nat.add_0_r
1552 | congruence
1553 | break_innermost_match_step
1554 | progress break_match
1555 | progress break_match_hyps ].
1556 Qed.
1557
1558 Lemma fst_merge_node {descr : description} (n : node idx) (d : t)
1559 : fst (dag.merge_node n d) = match reverse_lookup d n with
1560 | Some i => i
1561 | None => size d
1562 end.
1563 Proof. cbv [merge_node]; break_innermost_match; reflexivity. Qed.
1564
1565 Lemma lookup_bounds_merge_node
1566 {descr : description} (n : node idx) (d : t) i
1567 {ok : ok d}
1568 : dag.lookup_bounds (snd (dag.merge_node n d)) i = match dag.lookup_bounds d i with
1569 | Some v => Some v
1570 | None
1571 => if (i =? size d)%N && Option.is_None (reverse_lookup d n)
1572 then bound_node_idx_via_PHOAS (lookup_bounds d) n
1573 else None
1574 end.
1575 Proof.
1576 cbv [merge_node]; break_innermost_match; cbn [snd]; reflect_hyps.
1577 all: repeat first [ progress destruct_head'_and
1578 | progress subst
1579 | progress inversion_option
1580 | progress inversion_pair
1581 | reflexivity
1582 | assumption
1583 | lia
1584 | exfalso; assumption
1585 | rewrite Nat2N.id in *
1586 | rewrite ListUtil.nth_error_app
1587 | rewrite Nat.sub_diag in *
1588 | rewrite nth_error_length_error in * by lia
1589 | rewrite @nth_error_nil_error in *
1590 | break_innermost_match_step
1591 | break_innermost_match_hyps_step
1592 | progress cbv [lookup_bounds Crypto.Util.Option.bind size] in *
1593 | match goal with
1594 | [ H : nth_error (_ :: _) ?x = _ |- _ ] => destruct x eqn:?; cbn [nth_error] in H
1595 end
1596 | progress break_match ].
1597 Qed.
1598
1599 Lemma lookup_empty i : lookup empty i = None.
1600 Proof. cbv [empty lookup]; now rewrite nth_error_nil_error. Qed.
1601 Lemma reverse_lookup_empty n : reverse_lookup empty n = None.
1602 Proof. reflexivity. Qed.
1603 Lemma lookup_bounds_empty i : lookup_bounds empty i = None.
1604 Proof. cbv [empty lookup_bounds]; now rewrite nth_error_nil_error. Qed.
1605 Lemma size_empty : size empty = 0%N.
1606 Proof. reflexivity. Qed.
1607 Lemma size_ok_empty : size_ok empty.
1608 Proof. exact I. Qed.
1609
1610 Lemma size_merge_node {descr:description} n (d:t)
1611 : size (snd (merge_node n d)) = match reverse_lookup d n with Some _ => size d | None => N.succ (size d) end.
1612 Proof.
1613 cbv [merge_node size]; break_innermost_match; cbn [snd] in *; inversion_pair; subst; rewrite ?app_length; cbn [List.length]; lia.
1614 Qed.
1615
1616 Lemma size_ok_merge_node {descr:description} n (d:t)
1617 : ok d -> size_ok (snd (merge_node n d)).
1618 Proof. constructor. Qed.
1619
1620 Include DagExtraProperties.
1621 End dag.
1622 End Old.
1623 Module New.
1624 Module dag <: Dag.
1625 Module IdxMap <: UsualS := NMap <+ FMapFacts.Facts <+ Facts_RemoveHints <+ FMapFacts.AdditionalFacts.
1626 Module ListIdxMap <: UsualS := ListNMap.
1627 Module NodeIdxMap <: UsualS := ProdUsualMap OpMap ListIdxMap <+ FMapFacts.Facts <+ Facts_RemoveHints <+ FMapFacts.AdditionalFacts.
1628 Module IdxMapProperties := FMapFacts.OrdProperties IdxMap <+ OrdProperties_RemoveHints IdxMap.
1629 Module NodeIdxMapProperties := FMapFacts.OrdProperties NodeIdxMap <+ OrdProperties_RemoveHints NodeIdxMap.
1630
1631 Definition t : Type := NodeIdxMap.t idx * IdxMap.t (node idx * description * option ZRange.zrange) * N (* size *).
1632 Definition empty : t := (@NodeIdxMap.empty _, @IdxMap.empty _, 0%N).
1633 Definition size (d : t) : N := let '(_, _, sz) := d in sz.
1634 Definition lookup (d : t) (i : idx) : option (node idx)
1635 := let '(_, d, _) := d in option_map (fun '(n, _, _) => n) (IdxMap.find i d).
1636 Definition lookup_bounds (d : t) (i : idx) : option ZRange.zrange
1637 := (let '(_, d, _) := d in n <- IdxMap.find i d; let '(_n, _d, b) := n in b)%option.
1638 Definition reverse_lookup (d : t) (i : node idx) : option idx
1639 := let '(d, _, _) := d in NodeIdxMap.find i d.
1640 Definition size_ok (d : t) : Prop
1641 := let '(im, nm, n) := d in
1642 NodeIdxMap.cardinal im = N.to_nat (size d)
1643 /\ IdxMap.cardinal nm = N.to_nat (size d).
1644 Definition merge_node {descr : description} (n : node idx) (d : t) : idx * t
1645 := match reverse_lookup d n with
1646 | Some i => (i, d)
1647 | None
1648 => let lookup_bounds := lookup_bounds d in
1649 let '(d, d', sz) := d in
1650 (sz, (NodeIdxMap.add n sz d, IdxMap.add sz (n, descr, bound_node_idx_via_PHOAS lookup_bounds n) d', N.succ sz))
1651 end.
1652
1653 Include DagExtraDefinitions.
1654
1655 Module eager <: EagerDagDefinitions.
1656 Definition t := list (idx * node idx * eager_description).
1657 Definition force (d : dag.t) : eager.t
1658 := List.map (fun '(idx, (n, descr, _b)) => (idx, n, force_description descr))
1659 (IdxMap.elements (let '(_, d, _) := d in d)).
1660 Definition description_lookup (d : eager.t) (descr : string) : list idx
1661 := List.map (fun '(idx, _, _) => idx) (List.filter (fun '(_, _, descr') => match get_eager_description_description descr' with Some descr' => String.eqb descr descr' | _ => false end) d).
1662 Definition elements (d : t) : list (idx * node idx * eager_description) := d.
1663 End eager.
1664
1665 Lemma lookup_merge_node {descr : description} (n : node idx) (d : t) i
1666 {ok : ok d}
1667 : dag.lookup (snd (dag.merge_node n d)) i = match dag.lookup d i with
1668 | Some v => Some v
1669 | None
1670 => if (i =? size d)%N && Option.is_None (reverse_lookup d n)
1671 then Some n
1672 else None
1673 end.
1674 Proof.
1675 cbv [dag.merge_node andb is_None lookup dag.ok size option_map] in *;
1676 let tac :=
1677 repeat first [ assumption
1678 | reflexivity
1679 | lia
1680 | congruence
1681 | progress specialize_under_binders_by eassumption
1682 | progress subst
1683 | progress destruct_head'_and
1684 | progress destruct_head' iff
1685 | progress split_iff
1686 | progress break_innermost_match_hyps
1687 | progress specialize_by reflexivity
1688 | progress inversion_option
1689 | progress inversion_pair
1690 | progress reflect_hyps
1691 | progress cbn [fst snd option_map] in *
1692 | rewrite IdxMap.add_o
1693 | break_innermost_match_step ] in
1694 tac; specialize_all_ways; tac.
1695 Qed.
1696
1697 Lemma lookup_bounds_merge_node {descr : description} (n : node idx) (d : t) i
1698 {ok : ok d}
1699 : dag.lookup_bounds (snd (dag.merge_node n d)) i = match dag.lookup_bounds d i with
1700 | Some v => Some v
1701 | None
1702 => if (i =? size d)%N && Option.is_None (reverse_lookup d n)
1703 then bound_node_idx_via_PHOAS (lookup_bounds d) n
1704 else None
1705 end.
1706 Proof.
1707 destruct (ok).
1708 cbv [merge_node]; cbv [size_ok] in *; break_innermost_match; cbn [snd]; reflect_hyps.
1709 all: let tac :=
1710 repeat first [ progress destruct_head'_and
1711 | progress subst
1712 | progress inversion_option
1713 | progress inversion_pair
1714 | reflexivity
1715 | assumption
1716 | lia
1717 | exfalso; assumption
1718 | rewrite IdxMap.add_o
1719 | progress specialize_under_binders_by reflexivity
1720 | break_innermost_match_step
1721 | break_innermost_match_hyps_step
1722 | progress cbv [lookup_bounds Crypto.Util.Option.bind size bounds_ok option_map lookup] in * ] in
1723 tac;
1724 repeat match goal with
1725 | [ H : _ = Some _ |- _ ] => progress specialize_all_ways_under_binders_by rewrite H
1726 end;
1727 tac.
1728 Qed.
1729
1730 Lemma reverse_lookup_merge_node {d : t}
1731 {ok : ok d} {descr : description} (n n' : node idx)
1732 : dag.reverse_lookup (snd (dag.merge_node n d)) n'
1733 = if node_beq N.eqb n' n
1734 then Some (fst (dag.merge_node n d))
1735 else dag.reverse_lookup d n'.
1736 Proof.
1737 cbv [dag.merge_node andb is_None reverse_lookup dag.ok size] in *;
1738 repeat first [ assumption
1739 | reflexivity
1740 | lia
1741 | congruence
1742 | progress specialize_under_binders_by eassumption
1743 | progress subst
1744 | progress destruct_head'_and
1745 | progress reflect_hyps
1746 | progress cbn [fst snd option_map] in *
1747 | rewrite NodeIdxMap.add_o
1748 | break_innermost_match_step ].
1749 Qed.
1750
1751 Lemma fst_merge_node {descr : description} (n : node idx) (d : t)
1752 : fst (dag.merge_node n d) = match reverse_lookup d n with
1753 | Some i => i
1754 | None => size d
1755 end.
1756 Proof. cbv [merge_node]; break_innermost_match; reflexivity. Qed.
1757
1758 Lemma lookup_empty i : lookup empty i = None.
1759 Proof. cbv [empty lookup]; now rewrite IdxMap.find_empty. Qed.
1760 Lemma reverse_lookup_empty n : reverse_lookup empty n = None.
1761 Proof. cbv [empty reverse_lookup]; now rewrite NodeIdxMap.find_empty. Qed.
1762 Lemma lookup_bounds_empty i : lookup_bounds empty i = None.
1763 Proof. cbv [empty lookup_bounds]; now rewrite IdxMap.find_empty. Qed.
1764 Lemma size_empty : size empty = 0%N.
1765 Proof. reflexivity. Qed.
1766 Lemma size_ok_empty : size_ok empty.
1767 Proof. cbv [size_ok empty size]; now rewrite NodeIdxMapProperties.P.cardinal_1, IdxMapProperties.P.cardinal_1 by first [ apply NodeIdxMap.empty_1 | apply IdxMap.empty_1 ]. Qed.
1768
1769 Lemma size_merge_node {descr:description} n (d:t)
1770 : size (snd (merge_node n d)) = match reverse_lookup d n with Some _ => size d | None => N.succ (size d) end.
1771 Proof.
1772 cbv [merge_node size]; break_innermost_match; cbn [snd] in *; inversion_pair; subst; try reflexivity.
1773 Qed.
1774
1775 Lemma size_ok_merge_node {descr:description} n (d:t)
1776 : ok d -> size_ok (snd (merge_node n d)).
1777 Proof.
1778 cbv [merge_node size_ok size ok]; break_innermost_match; cbn [snd] in *; inversion_pair; subst;
1779 rewrite ?NodeIdxMap.cardinal_add, ?IdxMap.cardinal_add, ?NodeIdxMap.mem_find_b, ?IdxMap.mem_find_b; try solve [ intuition auto ]; [].
1780 cbv [reverse_lookup lookup option_map idx] in *.
1781 repeat first [ progress intros
1782 | progress destruct_head'_and
1783 | progress split_iff
1784 | congruence
1785 | lia
1786 | break_innermost_match_step
1787 | break_innermost_match_hyps_step
1788 | progress specialize_under_binders_by reflexivity
1789 | match goal with
1790 | [ H : _ = Some _ |- _ ] => progress specialize_under_binders_by rewrite H
1791 end ].
1792 Qed.
1793
1794 Include DagExtraProperties.
1795 End dag.
1796 End New.
1797 Require coqutil.Tactics.autoforward coqutil.Decidable coqutil.Tactics.Tactics.
1798 Module WithDag (dag : Dag).
1799 Global Arguments dag.t : simpl never.
1800 Global Arguments dag.empty : simpl never.
1801 Global Arguments dag.size : simpl never.
1802 Global Arguments dag.lookup : simpl never.
1803 Global Arguments dag.lookup_bounds : simpl never.
1804 Global Arguments dag.reverse_lookup : simpl never.
1805 Global Arguments dag.ok : simpl never.
1806 Global Arguments dag.all_nodes_ok : simpl never.
1807 Global Arguments dag.merge_node : simpl never.
1808 Global Arguments dag.gensym : simpl never.
1809 Global Strategy 1000 [
1810 dag.t
1811 dag.empty
1812 dag.size
1813 dag.lookup
1814 dag.lookup_bounds
1815 dag.reverse_lookup
1816 dag.ok
1817 dag.all_nodes_ok
1818 dag.merge_node
1819 dag.gensym
1820 ].
1821 Notation dag := dag.t.
1822 Declare Scope dagM_scope.
1823 Delimit Scope dagM_scope with dagM.
1824 Bind Scope dagM_scope with dag.M.
1825 Notation "x <- y ; f" := (dag.bind y (fun x => f%dagM)) : dagM_scope.
1826
1827 Section WithDag.
1828 Context (ctx : symbol -> option Z) (dag : dag.t).
1829 Definition reveal_step reveal (i : idx) : expr :=
1830 match dag.lookup dag i with
1831 | None => (* undefined *) ExprRef i
1832 | Some (op, args) => ExprApp (op, List.map reveal args)
1833 end.
1834 Fixpoint reveal (n : nat) (i : idx) :=
1835 match n with
1836 | O => ExprRef i
1837 | S n => reveal_step (reveal n) i
1838 end.
1839
1840 Definition reveal_node n '(op, args) :=
1841 ExprApp (op, List.map (reveal n) args).
1842
1843 (** given a set of indices, get the set of indices of their arguments *)
1844 Definition reveal_gather_deps_args (ls : NSet.t) : NSet.t
1845 := fold_right
1846 (fun i so_far => match dag.lookup dag i with
1847 | None => so_far
1848 | Some (_op, args) => fold_right NSet.add so_far args
1849 end)
1850 NSet.empty
1851 (NSet.elements ls).
1852
1853 (** given a set of seen indices and a set of newly-revealed indices,
1854 we want to merge the new indices into what's been seen and recurse
1855 on the new indices *)
1856 Definition reveal_gather_deps_step reveal_gather_deps (so_far : NSet.t) (new_idxs : NSet.t) : NSet.t
1857 := let new_idxs := NSet.diff new_idxs so_far in
1858 if NSet.is_empty new_idxs
1859 then so_far
1860 else reveal_gather_deps (NSet.union so_far new_idxs) (reveal_gather_deps_args new_idxs).
1861
1862 Fixpoint reveal_gather_deps_list (n : nat) (so_far : NSet.t) (new_idxs : NSet.t) : NSet.t
1863 := match n with
1864 | O => NSet.union so_far new_idxs
1865 | S n => reveal_gather_deps_step (reveal_gather_deps_list n) so_far new_idxs
1866 end.
1867
1868 Definition reveal_gather_deps (n : nat) (i : idx) : NSet.t
1869 := reveal_gather_deps_list n NSet.empty (NSet.singleton i).
1870
1871 Definition reveal_step_from_deps reveal (deps : NSet.t) (i : idx) : expr
1872 := if NSet.mem i deps
1873 then match dag.lookup dag i with
1874 | None => (* undefined *) ExprRef i
1875 | Some (op, args) => ExprApp (op, List.map reveal args)
1876 end
1877 else ExprRef i.
1878 Fixpoint reveal_from_deps_fueled (fuel : nat) (deps : NSet.t) (i : idx) :=
1879 match fuel with
1880 | O => ExprRef i
1881 | S fuel => reveal_step_from_deps (reveal_from_deps_fueled fuel deps) deps i
1882 end.
1883 (** depth determines which indices get expanded, but all references
1884 to the same index get expanded if they appear in the output *)
1885 Definition reveal_at_least n (i : idx) : expr
1886 := reveal_from_deps_fueled (S (N.to_nat (dag.size dag))) (reveal_gather_deps n i) i.
1887
1888 Definition reveal_node_at_least n '(op, args) :=
1889 ExprApp (op, List.map (reveal_at_least n) args).
1890
1891 Local Unset Elimination Schemes.
1892 Inductive eval : expr -> Z -> Prop :=
1893 | ERef i op args args' n
1894 (_:dag.lookup dag i = Some (op, args))
1895 (_:List.Forall2 eval (map ExprRef args) args')
1896 (_:interp_op ctx op args' = Some n)
1897 : eval (ExprRef i) n
1898 | EApp op args args' n
1899 (_:List.Forall2 eval args args')
1900 (_:interp_op ctx op args' = Some n)
1901 : eval (ExprApp (op, args)) n.
1902
1903 Variant eval_node : node idx -> Z -> Prop :=
1904 | ENod op args args' n
1905 (_:List.Forall2 eval (map ExprRef args) args')
1906 (_:interp_op ctx op args' = Some n)
1907 : eval_node (op, args) n.
1908
1909
1910 Section eval_ind.
1911 Context (P : expr -> Z -> Prop)
1912 (HRef : forall i op args args' n, dag.lookup dag i = Some (op, args) ->
1913 Forall2 (fun e n => eval e n /\ P e n) (map ExprRef args) args' ->
1914 interp_op ctx op args' = Some n ->
1915 P (ExprRef i) n)
1916 (HApp : forall op args args' n,
1917 Forall2 (fun i e => eval i e /\ P i e) args args' ->
1918 interp_op ctx op args' = Some n ->
1919 P (ExprApp (op, args)) n).
1920 Fixpoint eval_ind i n (pf : eval i n) {struct pf} : P i n :=
1921 match pf with
1922 | ERef _ _ _ _ _ A B C => HRef _ _ _ _ _ A (Forall2_weaken (fun _ _ D => conj D (eval_ind _ _ D)) _ _ B) C
1923 | EApp _ _ _ _ A B => HApp _ _ _ _ (Forall2_weaken (fun _ _ C => conj C (eval_ind _ _ C)) _ _ A) B
1924 end.
1925 End eval_ind.
1926
1927 Lemma eval_eval : forall e v1, eval e v1 -> forall v2, eval e v2 -> v1=v2.
1928 Proof using Type.
1929 induction 1; inversion 1; subst;
1930 enough (args' = args'0) by congruence;
1931 try replace args0 with args in * by congruence.
1932 { eapply Forall2_map_l in H0.
1933 eapply Forall2_flip in H0.
1934 eapply (proj1 (Forall2_map_l _ _ _)) in H5.
1935 epose proof Forall2_trans H0 H5 as HH.
1936 eapply Forall2_eq, Forall2_weaken, HH; cbv beta; clear; firstorder. }
1937 { eapply Forall2_flip in H.
1938 epose proof Forall2_trans H H4 as HH.
1939 eapply Forall2_eq, Forall2_weaken, HH; cbv beta; clear; firstorder. }
1940 Qed.
1941
1942 Lemma eval_eval_Forall2 xs vxs (_ : Forall2 eval xs vxs)
1943 vys (_ : Forall2 eval xs vys) : vxs = vys.
1944 Proof using Type.
1945 revert dependent vys; induction H; inversion 1; subst;
1946 eauto; eauto using f_equal2, IHForall2, eval_eval.
1947 Qed.
1948
1949 Lemma eval_reveal : forall n i, forall v, eval (ExprRef i) v ->
1950 forall e, reveal n i = e -> eval e v.
1951 Proof using Type.
1952 induction n; cbn [reveal]; cbv [reveal_step]; intros; subst; eauto; [].
1953 inversion H; subst; clear H.
1954 rewrite H1; econstructor; try eassumption; [].
1955 eapply (proj1 (Forall2_map_l _ _ _)) in H2.
1956 clear dependent i; clear dependent v.
1957 induction H2; cbn; eauto.
1958 Qed.
1959
1960 Lemma eval_node_reveal_node : forall n v, eval_node n v ->
1961 forall f e, reveal_node f n = e -> eval e v.
1962 Proof using Type.
1963 cbv [reveal_node]; inversion 1; intros; subst.
1964 econstructor; eauto.
1965 eapply (proj1 (Forall2_map_l _ _ _)) in H0; eapply Forall2_map_l.
1966 eapply Forall2_weaken; try eassumption; []; cbv beta; intros.
1967 eapply eval_reveal; eauto.
1968 Qed.
1969
1970 Lemma eval_reveal_from_deps_fueled deps : forall n i, forall v, eval (ExprRef i) v ->
1971 forall e, reveal_from_deps_fueled n deps i = e -> eval e v.
1972 Proof using Type.
1973 induction n; cbn [reveal_from_deps_fueled]; cbv [reveal_step_from_deps]; intros; subst; eauto; [].
1974 break_innermost_match_step; eauto; [].
1975 inversion H; subst; clear H.
1976 rewrite H1; econstructor; try eassumption; [].
1977 eapply (proj1 (Forall2_map_l _ _ _)) in H2.
1978 clear dependent i; clear dependent v.
1979 induction H2; cbn; eauto.
1980 Qed.
1981
1982 Lemma eval_reveal_at_least : forall n i, forall v, eval (ExprRef i) v ->
1983 forall e, reveal_at_least n i = e -> eval e v.
1984 Proof using Type.
1985 cbv [reveal_at_least].
1986 intros; eapply eval_reveal_from_deps_fueled; eassumption.
1987 Qed.
1988
1989 Lemma eval_node_reveal_node_at_least : forall n v, eval_node n v ->
1990 forall f e, reveal_node_at_least f n = e -> eval e v.
1991 Proof using Type.
1992 cbv [reveal_node]; inversion 1; intros; subst.
1993 econstructor; eauto.
1994 eapply (proj1 (Forall2_map_l _ _ _)) in H0; eapply Forall2_map_l.
1995 eapply Forall2_weaken; try eassumption; []; cbv beta; intros.
1996 eapply eval_reveal_at_least; eauto.
1997 Qed.
1998 End WithDag.
1999
2000 Definition merge_node {descr : description} (n : node idx) : dag.M idx
2001 := dag.merge_node n.
2002
2003 Fixpoint merge {descr : description} (e : expr) (d : dag) : idx * dag :=
2004 match e with
2005 | ExprRef i => (i, d)
2006 | ExprApp (op, args) =>
2007 let idxs_d := List.foldmap merge args d in
2008 let idxs := if commutative op
2009 then N.sort (fst idxs_d)
2010 else (fst idxs_d) in
2011 merge_node (op, idxs) (snd idxs_d)
2012 end.
2013
2014 Lemma node_beq_sound e x : node_beq N.eqb e x = true -> e = x.
2015 Proof using Type.
2016 eapply Prod.internal_prod_dec_bl.
2017 { intros X Y; destruct (op_beq_spec X Y); congruence. }
2018 { intros X Y. eapply ListUtil.internal_list_dec_bl, N.eqb_eq. }
2019 Qed.
2020
2021 Lemma eval_weaken_merge_node G d {dok : dag.ok d} {descr:description} x e n : eval G d e n -> eval G (snd (dag.merge_node x d)) e n.
2022 Proof using Type.
2023 induction 1; subst; econstructor; eauto.
2024 { erewrite dag.lookup_merge_node by assumption.
2025 match goal with H : _ |- _ => rewrite H end; reflexivity. }
2026 all : eapply Forall2_weaken; [|eassumption].
2027 { intuition eauto. eapply H2. }
2028 { intuition eauto. eapply H1. }
2029 Qed.
2030
2031 Lemma eval_weaken_symbols G1 G2 d e n
2032 (H : forall s v, G1 s = Some v -> G2 s = Some v)
2033 : eval G1 d e n -> eval G2 d e n.
2034 Proof using Type.
2035 induction 1; subst; econstructor;
2036 intuition eauto using interp_op_weaken_symbols.
2037 { eapply Forall2_weaken; [|eassumption]; intros ? ? (?&?); eauto. }
2038 { eapply Forall2_weaken; [|eassumption]; intros ? ? (?&?); eauto. }
2039 Qed.
2040
2041 Lemma eval_eval0 d e n G : eval (fun _ => None) d e n -> eval G d e n.
2042 Proof using Type. eapply eval_weaken_symbols; congruence. Qed.
2043
2044 Lemma permute_commutative G op args n : commutative op = true ->
2045 interp_op G op args = Some n ->
2046 forall args', Permutation.Permutation args args' ->
2047 interp_op G op args' = Some n.
2048 Proof using Type.
2049 destruct op; inversion 1; cbn; intros ? ? Hp;
2050 try (erewrite <- Z.fold_right_Proper_Permutation_add; eauto);
2051 try (erewrite <- Z.fold_right_Proper_Permutation_mul; eauto);
2052 try (erewrite <- Z.fold_right_Proper_Permutation_land; eauto);
2053 try (erewrite <- Z.fold_right_Proper_Permutation_lor; eauto);
2054 try (erewrite <- Z.fold_right_Proper_Permutation_lxor; eauto).
2055 { erewrite <-(Z.fold_right_Proper_Permutation_add _ _ eq_refl _ (map _ args'));
2056 eauto using Permutation.Permutation_map. }
2057 Qed.
2058
2059 (* the gensym state cannot map anything past the end of the dag *)
2060 Definition gensym_ok (G : symbol -> option Z) (d : dag) := forall s _v, G s = Some _v -> (s < dag.size d)%N.
2061 Definition dag_ok G (d : dag) := dag.ok d /\ dag.all_nodes_ok d /\ forall i r, dag.lookup d i = Some r -> exists v, eval G d (ExprRef i) v.
2062 Definition gensym_dag_ok G d := gensym_ok G d /\ dag_ok G d.
2063
2064 Lemma gensym_ok_size_Proper G d1 d2
2065 (H : (dag.size d1 <= dag.size d2)%N)
2066 : gensym_ok G d1 -> gensym_ok G d2.
2067 Proof using Type. cbv [gensym_ok]; intros; specialize_under_binders_by eassumption; lia. Qed.
2068
2069 Lemma gensym_ok_merge_node G d {descr:description} n
2070 : gensym_ok G d -> gensym_ok G (snd (dag.merge_node n d)).
2071 Proof using Type. apply gensym_ok_size_Proper, dag.size_merge_node_le. Qed.
2072
2073 Lemma empty_gensym_dag_ok : gensym_dag_ok (fun _ => None) dag.empty.
2074 Proof using Type.
2075 cbv [gensym_dag_ok dag_ok gensym_ok].
2076 repeat match goal with |- _ /\ _ => split end; try exact _; intros *;
2077 rewrite ?dag.lookup_empty; try congruence.
2078 Qed.
2079
2080 Lemma eval_merge_node {descr descr' descr'' descr'''} :
2081 forall G d, gensym_dag_ok G d ->
2082 forall op args n, let e := (op, args) in
2083 eval G d (ExprApp (op, List.map ExprRef args)) n ->
2084 eval G (snd (@merge_node descr e d)) (ExprRef (fst (@merge_node descr' e d))) n /\
2085 gensym_dag_ok G (snd (@merge_node descr'' e d)) /\
2086 forall i e', eval G d i e' -> eval G (snd (@merge_node descr''' e d)) i e'.
2087 Proof using Type.
2088 intros.
2089 cbv beta delta [merge_node].
2090 inversion H0; subst.
2091 cbv [gensym_dag_ok dag_ok] in *; destruct_head'_and.
2092 assert (Hnok : node_ok (dag.size d) e).
2093 { subst e; cbv [node_ok]; split; intros; inversion_pair; subst; cbn [interp_op snd] in *.
2094 all: break_innermost_match_hyps; inversion_option; subst.
2095 all: cbv [gensym_ok] in *.
2096 all: specialize_under_binders_by eassumption; try lia.
2097 cbv [node_args_ok node_arg_ok].
2098 match goal with
2099 | [ H : forall s v, ?G s = Some v -> (s < dag.size ?d)%N,
2100 H' : Forall2 (eval ?G ?d) (map ExprRef ?args) ?args',
2101 H'' : dag.ok ?d
2102 |- Forall _ ?args ]
2103 => clear -H H' H''; revert args' H'; induction args;
2104 inversion 1; subst; constructor; eauto
2105 end.
2106 inversion_one_head' @eval.
2107 eapply dag.lookup_value_size; eauto. }
2108 repeat match goal with |- _ /\ _ => split end; try exact _.
2109 1: econstructor; try eassumption.
2110 all: eauto using Forall2_weaken, eval_weaken_merge_node.
2111 all: try now apply gensym_ok_merge_node.
2112 { now rewrite dag.lookup_merge_node' by assumption. }
2113 { apply @dag.merge_node_ok; try assumption.
2114 apply Hnok. }
2115 { intros *; rewrite dag.lookup_merge_node by assumption.
2116 break_innermost_match; inversion 1; subst; specialize_under_binders_by eassumption; destruct_head'_ex.
2117 all: eauto using eval_weaken_merge_node.
2118 reflect_hyps; destruct_head'_and; subst.
2119 lazymatch goal with
2120 | [ |- context[snd (@dag.merge_node ?descr ?e ?d)] ]
2121 => replace (dag.size d) with (fst (@dag.merge_node descr e d))
2122 by (rewrite dag.fst_merge_node; break_innermost_match; congruence)
2123 end.
2124 eexists; econstructor;
2125 [ rewrite dag.lookup_merge_node' by assumption; reflexivity
2126 | eauto using Forall2_weaken, eval_weaken_merge_node .. ]. }
2127 Qed.
2128
2129 Import coqutil.Tactics.autoforward coqutil.Decidable coqutil.Tactics.Tactics.
2130 Global Set Default Goal Selector "1".
2131
2132 Lemma eval_merge {descr:description} G :
2133 forall e n,
2134 forall d, gensym_dag_ok G d ->
2135 eval G d e n ->
2136 eval G (snd (merge e d)) (ExprRef (fst (merge e d))) n /\
2137 gensym_dag_ok G (snd (merge e d)) /\
2138 forall i e', eval G d i e' -> eval G (snd (merge e d)) i e'.
2139 Proof using Type.
2140 induction e; intros; eauto; [].
2141 rename n0 into v.
2142
2143 set (merge _ _) as m; cbv beta iota delta [merge] in m; fold @merge in m.
2144 destruct n as (op&args).
2145 repeat match goal with
2146 m := let x := ?A in @?B x |- _ =>
2147 let y := fresh x in
2148 set A as y;
2149 let m' := eval cbv beta in (B y) in
2150 change m' in (value of m)
2151 end.
2152
2153 inversion H1; clear H1 ; subst.
2154
2155 cbn [fst snd] in *.
2156 assert (gensym_dag_ok G (snd idxs_d) /\
2157 Forall2 (fun i v => eval G (snd idxs_d) (ExprRef i) v) (fst idxs_d) args' /\
2158 forall i e', eval G d i e' -> eval G (snd idxs_d) i e'
2159 ) as HH; [|destruct HH as(?&?&?)].
2160 { clear m idxs H6 v op; revert dependent d; revert dependent args'.
2161 induction H; cbn; intros; inversion H4; subst;
2162 split_and; pose proof @Forall2_weaken; typeclasses eauto 8 with core. }
2163 clearbody idxs_d.
2164
2165 enough (eval G (snd idxs_d) (ExprApp (op, map ExprRef idxs)) v) by
2166 (unshelve (let lem := open_constr:(eval_merge_node _ _ ltac:(eassumption) op idxs v) in
2167 edestruct lem as (?&?&?)); eauto); clear m.
2168
2169 pose proof length_Forall2 H4; pose proof length_Forall2 H2.
2170
2171 cbn [fst snd] in *; destruct (commutative op) eqn:?; cycle 1; subst idxs.
2172
2173 { econstructor; eauto.
2174 eapply ListUtil.Forall2_forall_iff; rewrite map_length; try congruence; [].
2175 intros i Hi.
2176 unshelve (epose proof (proj1 (ListUtil.Forall2_forall_iff _ _ _ _ _ _) H2 i _));
2177 shelve_unifiable; try congruence; [].
2178 rewrite ListUtil.map_nth_default_always. eapply H8. }
2179
2180 pose proof N.Sort.Permuted_sort (fst idxs_d) as Hperm.
2181 eapply (Permutation.Permutation_Forall2 Hperm) in H2.
2182 case H2 as (argExprs&Hperm'&H2).
2183 eapply permute_commutative in H6; try eassumption; [].
2184 epose proof Permutation.Permutation_length Hperm.
2185 epose proof Permutation.Permutation_length Hperm'.
2186
2187 { econstructor; eauto.
2188 eapply ListUtil.Forall2_forall_iff; rewrite map_length; try congruence; [|].
2189 { setoid_rewrite <-H8. setoid_rewrite <-H9. eassumption. }
2190 intros i Hi.
2191 unshelve (epose proof (proj1 (ListUtil.Forall2_forall_iff _ _ _ _ _ _) H2 i _));
2192 shelve_unifiable; try trivial; [|].
2193 { setoid_rewrite <-H8. setoid_rewrite <-H9. eassumption. }
2194 rewrite ListUtil.map_nth_default_always. eapply H10. }
2195 Unshelve. all : constructor.
2196 Qed.
2197
2198 Definition zconst s (z:Z) := const (Z.land z (Z.ones (Z.of_N s)))%Z.
2199
2200 Section WithContext.
2201 Context (ctx : symbol -> option Z).
2202 Fixpoint interp_expr (e : expr) : option Z :=
2203 match e with
2204 | ExprApp (o, arges) =>
2205 args <- Option.List.lift (List.map interp_expr arges);
2206 interp_op ctx o args
2207 | _ => None
2208 end%option.
2209 End WithContext.
2210 Definition interp0_expr := interp_expr (fun _ => None).
2211
2212 Lemma eval_interp_expr G e : forall d v, interp_expr G e = Some v -> eval G d e v.
2213 Proof using Type.
2214 induction e; cbn; try discriminate; intros.
2215 case n in *; cbn [fst snd] in *.
2216 destruct (Option.List.lift _) eqn:? in *; try discriminate.
2217 econstructor; try eassumption; [].
2218 clear dependent v.
2219 revert dependent l0.
2220 induction H; cbn in *.
2221 { inversion 1; subst; eauto. }
2222 destruct (interp_expr _) eqn:? in *; cbn in *; try discriminate; [].
2223 destruct (fold_right _ _ _) eqn:? in *; cbn in *; try discriminate; [].
2224 specialize (fun d => H d _ eq_refl).
2225 inversion 1; subst.
2226 econstructor; trivial; [].
2227 eapply IHForall; eassumption.
2228 Qed.
2229
2230 Lemma eval_interp0_expr e v (H : interp0_expr e = Some v) : forall G d, eval G d e v.
2231 Proof using Type.
2232 cbv [interp0_expr]; intros.
2233 eapply eval_interp_expr, eval_weaken_symbols in H; [eassumption|congruence].
2234 Qed.
2235
2236 Section bound_expr_via_PHOAS.
2237 Import Crypto.Util.ZRange.
2238 Import API.Compilers.
2239 Import AbstractInterpretation.ZRange.Compilers.
2240 Import AbstractInterpretation.ZRangeProofs.Compilers.
2241
2242 Local Notation interp_PHOAS_op := (ZRange.ident.option.interp true).
2243
2244 Fixpoint bound_expr_via_PHOAS (d : dag) (e : Symbolic.expr) : option zrange
2245 := match e with
2246 | ExprApp (o, args)
2247 => match op_to_PHOAS_bounds o with
2248 | Some o
2249 => o (List.map (fun e 'tt => bound_expr_via_PHOAS d e) args)
2250 | None => None
2251 end
2252 | ExprRef i => dag.lookup_bounds d i
2253 end.
2254
2255 Local Coercion is_true : bool >-> Sortclass.
2256
2257 Fixpoint eval_bound_expr_via_PHOAS' G d (Hok : gensym_dag_ok G d) e b
2258 (H_dag : forall i b, dag.lookup_bounds d i = Some b -> forall v, eval G d (ExprRef i) v -> is_bounded_by_bool v b = true)
2259 {struct e}
2260 : bound_expr_via_PHOAS d e = Some b ->
2261 forall v, eval G d e v -> is_bounded_by_bool v b = true.
2262 Proof using Type.
2263 intros H v.
2264 assert (dag.ok d) by apply Hok.
2265 specialize (fun e v b H H_dag => eval_bound_expr_via_PHOAS' G d Hok e b H_dag H v).
2266 destruct e as [?|[n args] ]; cbn [bound_expr_via_PHOAS] in *.
2267 { clear eval_bound_expr_via_PHOAS'; intros; inversion_option; eauto. }
2268 let P := lazymatch type of eval_bound_expr_via_PHOAS' with forall e v, @?P e v => P end in
2269 assert (eval_bound_expr_via_PHOAS'_Forall : forall args', List.length args = List.length args' -> Forall2 P args args').
2270 { clear -eval_bound_expr_via_PHOAS'.
2271 induction args as [|arg args IH], args'; cbn [List.length];
2272 first [ constructor; try apply IH | clear; intro; exfalso; congruence ].
2273 { apply eval_bound_expr_via_PHOAS'. }
2274 { clear eval_bound_expr_via_PHOAS'; congruence. } }
2275 clear eval_bound_expr_via_PHOAS'.
2276 break_innermost_match_hyps; inversion_option.
2277 inversion 1; subst.
2278 eapply (@interp_op_op_to_PHOAS_bounds G n); try (eassumption || reflexivity).
2279 rewrite !Forall2_map_r_iff.
2280 eassert (H' : List.length _ = List.length _) by (eapply eq_length_Forall2; eassumption).
2281 specialize (eval_bound_expr_via_PHOAS'_Forall _ H').
2282 rewrite !Forall2_forall_iff_nth_error.
2283 intro i;
2284 repeat match goal with
2285 | [ H : Forall2 _ _ _ |- _ ] => rewrite Forall2_forall_iff_nth_error in H; specialize (H i)
2286 | [ H : Forall _ _ |- _ ] => rewrite Forall_forall_iff_nth_error in H; specialize (H i)
2287 end.
2288 cbv [option_eq] in *.
2289 break_innermost_match; break_innermost_match_hyps; inversion_option; auto; tauto.
2290 Qed.
2291
2292 Lemma eval_bound_expr_via_PHOAS_dag G d (Hok : gensym_dag_ok G d)
2293 : forall i b, dag.lookup_bounds d i = Some b -> forall v, eval G d (ExprRef i) v -> is_bounded_by_bool v b = true.
2294 Proof.
2295 assert (dag.ok d) by apply Hok.
2296 assert (dag.all_nodes_ok d) by apply Hok.
2297 intro i; rewrite dag.lookup_bounds_lookup by apply Hok.
2298 intros b H' v He.
2299 inversion_one_head' @eval.
2300 repeat lazymatch goal with H : _ |- _ => tryif constr_eq H i then fail else revert H end.
2301 set (k := dag.lookup _ _) in *.
2302 revert k.
2303 let P := match goal with |- let k := _ in @?P k => P end in
2304 apply (dag.lookup_ind d P); intros; inversion_option; inversion_pair; subst.
2305 eapply interp_op_bound_node_idx_via_PHOAS; try eassumption; [].
2306 eapply Forall_impl; [ | eassumption ]; cbv beta; intros *.
2307 rewrite dag.lookup_bounds_lookup by assumption.
2308 destruct_head'_ex; destruct_head'_and.
2309 break_innermost_match; intros; inversion_option.
2310 inversion_one_head' @eval.
2311 match goal with
2312 | [ H : ?x = Some _, H' : ?x = _ |- _ ] => rewrite H in H'
2313 end.
2314 inversion_option; subst.
2315 eauto.
2316 Qed.
2317
2318 Lemma eval_bound_expr_via_PHOAS G d (Hok : gensym_dag_ok G d) e b
2319 : bound_expr_via_PHOAS d e = Some b ->
2320 forall v, eval G d e v -> is_bounded_by_bool v b = true.
2321 Proof using Type.
2322 eauto using eval_bound_expr_via_PHOAS', eval_bound_expr_via_PHOAS_dag.
2323 Qed.
2324 End bound_expr_via_PHOAS.
2325
2326 Notation bound_expr := bound_expr_via_PHOAS.
2327 Lemma eval_bound_expr G d e b : bound_expr d e = Some b ->
2328 forall v, gensym_dag_ok G d -> eval G d e v -> (ZRange.lower b <= v <= ZRange.upper b)%Z.
2329 Proof using Type.
2330 intros H v Hok He.
2331 eapply eval_bound_expr_via_PHOAS in He; [ | eassumption .. ].
2332 reflect_hyps; lia.
2333 Qed.
2334
2335 Import coqutil.Tactics.Tactics.
2336 Ltac t:= match goal with
2337 | _ => progress intros
2338 | H : eval _ _ (ExprApp _) _ |- _ => inversion H; clear H; subst
2339 | H : Forall _ (cons _ _) |- _ => inversion H; clear H; subst
2340 | H : Forall _ nil |- _ => inversion H; clear H; subst
2341 | H : Forall2 _ (cons _ _) _ |- _ => inversion H; clear H; subst
2342 | H : Forall2 _ nil _ |- _ => inversion H; clear H; subst
2343 | H : Forall2 _ _ (cons _ _) |- _ => inversion H; clear H; subst
2344 | H : Forall2 _ _ nil |- _ => inversion H; clear H; subst
2345 | H : _ = true |- _ => autoforward with typeclass_instances in H
2346 | H : forall b, _ |- _ => pose proof (H _ ltac:(eassumption) _ _ ltac:(eassumption)); clear H
2347 | H : eval _ ?d ?e ?v1, G: eval _ ?d ?e ?v2 |- _ =>
2348 assert_fails (constr_eq v1 v2);
2349 eapply (eval_eval _ d e v1 H v2) in G
2350 | _ => progress cbv [interp_op] in *
2351 | _ => progress cbn [fst snd] in *
2352 | _ => progress destruct_one_match
2353 | _ => progress Option.inversion_option
2354 | _ => progress subst
2355 end.
2356
2357 Lemma bound_sum' G d
2358 es (He : Forall (fun e => forall b, bound_expr d e = Some b ->
2359 forall (v : Z), eval G d e v -> (ZRange.lower b <= v <= ZRange.upper b)%Z) es)
2360 : forall
2361 bs (Hb : Option.List.lift (map (bound_expr d) es) = Some bs)
2362 vs (Hv : Forall2 (eval G d) es vs)
2363 , (fold_right Z.add 0 (List.map ZRange.lower bs) <= fold_right Z.add 0 vs <= fold_right Z.add 0 (List.map ZRange.upper bs))%Z.
2364 Proof using Type.
2365 induction He; cbn in *; repeat t; cbn in *; [ lia | ].
2366 destruct (bound_expr _) eqn:? in *; cbn in *; repeat t.
2367 destruct (fold_right (B:=option _) _) eqn:? in *; cbn in *; repeat t; cbn in *.
2368 specialize (IHHe _ ltac:(eassumption) _ ltac:(eassumption)); cbn.
2369 specialize (H _ ltac:(exact eq_refl) _ ltac:(eassumption)).
2370 Lia.lia.
2371 Qed.
2372
2373 Import Crypto.Util.ZRange.
2374
2375 Lemma bound_sum G d es
2376 (Hok : gensym_dag_ok G d)
2377 bs (Hb : Option.List.lift (map (bound_expr d) es) = Some bs)
2378 vs (Hv : Forall2 (eval G d) es vs)
2379 : (fold_right Z.add 0 (List.map ZRange.lower bs) <= fold_right Z.add 0 vs <= fold_right Z.add 0 (List.map ZRange.upper bs))%Z.
2380 Proof using Type.
2381 eapply bound_sum' in Hb; eauto.
2382 eapply Forall_forall; intros.
2383 eapply eval_bound_expr; eauto.
2384 Qed.
2385
2386 Definition isCst (e : expr) :=
2387 match e with ExprApp ((const _), []) => true | _ => false end.
2388
2389 Module Rewrite.
2390 Class Ok r := rwok : forall G d e v, gensym_dag_ok G d -> eval G d e v -> eval G d (r d e) v.
2391 Class description_of (r : dag -> expr -> expr) := describe : string.
2392 #[global] Bind Scope string_scope with description_of.
2393 #[global] Typeclasses Opaque description_of.
2394 Ltac resolve_match_using_hyp :=
2395 match goal with |- context[match ?x with _ => _ end] =>
2396 match goal with H : x = ?v |- _ =>
2397 let h := Head.head v in
2398 is_constructor h;
2399 rewrite H
2400 end end.
2401
2402 Create HintDb step_db discriminated.
2403
2404 Ltac step := match goal with
2405 | |- Ok ?r => cbv [Ok r]; intros
2406 | _ => solve [trivial | contradiction]
2407 | _ => resolve_match_using_hyp
2408 | _ => inversion_option_step
2409
2410 | H : _ = ?v |- _ => is_var v; progress subst v
2411 | H : ?v = _ |- _ => is_var v; progress subst v
2412
2413 | H : eval _ ?d ?e ?v1, G: eval _ ?d ?e ?v2 |- _ =>
2414 assert_fails (constr_eq v1 v2);
2415 eapply (eval_eval _ d e v1 H v2) in G
2416 | |- eval _ ?d ?e ?v =>
2417 match goal with
2418 H : eval _ d e ?v' |- _ =>
2419 let Heq := fresh in
2420 enough (Heq : v = v') by (rewrite Heq; exact H);
2421 try (clear H; clear e)
2422 end
2423
2424 | H: interp_op _ (const _) nil = Some _ |- _ => inversion H; clear H; subst
2425 | H: interp0_op _ _ = Some _ |- _ => eapply interp_op_interp0_op in H
2426 | H: interp0_expr _ = Some _ |- _ => eapply eval_interp0_expr in H
2427 | H: bound_expr _ _ = Some _ |- _ => eapply eval_bound_expr in H; eauto; [ ]
2428
2429 | H : (?x <=? ?y)%N = ?b |- _ => is_constructor b; destruct (N.leb_spec x y); (inversion H || clear H)
2430 | H : andb _ _ = true |- _ => eapply Bool.andb_prop in H; case H as (?&?)
2431 | H : N.eqb ?n _ = true |- _ => eapply N.eqb_eq in H; try subst n
2432 | H : Z.eqb ?n _ = true |- _ => eapply Z.eqb_eq in H; try subst n
2433 | H : expr_beq ?a ?b = true |- _ => replace a with b in * by (symmetry;exact (expr_beq_true a b H)); clear H
2434 | _ => progress destruct_one_match_hyp
2435 | _ => progress destruct_one_match
2436
2437 | H : eval _ _ ?e _ |- _ => assert_fails (is_var e); inversion H; clear H; subst
2438 | H : Forall2 (eval _ _) (cons _ _) _ |- _ => inversion H; clear H; subst
2439 | H : Forall2 (eval _ _) _ (cons _ _) |- _ => inversion H; clear H; subst
2440 | H : Forall2 _ _ nil |- _ => inversion H; clear H; subst
2441 | H : Forall2 _ nil _ |- _ => inversion H; clear H; subst
2442
2443 | _ => progress cbn [fst snd map option_map] in *
2444 | _ => progress cbn [ZRange.lower ZRange.upper invert_Some op_to_Z_binop identity] in *
2445 | _ => progress autorewrite with zsimplify_const step_db
2446 end.
2447
2448 Ltac Econstructor :=
2449 match goal with
2450 | |- Forall2 (eval _ _) _ _ => econstructor
2451 | |- eval _ _ ?e _ => econstructor
2452 end.
2453
2454 Ltac t := repeat (step || Econstructor || eauto || (progress cbn [interp0_op interp_op] in * ) ).
2455
2456 #[local] Hint Rewrite Z.fold_right_land_ones_id : step_db.
2457
2458 Definition slice0 (d : dag) :=
2459 fun e => match e with
2460 ExprApp (slice 0 s, [(ExprApp ((addZ|mulZ|negZ|shlZ|shrZ|andZ|orZ|xorZ) as o, args))]) =>
2461 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)
2462 | _ => e end.
2463 #[local] Instance describe_slice0 : description_of Rewrite.slice0
2464 := "Merges (slice 0 s) into addZ,mulZ,negZ,shlZ,shrZ,andZ,orZ,xorZ".
2465 Global Instance slice0_ok : Ok slice0. Proof using Type. t. Qed.
2466
2467 Definition slice01_addcarryZ (d : dag) :=
2468 fun e => match e with
2469 ExprApp (slice 0 1, [(ExprApp (addcarryZ s, args))]) =>
2470 ExprApp (addcarry s, args)
2471 | _ => e end.
2472 #[local] Instance describe_slice01_addcarryZ : description_of Rewrite.slice01_addcarryZ
2473 := "Merges (slice 0 1) into addcarryZ".
2474 Global Instance slice01_addcarryZ_ok : Ok slice01_addcarryZ.
2475 Proof using Type. t; rewrite ?Z.shiftr_0_r, ?Z.land_ones, ?Z.shiftr_div_pow2; trivial; Lia.lia. Qed.
2476
2477 Definition slice01_subborrowZ (d : dag) :=
2478 fun e => match e with
2479 ExprApp (slice 0 1, [(ExprApp (subborrowZ s, args))]) =>
2480 ExprApp (subborrow s, args)
2481 | _ => e end.
2482 #[local] Instance describe_slice01_subborrowZ : description_of Rewrite.slice01_subborrowZ
2483 := "Merges (slice 0 1) into subborrowZ".
2484 Global Instance slice01_subborrowZ_ok : Ok slice01_subborrowZ.
2485 Proof using Type. t; rewrite ?Z.shiftr_0_r, ?Z.land_ones, ?Z.shiftr_div_pow2; trivial; Lia.lia. Qed.
2486
2487 Definition slice_set_slice (d : dag) :=
2488 fun e => match e with
2489 ExprApp (slice 0 s1, [ExprApp (set_slice 0 s2, [_; e'])]) =>
2490 if N.leb s1 s2 then ExprApp (slice 0 s1, [e']) else e | _ => e end.
2491 #[local] Instance describe_slice_set_slice : description_of Rewrite.slice_set_slice
2492 := "Simplifies slice applied to set_slice".
2493 Global Instance slice_set_slice_ok : Ok slice_set_slice.
2494 Proof using Type. t. f_equal. Z.bitblast. Qed.
2495
2496 Definition set_slice_set_slice (d : dag) :=
2497 fun e => match e with
2498 ExprApp (set_slice lo1 s1, [ExprApp (set_slice lo2 s2, [x; e']); y]) =>
2499 if andb (N.eqb lo1 lo2) (N.leb s2 s1) then ExprApp (set_slice lo1 s1, [x; y]) else e | _ => e end.
2500 #[local] Instance describe_set_slice_set_slice : description_of Rewrite.set_slice_set_slice
2501 := "Simplifies set_slice applied to set_slice".
2502 Global Instance set_slice_set_slice_ok : Ok set_slice_set_slice.
2503 Proof using Type. t. f_equal. Z.bitblast. Qed.
2504
2505 Definition set_slice0_small (d : dag) :=
2506 fun e => match e with
2507 ExprApp (set_slice 0 s, [x; y]) =>
2508 match bound_expr d x, bound_expr d y with Some a, Some b =>
2509 if Z.leb 0 (ZRange.lower a) && Z.leb 0 (ZRange.lower b) && Z.leb (ZRange.upper a) (Z.ones (Z.of_N s)) && Z.leb (ZRange.upper b) (Z.ones (Z.of_N s)) then y
2510 else e | _, _ => e end | _ => e end%bool.
2511 #[local] Instance describe_set_slice0_small : description_of Rewrite.set_slice0_small
2512 := "Simplifies set_slice when the slice being set fully overwrites the original".
2513 Global Instance set_slice0_small_ok : Ok set_slice0_small.
2514 Proof using Type.
2515 t.
2516 destruct_head'_and.
2517 rewrite Z.ones_equiv, <- Z.lt_le_pred in * |- .
2518 assert ((0 <= y < 2^Z.of_N sz)%Z) by lia; clear dependent z.
2519 assert ((0 <= y0 < 2^Z.of_N sz)%Z) by lia; clear dependent z0.
2520 rewrite ?Z.shiftl_0_r, Z.land_ones, Z.mod_small by lia.
2521 destruct (Z.eq_dec y 0); subst.
2522 { rewrite Z.ldiff_0_l, Z.lor_0_r; trivial. }
2523 rewrite Z.ldiff_ones_r_low, Z.lor_0_r; try Lia.lia.
2524 eapply Z.log2_lt_pow2; Lia.lia.
2525 Qed.
2526
2527 Definition truncate_small (d : dag) :=
2528 fun e => match e with
2529 ExprApp (slice 0%N s, [e']) =>
2530 match bound_expr d e' with Some b =>
2531 if Z.leb 0 (ZRange.lower b) && Z.leb (ZRange.upper b) (Z.ones (Z.of_N s))
2532 then e'
2533 else e | _ => e end | _ => e end.
2534 #[local] Instance describe_truncate_small : description_of Rewrite.truncate_small
2535 := "Simplifies slice when it's a no-op".
2536 Global Instance truncate_small_ok : Ok truncate_small. Proof using Type. t; []. cbn in *; eapply Z.land_ones_low_alt_ones; eauto. lia. Qed.
2537
2538 Definition addcarry_bit (d : dag) :=
2539 fun e => match e with
2540 ExprApp (addcarry s, ([ExprApp (const a, nil);b])) =>
2541 if option_beq zrange_beq (bound_expr d b) (Some r[0~>1]%zrange) then
2542 match interp0_op (addcarry s) [a; 0], interp0_op (addcarry s) [a; 1] with
2543 | Some 0, Some 1 => b
2544 | Some 0, Some 0 => ExprApp (const 0, nil)
2545 | _, _ => e
2546 end else e | _ => e end%Z%bool.
2547 #[local] Instance describe_addcarry_bit : description_of Rewrite.addcarry_bit
2548 := "Simplifies (addcarry s, [const a; b]) when b is known to be a single bit".
2549 Global Instance addcarry_bit_ok : Ok addcarry_bit.
2550 Proof using Type.
2551 repeat step;
2552 [instantiate (1:=G) in E0; instantiate (1:=G) in E1|];
2553 reflect_hyps; repeat step;
2554 assert (y0 = 0 \/ y0 = 1)%Z as HH by Lia.lia; case HH as [|];
2555 subst; repeat step; repeat Econstructor; cbn; congruence.
2556 Qed.
2557
2558 Definition addoverflow_bit (d : dag) :=
2559 fun e => match e with
2560 ExprApp (addoverflow s, ([ExprApp (const a, nil);b])) =>
2561 if option_beq zrange_beq (bound_expr d b) (Some r[0~>1]%zrange) then
2562 match interp0_op (addoverflow s) [a; 0] , interp0_op (addoverflow s) [a; 1] with
2563 | Some 0, Some 1 => b
2564 | Some 0, Some 0 => ExprApp (const 0, nil)
2565 | _, _ => e
2566 end else e | _ => e end%Z%bool.
2567 #[local] Instance describe_addoverflow_bit : description_of Rewrite.addoverflow_bit
2568 := "Simplifies (addoverflow s, [const a; b]) when b is known to be a single bit".
2569 Global Instance addoverflow_bit_ok : Ok addoverflow_bit.
2570 Proof using Type.
2571 repeat step;
2572 [instantiate (1:=G) in E0; instantiate (1:=G) in E1|];
2573 reflect_hyps; repeat step;
2574 assert (y0 = 0 \/ y0 = 1)%Z as HH by Lia.lia; case HH as [|];
2575 subst; repeat step; repeat Econstructor; cbn; congruence.
2576 Qed.
2577
2578 Definition addbyte_small (d : dag) :=
2579 fun e => match e with
2580 ExprApp (add (8%N as s), args) =>
2581 match Option.List.lift (List.map (bound_expr d) args) with
2582 | Some bounds =>
2583 if Z.leb 0 (List.fold_right Z.add 0%Z (List.map lower bounds)) && Z.leb (List.fold_right Z.add 0%Z (List.map upper bounds)) (Z.ones (Z.of_N s))
2584 then ExprApp (add 64%N, args)
2585 else e | _ => e end | _ => e end.
2586 #[local] Instance describe_addbyte_small : description_of Rewrite.addbyte_small
2587 := "Replaces (add 8, args) with (add 64, args) when doing so doesn't change semantics".
2588 Global Instance addbyte_small_ok : Ok addbyte_small.
2589 Proof using Type.
2590 t; f_equal.
2591 let H := match goal with H : Forall2 (eval _ _) _ _ |- _ => H end in
2592 eapply bound_sum in H; eauto.
2593 rewrite Z.ones_equiv in * |- ; rewrite !Z.land_ones, !Z.mod_small; try lia;
2594 replace (Z.of_N 8) with 8 in * by (vm_compute; reflexivity);
2595 replace (Z.of_N 64) with 64 in * by (vm_compute; reflexivity); lia.
2596 Qed.
2597
2598 Definition addcarry_small (d : dag) :=
2599 fun e => match e with
2600 ExprApp (addcarry s, args) =>
2601 match Option.List.lift (List.map (bound_expr d) args) with
2602 | Some bounds =>
2603 if Z.leb 0 (List.fold_right Z.add 0%Z (List.map lower bounds)) && Z.leb (List.fold_right Z.add 0%Z (List.map upper bounds)) (Z.ones (Z.of_N s))
2604 then (ExprApp (const 0, nil))
2605 else e | _ => e end | _ => e end.
2606 #[local] Instance describe_addcarry_small : description_of Rewrite.addcarry_small
2607 := "Replaces (addcarry _, args) with 0 when bounds analysis can prove there's no carry".
2608 Global Instance addcarry_small_ok : Ok addcarry_small.
2609 Proof using Type.
2610 t; f_equal.
2611 let H := match goal with H : Forall2 (eval _ _) _ _ |- _ => H end in
2612 eapply bound_sum in H; eauto.
2613 rewrite Z.ones_equiv in * |- ; rewrite Z.shiftr_div_pow2, Z.div_small; cbn; lia.
2614 Qed.
2615
2616 Definition addoverflow_small (d : dag) :=
2617 fun e => match e with
2618 ExprApp (addoverflow s, ([_]|[_;_]|[_;_;_]) as args) =>
2619 match Option.List.lift (List.map (bound_expr d) args) with
2620 | Some bounds =>
2621 if List.forallb (Z.leb 0) (List.map lower bounds) && Z.leb (List.fold_right Z.add 0%Z (List.map upper bounds)) (Z.ones (Z.of_N s-1))
2622 then (ExprApp (const 0, nil))
2623 else e | _ => e end | _ => e end.
2624 #[local] Instance describe_addoverflow_small : description_of Rewrite.addoverflow_small
2625 := "Replaces (addoverflow _, args) when there are at most 3 args and when bounds analysis can prove there's no overflow".
2626 Global Instance addoverflow_small_ok : Ok addoverflow_small.
2627 Proof using Type.
2628 t; cbv [Option.List.lift Crypto.Util.Option.bind fold_right map List.forallb] in *;
2629 BreakMatch.break_match_hyps; Option.inversion_option; t;
2630 epose proof Z.ones_equiv (Z.of_N s -1);
2631 destruct_head'_and; reflect_hyps; destruct_head'_and.
2632 all : rewrite Z.land_ones, !Z.mod_small, !Z.signed_small, !Z.eqb_refl; trivial.
2633 all : try split; try Lia.lia.
2634 all : replace (Z.of_N s) with (1+(Z.of_N s-1))%Z at 1 by Lia.lia;
2635 rewrite Z.pow_add_r; try Lia.lia.
2636 all : destruct s; cbn in * |- ; lia.
2637 Qed.
2638
2639 Definition constprop (d : dag) :=
2640 fun e => match interp0_expr e with
2641 | Some v => ExprApp (const v, nil)
2642 | _ => e end.
2643 #[local] Instance describe_constprop : description_of Rewrite.constprop
2644 := "Performs constant propagation, evaluating expressions that are known to be constant".
2645 Global Instance constprop_ok : Ok constprop.
2646 Proof using Type. t. f_equal; eauto using eval_eval. Qed.
2647
2648 (* convert unary operations to slice *)
2649 Definition unary_truncate (d : dag) :=
2650 fun e => match e with
2651 ExprApp (o, [x]) =>
2652 match unary_truncate_size o with
2653 | Some (-1)%Z => x
2654 | Some 0%Z => ExprApp (const 0, nil)
2655 | Some (Zpos p)
2656 => ExprApp (slice 0%N (Npos p), [x])
2657 | _ => e end | _ => e end.
2658 #[local] Instance describe_unary_truncate : description_of Rewrite.unary_truncate
2659 := "Some operations are equivalent to truncation when applied to only one argument; this pass canonicalizes such expressions".
2660 Global Instance unary_truncate_ok : Ok unary_truncate.
2661 Proof using Type.
2662 t.
2663 all: repeat first [ progress cbv [unary_truncate_size] in *
2664 | progress cbn [fold_right Z.of_N] in *
2665 | progress change (Z.of_N 0) with 0 in *
2666 | progress change (Z.ones 0) with 0 in *
2667 | apply (f_equal (@Some _))
2668 | lia
2669 | progress autorewrite with zsimplify_const
2670 | progress break_innermost_match_hyps
2671 | match goal with
2672 | [ H : Z.of_N ?s = 0 |- _ ] => is_var s; destruct s; try lia
2673 | [ H : Z.of_N ?s = Z.pos _ |- _ ] => is_var s; destruct s; try lia
2674 | [ H : Z.pos _ = Z.pos _ |- _ ] => inversion H; clear H
2675 end
2676 | progress t ].
2677 Qed.
2678
2679 Lemma fold_right_filter_identity_gen A B C f init F G xs
2680 (Hid : forall x y, F x = false -> G (f x y) = G y)
2681 (HProper : forall x y y', G y = G y' -> G (f x y) = G (f x y'))
2682 : G (@fold_right A B f init (filter F xs)) = G (@fold_right A B f init xs) :> C.
2683 Proof.
2684 induction xs as [|x xs IH]; [ | specialize (Hid x) ]; cbn; break_innermost_match; cbn; rewrite ?Hid by auto; auto; congruence.
2685 Qed.
2686
2687 Lemma fold_right_filter_identity A B f init F xs
2688 (Hid : forall x y, F x = false -> f x y = y)
2689 : @fold_right A B f init (filter F xs) = @fold_right A B f init xs.
2690 Proof.
2691 apply fold_right_filter_identity_gen with (G:=id); cbv [id]; intuition (subst; eauto).
2692 Qed.
2693
2694 Lemma interp_op_drop_identity o id : identity o = Some id ->
2695 forall G xs, interp_op G o xs = interp_op G o (List.filter (fun v => negb (Z.eqb v id)) xs).
2696 Proof using Type.
2697 destruct o; cbn [identity invert_Some op_to_Z_binop]; intro; inversion_option; subst; intros G xs; cbn [interp_op identity invert_Some op_to_Z_binop]; f_equal.
2698 all: break_innermost_match_hyps; break_innermost_match; inversion_option; subst.
2699 all: rewrite ?fold_right_map.
2700 all: rewrite ?fold_right_filter_identity by now intros; reflect_hyps; subst; auto with zarith; autorewrite with zsimplify_const; lia.
2701 all: repeat first [ reflexivity
2702 | progress autorewrite with zsimplify_const ].
2703 { (idtac + symmetry); apply fold_right_filter_identity_gen with (G:=fun x => Z.land x _).
2704 all: intros; reflect_hyps; subst.
2705 all: rewrite <- ?Z.land_assoc, ?(Z.land_comm (Z.ones _)), ?Z.land_ones in * by lia.
2706 all: push_Zmod; pull_Zmod.
2707 all: congruence. }
2708 Qed.
2709
2710 Lemma interp_op_drop_identity_after_0 o id : identity_after_0 o = Some id ->
2711 forall G x xs, interp_op G o (x :: xs) = interp_op G o (x :: List.filter (fun v => negb (Z.eqb v id)) xs).
2712 Proof using Type.
2713 destruct o; cbn [identity_after_0]; intro; inversion_option; subst; intros G x xs; cbn [interp_op]; f_equal.
2714 all: rewrite ?fold_right_map.
2715 all: rewrite ?fold_right_filter_identity by now intros; reflect_hyps; subst; auto with zarith; autorewrite with zsimplify_const; lia.
2716 all: repeat first [ reflexivity
2717 | progress autorewrite with zsimplify_const ].
2718 Qed.
2719
2720 Lemma interp_op_nil_is_identity o i (Hi : identity o = Some i)
2721 G : interp_op G o [] = Some i.
2722 Proof using Type.
2723 destruct o; cbn [identity invert_Some op_to_Z_binop] in *; break_innermost_match_hyps; inversion_option; subst; cbn [interp_op fold_right identity invert_Some op_to_Z_binop]; f_equal.
2724 all: cbn [interp_op fold_right]; autorewrite with zsimplify_const; try reflexivity.
2725 { cbn [identity]; break_innermost_match; try reflexivity.
2726 rewrite Z.land_ones by lia; Z.rewrite_mod_small; try reflexivity;
2727 (* compat with older versions of Coq (needed for 8.11, not for 8.13) *)
2728 rewrite Z.mod_small; rewrite ?Z.log2_lt_pow2; cbn [Z.log2]; try lia. }
2729 { change 1 with (Z.ones 1).
2730 Z.bitblast. }
2731 Qed.
2732
2733 Lemma interp_op_always_interps G o args
2734 : op_always_interps o = true -> interp_op G o args <> None.
2735 Proof. destruct o; cbn; congruence. Qed.
2736
2737 Lemma interp0_op_always_interps o args
2738 : op_always_interps o = true -> interp0_op o args <> None.
2739 Proof. apply interp_op_always_interps. Qed.
2740
2741 (* completeness check, just update the definition if this doesn't go through *)
2742 Lemma interp_op_always_interps_complete o
2743 : op_always_interps o = false -> exists G args, interp_op G o args = None.
2744 Proof.
2745 destruct o; cbn; try solve [ inversion 1 ]; intros _; do 2 try eapply ex_intro.
2746 all: repeat match goal with
2747 | [ |- match ?ev with [] => None | _ => _ end = None ] => let __ := open_constr:(eq_refl : ev = []) in cbv beta iota
2748 | [ |- match ?ev with _ :: _ => None | _ => _ end = None ] => let __ := open_constr:(eq_refl : ev = _ :: _) in cbv beta iota
2749 | [ |- None = None ] => reflexivity
2750 end.
2751 Unshelve. all: shelve_unifiable.
2752 all: lazymatch goal with
2753 | [ |- Z ] => exact 0%Z
2754 | [ |- _ -> option _ ] => intro; exact None
2755 | [ |- list _ ] => exact nil
2756 | _ => idtac
2757 end.
2758 all: fail_if_goals_remain ().
2759 Qed.
2760
2761 Lemma invert_interp_op_associative o : associative o = true ->
2762 forall G x xs v, interp_op G o (x :: xs) = Some v ->
2763 exists v', interp_op G o xs = Some v' /\
2764 interp_op G o [x; v'] = Some v.
2765 Proof using Type.
2766 destruct o; inversion 1; intros * HH; inversion HH; clear HH; subst; cbn;
2767 eexists; split; eauto; f_equal; break_innermost_match; try ring; try solve [Z.bitblast].
2768 { rewrite !Z.add_0_r, ?Z.land_ones; push_Zmod; pull_Zmod; Lia.lia. }
2769 { rewrite !Z.mul_1_r, ?Z.land_ones; push_Zmod; pull_Zmod; Lia.lia. }
2770 Qed.
2771
2772 (** 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 *)
2773 (* is it okay for associative to imply identity? *)
2774 Lemma interp_op_associative_spec_fold o : associative o = true ->
2775 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.
2776 Proof using Type.
2777 intros H G; induction xs as [|x xs IHxs]; cbn [fold_right]; [ reflexivity | ].
2778 rewrite <- IHxs; clear IHxs.
2779 destruct o; inversion H; cbn [interp_op Crypto.Util.Option.bind fold_right identity invert_Some op_to_Z_binop]; break_innermost_match; f_equal.
2780 all: autorewrite with zsimplify_const.
2781 all: try solve [ Z.bitblast ].
2782 all: try solve [ rewrite ?Z.land_ones in *; push_Zmod; pull_Zmod; Lia.lia ].
2783 Qed.
2784
2785 Lemma interp_op_associative_spec_id o : associative o = true ->
2786 forall G, interp_op G o [] = identity o.
2787 Proof using Type.
2788 intros H G.
2789 pose proof (fun id H => interp_op_nil_is_identity o id H G) as H1.
2790 destruct o; inversion H; cbn [identity] in *; break_innermost_match_hyps; erewrite H1; try reflexivity.
2791 Qed.
2792
2793 Lemma interp_op_associative_identity_Some o : associative o = true ->
2794 forall G xs vxs, interp_op G o xs = Some vxs -> Option.is_Some (identity o) = true.
2795 Proof using Type.
2796 intros H G xs vxs H1; rewrite <- interp_op_associative_spec_id with (G:=G) by assumption.
2797 rewrite interp_op_associative_spec_fold in H1 by assumption.
2798 cbv [Option.is_Some]; break_innermost_match; try reflexivity.
2799 exfalso.
2800 clear -H1.
2801 revert dependent vxs; induction xs as [|?? IH]; cbn in *; intros; inversion_option.
2802 unfold Crypto.Util.Option.bind at 1 in H1; break_innermost_match_hyps; eauto.
2803 Qed.
2804
2805 Lemma interp_op_associative_spec_assoc o : associative o = true ->
2806 forall G ys vys, interp_op G o ys = Some vys ->
2807 forall zs vzs, interp_op G o zs = Some vzs ->
2808 forall x, ((xy <- interp_op G o [x; vys]; interp_op G o [xy; vzs]) = (yz <- interp_op G o [vys; vzs]; interp_op G o [x; yz]))%option.
2809 Proof.
2810 destruct o; inversion 1; intros * H1 * H2; cbn [interp_op fold_right Crypto.Util.Option.bind identity invert_Some op_to_Z_binop] in *.
2811 all: intros; autorewrite with zsimplify_const; f_equal; inversion_option.
2812 all: rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod; rewrite <- ?Z.land_ones by lia.
2813 all: try solve [ f_equal; lia ].
2814 all: try reflexivity.
2815 all: try solve [ Z.bitblast ].
2816 all: try lia.
2817 Qed.
2818
2819 Lemma interp_op_associative_spec_concat o : associative o = true ->
2820 forall G xs, interp_op G o (List.concat xs) = (vxs <-- List.map (interp_op G o) xs; interp_op G o vxs)%option.
2821 Proof using Type.
2822 intros H G; induction xs as [|x xs IHxs]; cbn [fold_right]; [ reflexivity | ].
2823 cbn [List.concat List.map Option.List.bind_list].
2824 rewrite interp_op_associative_spec_fold, fold_right_app, <- interp_op_associative_spec_fold by assumption.
2825 rewrite IHxs; clear IHxs.
2826 setoid_rewrite Option.List.bind_list_cps_id; rewrite <- Option.List.eq_bind_list_lift.
2827 destruct (Option.List.lift (map (interp_op G o) xs)) as [vxs|]; cbn [Crypto.Util.Option.bind].
2828 { revert vxs; clear xs.
2829 induction x as [|x xs IHxs]; intro vxs.
2830 { cbn [fold_right].
2831 destruct (interp_op G o []) as [id|] eqn:H'; cbn [Crypto.Util.Option.bind].
2832 { etransitivity; erewrite interp_op_drop_identity by (erewrite <- interp_op_associative_spec_id; eassumption); [ | reflexivity ].
2833 cbn [List.filter]; unfold negb at 2; break_innermost_match_step; reflect_hyps; try congruence. }
2834 { pose proof (interp_op_associative_identity_Some o H G vxs) as H1.
2835 rewrite interp_op_associative_spec_id in * by assumption.
2836 rewrite H' in *.
2837 cbn [Option.is_Some] in *.
2838 destruct interp_op; try reflexivity; specialize (H1 _ eq_refl); congruence. } }
2839 { cbn [fold_right].
2840 rewrite IHxs; clear IHxs.
2841 symmetry; rewrite interp_op_associative_spec_fold by assumption; cbn [fold_right]; rewrite <- interp_op_associative_spec_fold by assumption.
2842 unfold Crypto.Util.Option.bind at 2; break_innermost_match_step; cbn [Crypto.Util.Option.bind]; [ | reflexivity ].
2843 symmetry; rewrite interp_op_associative_spec_fold by assumption; cbn [fold_right]; rewrite <- interp_op_associative_spec_fold by assumption.
2844 symmetry.
2845 setoid_rewrite interp_op_associative_spec_fold at 2; [ | assumption ].
2846 cbn [fold_right].
2847 setoid_rewrite <- interp_op_associative_spec_fold; [ | assumption ].
2848 destruct (interp_op G o vxs) eqn:?; cbn [Crypto.Util.Option.bind]; [ | cbv [Crypto.Util.Option.bind]; break_match; reflexivity ].
2849 eapply interp_op_associative_spec_assoc; eassumption. } }
2850 { etransitivity; [ | cbv [Crypto.Util.Option.bind]; break_innermost_match; reflexivity ].
2851 induction x as [|? ? IHx]; cbn; rewrite ?IHx; reflexivity. }
2852 Qed.
2853
2854 Lemma interp_op_associative_app_bind G o : associative o = true ->
2855 forall xs ys,
2856 interp_op G o (xs ++ ys) = (vxs <- interp_op G o xs; vys <- interp_op G o ys; interp_op G o [vxs; vys])%option.
2857 Proof using Type.
2858 intros.
2859 etransitivity; [ etransitivity; [ | refine (interp_op_associative_spec_concat o H G [xs; ys]) ] | ].
2860 { cbn [concat]; rewrite List.app_nil_r; reflexivity. }
2861 { cbn [map Option.List.bind_list].
2862 cbv [Crypto.Util.Option.bind]; break_innermost_match; reflexivity. }
2863 Qed.
2864
2865 Lemma interp_op_associative_app G o : associative o = true ->
2866 forall xs vxs, interp_op G o xs = Some vxs ->
2867 forall ys vys, interp_op G o ys = Some vys ->
2868 interp_op G o (xs ++ ys) = interp_op G o [vxs; vys].
2869 Proof using Type.
2870 intros H * H1 * H2.
2871 rewrite interp_op_associative_app_bind, H1, H2 by assumption.
2872 reflexivity.
2873 Qed.
2874
2875 Lemma interp_op_associative_idempotent G o : associative o = true ->
2876 forall xs vxs, interp_op G o xs = Some vxs ->
2877 interp_op G o [vxs] = Some vxs.
2878 Proof using Type.
2879 intros H xs vxs H1.
2880 pose proof (interp_op_associative_spec_concat o H G [ xs ]) as H2.
2881 cbn in H2.
2882 rewrite List.app_nil_r, H1 in H2; cbn [Crypto.Util.Option.bind] in *; congruence.
2883 Qed.
2884
2885 Lemma interp_op_associative_cons o : associative o = true ->
2886 forall G x xs ys v,
2887 interp_op G o xs = Some v -> interp_op G o ys = Some v ->
2888 interp_op G o (x :: xs) = interp_op G o (x :: ys).
2889 Proof using Type.
2890 intros H * H1 H2.
2891 etransitivity; [ etransitivity | ]; [ | refine (interp_op_associative_spec_concat o H _ [ [x]; xs]) | ].
2892 all: cbn [concat List.app map Option.List.bind_list]; rewrite ?List.app_nil_r.
2893 1: reflexivity.
2894 symmetry; etransitivity; [ etransitivity | ]; [ | refine (interp_op_associative_spec_concat o H _ [ [x]; ys]) | ].
2895 all: cbn [concat List.app map Option.List.bind_list]; rewrite ?List.app_nil_r.
2896 1: reflexivity.
2897 rewrite !H1, H2; cbn [Crypto.Util.Option.bind].
2898 reflexivity.
2899 Qed.
2900
2901 Definition flatten_associative (d : dag) :=
2902 fun e => match e with
2903 ExprApp (o, args) =>
2904 if associative o then
2905 ExprApp (o, List.flat_map (fun e' =>
2906 match e' with
2907 | ExprApp (o', args') => if op_beq o o' then args' else [e']
2908 | _ => [e'] end) args)
2909 else e | _ => e end.
2910 #[local] Instance describe_flatten_associative : description_of Rewrite.flatten_associative
2911 := "Flattens nested associative operations, such as turning (add [x; add [y; z]]) into (add [x; y; z])".
2912 Global Instance flatten_associative_ok : Ok flatten_associative.
2913 Proof using Type.
2914 repeat step.
2915 let v := match goal with v : Z |- _ => v end in
2916 let H := match goal with H : Forall2 (eval _ _) _ _ |- _ => H end in
2917 revert dependent v; induction H; cbn.
2918 { econstructor; eauto. }
2919 intros ? H4.
2920 pose proof H4.
2921 eapply invert_interp_op_associative in H4; eauto. destruct H4 as (?&?&?).
2922 specialize (IHForall2 _ ltac:(eassumption)).
2923 inversion IHForall2; subst.
2924 let x := match goal with |- context[match x with ExprRef _ => _ | _ => _ end] => x end in
2925 destruct x as [i|[o' args''] ].
2926 { econstructor. { econstructor. eauto. eauto. }
2927 erewrite interp_op_associative_cons; eauto. }
2928 { destruct (op_beq_spec o o'); subst; cycle 1.
2929 { econstructor. { econstructor. eauto. eauto. }
2930 erewrite interp_op_associative_cons; eauto. }
2931 let H := match goal with H : eval _ _ (ExprApp (_, ?args)) _ |- eval _ _ (ExprApp (_, ?args ++ _)) _ => H end in
2932 inversion H; clear H; subst.
2933 econstructor; eauto using Forall2_app.
2934 erewrite interp_op_associative_app; eauto. }
2935 Qed.
2936
2937 Definition flatten_bounded_associative (d : dag) :=
2938 fun e => match e with
2939 ExprApp (o, args) =>
2940 ExprApp (o, List.flat_map (fun e' =>
2941 match e' with
2942 | ExprApp (o', args') => match bounds_for_drop_inner_associative o o' with
2943 | Some drop_always => args'
2944 | Some (drop_if_bounded bound o'') => match bound_expr d (ExprApp (o'', args')) with
2945 | Some ubound => if is_tighter_than_bool ubound bound then args' else [e']
2946 | _ => [e'] end | _ => [e'] end | _ => [e'] end) args) | _ => e end.
2947 #[local] Instance describe_flatten_bounded_associative : description_of Rewrite.flatten_bounded_associative
2948 := "Flattens some nested operations such as add inside addcarry".
2949
2950 Lemma fold_right_add_cps_id init ls
2951 : fold_right Z.add init ls = fold_right Z.add 0 ls + init.
2952 Proof. induction ls; cbn; lia. Qed.
2953
2954 Global Instance flatten_bounded_associative_ok : Ok flatten_bounded_associative.
2955 Proof using Type.
2956 cbv [Ok flatten_bounded_associative].
2957 intros G d e v Hok He.
2958 destruct He; try solve [ t ]; [].
2959 lazymatch goal with
2960 | [ H0 : Forall2 ?P ?args ?args', H1 : interp_op _ _ ?args' = _
2961 |- eval _ _ (ExprApp (_, flat_map ?f args)) _ ]
2962 => epose [] as preargs; epose [] as preargs';
2963 assert (Hpre : Forall2 P preargs preargs') by constructor;
2964 change (flat_map f args) with (preargs ++ flat_map f args); change args' with (preargs' ++ args') in H1;
2965 clearbody preargs preargs';
2966 revert preargs preargs' Hpre H1;
2967 induction H0; cbn [flat_map]; intros *
2968 end.
2969 { rewrite !List.app_nil_r; intros; t. }
2970 { rewrite app_cons_app_app, !app_assoc.
2971 break_innermost_match; reflect_hyps.
2972 all: try solve [ intro; apply IHForall2, Forall2_app; auto ].
2973 all: [ > | ].
2974 all: let H := match goal with H : bounds_for_drop_inner_associative _ _ = _ |- _ => H end in
2975 cbv [bounds_for_drop_inner_associative Crypto.Util.Option.bind unary_truncate_size] in H.
2976 all: repeat first [ progress inversion_option | break_innermost_match_hyps_step ].
2977 all: match goal with
2978 | [ H : _ = _ :> drop_kind |- _ ] => inversion H; clear H
2979 end.
2980 all: subst.
2981 all: match goal with
2982 | [ H : eval _ _ (ExprApp _) _ |- _ ] => inversion H; clear H
2983 end; subst.
2984 all: lazymatch goal with
2985 | [ H : bound_expr _ _ = _ |- _ ]
2986 => let H' := fresh in
2987 pose proof H as H';
2988 cbn [bound_expr] in H; break_innermost_match_hyps; inversion_option; subst;
2989 (eapply eval_bound_expr in H';
2990 [ | try eassumption; (econstructor; [ eassumption | cbn [interp_op]; reflexivity ]) .. ])
2991 | _ => idtac
2992 end.
2993 all: reflect_hyps.
2994 all: repeat step.
2995 all: intros; eapply IHForall2; try apply Forall2_app; clear IHForall2.
2996 all: lazymatch goal with
2997 | [ |- Forall2 _ _ _ ] => eassumption
2998 | _ => idtac
2999 end.
3000 all: cbn [interp_op Option.invert_Some op_to_Z_binop identity] in *; inversion_option; subst.
3001 all: rewrite !fold_right_app.
3002 all: cbn [fold_right].
3003 all: repeat first [ match goal with
3004 | [ |- context[fold_right Z.add ?init ?ls] ]
3005 => lazymatch init with
3006 | 0 => fail
3007 | _ => rewrite (fold_right_add_cps_id init ls)
3008 end
3009 end
3010 | reflexivity ].
3011 all: rewrite !Z.land_ones, ?Z.ones_equiv in * by lia.
3012 all: Z.rewrite_mod_small.
3013 all: try reflexivity. }
3014 Qed.
3015
3016 Definition consts_commutative (d : dag) :=
3017 fun e => match e with
3018 ExprApp (o, args) =>
3019 if commutative o then
3020 let csts_exprs := List.partition isCst args in
3021 if associative o
3022 then match interp0_expr (ExprApp (o, fst csts_exprs)) with
3023 | Some v => ExprApp (o, ExprApp (const v, nil):: snd csts_exprs)
3024 | _ => ExprApp (o, fst csts_exprs ++ snd csts_exprs)
3025 end
3026 else ExprApp (o, fst csts_exprs ++ snd csts_exprs)
3027 else e | _ => e end.
3028 #[local] Instance describe_consts_commutative : description_of Rewrite.consts_commutative
3029 := "Moves all constants to the beginning of commutative n-ary operation lists, additionally combining the constants into a single node when the operation is associative".
3030
3031 Global Instance consts_commutative_ok : Ok consts_commutative.
3032 Proof using Type.
3033 step.
3034 destruct_one_head' @expr; trivial.
3035 destruct_one_head' node.
3036 destruct commutative eqn:?; trivial.
3037 inversion_one_head' @eval.
3038 let l := match goal with l : list expr |- _ => l end in
3039 epose proof Permutation_partition l isCst.
3040 let H := match goal with H : Forall2 (eval _ _) _ _ |- _ => H end in
3041 eapply Permutation.Permutation_Forall2 in H; [|eassumption].
3042 destruct_head'_ex; destruct_head'_and.
3043 epose proof permute_commutative _ _ _ _ ltac:(eassumption) ltac:(eassumption) _ ltac:(eassumption).
3044 break_match; [|solve[repeat Econstructor; eauto] .. ].
3045
3046 set (fst (partition isCst l)) as csts in *; clearbody csts.
3047 set (snd (partition isCst l)) as exps in *; clearbody exps.
3048 clear dependent l. clear dependent args'.
3049 move o at top; move Heqb0 at top; move Heqb at top.
3050 let H := match goal with H : interp0_expr _ = Some _ |- _ => H end in
3051 eapply eval_interp0_expr in H; instantiate (1:=d) in H; instantiate (1:=G) in H.
3052
3053 let H := match goal with H : Forall2 (eval _ _) (_ ++ _) _ |- _ => H end in
3054 eapply Forall2_app_inv_l in H; destruct H as (?&?&?&?&?); subst.
3055 econstructor. { econstructor. econstructor. econstructor. exact eq_refl. eassumption. }
3056
3057 inversion_one_head' @eval.
3058 let H := multimatch goal with H : Forall2 (eval _ _) _ _ |- _ => H end in
3059 eapply eval_eval_Forall2 in H; eauto; progress subst.
3060 clear dependent exps. clear dependent csts.
3061
3062 change (?x :: ?xs) with ([x] ++ xs).
3063 rewrite interp_op_associative_app_bind in * by assumption.
3064 erewrite interp_op_associative_idempotent by eassumption; cbn [Crypto.Util.Option.bind].
3065 unfold Crypto.Util.Option.bind in * |- .
3066 break_innermost_match_hyps; inversion_option; subst; cbn [Crypto.Util.Option.bind].
3067 assumption.
3068 Qed.
3069
3070 Definition neqconst i := fun a : expr => negb (option_beq Z.eqb (interp0_expr a) (Some i)).
3071 Definition drop_identity (d : dag) :=
3072 fun e => match e with ExprApp (o, args) =>
3073 match identity o with
3074 | Some i =>
3075 let args := List.filter (neqconst i) args in
3076 match args with
3077 | nil => ExprApp (const i, nil)
3078 | _ => ExprApp (o, args)
3079 end
3080 | _ => match identity_after_0 o, args with
3081 | Some i, arg :: args =>
3082 let args := List.filter (neqconst i) args in
3083 ExprApp (o, arg :: args)
3084 | _, _ => e end end | _ => e end.
3085 #[local] Instance describe_drop_identity : description_of Rewrite.drop_identity
3086 := "Drops constant identity subexpressions, such as 0s in add and 1s in mul".
3087
3088 Lemma filter_neqconst_helper G d id
3089 l args
3090 (H : Forall2 (eval G d) l args)
3091 : exists args',
3092 Forall2 (eval G d) (filter (neqconst id) l) args'
3093 /\ List.filter (fun v => negb (Z.eqb v id)) args' = List.filter (fun v => negb (Z.eqb v id)) args.
3094 Proof.
3095 induction H; cbn; [ eexists; split; constructor | ].
3096 destruct_head'_ex; destruct_head'_and.
3097 unfold neqconst at 1.
3098 unfold negb at 1; break_innermost_match_step; reflect_hyps.
3099 all: unfold negb at 1; break_innermost_match_step; reflect_hyps.
3100 all: repeat first [ match goal with
3101 | [ H : interp0_expr ?e = Some _, H' : eval ?Gv ?dv ?e _ |- _ ]
3102 => apply eval_interp0_expr with (G:=Gv) (d:=dv) in H
3103 end
3104 | progress reflect_hyps
3105 | congruence
3106 | progress subst
3107 | solve [ eauto ]
3108 | step; eauto; [] ].
3109 all: econstructor; split; [ constructor; eassumption | cbn [filter] ].
3110 all: unfold negb in *; break_innermost_match; reflect_hyps; try congruence.
3111 Qed.
3112
3113 Lemma filter_neqconst G d o id
3114 (Hid : identity o = Some id)
3115 l args
3116 (H : Forall2 (eval G d) l args)
3117 : exists args',
3118 Forall2 (eval G d) (filter (neqconst id) l) args'
3119 /\ interp_op G o args' = interp_op G o args.
3120 Proof.
3121 edestruct filter_neqconst_helper as [args' [H1 H2] ]; try eassumption.
3122 exists args'; split; try eassumption.
3123 erewrite interp_op_drop_identity, H2, <- interp_op_drop_identity by eassumption.
3124 reflexivity.
3125 Qed.
3126
3127 Lemma filter_neqconst' G d o id
3128 (Hid : identity_after_0 o = Some id)
3129 e arg l args
3130 (H0 : eval G d e arg)
3131 (H : Forall2 (eval G d) l args)
3132 : exists args',
3133 Forall2 (eval G d) (filter (neqconst id) l) args'
3134 /\ interp_op G o (arg :: args') = interp_op G o (arg :: args).
3135 Proof.
3136 edestruct filter_neqconst_helper as [args' [H1 H2] ]; try eassumption.
3137 exists args'; split; try eassumption.
3138 erewrite interp_op_drop_identity_after_0, H2, <- interp_op_drop_identity_after_0 by eassumption.
3139 reflexivity.
3140 Qed.
3141
3142 Global Instance drop_identity_Ok : Ok drop_identity.
3143 Proof using Type.
3144 repeat (step; eauto; []).
3145 inversion H; subst; clear H.
3146 destruct identity eqn:?; [ | destruct identity_after_0 eqn:? ]; break_innermost_match.
3147 all: repeat (step; eauto; []).
3148 all: pose proof filter_neqconst.
3149 all: pose proof filter_neqconst'.
3150 all: specialize_under_binders_by eassumption.
3151 all: destruct_head'_ex.
3152 all: destruct_head'_and.
3153 all: repeat first [ progress subst
3154 | progress inversion_option
3155 | match goal with
3156 | [ H : ?ls = nil, H' : context[?ls] |- _ ] => rewrite H in H'
3157 | [ H : ?ls = cons _ _, H' : context[?ls] |- _ ] => rewrite H in H'
3158 | [ H : Forall2 _ nil _ |- _ ] => inversion H; clear H
3159 | [ H : ?x = Some _, H' : context[?x] |- _ ] => rewrite H in H'
3160 end
3161 | erewrite interp_op_nil_is_identity in * by eassumption
3162 | solve [ t ] ].
3163 Qed.
3164
3165 Definition fold_consts_to_and (d : dag) :=
3166 fun e => match consts_commutative d e with
3167 | ExprApp ((and _ | andZ) as o, ExprApp (const v, nil) :: args)
3168 => let v' := match o with
3169 | and sz => Z.land v (Z.ones (Z.of_N sz))
3170 | _ => v
3171 end in
3172 if (v' <? 0)%Z
3173 then if (v' =? -1)%Z
3174 then ExprApp (andZ, args)
3175 else ExprApp (andZ, ExprApp (const v', nil) :: args)
3176 else if (v' =? 0)
3177 then ExprApp (const 0, nil)
3178 else let v_sz := (1 + Z.log2 v') in
3179 if (v' =? Z.ones v_sz)%Z
3180 then ExprApp (and (Z.to_N v_sz), args)
3181 else ExprApp (and (Z.to_N v_sz), ExprApp (const v', nil) :: args)
3182 | _ => e
3183 end.
3184 #[local] Instance describe_fold_consts_to_and : description_of Rewrite.fold_consts_to_and
3185 := "Truncates constant arguments to bitwise and, dropping them if they provably do not change the result".
3186
3187 Global Instance fold_consts_to_and_Ok : Ok fold_consts_to_and.
3188 Proof using Type.
3189 repeat (step; eauto; []).
3190 break_innermost_match; try assumption; reflect_hyps.
3191 all: match goal with
3192 | [ H : eval _ _ ?e _, H' : consts_commutative _ ?e = _ |- _ ]
3193 => eapply consts_commutative_ok in H; [ | eassumption .. ];
3194 rewrite H' in H; clear e H'
3195 end.
3196 all: repeat (step; eauto; []).
3197 all: cbn [interp_op fold_right identity invert_Some op_to_Z_binop] in *; inversion_option; subst.
3198 all: repeat first [ match goal with
3199 | [ H : Z.land _ (Z.ones (Z.of_N ?sz)) < 0 |- _ ]
3200 => exfalso; revert H; clear; rewrite Z.land_neg;
3201 pose proof (Z.ones_nonneg (Z.of_N sz) ltac:(lia));
3202 lia
3203 | [ |- context[fold_right Z.land ?v ?ls] ]
3204 => lazymatch v with -1 => fail | _ => idtac end;
3205 rewrite (@Z.fold_right_land_m1_cps v ls)
3206 | [ H : Z.land ?x ?y = _ |- context[Z.land (Z.land ?x _) ?y] ]
3207 => rewrite !(Z.land_comm x), <- !Z.land_assoc, H
3208 | [ |- context[Z.land ?x ?y] ]
3209 => match goal with
3210 | [ |- context[Z.land ?y ?x] ]
3211 => rewrite (Z.land_comm x y)
3212 end
3213 | [ H : ?x = Z.ones _ |- _ ]
3214 => is_var x; rewrite <- H
3215 | [ |- Z.land (Z.land ?x ?y) (Z.ones (1 + Z.log2 ?x)) = Z.land ?x ?y ]
3216 => rewrite !(Z.land_comm x), <- !Z.land_assoc; f_equal
3217 | [ |- Z.land (Z.land (Z.land ?y ?s) ?v) (Z.ones (1 + Z.log2 (Z.land ?y ?s))) = Z.land (Z.land ?y ?v) ?s ]
3218 => cut (Z.land (Z.land y s) (Z.ones (1 + Z.log2 (Z.land y s))) = Z.land y s);
3219 [ rewrite <- !(Z.land_comm v), <- !Z.land_assoc;
3220 let H := fresh in intro H; rewrite H; reflexivity
3221 | generalize dependent (Z.land y s); intros ]
3222 | [ H : context[Z.land ?y (Z.ones ?z)] |- context[Z.land (Z.ones ?z) ?y] ]
3223 => rewrite (Z.land_comm (Z.ones z) y)
3224 | [ H : ?lhs = ?rhs |- _ ]
3225 => lazymatch rhs with context[lhs] => idtac end;
3226 rewrite <- !H
3227 end
3228 | progress autorewrite with zsimplify_const
3229 | apply (f_equal (@Some _))
3230 | progress cbn [fold_right]
3231 | rewrite Z2N.id by auto with zarith
3232 | solve [ t ]
3233 | solve [ Z.bitblast;
3234 repeat first [ now rewrite Z.bits_above_log2 by lia
3235 | progress Z.bitblast_core
3236 | lazymatch goal with
3237 | [ H : ?i < ?v, H' : context[Z.land ?y (Z.ones ?v)] |- context[Z.testbit ?y ?i] ]
3238 => (replace (Z.testbit y i) with (Z.testbit (Z.land y (Z.ones v)) i) by Z.bitblast_core;
3239 rewrite Z.bits_above_log2 by lia)
3240 end ] ]
3241 | t ].
3242 Qed.
3243
3244 Definition xor_same (d : dag) :=
3245 fun e => match e with ExprApp (xor _,[x;y]) =>
3246 if expr_beq x y then ExprApp (const 0, nil) else e | _ => e end.
3247 #[local] Instance describe_xor_same : description_of Rewrite.xor_same
3248 := "Replaces xor x x with 0".
3249 Global Instance xor_same_ok : Ok xor_same.
3250 Proof using Type.
3251 t; cbn [fold_right]. rewrite Z.lxor_0_r, Z.lxor_nilpotent; trivial.
3252 Qed.
3253
3254 Definition shift_to_mul (d : dag) :=
3255 fun e => match e with
3256 ExprApp ((shl _ | shlZ) as o, [e'; ExprApp (const v, [])]) =>
3257 let o' := match o with shl bitwidth => mul bitwidth | shlZ => mulZ | _ => o (* impossible *) end in
3258 let bw := match o with shl bitwidth => Some bitwidth | shlZ => None | _ => None (* impossible *) end in
3259 if Z.eqb v 0
3260 then match bw with
3261 | Some N0 => ExprApp (const 0, nil)
3262 | Some (Npos p) => ExprApp (slice 0%N (Npos p), [e'])
3263 | None => e'
3264 end
3265 else if Z.ltb 0 v
3266 then ExprApp (o', [e'; ExprApp (const (2^v)%Z, [])])
3267 else e | _ => e end.
3268 #[local] Instance describe_shift_to_mul : description_of Rewrite.shift_to_mul
3269 := "Rewrites shl to an equivalent multiplication".
3270 Global Instance shift_to_mul_ok : Ok shift_to_mul.
3271 Proof. t; cbn in *; rewrite ?Z.shiftl_mul_pow2, ?Z.land_0_r by lia; repeat (lia + f_equal). Qed.
3272
3273 (* o is like mul *)
3274 (* invariant: Forall2 (fun x '(y, z) => eval (o x i) matches eval (o y z)) input output *)
3275 Definition split_consts (d : dag) (o : op) (i : Z) : list expr -> list (expr * Z)
3276 := List.map
3277 (fun e
3278 => match e with
3279 | ExprApp (o', args)
3280 => if op_beq o' o
3281 then
3282 let '(csts, exprs) :=
3283 if commutative o' && associative o'
3284 then let '(csts, exprs) := List.partition isCst args in
3285 (interp0_expr (ExprApp (o', csts)), exprs)
3286 else
3287 (* nest matches for fewer proof cases *)
3288 match match args with
3289 | [arg; ExprApp ((const c), _)]
3290 => Some (c, arg)
3291 | _ => None
3292 end with
3293 | Some (c, arg) => (Some c, [arg])
3294 | None => (Some i, args)
3295 end
3296 in
3297 match csts, exprs with
3298 | None, _ => (e, i)
3299 | Some c, [arg] => (arg, c)
3300 | Some c, args => (ExprApp (o', args), c)
3301 end
3302 else (e, i)
3303 | _ => (e, i)
3304 end%bool).
3305
3306 (* invariant: input is a permutation of concat (List.map (fun '(e, zs) => List.map (pair e) zs) output) *)
3307 Definition group_consts (d : dag) (ls : list (expr * Z)) : list (expr * list Z)
3308 := Option.List.map
3309 (fun xs => match xs with
3310 | [] => None
3311 | (e, z) :: xs => Some (e, z :: List.map snd xs)
3312 end)
3313 (List.groupAllBy (fun x y => expr_beq (fst x) (fst y)) ls).
3314
3315 (* o is like add *)
3316 (* spec: if interp0_op o zs is always Some _, then Forall2 (fun '(e, zs) '(e', z) => e = e' /\ interp0_op o zs = Some z) input output *)
3317 Definition compress_consts (d : dag) (o : op) (ls : list (expr * list Z)) : list (expr * Z)
3318 := List.flat_map
3319 (fun '(e, zs) => match interp0_op o zs with
3320 | None => List.map (pair e) zs
3321 | Some z => [(e, z)]
3322 end)
3323 ls.
3324
3325 (* o is like mul *)
3326 (* spec is that Forall (fun '(e, z) e' => o (eval e) z matches eval e') inputs outputs *)
3327 Definition app_consts (d : dag) (o : op) (ls : list (expr * Z)) : list expr
3328 := List.map (fun '(e, z) => let z := ExprApp (const z, []) in
3329 let default := ExprApp (o, [e; z]) in
3330 if associative o
3331 then match e with
3332 | ExprApp (o', args)
3333 => if op_beq o' o
3334 then ExprApp (o, args ++ [z])
3335 else default
3336 | _ => default end else default)
3337 ls.
3338
3339 Definition combine_consts_pre (d : dag) : expr -> expr :=
3340 fun e => match e with ExprApp (o, args) =>
3341 if commutative o && associative o && op_always_interps o then match combines_to o with
3342 | Some o' => match identity o' with
3343 | Some idv =>
3344 ExprApp (o, app_consts d o' (compress_consts d o (group_consts d (split_consts d o' idv args))))
3345 | None => e end | None => e end else e | _ => e end%bool.
3346
3347 Definition cleanup_combine_consts (d : dag) : expr -> expr :=
3348 let simp_outside := List.fold_left (fun e f => f e) [flatten_associative d] in
3349 let simp_inside := List.fold_left (fun e f => f e) [constprop d;drop_identity d;unary_truncate d;truncate_small d] in
3350 fun e => simp_outside match e with ExprApp (o, args) =>
3351 ExprApp (o, List.map simp_inside args)
3352 | _ => e end.
3353
3354 Definition combine_consts (d : dag) : expr -> expr := fun e => cleanup_combine_consts d (combine_consts_pre d e).
3355 #[local] Instance describe_combine_consts : description_of Rewrite.combine_consts
3356 := "Rewrites expressions like (x + x * 5) into (x * 6)".
3357
3358 Lemma split_consts_correct o i ls G d argsv
3359 (HGdok : gensym_dag_ok G d)
3360 (H : Forall2 (eval G d) ls argsv)
3361 (Hi : identity o = Some i)
3362 : Forall2 (fun '(e, z) v => exists v', eval G d e v' /\ (interp_op G o [v'; z] = Some v \/ (z = i /\ (v = v' \/ interp_op G o [v'] = Some v)))) (split_consts d o i ls) argsv.
3363 Proof.
3364 assert (eval G d (ExprApp (o, [])) i) by now econstructor; [ constructor | apply interp_op_nil_is_identity; assumption ].
3365 cbv [split_consts].
3366 revert dependent argsv; intro argsv.
3367 revert argsv; induction ls as [|x xs IH], argsv as [|v argsv];
3368 try specialize (IH argsv); intros; cbn [List.map];
3369 invlist Forall2; specialize_by_assumption; constructor; try assumption; clear IH.
3370 repeat first [ progress inversion_pair
3371 | progress subst
3372 | progress inversion_option
3373 | progress inversion_list
3374 | progress destruct_head'_ex
3375 | progress destruct_head'_and
3376 | progress reflect_hyps
3377 | rewrite app_nil_r in *
3378 | solve [ eauto 10 ]
3379 | eapply ex_intro; split; [ now unshelve (repeat first [ eassumption | econstructor ]) | ]
3380 | match goal with
3381 | [ |- (let '(x, y) := match ?v with _ => _ end in _) _ ]
3382 => tryif is_var v then destruct v else destruct v eqn:?
3383 | [ H : (match ?v with _ => _ end) = _ |- _ ]
3384 => tryif is_var v then destruct v else destruct v eqn:?
3385 | [ H : Forall2 _ (_ :: _) _ |- _ ] => rewrite Forall2_cons_l_ex_iff in H
3386 | [ H : Forall2 _ [] _ |- _ ] => rewrite Forall2_nil_l_iff in H
3387 | [ H : Forall _ (_ :: _) |- _ ] => rewrite Forall_cons_iff in H
3388 | [ H : Forall2 _ (_ ++ _) _ |- _ ] => apply Forall2_app_inv_l in H
3389 | [ H : interp_op _ (const _) _ = _ |- _ ] => cbn [interp_op] in H
3390 | [ H : andb _ _ = true |- _ ] => rewrite Bool.andb_true_iff in H
3391 | [ H : ?x = Some _, H' : ?x = Some _ |- _ ] => rewrite H in H'
3392 | [ H : context[interp_op _ _ (_ ++ _)] |- _ ] => rewrite interp_op_associative_app_bind in H by assumption; cbv [Crypto.Util.Option.bind] in H
3393 | [ H : partition _ _ = _ |- _ ]
3394 => let H' := fresh in
3395 pose proof H as H'; apply List.Forall_partition in H';
3396 let H' := fresh in
3397 pose proof H as H'; apply List.partition_eq_filter in H';
3398 apply List.partition_permutation in H
3399 | [ H : Permutation _ ?l, H' : Forall2 _ ?l ?args, H'' : interp_op _ _ ?args = Some _ |- _ ]
3400 => is_var args; eapply Permutation_Forall2 in H'; [ | symmetry; exact H ];
3401 let H''' := fresh in
3402 destruct H' as [? [H''' H'] ];
3403 eapply permute_commutative in H''; try exact H'''; try assumption; [];
3404 clear args H'''
3405 | [ H : eval _ _ (ExprApp _) _ |- _ ] => inversion H; clear H
3406 | [ H : interp0_expr (ExprApp _) = Some _ |- _ ]
3407 => eapply eval_interp0_expr in H
3408 | [ H : Forall2 (eval _ _) ?ls ?v1, H' : Forall2 (eval _ _) ?ls ?v2 |- _ ]
3409 => assert (v1 = v2) by (eapply eval_eval_Forall2; eassumption);
3410 clear H'
3411 | [ H : Permutation (@filter ?A ?f ?ls) ?ls |- _ ]
3412 => apply Permutation_length, List.filter_eq_length_eq in H;
3413 generalize dependent (@filter A f ls); intros; subst
3414 | [ H : interp_op _ ?o [?x] = Some _ |- context[interp_op _ ?o (?x :: ?ls)] ]
3415 => change (x :: ls) with ([x] ++ ls);
3416 rewrite interp_op_associative_app_bind, H by assumption;
3417 try erewrite interp_op_associative_idempotent by eassumption;
3418 cbn [Crypto.Util.Option.bind]
3419 | [ H : commutative ?o = true, H' : interp_op _ ?o [?a; ?b] = Some ?v |- interp_op _ ?o [?b; ?a] = Some ?v \/ _ ]
3420 => left; erewrite permute_commutative; [ reflexivity | .. ]; try eassumption; rewrite Permutation_rev; reflexivity
3421 end
3422 | erewrite <- interp_op_associative_app by eassumption ].
3423 Qed.
3424
3425 Lemma group_consts_Permutation (d : dag) ls
3426 : Permutation (List.concat (List.map (fun '(e, zs) => List.map (pair e) zs) (group_consts d ls))) ls.
3427 Proof.
3428 cbv [group_consts].
3429 let fv := match goal with |- context[List.groupAllBy ?f ls] => f end in
3430 pose proof (@List.Forall_groupAllBy _ fv ls) as H;
3431 etransitivity; [ | apply List.concat_groupAllBy with (f:=fv) ];
3432 generalize dependent (List.groupAllBy fv ls); intro gfls; intros.
3433 match goal with |- ?R ?x ?y => cut (x = y); [ intros ->; reflexivity | ] end.
3434 apply f_equal.
3435 induction H; [ reflexivity | ]; cbn.
3436 break_innermost_match; cbn [List.map]; try solve [ exfalso; assumption ].
3437 repeat (f_equal; try assumption; []).
3438 cbn [fst snd] in *.
3439 lazymatch goal with
3440 | [ H : Forall _ ?ls |- map (pair _) (map snd ?ls) = ?ls ]
3441 => revert H; clear
3442 end.
3443 intro H; induction H; destruct_head'_prod; cbn [List.map fst snd]; reflect_hyps; subst; cbn [fst snd].
3444 all: f_equal; assumption.
3445 Qed.
3446
3447 Lemma group_consts_nonempty d ls
3448 : Forall (fun '(e, zs) => zs <> nil) (group_consts d ls).
3449 Proof.
3450 cbv [group_consts].
3451 let fv := match goal with |- context[List.groupAllBy ?f ls] => f end in
3452 pose proof (@List.Forall_groupAllBy_full _ fv ls) as H;
3453 generalize dependent (List.groupAllBy fv ls); intro gfls; intros.
3454 induction gfls as [|x xs IH]; cbn [list_rect Option.List.map fold_right] in *; break_innermost_match; destruct_head'_and; destruct_head'_False;
3455 constructor; try congruence; eauto.
3456 Qed.
3457
3458 Lemma compress_consts_correct d o ls
3459 (Ho : op_always_interps o = true)
3460 : Forall2 (fun '(e, zs) '(e', z) => e = e' /\ interp0_op o zs = Some z) ls (compress_consts d o ls).
3461 Proof.
3462 cbv [compress_consts].
3463 induction ls as [|x xs IH]; cbn [List.flat_map]; break_innermost_match; cbn [List.app];
3464 try solve [ exfalso; eapply interp0_op_always_interps; eassumption ]; constructor; eauto.
3465 Qed.
3466
3467 (* in a more specific, usable form *)
3468 Lemma compress_consts_correct_alt G d o' o ls argsv
3469 (HGdok : gensym_dag_ok G d)
3470 (Ho : op_always_interps o = true)
3471 (H : Forall2 (fun '(e, zs) v => exists z, interp0_op o zs = Some z /\ exists v', (exists xs, interp_op G o' xs = Some z) /\ eval G d e v' /\ interp_op G o' [v'; z] = Some v) ls argsv)
3472 : Forall2 (fun '(e, z) v => exists v', (exists xs, interp_op G o' xs = Some z) /\ eval G d e v' /\ interp_op G o' [v'; z] = Some v) (compress_consts d o ls) argsv.
3473 Proof.
3474 eapply compress_consts_correct in Ho.
3475 apply Forall2_flip in H.
3476 eapply Forall2_trans in Ho; [ | exact H ].
3477 apply Forall2_flip.
3478 eapply Forall2_weaken; [ | eassumption ]; cbv beta.
3479 intros; repeat (destruct_head'_ex || destruct_head'_prod || destruct_head'_and || subst).
3480 repeat first [ progress inversion_option
3481 | progress subst
3482 | match goal with
3483 | [ H : ?x = Some _, H' : ?x = Some _ |- _ ] => rewrite H in H'
3484 end
3485 | solve [ eauto ] ].
3486 Qed.
3487
3488 Lemma app_consts_correct G d o ls argsv
3489 (HGdok : gensym_dag_ok G d)
3490 (H : Forall2 (fun '(e, z) v => exists v', (exists xs, interp_op G o xs = Some z) /\ eval G d e v' /\ interp_op G o [v'; z] = Some v) ls argsv)
3491 : Forall2 (eval G d) (app_consts d o ls) argsv.
3492 Proof.
3493 cbv [app_consts].
3494 induction H; cbn [List.map]; constructor.
3495 all: repeat first [ assumption
3496 | progress destruct_head'_prod
3497 | progress destruct_head'_ex
3498 | progress destruct_head'_and
3499 | progress subst
3500 | progress reflect_hyps
3501 | break_innermost_match_step
3502 | match goal with
3503 | [ |- eval _ _ (ExprApp (_, [_; _])) _ ]
3504 => econstructor; [ | eassumption ]; unshelve (repeat (constructor; [ shelve | ])); [ .. | constructor ]
3505 | [ |- eval _ _ (ExprApp (const ?z, [])) _ ]
3506 => econstructor; [ constructor | reflexivity ]
3507 end
3508 | step; eauto; []
3509 | match goal with
3510 | [ |- eval _ _ (ExprApp (_, _ ++ _)) _ ]
3511 => econstructor; [ repeat first [ eassumption | apply Forall2_app | apply Forall2_cons | apply Forall2_nil ] | ]
3512 end
3513 | erewrite interp_op_associative_app; try eassumption; []
3514 | eapply interp_op_associative_idempotent; try eassumption ].
3515 Qed.
3516
3517 Lemma combines_to_correct o o' v G xs vxs xsv
3518 (H : combines_to o = Some o')
3519 (H' : Forall2 (fun x vx => interp_op G o' [v; x] = Some vx) xs vxs)
3520 (H'' : interp_op G o xs = Some xsv)
3521 : interp_op G o' [v; xsv] = interp_op G o vxs.
3522 Proof.
3523 cbv [combines_to] in H; destruct o; inversion_option; subst.
3524 all: cbn [interp_op fold_right op_to_Z_binop invert_Some identity] in *; break_innermost_match; inversion_option; subst; apply f_equal.
3525 all: autorewrite with zsimplify_const in *; try reflexivity.
3526 all: rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod.
3527 all: eapply Forall2_weaken in H';
3528 [
3529 | intros *;
3530 let H := fresh in
3531 intro H;
3532 inversion_option;
3533 autorewrite with zsimplify_const in H;
3534 rewrite ?Z.land_ones in H by lia; exact H ].
3535 all: rewrite <- Forall2_map_l in H'.
3536 all: apply Forall2_eq in H'; subst.
3537 all: induction xs as [|x xs IH]; cbn [fold_right List.map]; autorewrite with zsimplify_const; try reflexivity.
3538 all: push_Zmod; pull_Zmod.
3539 all: revert IH; push_Zmod; intro IH; rewrite <- IH; clear IH; pull_Zmod.
3540 all: rewrite <- Z.mul_add_distr_l.
3541 all: reflexivity.
3542 Qed.
3543
3544 (* should this be factored differently? *)
3545 Lemma interp_op_combines_to_idempotent G o o' (H : combines_to o = Some o') xs vxs
3546 : interp_op G o xs = Some vxs -> interp_op G o' [vxs] = Some vxs.
3547 Proof.
3548 destruct o; cbv [combines_to] in *; inversion_option; subst; cbn [interp_op fold_right op_to_Z_binop invert_Some identity]; break_innermost_match; intros; inversion_option; subst.
3549 all: autorewrite with zsimplify_const.
3550 all: apply f_equal; try reflexivity.
3551 rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod.
3552 reflexivity.
3553 Qed.
3554
3555 Lemma interp_op_combines_to_idempotent_rev G o o' (H : combines_to o = Some o') xs vxs
3556 : interp_op G o' xs = Some vxs -> interp_op G o [vxs] = Some vxs.
3557 Proof.
3558 destruct o; cbv [combines_to] in *; inversion_option; subst; cbn [interp_op fold_right]; intros; inversion_option; subst.
3559 all: autorewrite with zsimplify_const.
3560 all: apply f_equal; try reflexivity.
3561 rewrite ?Z.land_ones by lia; push_Zmod; pull_Zmod.
3562 reflexivity.
3563 Qed.
3564
3565 Lemma interp_op_combines_to_singleton_same_size G o o' (H : combines_to o = Some o') v
3566 : interp_op G o [v] = interp_op G o' [v].
3567 Proof.
3568 destruct o; cbv [combines_to] in *; inversion_option; subst; cbn [interp_op fold_right op_to_Z_binop invert_Some identity]; intros; break_innermost_match; inversion_option; subst.
3569 all: autorewrite with zsimplify_const.
3570 all: reflexivity.
3571 Qed.
3572
3573 (* a more general version useful for us *)
3574 Lemma combines_to_correct_or o o' v G xs vxs xsv
3575 (Ho : associative o = true)
3576 (Ho' : op_always_interps o = true)
3577 (H : combines_to o = Some o')
3578 (H' : Forall2 (fun x vx => interp_op G o' [v; x] = Some vx \/ interp_op G o' [v; x] = interp_op G o' [vx]) xs vxs)
3579 (H'' : interp_op G o xs = Some xsv)
3580 : interp_op G o' [v; xsv] = interp_op G o vxs.
3581 Proof.
3582 rewrite <- (List.concat_map_singleton vxs).
3583 rewrite interp_op_associative_spec_concat, map_map by assumption.
3584 rewrite Option.List.bind_list_cps_id, <- Option.List.eq_bind_list_lift; cbv [Crypto.Util.Option.bind]; break_match; revgoals.
3585 { exfalso.
3586 let H := match goal with H : _ = None |- _ => H end in
3587 revert H; clear -Ho Ho'.
3588 cbv [Option.List.lift].
3589 induction vxs as [|?? IH]; cbn; cbv [Crypto.Util.Option.bind] in *; break_match; try congruence.
3590 intro; eapply interp_op_always_interps; eassumption. }
3591 eapply combines_to_correct; try eassumption.
3592 let l := match goal with |- Forall2 _ _ ?l => l end in
3593 revert dependent xsv; revert dependent l.
3594 cbv [Option.List.lift] in *.
3595 induction H'; cbn [List.map fold_right]; intros [|z xs]; intros; cbv [Crypto.Util.Option.bind] in *; break_match_hyps.
3596 all: inversion_option; inversion_list; subst; constructor.
3597 all: repeat first [ break_innermost_match_hyps_step
3598 | progress inversion_option
3599 | progress subst
3600 | assumption
3601 | match goal with
3602 | [ H : forall x, Some _ = Some x -> _ |- _ ] => specialize (H _ eq_refl)
3603 | [ H : context[?x :: ?l] |- _ ]
3604 => is_var x; is_var l; change (x :: l) with ([x] ++ l) in *;
3605 rewrite interp_op_associative_app_bind in H by assumption;
3606 cbv [Crypto.Util.Option.bind] in H
3607 | [ H : context[interp_op _ _ [_] ] |- _ ] => erewrite interp_op_combines_to_idempotent_rev in H by eassumption
3608 end
3609 | progress destruct_head'_or
3610 | erewrite interp_op_combines_to_singleton_same_size in * by eassumption
3611 | congruence ].
3612 Qed.
3613
3614 Lemma combines_to_correct_alt G d o o' xs ys i z z1 e
3615 (Ho : combines_to o = Some o')
3616 (Hi : identity o' = Some i)
3617 (Ha : associative o = true)
3618 (Hai : op_always_interps o = true)
3619 (H : Forall2 (fun x y => exists v', eval G d e v' /\ (interp_op G o' [v'; x] = Some y \/ (x = i /\ (y = v' \/ interp_op G o' [v'] = Some y)))) xs ys)
3620 (H' : interp_op G o ys = Some z1)
3621 (Hz : interp_op G o xs = Some z)
3622 (Hnonempty : xs <> nil)
3623 : exists v' : Z, (exists xs0 : list Z, interp_op G o' xs0 = Some z) /\ eval G d e v' /\ interp_op G o' [v'; z] = Some z1.
3624 Proof.
3625 cut (exists v', eval G d e v');
3626 [ intros [ev ?]; exists ev
3627 | match goal with
3628 | [ H : Forall2 _ ?l _, H' : ?l <> [] |- _ ]
3629 => inversion H; subst; try congruence; destruct_head'_ex; destruct_head'_and; eauto
3630 end ].
3631 repeat apply conj.
3632 { eexists [_]; eapply interp_op_combines_to_idempotent; eassumption. }
3633 { assumption. }
3634 { rewrite <- H'.
3635 eapply combines_to_correct_or; try eassumption.
3636 clear z1 z H' Hz Hnonempty.
3637 induction H; constructor; eauto.
3638 repeat (destruct_head'_ex; destruct_head'_and; destruct_head'_or).
3639 all: repeat (step; eauto; []); subst; eauto.
3640 all: erewrite @interp_op_drop_identity in * by eassumption; cbn [filter] in *; cbv [negb] in *; break_innermost_match; break_innermost_match_hyps;
3641 reflect_hyps; subst.
3642 all: try congruence.
3643 all: try now (idtac + left); apply interp_op_nil_is_identity.
3644 all: eauto. }
3645 Qed.
3646
3647 Lemma combine_consts_helper o o' G d ls args i
3648 (H : Forall2
3649 (fun '(e, zs) y =>
3650 Forall2
3651 (fun '(e, z') (v : Z) =>
3652 exists v' : Z, eval G d e v' /\ (interp_op G o' [v'; z'] = Some v \/ (z' = i /\ (v = v' \/ interp_op G o' [v'] = Some v))))
3653 (map (pair e) zs) y)
3654 ls args)
3655 (Hi' : identity o' = Some i)
3656 (Halways : op_always_interps o = true)
3657 (Hassoc : associative o = true)
3658 (Hc : combines_to o = Some o')
3659 (Hnonempty : Forall (fun '(e, zs) => zs <> nil) ls)
3660 : exists args',
3661 interp_op G o (concat args) = interp_op G o args'
3662 /\ Forall2
3663 (fun '(e, zs) (v0 : Z) =>
3664 exists z' : Z,
3665 interp0_op o zs = Some z' /\
3666 (exists v' : Z, (exists xs : list Z, interp_op G o' xs = Some z') /\ eval G d e v' /\ interp_op G o' [v'; z'] = Some v0))
3667 ls args'.
3668 Proof.
3669 revert ls args H Hnonempty.
3670 induction ls as [|x xs IH], args as [|arg args]; try specialize (IH args).
3671 all: rewrite ?Forall2_nil_l_iff, ?Forall2_nil_r_iff, ?Forall2_cons_cons_iff; try congruence.
3672 { exists nil; split; [ cbn; reflexivity | constructor ]. }
3673 repeat first [ progress destruct_head_prod
3674 | progress destruct_head_and
3675 | progress destruct_head_ex
3676 | progress intros
3677 | progress specialize_by_assumption
3678 | progress invlist Forall ].
3679 match goal with
3680 | [ |- ex ?P ] => cut (exists a b, P ([a] ++ b)); [ intros [a [b ?] ]; exists ([a] ++ b); assumption | ]
3681 end.
3682 cbv beta.
3683 rewrite !interp_op_associative_app_bind by assumption.
3684 setoid_rewrite interp_op_associative_app_bind; [ | assumption ].
3685 cbv [Crypto.Util.Option.bind]; break_innermost_match; inversion_option; subst; do 2 eexists; break_innermost_match; split; try reflexivity.
3686 all: repeat first [ progress inversion_option
3687 | match goal with
3688 | [ H : interp_op _ _ ?l = Some ?x, H' : interp_op _ _ [?v] = Some ?x' |- interp_op _ _ [?x; ?y] = interp_op _ _ [?x'; ?y'] ]
3689 => erewrite interp_op_associative_idempotent in H' by first [ exact H | assumption ]
3690 | [ H : Some _ = _ |- _ ] => symmetry in H
3691 | [ H : interp_op _ _ [?x] = _ |- _ ]
3692 => tryif is_evar x then fail else erewrite interp_op_associative_idempotent in H by eassumption
3693 | [ H : interp_op _ _ _ = None |- _ ]
3694 => apply interp_op_always_interps in H; [ exfalso | assumption ]
3695 end
3696 | progress subst
3697 | progress cbn [List.app]
3698 | apply Forall2_cons
3699 | eassumption
3700 | rewrite @Forall2_map_l_iff in *
3701 | match goal with
3702 | [ |- exists z, interp0_op ?o ?l = Some z /\ _ ]
3703 => let H := fresh in
3704 destruct (interp0_op o l) eqn:H;
3705 [ eexists; split; [ reflexivity | ]
3706 | apply interp_op_always_interps in H; [ exfalso | assumption ] ]
3707 end ].
3708 all: try congruence.
3709 eapply combines_to_correct_alt; try ((idtac + eapply interp_op_interp0_op); eassumption).
3710 Unshelve.
3711 all: try solve [ constructor ].
3712 Qed.
3713
3714 Global Instance cleanup_combine_consts_Ok : Ok cleanup_combine_consts.
3715 Proof.
3716 repeat (step; eauto; []); cbn [fold_left].
3717 repeat match goal with
3718 | [ |- eval _ _ (?r ?d ?e) _ ]
3719 => apply (_:Ok r); try assumption
3720 end.
3721 econstructor; [ | eassumption ].
3722 rewrite Forall2_map_l.
3723 rewrite !@Forall2_forall_iff_nth_error in *; cbv [option_eq] in *.
3724 intros.
3725 repeat match goal with
3726 | [ H : context[nth_error ?l] |- context[nth_error ?l ?i] ] => specialize (H i)
3727 end.
3728 break_innermost_match; eauto.
3729 cbn [fold_left].
3730 repeat lazymatch goal with
3731 | H : eval ?c ?d ?e _ |- context[?r ?d ?e] =>
3732 let Hr := fresh in epose proof ((_:Ok r) _ _ _ _ ltac:(eassumption) H) as Hr; clear H
3733 end.
3734 assumption.
3735 Qed.
3736
3737 Global Instance combine_consts_pre_Ok : Ok combine_consts_pre.
3738 Proof using Type.
3739 repeat (step; eauto; []).
3740 match goal with
3741 | [ |- context[split_consts ?d ?o ?i ?l] ]
3742 => pose proof (@split_consts_correct o i l _ _ _ ltac:(eassumption) ltac:(eassumption) ltac:(assumption)) as Hs
3743 end.
3744 match goal with
3745 | [ |- context[group_consts ?d ?ls] ]
3746 => pose proof (@group_consts_Permutation d ls) as Hg;
3747 pose proof (@group_consts_nonempty d ls) as Hg'
3748 end.
3749 eapply Permutation_Forall2 in Hs; [ | symmetry; exact Hg ].
3750 destruct Hs as [? [? Hs] ].
3751 repeat match goal with H : _ /\ _ |- _ => destruct H end.
3752 let H := match goal with H : interp_op _ _ _ = Some _ |- _ => H end in
3753 eapply permute_commutative in H; [ | eassumption .. ].
3754 rewrite Forall2_concat_l_ex_iff in Hs.
3755 destruct Hs as [? [? Hs] ]; subst.
3756 rewrite Forall2_map_l_iff in Hs.
3757 eapply Forall2_weaken, combine_consts_helper in Hs; try assumption; try solve [ intros; destruct_head'_prod; eassumption ]; [ | try eassumption .. ].
3758 destruct Hs as [? [? Hs] ].
3759 econstructor; [ apply app_consts_correct, compress_consts_correct_alt; try assumption | ].
3760 { eassumption. }
3761 { congruence. }
3762 Qed.
3763
3764 Global Instance combine_consts_Ok : Ok combine_consts.
3765 Proof. repeat step; apply cleanup_combine_consts_Ok, combine_consts_pre_Ok; assumption. Qed.
3766
3767 (* M-x query-replace-regex RET \(| RewritePass\.\)\([^ ]*\) => _ RET \1\2 => \2 *)
3768 Definition named_pass (name : RewritePass.rewrite_pass) : dag -> expr -> expr
3769 := match name with
3770 | RewritePass.addbyte_small => addbyte_small
3771 | RewritePass.addcarry_bit => addcarry_bit
3772 | RewritePass.addcarry_small => addcarry_small
3773 | RewritePass.addoverflow_bit => addoverflow_bit
3774 | RewritePass.addoverflow_small => addoverflow_small
3775 | RewritePass.combine_consts => combine_consts
3776 | RewritePass.constprop => constprop
3777 | RewritePass.consts_commutative => consts_commutative
3778 | RewritePass.drop_identity => drop_identity
3779 | RewritePass.flatten_associative => flatten_associative
3780 | RewritePass.flatten_bounded_associative => flatten_bounded_associative
3781 | RewritePass.fold_consts_to_and => fold_consts_to_and
3782 | RewritePass.set_slice0_small => set_slice0_small
3783 | RewritePass.set_slice_set_slice => set_slice_set_slice
3784 | RewritePass.shift_to_mul => shift_to_mul
3785 | RewritePass.slice0 => slice0
3786 | RewritePass.slice01_addcarryZ => slice01_addcarryZ
3787 | RewritePass.slice01_subborrowZ => slice01_subborrowZ
3788 | RewritePass.slice_set_slice => slice_set_slice
3789 | RewritePass.truncate_small => truncate_small
3790 | RewritePass.unary_truncate => unary_truncate
3791 | RewritePass.xor_same => xor_same
3792 end.
3793
3794 Global Instance named_pass_Ok {n} : Ok (named_pass n).
3795 Proof. destruct n; cbv [named_pass]; exact _. Qed.
3796
3797 Global Instance describe_pass n : description_of (named_pass n).
3798 Proof.
3799 destruct n; cbv [named_pass]; try exact _.
3800 all: fail_if_goals_remain ().
3801 Defined.
3802
3803 Definition expr {rewriting_passes : rewriting_passes_opt} (d : dag) : expr -> expr :=
3804 List.fold_left (fun e f => f d e)
3805 (List.map named_pass rewriting_passes).
3806
3807 Local Instance expr_Ok {rewriting_passes : rewriting_passes_opt} : Ok expr.
3808 Proof.
3809 pose proof (@named_pass_Ok).
3810 cbv [expr]; induction rewriting_passes; cbn [map fold_left]; cbv [Ok] in *; eauto.
3811 Qed.
3812
3813 Lemma eval_expr {rewriting_passes : rewriting_passes_opt} c d e v : gensym_dag_ok c d -> eval c d e v -> eval c d (expr d e) v.
3814 Proof.
3815 apply expr_Ok.
3816 Qed.
3817 End Rewrite.
3818
3819 Definition simplify {opts : symbolic_options_computed_opt} (dag : dag) (e : node idx) :=
3820 Rewrite.expr dag (reveal_node_at_least dag node_reveal_depth e).
3821
3822 Lemma eval_simplify {opts : symbolic_options_computed_opt} G d n v : gensym_dag_ok G d -> eval_node G d n v -> eval G d (simplify d n) v.
3823 Proof using Type. eauto using Rewrite.eval_expr, eval_node_reveal_node_at_least. Qed.
3824
3825 Definition reg_state := Tuple.tuple (option idx) (compute! (List.length widest_registers)).
3826 Definition flag_state := Tuple.tuple (option idx) 6.
3827 Definition mem_state := list (idx * idx).
3828
3829 Definition get_flag (st : flag_state) (f : FLAG) : option idx
3830 := let '(cfv, pfv, afv, zfv, sfv, ofv) := st in
3831 match f with
3832 | CF => cfv
3833 | PF => pfv
3834 | AF => afv
3835 | ZF => zfv
3836 | SF => sfv
3837 | OF => ofv
3838 end.
3839 Definition set_flag_internal (st : flag_state) (f : FLAG) (v : option idx) : flag_state
3840 := let '(cfv, pfv, afv, zfv, sfv, ofv) := st in
3841 (match f with CF => v | _ => cfv end,
3842 match f with PF => v | _ => pfv end,
3843 match f with AF => v | _ => afv end,
3844 match f with ZF => v | _ => zfv end,
3845 match f with SF => v | _ => sfv end,
3846 match f with OF => v | _ => ofv end).
3847 Definition set_flag (st : flag_state) (f : FLAG) (v : idx) : flag_state
3848 := set_flag_internal st f (Some v).
3849 Definition havoc_flag (st : flag_state) (f : FLAG) : flag_state
3850 := set_flag_internal st f None.
3851 Definition havoc_flags : flag_state
3852 := (None, None, None, None, None, None).
3853 Definition reverse_lookup_flag (st : flag_state) (i : idx) : option FLAG
3854 := option_map
3855 (@snd _ _)
3856 (List.find (fun v => option_beq N.eqb (Some i) (fst v))
3857 (Tuple.to_list _ (Tuple.map2 (@pair _ _) st (CF, PF, AF, ZF, SF, OF)))).
3858
3859 Definition get_reg (st : reg_state) (ri : N) : option idx
3860 := Tuple.nth_default None (N.to_nat ri) st.
3861 Definition set_reg (st : reg_state) (ri : N) (i : idx) : reg_state
3862 := Tuple.from_list_default None _ (ListUtil.set_nth
3863 (N.to_nat ri)
3864 (Some i)
3865 (Tuple.to_list _ st)).
3866 Definition reverse_lookup_widest_reg (st : reg_state) (i : idx) : option REG
3867 := option_map
3868 (fun v => widest_register_of_index (N.of_nat (fst v)))
3869 (List.find (fun v => option_beq N.eqb (Some i) (snd v))
3870 (List.enumerate (Tuple.to_list _ st))).
3871
3872 Definition load (a : idx) (s : mem_state) : option idx :=
3873 option_map snd (find (fun p => fst p =? a)%N s).
3874 Definition remove (a : idx) (s : mem_state) : list idx * mem_state :=
3875 let '(vs, s) := List.partition (fun p => fst p =? a)%N s in
3876 (List.map snd vs, s).
3877 Definition store (a v : idx) (s : mem_state) : option mem_state :=
3878 n <- indexof (fun p => fst p =? a)%N s;
3879 Some (ListUtil.update_nth n (fun ptsto => (fst ptsto, v)) s).
3880 Definition reverse_lookup_mem (st : mem_state) (i : idx) : option (N * idx)
3881 := option_map
3882 (fun '(n, (_, ptsto)) => (N.of_nat n, ptsto))
3883 (List.find (fun v => N.eqb i (fst (snd v)))
3884 (List.enumerate st)).
3885
3886 Local Unset Boolean Equality Schemes.
3887 Local Unset Decidable Equality Schemes.
3888 Record symbolic_state := { dag_state :> dag ; symbolic_reg_state :> reg_state ; symbolic_flag_state :> flag_state ; symbolic_mem_state :> mem_state }.
3889 Local Set Boolean Equality Schemes.
3890 Local Set Decidable Equality Schemes.
3891
3892 Definition update_dag_with (st : symbolic_state) (f : dag -> dag) : symbolic_state
3893 := {| dag_state := f st.(dag_state); symbolic_reg_state := st.(symbolic_reg_state) ; symbolic_flag_state := st.(symbolic_flag_state) ; symbolic_mem_state := st.(symbolic_mem_state) |}.
3894 Definition update_reg_with (st : symbolic_state) (f : reg_state -> reg_state) : symbolic_state
3895 := {| dag_state := st.(dag_state); symbolic_reg_state := f st.(symbolic_reg_state) ; symbolic_flag_state := st.(symbolic_flag_state) ; symbolic_mem_state := st.(symbolic_mem_state) |}.
3896 Definition update_flag_with (st : symbolic_state) (f : flag_state -> flag_state) : symbolic_state
3897 := {| dag_state := st.(dag_state); symbolic_reg_state := st.(symbolic_reg_state) ; symbolic_flag_state := f st.(symbolic_flag_state) ; symbolic_mem_state := st.(symbolic_mem_state) |}.
3898 Definition update_mem_with (st : symbolic_state) (f : mem_state -> mem_state) : symbolic_state
3899 := {| dag_state := st.(dag_state); symbolic_reg_state := st.(symbolic_reg_state) ; symbolic_flag_state := st.(symbolic_flag_state) ; symbolic_mem_state := f st.(symbolic_mem_state) |}.
3900
3901 Global Instance show_reg_state : Show reg_state := fun st =>
3902 show (List.combine widest_registers (Option.List.map id (Tuple.to_list _ st))).
3903
3904 Global Instance show_flag_state : Show flag_state :=
3905 fun '(cfv, pfv, afv, zfv, sfv, ofv) => (
3906 "(*flag_state*)(CF="++show cfv
3907 ++" PF="++show pfv
3908 ++" AF="++show afv
3909 ++" ZF="++show zfv
3910 ++" SF="++show sfv
3911 ++" ZF="++show zfv
3912 ++" OF="++show ofv++")")%string.
3913 Global Instance show_lines_dag : ShowLines dag := (fun d:dag =>
3914 ["(*dag*)["]
3915 ++List.map (fun '(i, v, descr) =>"(*"++show i ++"*) " ++ show v++";"
3916 ++ (if dag.get_eager_description_always_show descr
3917 then match dag.get_eager_description_description descr with
3918 | Some descr => " " ++ String.Tab ++ "(*" ++ descr ++ "*)"
3919 | None => ""
3920 end
3921 else ""))%string (dag.eager.elements (dag.eager.force d))
3922 ++["]"])%list%string.
3923 Global Instance show_lines_mem_state : ShowLines mem_state :=
3924 @show_lines_list _ ShowLines_of_Show.
3925
3926 Global Instance ShowLines_symbolic_state : ShowLines symbolic_state :=
3927 fun X : symbolic_state =>
3928 match X with
3929 | {|
3930 dag_state := ds;
3931 symbolic_reg_state := rs;
3932 symbolic_flag_state := fs;
3933 symbolic_mem_state := ms
3934 |} =>
3935 ["(*symbolic_state*) {|";
3936 " dag_state :="] ++ show_lines ds ++ [";";
3937 (" symbolic_reg_state := " ++ show rs ++ ";")%string;
3938 (" symbolic_flag_state := " ++ show fs ++";")%string;
3939 " symbolic_mem_state :="] ++show_lines ms ++ [";";
3940 "|}"]
3941 end%list%string.
3942
3943
3944 Module error.
3945 Local Unset Boolean Equality Schemes.
3946 Local Unset Decidable Equality Schemes.
3947 Variant error :=
3948 | get_flag (f : FLAG) (s : flag_state)
3949 | get_reg (r : N + REG) (s : reg_state)
3950 | load (a : idx) (s : symbolic_state)
3951 | remove (a : idx) (s : symbolic_state)
3952 | remove_has_duplicates (a : idx) (vs : list idx) (s : symbolic_state)
3953 | store (a v : idx) (s : symbolic_state)
3954 | set_const (_ : CONST) (_ : idx)
3955 | expected_const (_ : idx) (_ : expr)
3956
3957 | unsupported_memory_access_size (_:N)
3958 | unsupported_label_in_memory (_:string)
3959 | unsupported_label_argument (_:JUMP_LABEL)
3960 | unimplemented_prefix (_:NormalInstruction)
3961 | unimplemented_instruction (_ : NormalInstruction)
3962 | unsupported_line (_ : RawLine)
3963 | ambiguous_operation_size (_ : NormalInstruction)
3964 .
3965
3966 Global Instance show_lines_error : ShowLines error
3967 := fun e
3968 => match e with
3969 | get_flag f s
3970 => ["In flag state " ++ show_flag_state s;
3971 "Flag " ++ show f ++ " was read without being set."]
3972 | get_reg (inl i) s
3973 => ["Invalid reg index " ++ show i]
3974 | get_reg (inr r) s
3975 => ["In reg state " ++ show_reg_state s;
3976 "Register " ++ show (r : REG) ++ " read without being set."]
3977 | load a s
3978 => (["In mem state:"]
3979 ++ show_lines_mem_state s
3980 ++ ["Index " ++ show a ++ " loaded without being present."]%string)%list
3981 | remove a s
3982 => (["In mem state:"]
3983 ++ show_lines_mem_state s
3984 ++ ["Index " ++ show a ++ " removed without being present."]%string)%list
3985 | remove_has_duplicates a ls s
3986 => (["In mem state:"]
3987 ++ show_lines_mem_state s
3988 ++ ["Index " ++ show a ++ " occurs multiple times during removal (" ++ show ls ++ ")."]%string)%list
3989 | store a v s
3990 => (["In mem state:"]
3991 ++ show_lines_mem_state s
3992 ++ ["Index " ++ show a ++ " updated (with value " ++ show v ++ ") without being present."]%string)%list
3993 | set_const c i
3994 => ["SetOperand called with Syntax.const " ++ show c ++ " " ++ show i]%string
3995 | expected_const i x
3996 => ["RevealConst called at " ++ show i ++ " resulted in non-const value " ++ show x]
3997 | unsupported_memory_access_size n => ["error.unsupported_memory_access_size " ++ show n]
3998 | unsupported_label_in_memory l => ["error.unsupported_label_in_memory " ++ l]
3999 | unsupported_label_argument l => ["error.unsupported_label_argument " ++ show l]
4000 | unimplemented_instruction n => ["error.unimplemented_instruction " ++ show n]
4001 | unimplemented_prefix n => ["error.unimplemented_prefix " ++ show n]
4002 | unsupported_line n => ["error.unsupported_line " ++ show n]
4003 | ambiguous_operation_size n => ["error.ambiguous_operation_size " ++ show n]
4004 end%string.
4005 Global Instance Show_error : Show error := _.
4006 End error.
4007 Notation error := error.error.
4008
4009 Definition M T := symbolic_state -> ErrorT (error * symbolic_state) (T * symbolic_state).
4010 Definition ret {A} (x : A) : M A :=
4011 fun s => Success (x, s).
4012 Definition err {A} (e : error) : M A :=
4013 fun s => Error (e, s).
4014 Definition some_or {A} (f : symbolic_state -> option A) (e : symbolic_state -> error) : M A :=
4015 fun st => match f st with Some x => Success (x, st) | None => Error (e st, st) end.
4016 Definition bind {A B} (x : M A) (f : A -> M B) : M B :=
4017 fun s => (x_s <- x s; f (fst x_s) (snd x_s))%error.
4018 Definition lift_dag {A} (v : dag.M A) : M A :=
4019 fun s => let '(v, d) := v s.(dag_state) in
4020 Success (v, update_dag_with s (fun _ => d)).
4021
4022 Declare Scope x86symex_scope.
4023 Delimit Scope x86symex_scope with x86symex.
4024 Bind Scope x86symex_scope with M.
4025 Notation "x <- y ; f" := (bind y (fun x => f%x86symex)) : x86symex_scope.
4026 Section MapM. (* map over a list in the state monad *)
4027 Context {A B} (f : A -> M B).
4028 Fixpoint mapM (l : list A) : M (list B) :=
4029 match l with
4030 | nil => ret nil
4031 | cons a l => b <- f a; bs <- mapM l; ret (cons b bs)
4032 end%x86symex.
4033 End MapM.
4034 Definition mapM_ {A B} (f: A -> M B) l : M unit := _ <- mapM f l; ret tt.
4035
4036 Definition error_get_reg_of_reg_index ri : symbolic_state -> error
4037 := error.get_reg (let r := widest_register_of_index ri in
4038 if (reg_index r =? ri)%N
4039 then inr r
4040 else inl ri).
4041
4042 Definition GetFlag f : M idx :=
4043 some_or (fun s => get_flag s f) (error.get_flag f).
4044 Definition GetReg64 ri : M idx :=
4045 some_or (fun st => get_reg st ri) (error_get_reg_of_reg_index ri).
4046 Definition Load64 (a : idx) : M idx := some_or (load a) (error.load a).
4047 Definition Remove64 (a : idx) : M idx
4048 := fun s => let '(vs, m) := remove a s in
4049 match vs with
4050 | [] => Error (error.remove a s, s)
4051 | [v] => Success (v, update_mem_with s (fun _ => m))
4052 | vs => Error (error.remove_has_duplicates a vs s, s)
4053 end.
4054 Definition SetFlag f i : M unit :=
4055 fun s => Success (tt, update_flag_with s (fun s => set_flag s f i)).
4056 Definition HavocFlags : M unit :=
4057 fun s => Success (tt, update_flag_with s (fun _ => Tuple.repeat None 6)).
4058 Definition PreserveFlag {T} (f : FLAG) (k : M T) : M T :=
4059 vf <- (fun s => Success (get_flag s f, s));
4060 x <- k;
4061 _ <- (fun s => Success (tt, update_flag_with s (fun s => set_flag_internal s f vf)));
4062 ret x.
4063 Definition SetReg64 rn i : M unit :=
4064 fun s => Success (tt, update_reg_with s (fun s => set_reg s rn i)).
4065 Definition Store64 (a v : idx) : M unit :=
4066 ms <- some_or (store a v) (error.store a v);
4067 fun s => Success (tt, update_mem_with s (fun _ => ms)).
4068 Definition Merge {descr : description} (e : expr) : M idx := fun s =>
4069 let i_dag := merge e s in
4070 Success (fst i_dag, update_dag_with s (fun _ => snd i_dag)).
4071 Definition App {opts : symbolic_options_computed_opt} {descr : description} (n : node idx) : M idx :=
4072 fun s => Merge (simplify s n) s.
4073 Definition Reveal n (i : idx) : M expr :=
4074 fun s => Success (reveal s n i, s).
4075 Definition RevealConst (i : idx) : M Z :=
4076 x <- Reveal 1 i;
4077 match x with
4078 | ExprApp (const n, nil) => ret n
4079 | _ => err (error.expected_const i x)
4080 end.
4081
4082 Definition GetReg {opts : symbolic_options_computed_opt} {descr:description} r : M idx :=
4083 let '(rn, lo, sz) := index_and_shift_and_bitcount_of_reg r in
4084 v <- GetReg64 rn;
4085 App ((slice lo sz), [v]).
4086 Definition SetReg {opts : symbolic_options_computed_opt} {descr:description} r (v : idx) : M unit :=
4087 let '(rn, lo, sz) := index_and_shift_and_bitcount_of_reg r in
4088 if N.eqb sz 64
4089 then v <- App (slice 0 64, [v]);
4090 SetReg64 rn v (* works even if old value is unspecified *)
4091 else old <- GetReg64 rn;
4092 v <- App ((set_slice lo sz), [old; v]);
4093 SetReg64 rn v.
4094
4095 Class AddressSize := address_size : OperationSize.
4096 Definition Address {opts : symbolic_options_computed_opt} {descr:description} {sa : AddressSize} (a : MEM) : M idx :=
4097 _ <- match a.(mem_base_label) with
4098 | None => ret tt
4099 | Some l => err (error.unsupported_label_in_memory l)
4100 end;
4101 base <- match a.(mem_base_reg) with
4102 | Some r => GetReg r
4103 | None => App ((const 0), nil)
4104 end;
4105 index <- match a.(mem_scale_reg) with
4106 | Some (z, r) => z <- App (zconst sa z, []); r <- GetReg r; App (mul sa, [r; z])
4107 | None => App ((const 0), nil)
4108 end;
4109 offset <- App (match a.(mem_offset) with
4110 | Some s => (zconst sa s, nil)
4111 | None => (const 0, nil) end);
4112 bi <- App (add sa, [base; index]);
4113 App (add sa, [bi; offset]).
4114
4115 Definition Load {opts : symbolic_options_computed_opt} {descr:description} {s : OperationSize} {sa : AddressSize} (a : MEM) : M idx :=
4116 if negb (orb (Syntax.operand_size a s =? 8 )( Syntax.operand_size a s =? 64))%N
4117 then err (error.unsupported_memory_access_size (Syntax.operand_size a s)) else
4118 addr <- Address a;
4119 v <- Load64 addr;
4120 App ((slice 0 (Syntax.operand_size a s)), [v]).
4121
4122 Definition Remove {opts : symbolic_options_computed_opt} {descr:description} {s : OperationSize} {sa : AddressSize} (a : MEM) : M idx :=
4123 if negb (orb (Syntax.operand_size a s =? 8 )( Syntax.operand_size a s =? 64))%N
4124 then err (error.unsupported_memory_access_size (Syntax.operand_size a s)) else
4125 addr <- Address a;
4126 v <- Remove64 addr;
4127 App ((slice 0 (Syntax.operand_size a s)), [v]).
4128
4129 Definition Store {opts : symbolic_options_computed_opt} {descr:description} {s : OperationSize} {sa : AddressSize} (a : MEM) v : M unit :=
4130 if negb (orb (Syntax.operand_size a s =? 8 )( Syntax.operand_size a s =? 64))%N
4131 then err (error.unsupported_memory_access_size (Syntax.operand_size a s)) else
4132 addr <- Address a;
4133 old <- Load64 addr;
4134 v <- App (slice 0 (Syntax.operand_size a s), [v]);
4135 v <- App (set_slice 0 (Syntax.operand_size a s), [old; v])%N;
4136 Store64 addr v.
4137
4138 (* note: this could totally just handle truncation of constants if semanics handled it *)
4139 Definition GetOperand {opts : symbolic_options_computed_opt} {descr:description} {s : OperationSize} {sa : AddressSize} (o : ARG) : M idx :=
4140 match o with
4141 | Syntax.const a => App (zconst s a, [])
4142 | mem a => Load a
4143 | reg r => GetReg r
4144 | label l => err (error.unsupported_label_argument l)
4145 end.
4146
4147 Definition SetOperand {opts : symbolic_options_computed_opt} {descr:description} {s : OperationSize} {sa : AddressSize} (o : ARG) (v : idx) : M unit :=
4148 match o with
4149 | Syntax.const a => err (error.set_const a v)
4150 | mem a => Store a v
4151 | reg a => SetReg a v
4152 | label l => err (error.unsupported_label_argument l)
4153 end.
4154
4155 Local Unset Elimination Schemes.
4156 Inductive pre_expr : Set :=
4157 | PreARG (_ : ARG)
4158 | PreFLG (_ : FLAG)
4159 | PreRef (_ : idx)
4160 | PreApp (_ : op) (_ : list pre_expr).
4161 (* note: need custom induction principle *)
4162 Local Set Elimination Schemes.
4163 Local Coercion PreARG : ARG >-> pre_expr.
4164 Local Coercion PreFLG : FLAG >-> pre_expr.
4165 Local Coercion PreRef : idx >-> pre_expr.
4166 Example __testPreARG_boring : ARG -> list pre_expr := fun x : ARG => @cons pre_expr x nil.
4167 (*
4168 Example __testPreARG : ARG -> list pre_expr := fun x : ARG => [x].
4169 *)
4170
4171 Fixpoint Symeval {opts : symbolic_options_computed_opt} {descr:description} {s : OperationSize} {sa : AddressSize} (e : pre_expr) : M idx :=
4172 match e with
4173 | PreARG o => GetOperand o
4174 | PreFLG f => GetFlag f
4175 | PreRef i => ret i
4176 | PreApp op args =>
4177 idxs <- mapM Symeval args;
4178 App (op, idxs)
4179 end.
4180
4181 Definition rcrcnt s cnt : Z :=
4182 if N.eqb s 8 then Z.land cnt 31 mod 9 else
4183 if N.eqb s 16 then Z.land cnt 31 mod 17 else
4184 Z.land cnt (Z.of_N s-1).
4185
4186 Notation "f @ ( x , y , .. , z )" := (PreApp f (@cons pre_expr x (@cons pre_expr y .. (@cons pre_expr z nil) ..))) (at level 10) : x86symex_scope.
4187 Definition SymexNormalInstruction {opts : symbolic_options_computed_opt} {descr:description} (instr : NormalInstruction) : M unit :=
4188 let stack_addr_size : AddressSize := 64%N in
4189 let sa : AddressSize := 64%N in
4190 match Syntax.operation_size instr with Some s =>
4191 match Syntax.prefix instr with None =>
4192 let s : OperationSize := s in
4193 let resize_reg r := some_or (fun _ => reg_of_index_and_shift_and_bitcount_opt (reg_index r, 0%N (* offset *), s)) (fun _ => error.unimplemented_instruction instr) in
4194 match instr.(Syntax.op), instr.(args) with
4195 | (mov | movzx | movabs | movdqa | movdqu | movq | movd | movups), [dst; src] => (* Note: unbundle when switching from N to Z *)
4196 v <- GetOperand src;
4197 SetOperand dst v
4198 | xchg, [a; b] => (* Note: unbundle when switching from N to Z *)
4199 va <- GetOperand a;
4200 vb <- GetOperand b;
4201 _ <- SetOperand b va;
4202 SetOperand a vb
4203 | cmovc, [dst; src]
4204 | cmovb, [dst; src]
4205 | cmovo, [dst; src]
4206 =>
4207 let flag := match instr.(Syntax.op) with cmovo => OF | _ => CF end in
4208 v <- Symeval (selectznz@(flag, dst, src));
4209 SetOperand dst v
4210 | cmovnz, [dst; src] =>
4211 v <- Symeval (selectznz@(ZF, src, dst));
4212 SetOperand dst v
4213 | seto, [dst] =>
4214 of <- GetFlag OF;
4215 SetOperand dst of
4216 | setc, [dst] =>
4217 cf <- GetFlag CF;
4218 SetOperand dst cf
4219 | Syntax.add, [dst; src] =>
4220 v <- Symeval (add s@(dst, src));
4221 c <- Symeval (addcarry s@(dst, src));
4222 o <- Symeval (addoverflow s@(dst, src));
4223 _ <- SetOperand dst v;
4224 _ <- HavocFlags;
4225 _ <- SetFlag CF c;
4226 SetFlag OF o
4227 | Syntax.adc, [dst; src] =>
4228 v <- Symeval (add s@(dst, src, CF));
4229 c <- Symeval (addcarry s@(dst, src, CF));
4230 o <- Symeval (addoverflow s@(dst, src, CF));
4231 _ <- SetOperand dst v;
4232 _ <- HavocFlags;
4233 _ <- SetFlag CF c;
4234 SetFlag OF o
4235 | (adcx|adox) as op, [dst; src] =>
4236 let f := match op with adcx => CF | _ => OF end in
4237 v <- Symeval (add s@(dst, src, f));
4238 c <- Symeval (addcarry s@(dst, src, f));
4239 _ <- SetOperand dst v;
4240 SetFlag f c
4241 | Syntax.sub, [dst; src] =>
4242 v <- Symeval (add s@(dst, PreApp (neg s) [PreARG src]));
4243 c <- Symeval (subborrow s@(dst, src));
4244 _ <- SetOperand dst v;
4245 _ <- HavocFlags;
4246 SetFlag CF c
4247 | Syntax.sbb, [dst; src] =>
4248 v <- Symeval (add s@(dst, PreApp (neg s) [PreARG src], PreApp (neg s) [PreFLG CF]));
4249 c <- Symeval (subborrow s@(dst, src, CF));
4250 _ <- SetOperand dst v;
4251 _ <- HavocFlags;
4252 SetFlag CF c
4253 | lea, [reg dst; mem src] =>
4254 a <- Address src;
4255 SetOperand dst a
4256 | imul, ([dst as src1; src2] | [dst; src1; src2]) =>
4257 v <- Symeval (mulZ@(src1,src2));
4258 _ <- SetOperand dst v;
4259 HavocFlags
4260 | Syntax.xor, [dst; src] =>
4261 v <- Symeval (xorZ@(dst,src));
4262 _ <- SetOperand dst v;
4263 _ <- HavocFlags;
4264 zero <- Symeval (PreApp (const 0) nil);
4265 _ <- SetFlag CF zero;
4266 SetFlag OF zero
4267 | Syntax.and, [dst; src] =>
4268 v <- Symeval (andZ@(dst,src));
4269 _ <- SetOperand dst v;
4270 _ <- HavocFlags;
4271 zero <- Symeval (PreApp (const 0) nil); _ <- SetFlag CF zero; SetFlag OF zero
4272 | Syntax.or, [dst; src] => (* side effects of "or" are identical to side effects of "and" and "xor", according to https://en.wikibooks.org/wiki/X86_Assembly/Logic *)
4273 v <- Symeval (orZ@(dst,src));
4274 _ <- SetOperand dst v;
4275 _ <- HavocFlags;
4276 zero <- Symeval (PreApp (const 0) nil); _ <- SetFlag CF zero; SetFlag OF zero
4277 | Syntax.bzhi, [dst; src; cnt] =>
4278 cnt <- GetOperand cnt;
4279 cnt <- RevealConst cnt;
4280 v <- Symeval (andZ@(src,PreApp (const (Z.ones (Z.land cnt (Z.ones 8)))) nil));
4281 _ <- SetOperand dst v;
4282 _ <- HavocFlags;
4283 zero <- App (const 0, nil); SetFlag OF zero
4284 | Syntax.rcr, [dst; cnt] =>
4285 x <- GetOperand dst;
4286 cf <- GetFlag CF;
4287 cnt <- GetOperand cnt; cnt <- RevealConst cnt; let cnt := rcrcnt s cnt in
4288 cntv <- App (const cnt, nil);
4289 y <- App (rcr s, [x; cf; cntv]);
4290 _ <- SetOperand dst y;
4291 _ <- HavocFlags;
4292 if (cnt =? 1)%Z
4293 then cf <- App ((slice 0 1), cons (x) nil); SetFlag CF cf
4294 else ret tt
4295 | mulx, [hi; lo; src2] =>
4296 let src1 : ARG := rdx in
4297 v <- Symeval (mulZ@(src1,src2));
4298 vh <- Symeval (shrZ@(v,PreARG (Z.of_N s)));
4299 _ <- SetOperand lo v;
4300 SetOperand hi vh
4301 | (Syntax.mul | imul), [src2] =>
4302 let src1 : ARG := rax in
4303 v <- Symeval (mulZ@(src1,src2));
4304 vh <- Symeval (shrZ@(v,PreARG (Z.of_N s)));
4305 lo <- resize_reg rax;
4306 hi <- (if (s =? 8)%N
4307 then ret ah
4308 else resize_reg rdx);
4309 _ <- SetOperand (lo:ARG) v;
4310 _ <- SetOperand (hi:ARG) vh;
4311 HavocFlags (* This is conservative and can be made more precise *)
4312 | Syntax.shl, [dst; cnt] =>
4313 let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in
4314 v <- Symeval (shl s@(dst, cnt));
4315 _ <- SetOperand dst v;
4316 HavocFlags
4317 | Syntax.shlx, [dst; src; cnt] =>
4318 cnt <- GetOperand cnt;
4319 cnt <- RevealConst cnt;
4320 let cnt' := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in
4321 v <- Symeval (shl s@(src, cnt'));
4322 SetOperand dst v
4323 | Syntax.shr, [dst; cnt] =>
4324 let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in
4325 v <- Symeval (shr s@(dst, cnt));
4326 _ <- SetOperand dst v;
4327 HavocFlags
4328 | Syntax.sar, [dst; cnt] =>
4329 x <- GetOperand dst;
4330 let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in
4331 c <- Symeval cnt; rc <- Reveal 1 c;
4332 y <- App (sar s, [x; c]);
4333 _ <- SetOperand dst y;
4334 _ <- HavocFlags;
4335 if expr_beq rc (ExprApp (const 1%Z, nil))
4336 then (
4337 cf <- App ((slice 0 1), cons (x) nil);
4338 _ <- SetFlag CF cf;
4339 zero <- App (const 0, nil); SetFlag OF zero)
4340 else ret tt
4341 | shrd, [lo as dst; hi; cnt] =>
4342 let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in
4343 let cnt' := addZ@(Z.of_N s, PreApp negZ [cnt]) in
4344 v <- Symeval (or s@(shr s@(lo, cnt), shl s@(hi, cnt')));
4345 _ <- SetOperand dst v;
4346 HavocFlags
4347 | shld, [hi as dst; lo; cnt] =>
4348 let cnt := andZ@(cnt, (PreApp (const (Z.of_N s-1)%Z) nil)) in
4349 let cnt' := addZ@(Z.of_N s, PreApp negZ [cnt]) in
4350 v <- Symeval (or s@(shr s@(lo, cnt'), shl s@(hi, cnt)));
4351 _ <- SetOperand dst v;
4352 HavocFlags
4353 | inc, [dst] =>
4354 v <- Symeval (add s@(dst, PreARG 1%Z));
4355 o <- Symeval (addoverflow s@(dst, PreARG 1%Z));
4356 _ <- SetOperand dst v;
4357 _ <- PreserveFlag CF HavocFlags;
4358 SetFlag OF o
4359 | dec, [dst] =>
4360 v <- Symeval (add s@(dst, PreARG (-1)%Z));
4361 o <- Symeval (addoverflow s@(dst, PreARG (-1)%Z));
4362 _ <- SetOperand dst v;
4363 _ <- PreserveFlag CF HavocFlags;
4364 SetFlag OF o
4365 | test, [ea;eb] =>
4366 a <- GetOperand ea;
4367 b <- GetOperand eb;
4368 zero <- App (const 0, nil);
4369 _ <- HavocFlags;
4370 _ <- SetFlag CF zero;
4371 _ <- SetFlag OF zero;
4372 if Equality.ARG_beq ea eb
4373 then zf <- App (iszero, [a]); SetFlag ZF zf
4374 else ret tt
4375 | clc, [] => zero <- Merge (@ExprApp (const 0, nil)); SetFlag CF zero
4376 | push, [src]
4377 => v <- GetOperand src;
4378 rsp' <- GetOperand (s:=stack_addr_size) rsp;
4379 rsp' <- Symeval (s:=stack_addr_size) (add stack_addr_size@(rsp', PreARG (-(Z.of_N s/8))%Z));
4380 _ <- SetOperand rsp rsp';
4381 SetOperand (mem_of_reg rsp) v
4382 | pop, [dst]
4383 => v <- GetOperand (mem_of_reg rsp);
4384 rsp' <- GetOperand (s:=stack_addr_size) rsp;
4385 rsp' <- Symeval (s:=stack_addr_size) (add stack_addr_size@(rsp', PreARG ((Z.of_N s/8)%Z)));
4386 _ <- SetOperand rsp rsp';
4387 SetOperand dst v
4388
4389 | nop, [] => ret tt
4390
4391 | _, _ => err (error.unimplemented_instruction instr)
4392 end
4393 | Some prefix => err (error.unimplemented_prefix instr) end
4394 | None => err (error.ambiguous_operation_size instr) end%N%x86symex.
4395
4396 Definition SymexRawLine {opts : symbolic_options_computed_opt} {descr:description} (rawline : RawLine) : M unit :=
4397 match rawline with
4398 | EMPTY
4399 | LABEL _
4400 | DIRECTIVE _
4401 | ASCII_ _ _
4402 => ret tt
4403 | INSTR instr
4404 => SymexNormalInstruction instr
4405 | SECTION _
4406 | GLOBAL _
4407 | ALIGN _
4408 | DEFAULT_REL
4409 => err (error.unsupported_line rawline)
4410 end.
4411
4412 Definition SymexLine {opts : symbolic_options_computed_opt} line :=
4413 let descr:description := Build_description (Parse.show_Line_with_line_number line) false in
4414 SymexRawLine line.(rawline).
4415
4416 Fixpoint SymexLines {opts : symbolic_options_computed_opt} (lines : Lines) : M unit
4417 := match lines with
4418 | [] => ret tt
4419 | line :: lines
4420 => (st <- SymexLine line;
4421 SymexLines lines)
4422 end.
4423 End WithDag.
4424 Export Old.
4425 Include WithDag dag.