(** * Mapping predicates over [StringLike] things *)
Require Import Coq.Classes.Morphisms Coq.Classes.RelationClasses Coq.Program.Basics.
Require Import Coq.omega.Omega.
Require Import Coq.Numbers.Natural.Peano.NPeano.
Require Import Fiat.Parsers.StringLike.Core.
Require Import Fiat.Parsers.StringLike.Properties.
Require Import Fiat.Parsers.StringLike.ForallChars.
Require Import Fiat.Common.SetoidInstances.
Require Import Fiat.Common.

Set Implicit Arguments.
Local Open Scope string_like_scope.

Section for_first_char.
  Context {Char} {HSLM : StringLikeMin Char} {HSL : StringLike Char} {HSLP : StringLikeProperties Char}.

  Definition for_first_char (str : String) (P : Char -> Prop)
    := forall ch,
         take 1 str ~= [ ch ]
         -> P ch.

  Global Instance for_first_char_Proper
  : Proper (beq ==> pointwise_relation _ impl ==> impl) for_first_char.
  Proof.
    unfold pointwise_relation, respectful, for_first_char, impl.
    intros ?? H' ?? H'' H''' ? H.
    rewrite <- H' in H.
    eauto using is_char_Proper.
  Qed.

  Global Instance for_first_char_Proper_flip
  : Proper (beq ==> pointwise_relation _ (flip impl) ==> flip impl) for_first_char.
  Proof.
    unfold pointwise_relation, respectful, for_first_char, flip, impl.
    intros ?? H' ?? H'' H''' ? H.
    rewrite H' in H.
    eauto using is_char_Proper.
  Qed.

  Global Instance for_first_char_Proper_iff
  : Proper (beq ==> pointwise_relation _ iff ==> iff) for_first_char.
  Proof.
    unfold pointwise_relation, respectful.
    repeat intro; split;
    apply for_first_char_Proper; try assumption; repeat intro;
    match goal with
      | [ H : _ |- _ ] => apply H; assumption
    end.
  Qed.

  Lemma for_first_char_nil (str : String) P
  : length str = 0 -> for_first_char str P.
  Proof.
    intros H ch H'.
    apply length_singleton in H'.
    rewrite ?take_length, ?drop_length, H in H'.
    simpl in H'; omega.
  Qed.

  Lemma helper
        (P : nat -> nat -> Type)
        n
        (H0 : forall n0, P (min 1 (n - n0)) n0)
        (H1 : forall n0, P 1 (n0 + n))
        {n0}
  : P 1 n0.
  Proof.
    destruct (Compare_dec.le_dec n n0) as [H'|H'].
    { specialize (H1 (n0 - n)).
      rewrite Nat.sub_add in H1 by assumption; assumption. }
    { apply Compare_dec.not_le in H'.
      specialize (H0 n0).
      destruct (n - n0) as [|[|]] eqn:?; simpl in *; trivial; omega. }
  Defined.

  Lemma for_first_char__take n (str : String) P
  : for_first_char str P
    <-> for_first_char (take (S n) str) P.
  Proof.
    unfold for_first_char; repeat (split || intro);
    repeat match goal with
                         | [ H : _ |- _ ] => setoid_rewrite drop_length in H
                         | [ H : _ |- _ ] => setoid_rewrite take_length in H
                         | [ H : _ |- _ ] => setoid_rewrite drop_take in H
                         | [ H : _ |- _ ] => setoid_rewrite take_take in H
                         | [ H : _ |- _ ] => setoid_rewrite drop_drop in H
                         | [ H : _ /\ _ |- _ ] => destruct H
                         | [ H : context[min 1 ?x] |- _ ] => destruct x eqn:?; simpl in H
                         | [ H : is_true (take 0 _ ~= [ _ ]) |- _ ] => exfalso; apply length_singleton in H
                         | _ => omega
                         | _ => progress simpl in *; omega
                         | _ => solve [ eauto ]
                         | _ => solve [ eapply (@helper (fun a b => take a (drop b str) ~= [ ch ] -> P ch)); eauto ]
                       end.
  Qed.

  Lemma for_first_char_singleton (str : String) P ch
  : str ~= [ ch ] -> (P ch <-> for_first_char str P).
  Proof.
    intro H.
    pose proof (length_singleton _ _ H).
    unfold for_first_char.
    split; intro H'; repeat intro.
    { repeat match goal with
               | _ => intro
               | _ => omega
               | [ H : _ |- _ ] => rewrite drop_0 in H
               | [ H : _, H' : _ |- _ ] => rewrite (singleton_take H') in H
               | [ H : _ |- False ] => apply length_singleton in H
               | [ H : _ |- _ ] => rewrite take_length in H
               | [ H : _ |- _ ] => rewrite drop_length in H
               | [ H : ?x = 1, H' : context[?x] |- _ ] => rewrite H in H'
               | _ => erewrite singleton_unique; eassumption
               | [ H : appcontext[min] |- _ ] => revert H; apply Min.min_case_strong
             end. }
    { match goal with
        | [ H : _ |- _ ] => apply H
      end.
      rewrite take_long; trivial; omega. }
  Qed.

  Lemma for_first_char_singleton_length (str : String) P (H : length str = 1)
  : for_first_char str P <-> (forall ch, str ~= [ ch ] -> P ch).
  Proof.
    split.
    { intro H''.
      intros ch' H'''.
      apply (for_first_char_singleton _ _ _ H'''); assumption. }
    { destruct (singleton_exists _ H) as [ch H'].
      intro H''.
      apply (for_first_char_singleton _ P ch H'); eauto. }
  Qed.

  Global Opaque for_first_char.

  Lemma for_first_char_exists (str : String) P (H : length str >= 1)
  : for_first_char str P <-> (exists ch, take 1 str ~= [ ch ] /\ P ch).
  Proof.
    rewrite (for_first_char__take 0).
    assert (H' : length (take 1 str) = 1)
      by (rewrite take_length; apply Min.min_case_strong; omega).
    destruct (singleton_exists _ H') as [ch H''].
    rewrite for_first_char_singleton_length by exact H'.
    split; intros.
    { exists ch; split; eauto. }
    { destruct_head ex.
      destruct_head and.
      repeat match goal with
               | [ H : is_true (?str ~= [ ?ch ])%string_like, H' : is_true (?str ~= [ ?ch' ])%string_like |- _ ]
                 => assert (ch = ch') by (eapply singleton_unique; eassumption);
                   clear H'
             end.
      subst; assumption. }
  Qed.

  Lemma for_first_char_False (str : String) P
  : (forall ch, ~P ch) -> for_first_char str P -> length str = 0.
  Proof.
    intros H' H.
    case_eq (length str); trivial.
    pose proof (singleton_exists (take 1 str)) as H''.
    rewrite take_length in H''.
    intros n H'''.
    rewrite H''' in *.
    specialize (H'' eq_refl).
    destruct H'' as [ch H''].
    apply (for_first_char__take 0) in H.
    apply (for_first_char_singleton _ _ _ H'') in H.
    specialize (H' ch).
    exfalso; eauto.
  Qed.

  Lemma for_first_char_combine (str : String) (P P' : Char -> Prop) (T : Prop) (H : forall ch, P ch -> P' ch -> T)
        (H0 : for_first_char str P)
        (H1 : for_first_char str P')
  : length str = 0 \/ T.
  Proof.
    case_eq (length str).
    { left; reflexivity. }
    { intros n H'; right.
      pose proof (singleton_exists (take 1 str)) as H''.
      rewrite take_length, H' in H''.
      specialize (H'' eq_refl).
      destruct H'' as [ch H''].
      specialize (H ch).
      apply (for_first_char__take 0) in H0.
      apply (for_first_char__take 0) in H1.
      apply (for_first_char_singleton _ _ _ H'') in H0.
      apply (for_first_char_singleton _ _ _ H'') in H1.
      eauto. }
  Qed.

  Definition first_char_in (str : String) (ls : list Char)
    := for_first_char str (fun ch => List.In ch ls).

  Definition for_first_char__impl__first_char_in {str ls} {P : _ -> Prop}
             (H : forall ch, P ch -> List.In ch ls)
  : impl (for_first_char str P) (first_char_in str ls).
  Proof.
    unfold first_char_in.
    apply for_first_char_Proper; trivial; reflexivity.
  Qed.

  Definition first_char_in__impl__for_first_char {str ls} {P : _ -> Prop}
             (H : forall ch, List.In ch ls -> P ch)
  : impl (first_char_in str ls) (for_first_char str P).
  Proof.
    unfold first_char_in.
    apply for_first_char_Proper; trivial; reflexivity.
  Qed.

  Global Instance first_char_in__Proper
  : Proper (beq ==> eq ==> impl) first_char_in.
  Proof.
    unfold pointwise_relation, respectful, first_char_in, impl.
    repeat intro; subst.
    match goal with
      | [ H : _ |- _ ] => rewrite <- H; assumption
    end.
  Qed.

  Global Instance first_char_in__Proper_iff
  : Proper (beq ==> eq ==> iff) first_char_in.
  Proof.
    unfold pointwise_relation, respectful, first_char_in, impl.
    repeat intro; subst.
    match goal with
      | [ H : _ |- _ ] => rewrite <- H; reflexivity
    end.
  Qed.

  Lemma first_char_in__take n (str : String) ls
  : first_char_in str ls
    <-> first_char_in (take (S n) str) ls.
  Proof.
    unfold first_char_in; apply for_first_char__take.
  Qed.

  Lemma first_char_in_nil (str : String)
  : first_char_in str nil <-> length str = 0.
  Proof.
    unfold first_char_in.
    split.
    { eapply for_first_char_False; simpl; eauto. }
    { apply for_first_char_nil. }
  Qed.

  Lemma first_char_in_empty (str : String) (H : length str = 0) ls
  : first_char_in str ls.
  Proof.
    unfold first_char_in.
    apply for_first_char_nil; assumption.
  Qed.

  Lemma first_char_in_singleton_str (str : String) ls ch (H : str ~= [ ch ])
  : first_char_in str ls <-> List.In ch ls.
  Proof.
    unfold first_char_in.
    rewrite <- for_first_char_singleton; try eassumption; reflexivity.
  Qed.

  Lemma first_char_in__app_or_iff (str : String) (ls1 ls2 : list Char)
  : first_char_in str (ls1 ++ ls2)
    <-> (first_char_in str ls1 \/ first_char_in str ls2).
  Proof.
    unfold first_char_in.
    setoid_rewrite List.in_app_iff.
    rewrite !(for_first_char__take 0 str).
    generalize (singleton_exists (take 1 str)).
    rewrite take_length.
    case_eq (length str).
    { intros H _.
      split; intro H0;
      [ left; apply first_char_in_empty
      | apply for_first_char_nil ];
      rewrite take_length, H; reflexivity. }
    { intros ? ? H.
      specialize (H eq_refl).
      destruct H as [ch H].
      rewrite <- !for_first_char_singleton by eassumption; tauto. }
  Qed.

  Lemma first_char_in__or_app (str : String) (ls1 ls2 : list Char)
  : first_char_in str ls1 \/ first_char_in str ls2 -> first_char_in str (ls1 ++ ls2).
  Proof.
    unfold first_char_in.
    intros [?|?]; repeat intro;
    (eapply for_first_char_Proper; [ .. | eassumption ]; [ reflexivity | ]; intros ??);
    apply List.in_or_app; eauto.
  Qed.

  Global Opaque first_char_in.

  Definition first_char_in__iff__for_first_char' {str ls} {P : _ -> Prop}
             (H : forall ch, P ch <-> List.In ch ls)
  : first_char_in str ls <-> for_first_char str P.
  Proof.
    split_iff.
    split; first [ apply for_first_char__impl__first_char_in | apply first_char_in__impl__for_first_char ];
    assumption.
  Qed.

  Definition first_char_in__iff__for_first_char {str ls}
  : first_char_in str ls <-> for_first_char str (fun ch => List.In ch ls).
  Proof.
    apply first_char_in__iff__for_first_char'; reflexivity.
  Qed.

  Lemma first_char_in_exists (str : String) ls (H : length str >= 1)
  : first_char_in str ls <-> (exists ch, take 1 str ~= [ ch ] /\ List.In ch ls).
  Proof.
    erewrite first_char_in__iff__for_first_char, for_first_char_exists by assumption.
    reflexivity.
  Qed.

  Lemma forall_chars__impl__for_first_char (str : String) P (H : forall_chars str P)
  : for_first_char str P.
  Proof.
    case_eq (length str).
    { apply for_first_char_nil. }
    { intros n H'.
      eapply forall_chars_take in H.
      apply (for_first_char__take 0).
      apply for_first_char_singleton_length.
      { rewrite take_length, H'; reflexivity. }
      { apply forall_chars_singleton_length.
        { rewrite take_length, H'; reflexivity. }
        { eassumption. } } }
  Qed.

  Lemma for_first_char__for_first_char__iff_short (str : String) P (H : length str <= 1)
  : forall_chars str P <-> for_first_char str P.
  Proof.
    case_eq (length str).
    { intro H'.
      split; intro.
      { apply for_first_char_nil; assumption. }
      { apply forall_chars_nil; assumption. } }
    { intros [|] H'; [ | exfalso; omega ].
      rewrite forall_chars_singleton_length by assumption.
      rewrite for_first_char_singleton_length by assumption.
      reflexivity. }
  Qed.

End for_first_char.


(** Libraries. *)
Require Import String.
Require Import CoqlibC Errors ErrorsC.
Require Import AST Linking Smallstep.
(** Command-line flags. *)
Require Import Compopts.
(** newly added **)
Require Import BehaviorsC.
Require Export Compiler.
Require Import Simulation.
Require Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.
Require Import SemProps AdequacyLocal.

Require SimMemInjInvC.

Require Import RUSC.

Require Import MutrecHeader.
Require Import MutrecAspec MutrecBspec MutrecABspec MutrecA MutrecB.
Require Import MutrecABproof MutrecAproof MutrecBproof.

Require IdSimAsmIdInv.
Require IdSimClightIdInv.

Definition mutrec_relations :=
  fun r => exists P, r = mkPR (SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv P)
                              (SimMemInjInvC.SimSymbIdInv P)
                              SoundTop.Top.

Lemma asm_self_related (asm: Asm.program)
  :
    self_related mutrec_relations [(AsmC.module asm)].
Proof.
  intros r RELIN. unfold mutrec_relations in *. ss.
  des; clarify; eapply relate_single_program; intros WF.
  exploit IdSimAsmIdInv.asm_inj_inv_id; ss; eauto.
Qed.

Lemma clight_self_related (cls: Clight.program)
  :
    self_related mutrec_relations [(ClightC.module2 cls)].
Proof.
  intros r RELIN. unfold mutrec_relations in *. ss.
  des; clarify; eapply relate_single_program; intros WF.
  exploit IdSimClightIdInv.clight_inj_inv_id; ss; eauto.
Qed.

Lemma asms_self_related (asms: list Asm.program)
  :
    self_related mutrec_relations (map AsmC.module asms).
Proof.
  induction asms; ss; ii.
  exploit IHasms; ss; eauto. i.
  eapply (@program_relation.horizontal _ [(AsmC.module a)] _ [(AsmC.module a)]); eauto.
  eapply asm_self_related; eauto.
Qed.

Lemma clights_self_related (cls: list Clight.program)
  :
    self_related mutrec_relations (map ClightC.module2 cls).
Proof.
  induction cls; ss; ii.
  exploit IHcls; ss; eauto. i.
  eapply (@program_relation.horizontal _ [(ClightC.module2 a)] _ [(ClightC.module2 a)]); eauto.
  eapply clight_self_related; eauto.
Qed.

Require IdSimMutrecAIdInv.

Lemma specA_self_related
  :
    self_related mutrec_relations [MutrecAspec.module].
Proof.
  intros r RELIN. unfold mutrec_relations in *. ss.
  des; clarify; eapply relate_single_program; intros WF.
  exploit IdSimMutrecAIdInv.a_inj_inv_id; ss; eauto.
Qed.

Require IdSimMutrecBIdInv.

Lemma specB_self_related
  :
    self_related mutrec_relations [MutrecBspec.module].
Proof.
  intros r RELIN. unfold mutrec_relations in *. ss.
  des; clarify; eapply relate_single_program; intros WF.
  exploit IdSimMutrecBIdInv.b_inj_inv_id; ss; eauto.
Qed.

Lemma MutrecA_rusc
  :
    rusc mutrec_relations [MutrecAspec.module] [(ClightC.module2 MutrecA.prog)].
Proof.
  eapply (@relate_single_rusc
            _
            (SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv MutrecAproof.memoized_inv)
            (SimMemInjInvC.SimSymbIdInv MutrecAproof.memoized_inv)
            SoundTop.Top).
  - set MutrecAproof.sim_mod. unfold relate_single. i. esplits; ss; eauto.
  - unfold mutrec_relations. eauto.
Qed.

Lemma MutrecB_rusc
  :
    rusc mutrec_relations [MutrecBspec.module] [(AsmC.module MutrecB.prog)].
Proof.
  eapply (@relate_single_rusc
            _
            (SimMemInjInvC.SimMemInjInv SimMemInjInv.top_inv MutrecBproof.memoized_inv)
            (SimMemInjInvC.SimSymbIdInv MutrecBproof.memoized_inv)
            SoundTop.Top).
  - set MutrecBproof.sim_mod. unfold relate_single. i. esplits; ss; eauto.
  - unfold mutrec_relations. eauto.
Qed.

Theorem MutrecAB_AB_rusc
  :
    rusc bot1 [(MutrecABspec.module)] [(MutrecAspec.module) ; (MutrecBspec.module)]
.
Proof.
  unfold rusc. i. eapply mutrecABcorrect.
Qed.

Lemma MutrecAB_impl_rusc
 :
   rusc mutrec_relations
        [MutrecABspec.module]
        [(ClightC.module2 MutrecA.prog); (AsmC.module MutrecB.prog)].
Proof.
 etrans.
 - eapply rusc_mon; [|eapply MutrecAB_AB_rusc]; ss.
 - hexploit rusc_horizontal.
   + eapply MutrecA_rusc.
   + eapply MutrecB_rusc.
   + eapply specA_self_related.
   + eapply specB_self_related.
   + eapply clight_self_related.
   + eapply asm_self_related.
   + i. eauto.
Qed.

Theorem Mutrec_correct
        (srcs: list Clight.program)
        (hands: list Asm.program)
  :
    improves (sem ((map ClightC.module2 srcs) ++ (map AsmC.module hands) ++ [MutrecABspec.module]))
             (sem ((map ClightC.module2 srcs) ++ (map AsmC.module hands) ++ [(ClightC.module2 MutrecA.prog); (AsmC.module MutrecB.prog)])).
Proof.
  replace (map ClightC.module2 srcs ++ map AsmC.module hands ++ [MutrecABspec.module]) with
      ((map ClightC.module2 srcs ++ map AsmC.module hands) ++ [MutrecABspec.module]); cycle 1.
  { rewrite app_assoc. auto. }
  replace (map ClightC.module2 srcs ++ map AsmC.module hands
               ++ [ClightC.module2 MutrecA.prog; AsmC.module prog]) with
      ((map ClightC.module2 srcs ++ map AsmC.module hands) ++ [ClightC.module2 MutrecA.prog; AsmC.module prog]); cycle 1.
  { rewrite app_assoc. auto. }
  eapply rusc_adequacy_left_ctx.
  - eapply MutrecAB_impl_rusc.
  - eapply self_related_horizontal.
    + eapply clights_self_related.
    + eapply asms_self_related.
Qed.


From ch2o_compcert Require Export ch2o_lp64 ifs_ch2o.
From ch2o Require Import stringmap frontend_sound.

Local Open Scope string_scope.

Definition alloc_program_result: frontend_state K.
Proof.
set (a:=alloc_program (K:=K) decls ∅).
assert (match a with inl _ => False | inr _ => True end). { exact I. }
destruct a. { elim H. }
destruct p.
exact f.
Defined.

Definition Γ: env K := to_env alloc_program_result.
Definition δ: funenv K := to_funenv alloc_program_result.
Definition m0: mem K := to_mem alloc_program_result.
Definition S0 := initial_state m0 "main" [].

Goal env_t Γ = ∅.
Proof.
reflexivity.
Qed.

Goal stringmap_to_list (env_f Γ) = [("main", ([], sintT%T))].
reflexivity.
Qed.

(*

Compute stringmap_to_list δ.

*)

Goal stringmap_to_list δ = [
  ("main",
   if{# intV{sintT} 1} skip else skip ;;
   if{# intV{sintT} 0} skip else skip ;;
   ret
     (cast{sintT%T} (
        # intV{sintT} 17 / # intV{sintT} 2 /
        (# intV{sintT} 15 / # intV{sintT} 5))))
].
Proof.
reflexivity.
Qed.

Lemma δ_main: δ !! ("main": funname) = Some (
   if{# intV{sintT} 1} skip else skip ;;
   if{# intV{sintT} 0} skip else skip ;;
   ret
     (cast{sintT%T} (
        # intV{sintT} 17 / # intV{sintT} 2 /
        (# intV{sintT} 15 / # intV{sintT} 5))) : stmt K).
Proof.
reflexivity.
Qed.

Goal m0 = ∅.
Proof.
reflexivity.
Qed.

Goal S0 = State [] (Call "main" []) m0.
Proof.
reflexivity.
Qed.

Lemma alloc_program_eq: alloc_program decls empty = mret () alloc_program_result.
Proof.
reflexivity.
Qed.

Lemma Γ_valid: ✓ Γ.
Proof.
apply alloc_program_valid with (1:=alloc_program_eq).
Qed.

Lemma δ_valid: ✓{Γ,'{m0}} δ.
Proof.
apply alloc_program_valid with (1:=alloc_program_eq).
Qed.

Lemma m0_valid: ✓{Γ} m0.
apply alloc_program_valid with (1:=alloc_program_eq).
Qed.


Load LFindLoad.
From lfind Require Import LFind.

                    From adtind Require Import goal86.

 Require Import Extraction.
 Extract Inductive nat => nat [ "(O)" "S" ].
 Extract Inductive list => list [ "Nil" "Cons" ].
Definition lfind_example_1  := ( Succ (Succ (Succ Zero))).
Definition lfind_example_2  := ( Succ (Succ (Succ Zero))).
Definition lfind_example_3  := ( Succ (Succ (Succ (Succ Zero)))).
Definition lfind_example_4  := ( Succ Zero).
Definition lfind_example_5  := ( Succ Zero).
Definition lfind_example_6  := ( Succ (Succ Zero)).
Definition lfind_example_7  := ( Succ (Succ (Succ Zero))).
Definition lfind_example_8  := ( Succ Zero).
Definition lfind_example_9  := ( Succ (Succ (Succ (Succ Zero)))).
Definition lfind_example_10  := ( Succ (Succ Zero)).
Definition lfind_example_11  := ( Succ Zero).

                    Extraction "/home/yousef/lemmafinder/benchmark/_lfind_clam_lf_goal86_mult_succ_80_plus_assoc/lfind_extraction.ml" lfind_example_1 lfind_example_2 lfind_example_3 lfind_example_4 lfind_example_5 lfind_example_6 lfind_example_7 lfind_example_8 lfind_example_9 lfind_example_10 lfind_example_11 .


(*
 * Taking another shot at adding new constructors.
 *
 * My conclusion: I think it's really cool that we can express adding
 * a constructor as an equivalence, like I suspected.
 * But I'm not trying to fool anyone into thinking the way that I do this
 * is useful yet. It just gives clear path to something useful, separating
 * out the hard work from the easy work. A lot of the other changes we handle,
 * we handle efficiently and usefully. Just being able to do this at all surprised
 * people, so I think it's cute still.
 *)
Require Import List.
Require Import String.
Require Import ZArith.

Import ListNotations.

Require Import Ornamental.Ornaments.
Set DEVOID search prove coherence.
Set DEVOID search prove equivalence.
Set DEVOID lift type.
Set DEVOID search smart eliminators.

(*
 * Let's do more of the REPLICA benchmark and see what happens.
 * We start with the swap from Swap.v, then add the bool constructor.
 *
 * This is going to walk through more steps than actually needed long-term,
 * just to show the thought process. For simplicity, we are going to start
 * with just the functions.
 *)

(* --- Original --- *)

Definition Identifier := string.
Definition id_eq_dec := string_dec.

Module Old.

Inductive Term : Set :=
  | Var : Identifier -> Term
  | Int : Z -> Term
  | Eq : Term -> Term -> Term
  | Plus : Term -> Term -> Term
  | Times : Term -> Term -> Term
  | Minus : Term -> Term -> Term
  | Choose : Identifier -> Term -> Term.

End Old.

Module User5Session19.

Import Old.

Fixpoint identity (t : Term) : Term :=
  match t with
  | Var x => Var x
  | Int i => Int i
  | Eq a b => Eq (identity a) (identity b)
  | Plus a b => Plus (identity a) (identity b)
  | Times a b => Times (identity a) (identity b)
  | Minus a b => Minus (identity a) (identity b)
  | Choose x P => Choose x (identity P)
  end.

Fixpoint free_vars (t : Term) : list Identifier :=
  match t with
  | Var x => [x]
  | Int _ => []
  | Eq a b => free_vars a ++ free_vars b
  | Plus a b => free_vars a ++ free_vars b
  | Times a b => free_vars a ++ free_vars b
  | Minus a b => free_vars a ++ free_vars b
  | Choose x P =>
      filter (fun y => if id_eq_dec x y then false else true) (free_vars P)
  end.

End User5Session19.

Preprocess Module User5Session19 as OldProofs {
  opaque
    Coq.Init.Datatypes Coq.Strings.String Coq.Init.Logic Coq.Lists.List
}.

(* --- Swap --- *)

(*
 * This is the same swap from Swap.v, just one part of the change.
 *)

Module New.

Inductive Term : Set :=
  | Var : Identifier -> Term
  | Eq : Term -> Term -> Term
  | Int : Z -> Term
  | Plus : Term -> Term -> Term
  | Times : Term -> Term -> Term
  | Minus : Term -> Term -> Term
  | Choose : Identifier -> Term -> Term.

End New.

(* failures below are just redundant attempts at repairing projections *)
Find ornament Old.Term New.Term { mapping 0 }.
Repair Module Old.Term New.Term in OldProofs as NewProofs.

(* --- Add Bool --- *)

(*
 * OK, now let's extend with Bool.
 *)

Module AddBool.

Inductive Term : Set :=
  | Var : Identifier -> Term
  | Bool : bool -> Term
  | Eq : Term -> Term -> Term
  | Int : Z -> Term
  | Plus : Term -> Term -> Term
  | Times : Term -> Term -> Term
  | Minus : Term -> Term -> Term
  | Choose : Identifier -> Term -> Term.

End AddBool.

(* --- What's new? --- *)

(*
 * To capture the new information, the first thing we are going to do is split
 * extended AddBool type in half: the left projection and the right projection,
 * essentially. We should be able to produce these automatically, I believe,
 * but for now let's write them manually.
 *)

(*
 * The left projection is straightforward---just use the same structure as
 * the old type, but index by the new type. I think Conor McBride said this
 * is the reornament.
 *)
Inductive no_bools : AddBool.Term -> Type :=
| nb1 : forall i, no_bools (AddBool.Var i)
| nb2 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Eq t1 t2)
| nb3 : forall z, no_bools (AddBool.Int z)
| nb4 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Plus t1 t2)
| nb5 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Times t1 t2)
| nb6 : forall t1 t2, no_bools t1 -> no_bools t2 -> no_bools (AddBool.Minus t1 t2)
| nb7 : forall a t, no_bools t -> no_bools (AddBool.Choose a t).

(*
 * The right projection needs to handle the new case, plus all of the inductive
 * cases that may refer to the new case. There is some case explosion here
 * that we will need to make induction useful.
 *)
Inductive yes_bools : AddBool.Term -> Type :=
| yb1 : forall b, yes_bools (AddBool.Bool b)
| yb2left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Eq t1 (projT1 t2))
| yb2right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Eq (projT1 t1) t2)
| yb2 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Eq t1 t2)
| yb3left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Plus t1 (projT1 t2))
| yb3right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Plus (projT1 t1) t2)
| yb3 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Plus t1 t2)
| yb4left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Times t1 (projT1 t2))
| yb4right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Times (projT1 t1) t2)
| yb4 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Times t1 t2)
| yb5left : forall t1, yes_bools t1 -> forall t2 : sigT no_bools, yes_bools (AddBool.Minus t1 (projT1 t2))
| yb5right : forall t1 : sigT no_bools, forall t2, yes_bools t2 -> yes_bools (AddBool.Minus (projT1 t1) t2)
| yb5 : forall t1 t2, yes_bools t1 -> yes_bools t2 -> yes_bools (AddBool.Minus t1 t2)
| yb6 : forall a t, yes_bools t -> yes_bools (AddBool.Choose a t).

(*
 * The idea is that:
 * 1. New.Term is equivalent to sigT no_bools.
 * 2. There exists some non-indexed type Diff that is equivalent to sigT yes_bools.
 * 3. AddBool.Term is equivalent to sigT no_bools + sigT yes_bools.
 * 4. Thus, New.Term + Diff is equivalent to AddBool.Term.
 *
 * We are going to start by finding the ornaments that get us 1 and 2.
 *)

(* --- 1. New.Term is equivalent to sigT no_bools --- *)

(*
 * This is easy.
 * The left projection no_bools is an ornament. So we can easily do this:
 *)
Repair Module New.Term no_bools in NewProofs as NoBoolProofs.
(*
 * This proves the equivalence, and gives us all functions and proofs over
 * sigT no_bools.
 *)

(* --- 2. There exists some non-indexed type Diff that is equivalent to sigT yes_bools --- *)

(*
 * yes_bools must be the reornament of something.
 * We can just go in and remove the index.
 *)
Inductive Diff : Type :=
| DiffBool : bool -> Diff
| DiffEqLeft : Diff -> sigT no_bools -> Diff
| DiffEqRight : sigT no_bools -> Diff -> Diff
| DiffEq : Diff -> Diff -> Diff
| DiffPlusLeft : Diff -> sigT no_bools -> Diff
| DiffPlusRight : sigT no_bools -> Diff -> Diff
| DiffPlus : Diff -> Diff -> Diff
| DiffTimesLeft : Diff -> sigT no_bools -> Diff
| DiffTimesRight : sigT no_bools -> Diff -> Diff
| DiffTimes : Diff -> Diff -> Diff
| DiffMinusLeft : Diff -> sigT no_bools -> Diff
| DiffMinusRight : sigT no_bools -> Diff -> Diff
| DiffMinus : Diff -> Diff -> Diff
| DiffChoose : Identifier -> Diff -> Diff.

(*
 * Let's prove things over diff and port it to yes_bools.
 * For now, we will leave EpsilonLogic alone.
 * We'll deal with that later, since it involves extending a second type.
 * I just want to see what happens to our simple functions.
 *)
Module DiffProofs_fix.

Fixpoint identity (d : Diff) : Diff :=
  match d with
  | DiffBool b => DiffBool b
  | DiffEqLeft t1 t2 => DiffEqLeft (identity t1) (NoBoolProofs.identity t2)
  | DiffEqRight t1 t2 => DiffEqRight (NoBoolProofs.identity t1) (identity t2)
  | DiffEq t1 t2 => DiffEq (identity t1) (identity t2)
  | DiffPlusLeft t1 t2 => DiffPlusLeft (identity t1) (NoBoolProofs.identity t2)
  | DiffPlusRight t1 t2 => DiffPlusRight (NoBoolProofs.identity t1) (identity t2)
  | DiffPlus t1 t2 => DiffPlus (identity t1) (identity t2)
  | DiffTimesLeft t1 t2 => DiffTimesLeft (identity t1) (NoBoolProofs.identity t2)
  | DiffTimesRight t1 t2 => DiffTimesRight (NoBoolProofs.identity t1) (identity t2)
  | DiffTimes t1 t2 => DiffTimes (identity t1) (identity t2)
  | DiffMinusLeft t1 t2 => DiffMinusLeft (identity t1) (NoBoolProofs.identity t2)
  | DiffMinusRight t1 t2 => DiffMinusRight (NoBoolProofs.identity t1) (identity t2)
  | DiffMinus t1 t2 => DiffMinus (identity t1) (identity t2)
  | DiffChoose i t => DiffChoose i (identity t)
  end.

Fixpoint free_vars (d : Diff) : list Identifier :=
  match d with
  | DiffBool b => []
  | DiffEqLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2
  | DiffEqRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2
  | DiffEq t1 t2 => free_vars t1 ++ free_vars t2
  | DiffPlusLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2
  | DiffPlusRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2
  | DiffPlus t1 t2 => free_vars t1 ++ free_vars t2
  | DiffTimesLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2
  | DiffTimesRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2
  | DiffTimes t1 t2 => free_vars t1 ++ free_vars t2
  | DiffMinusLeft t1 t2 => free_vars t1 ++ NoBoolProofs.free_vars t2
  | DiffMinusRight t1 t2 => NoBoolProofs.free_vars t1 ++ free_vars t2
  | DiffMinus t1 t2 => free_vars t1 ++ free_vars t2
  | DiffChoose x t =>
      filter (fun y => if id_eq_dec x y then false else true) (free_vars t)
  end.

End DiffProofs_fix.

Preprocess Module DiffProofs_fix as DiffProofs {
  opaque
    Coq.Init.Datatypes Coq.Strings.String Coq.Init.Logic Coq.Lists.List
}.

(*
 * OK, then we port that to yes_bools:
 *)
Repair Module Diff yes_bools in DiffProofs as YesBoolProofs.
(*
 * Now we have proofs over sigT yes_bools.
 *)

(* --- 3. AddBool.Term is equivalent to sigT no_bools + sigT yes_bools --- *)

(*
 * We'll need a manual configuration for this one.
 * We'll start with a slow eliminator, and think about a fast eliminator later.
 * First we'll need this (should also be easy to automate at some point):
 *)
Lemma split:
  forall (t : AddBool.Term), no_bools t + yes_bools t.
Proof.
  intros. induction t.
  - left. constructor.
  - right. constructor.
  - induction IHt1, IHt2.
    + left. constructor; auto.
    + right. apply (yb2right (existT _ t1 a) t2 y).
    + right. apply (yb2left t1 b (existT _ t2 n)).
    + right. constructor; auto.
  - left. constructor.
  - induction IHt1, IHt2.
    + left. constructor; auto.
    + right. apply (yb3right (existT _ t1 a) t2 y).
    + right. apply (yb3left t1 b (existT _ t2 n)).
    + right. constructor; auto.
  - induction IHt1, IHt2.
    + left. constructor; auto.
    + right. apply (yb4right (existT _ t1 a) t2 y).
    + right. apply (yb4left t1 b (existT _ t2 n)).
    + right. constructor; auto.
  - induction IHt1, IHt2.
    + left. constructor; auto.
    + right. apply (yb5right (existT _ t1 a) t2 y).
    + right. apply (yb5left t1 b (existT _ t2 n)).
    + right. constructor; auto.
  - induction IHt.
    + left. constructor. auto.
    + right. constructor. auto.
Defined.

Lemma split_OK_left:
  forall (t : AddBool.Term) (H : no_bools t),
    inl H = split t.
Proof.
  intros. induction H; auto; simpl.
  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.
  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.
  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.
  - rewrite <- IHno_bools1. rewrite <- IHno_bools2. auto.
  - rewrite <- IHno_bools. auto.
Defined.

Lemma split_OK_right:
  forall (t : AddBool.Term) (H : yes_bools t),
    inr H = split t.
Proof.
  intros. induction H; auto; simpl.
  - induction t2. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - induction t1. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.
  - induction t2. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - induction t1. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.
  - induction t2. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - induction t1. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.
  - induction t2. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - induction t1. simpl.
    rewrite <- IHyes_bools. rewrite <- split_OK_left with (H := p). auto.
  - rewrite <- IHyes_bools1. rewrite <- IHyes_bools2. auto.
  - rewrite <- IHyes_bools. auto.
Defined.

(*
 * Configuration follows easily.
 *)
Definition A : Type := sigT no_bools + sigT yes_bools.
Definition B : Type := AddBool.Term.

Definition dep_constr_A_0 (s : sigT no_bools) : A := inl s.
Definition dep_constr_A_1 (s : sigT yes_bools) : A := inr s.

Definition dep_constr_B_0 (s : sigT no_bools) : B := projT1 s.
Definition dep_constr_B_1 (s : sigT yes_bools) : B := projT1 s.

Definition eta_A (a : A) : A := a.
Definition eta_B (b : B) : B := b.

Program Definition dep_elim_A (P : A -> Type)
  (f0 : forall s, P (dep_constr_A_0 s))
  (f1 : forall s, P (dep_constr_A_1 s))
  (a : A)
: P a.
Proof.
  induction a; auto.
Defined.

Program Definition dep_elim_B (P : B -> Type)
  (f0 : forall s, P (dep_constr_B_0 s))
  (f1 : forall s, P (dep_constr_B_1 s))
  (b : B)
: P b.
Proof.
  induction (split b).
  - apply (f0 (existT _ b a)).
  - apply (f1 (existT _ b b0)).
Defined.

Program Definition iota_A_0 P f0 f1 s (Q : P (dep_constr_A_0 s) -> Type)
: Q (dep_elim_A P f0 f1 (dep_constr_A_0 s)) -> Q (f0 s).
Proof.
  intros. apply X.
Defined.

Program Definition iota_A_1 P f0 f1 s (Q : P (dep_constr_A_1 s) -> Type)
: Q (dep_elim_A P f0 f1 (dep_constr_A_1 s)) -> Q (f1 s).
Proof.
  intros. apply X.
Defined.

Program Definition iota_B_0 P f0 f1 s (Q : P (dep_constr_B_0 s) -> Type)
: Q (dep_elim_B P f0 f1 (dep_constr_B_0 s)) -> Q (f0 s).
Proof.
  intros. unfold dep_constr_B_0 in *. unfold dep_elim_B in X.
  induction s. simpl in X.
  rewrite <- (split_OK_left x p) in X. apply X.
Defined.

Program Definition iota_B_1 P f0 f1 s (Q : P (dep_constr_B_1 s) -> Type)
: Q (dep_elim_B P f0 f1 (dep_constr_B_1 s)) -> Q (f1 s).
Proof.
  intros. unfold dep_constr_B_1 in *. unfold dep_elim_B in X.
  induction s. simpl in X.
  rewrite <- (split_OK_right x p) in X. apply X.
Defined.

Program Definition f : A -> B.
Proof.
  intros a. apply dep_elim_A with (P := fun _ => B); intros.
  - apply (dep_constr_B_0 s).
  - apply (dep_constr_B_1 s).
  - apply a.
Defined.

Program Definition g : B -> A.
Proof.
  intros b. apply dep_elim_B with (P := fun _ => A); intros.
  - apply (dep_constr_A_0 s).
  - apply (dep_constr_A_1 s).
  - apply b.
Defined.

Save equivalence A B { promote = f; forget = g }.
Configure Lift A B {
  constrs_a = dep_constr_A_0 dep_constr_A_1;
  constrs_b = dep_constr_B_0 dep_constr_B_1;
  elim_a = dep_elim_A;
  elim_b = dep_elim_B;
  eta_a = eta_A;
  eta_b = eta_B;
  iota_a = iota_A_0 iota_A_1;
  iota_b = iota_B_0 iota_B_1
}.

(*
 * Then we can write:
 *)
Module SumProofs.

Program Definition identity (a : A) : A.
Proof.
  apply dep_elim_A with (P := fun _ => A); intros.
  - apply dep_constr_A_0. apply NoBoolProofs.identity. apply s.
  - apply dep_constr_A_1. apply YesBoolProofs.identity. apply s.
  - apply a.
Defined.

Program Definition free_vars (a : A) : list Identifier.
Proof.
  apply dep_elim_A with (P := fun _ => list Identifier); intros.
  - apply NoBoolProofs.free_vars. apply s.
  - apply YesBoolProofs.free_vars. apply s.
  - apply a.
Defined.

End SumProofs.

Repair Module A B in NoBoolProofs as NoBoolProofs'.
Repair Module A B in YesBoolProofs as YesBoolProofs'.
Repair Module A B in SumProofs as AddBoolProofs.

Print AddBoolProofs.identity.
Print AddBoolProofs.free_vars.

(*
 * This works, but it gives you slow functions!
 * It does separate out the new information, though, and guarantee preservation
 * of the old behavior:
 *)
Module Manual.

Import AddBool.

  Fixpoint identity (t : Term) : Term :=
  match t with
  | Var x => Var x
  | Int i => Int i
  | Bool b => Bool b
  | Eq a b => Eq (identity a) (identity b)
  | Plus a b => Plus (identity a) (identity b)
  | Times a b => Times (identity a) (identity b)
  | Minus a b => Minus (identity a) (identity b)
  | Choose x P => Choose x (identity P)
  end.

Fixpoint free_vars (t : Term) : list Identifier :=
  match t with
  | Var x => [x]
  | Int _ => []
  | Bool _ => []
  | Eq a b => free_vars a ++ free_vars b
  | Plus a b => free_vars a ++ free_vars b
  | Times a b => free_vars a ++ free_vars b
  | Minus a b => free_vars a ++ free_vars b
  | Choose x P =>
      filter (fun y => if id_eq_dec x y then false else true) (free_vars P)
  end.

End Manual.

Lemma identity_OK:
  forall t, AddBoolProofs.identity t = Manual.identity t.
Proof.
  intros t. induction t; auto; simpl.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.identity. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.identity. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.identity. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.identity. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt.
    unfold AddBoolProofs.identity. simpl.
    induction (split t); reflexivity.
Defined.

Lemma free_vars_OK:
  forall t, AddBoolProofs.free_vars t = Manual.free_vars t.
Proof.
  intros t. induction t; auto; simpl.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.free_vars. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.free_vars. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.free_vars. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt1. rewrite <- IHt2.
    unfold AddBoolProofs.free_vars. simpl.
    induction (split t1), (split t2); reflexivity.
  - rewrite <- IHt.
    unfold AddBoolProofs.free_vars. simpl.
    induction (split t); reflexivity.
Defined.

(*
 * Can we get faster functions and proofs?
 * Let's try working directly with the final equivalence.
 *)

(* --- 4. Thus, New.Term + Diff is equivalent to AddBool.Term --- *)

(*
 * We already have slow correct functions.
 * Down here I'm exploring if we can get fast ones.
 * The developer effort to get fast ones here is way too high,
 * so I think the answer is for now, not reasonably, and getting
 * slow versions and checking correctness is the better use case.
 * There may be a better equivalence and configuration that gets you there,
 * or this may be a place to compose with another tool since it involves
 * a very different eliminator transformation.
 *
 * Still, you can look at this equivalence if you are interested.
 * Long-term, I think we're going to chain our work with CoqEAL or something
 * to handle this case efficiently.
 *)

Definition A' : Type := New.Term + Diff.
Definition B' : Type := AddBool.Term.

Program Definition dep_constr_A_0' (i : Identifier) : A'.
Proof.
  left. apply (New.Var i).
Defined.
Program Definition dep_constr_A_1' (b : bool) : A'.
Proof.
  right. apply (DiffBool b).
Defined.
Program Definition dep_constr_A_2' (a1 a2 : A') : A'.
Proof.
  induction a1, a2.
  - left. apply (New.Eq a t).
  - right. apply DiffEqLeft; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply DiffEqRight; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply (DiffEq b d).
Defined.
Program Definition dep_constr_A_3' (z : Z) : A'.
Proof.
  left. apply (New.Int z).
Defined.
Program Definition dep_constr_A_4' (a1 a2 : A') : A'.
Proof.
  induction a1, a2.
  - left. apply (New.Plus a t).
  - right. apply DiffPlusLeft; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply DiffPlusRight; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply (DiffPlus b d).
Defined.
Program Definition dep_constr_A_5' (a1 a2 : A') : A'.
Proof.
  induction a1, a2.
  - left. apply (New.Times a t).
  - right. apply DiffTimesLeft; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply DiffTimesRight; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply (DiffTimes b d).
Defined.
Program Definition dep_constr_A_6' (a1 a2 : A') : A'.
Proof.
  induction a1, a2.
  - left. apply (New.Minus a t).
  - right. apply DiffMinusLeft; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply DiffMinusRight; auto using NoBoolProofs.Term_to_no_bools.
  - right. apply (DiffMinus b d).
Defined.
Program Definition dep_constr_A_7' (i : Identifier) (a : A') : A'.
Proof.
  induction a.
  - left. apply (New.Choose i a).
  - right. apply DiffChoose; auto.
Defined.
Definition dep_constr_B_0' := AddBool.Var.
Definition dep_constr_B_1' := AddBool.Bool.
Definition dep_constr_B_2' := AddBool.Eq.
Definition dep_constr_B_3' := AddBool.Int.
Definition dep_constr_B_4' := AddBool.Plus.
Definition dep_constr_B_5' := AddBool.Times.
Definition dep_constr_B_6' := AddBool.Minus.
Definition dep_constr_B_7' := AddBool.Choose.

Definition eta_A' (a : A') : A' := a. (* should probably expand for real *)
Definition eta_B' (b : B') : B' := b.

Lemma dep_elim_A' (P : A' -> Type)
  (f0 : forall i : Identifier, P (dep_constr_A_0' i))
  (f1 : forall b : bool, P (dep_constr_A_1' b))
  (f2 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_2' t t0))
  (f3 : forall z : Z, P (dep_constr_A_3' z))
  (f4 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_4' t t0))
  (f5 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_5' t t0))
  (f6 : forall t : A', P t -> forall t0 : A', P t0 -> P (dep_constr_A_6' t t0))
  (f7 : forall (i : Identifier) (t : A'), P t -> P (dep_constr_A_7' i t))
  (t : A')
: P t.
Proof.
  assert (forall a, P (inl a)).
  - intros a. induction a.
    + apply f0.
    + apply (f2 (inl a1) IHa1 (inl a2) IHa2).
    + apply f3.
    + apply (f4 (inl a1) IHa1 (inl a2) IHa2).
    + apply (f5 (inl a1) IHa1 (inl a2) IHa2).
    + apply (f6 (inl a1) IHa1 (inl a2) IHa2).
    + apply (f7 i (inl a) IHa).
  - induction t; auto. induction b.
    + apply f1.
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f2 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f2 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).
    + apply (f2 (inr b1) IHb1 (inr b2) IHb2).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f4 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f4 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).
    + apply (f4 (inr b1) IHb1 (inr b2) IHb2).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f5 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f5 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).
    + apply (f5 (inr b1) IHb1 (inr b2) IHb2).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f6 (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s)) (inr b) IHb ).
    + rewrite <- (NoBoolProofs.Term_to_no_bools_retraction s).
      apply (f6 (inr b) IHb (inl (NoBoolProofs.Term_to_no_bools_inv s)) (X (NoBoolProofs.Term_to_no_bools_inv s))).
    + apply (f6 (inr b1) IHb1 (inr b2) IHb2).
    + apply (f7 i (inr b) IHb).
Defined.

Definition dep_elim_B' := AddBool.Term_rect.

Definition section_adjoint := Adjoint.fg_id' NoBoolProofs.Term_to_no_bools_inv NoBoolProofs.Term_to_no_bools NoBoolProofs.Term_to_no_bools_retraction NoBoolProofs.Term_to_no_bools_section.

Lemma is_adjoint a : NoBoolProofs.Term_to_no_bools_retraction (NoBoolProofs.Term_to_no_bools a) = f_equal NoBoolProofs.Term_to_no_bools (section_adjoint a).
Proof.
  apply Adjoint.g_adjoint.
Defined.

Program Definition iota_A_0' P f0 f1 f2 f3 f4 f5 f6 f7 i Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_0' i)) ->
  Q (f0 i).
Proof.
  intros. auto.
Defined.

Program Definition iota_B_0' P f0 f1 f2 f3 f4 f5 f6 f7 i Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_0' i)) ->
  Q (f0 i).
Proof.
  intros. auto.
Defined.

Program Definition iota_A_1' P f0 f1 f2 f3 f4 f5 f6 f7 b Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_1' b)) ->
  Q (f1 b).
Proof.
  intros. auto.
Defined.

Program Definition iota_B_1' P f0 f1 f2 f3 f4 f5 f6 f7 b Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_1' b)) ->
  Q (f1 b).
Proof.
  intros. auto.
Defined.

Lemma iota_A_2'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:
  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_2' a1 a2) =
  f2 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).
Proof.
  induction a1, a2; auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.
Defined.

Program Definition iota_A_2' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_2' a1 a2)) ->
  Q (f2 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).
Proof.
  intros. rewrite <- iota_A_2'_aux. auto.
Defined.

Program Definition iota_B_2' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_2' b1 b2)) ->
  Q (f2 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).
Proof.
  intros. auto.
Defined.

Program Definition iota_A_3' P f0 f1 f2 f3 f4 f5 f6 f7 z Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_3' z)) ->
  Q (f3 z).
Proof.
  intros. auto.
Defined.

Program Definition iota_B_3' P f0 f1 f2 f3 f4 f5 f6 f7 z Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_3' z)) ->
  Q (f3 z).
Proof.
  intros. auto.
Defined.

Lemma iota_A_4'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:
  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_4' a1 a2) =
  f4 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).
Proof.
  induction a1, a2; auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.
Defined.

Program Definition iota_A_4' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_4' a1 a2)) ->
  Q (f4 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).
Proof.
  intros. rewrite <- iota_A_4'_aux. auto.
Defined.

Program Definition iota_B_4' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_4' b1 b2)) ->
  Q (f4 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).
Proof.
  intros. auto.
Defined.

Lemma iota_A_5'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:
  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_5' a1 a2) =
  f5 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).
Proof.
  induction a1, a2; auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.
Defined.

Program Definition iota_A_5' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_5' a1 a2)) ->
  Q (f5 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).
Proof.
  intros. rewrite <- iota_A_5'_aux. auto.
Defined.

Program Definition iota_B_5' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_5' b1 b2)) ->
  Q (f5 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).
Proof.
  intros. auto.
Defined.

Lemma iota_A_6'_aux P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2:
  dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_6' a1 a2) =
  f6 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2).
Proof.
  induction a1, a2; auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint a). auto.
  - simpl. rewrite is_adjoint. destruct (section_adjoint t). auto.
Defined.

Program Definition iota_A_6' P f0 f1 f2 f3 f4 f5 f6 f7 a1 a2 Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_6' a1 a2)) ->
  Q (f6 a1 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a1) a2 (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a2)).
Proof.
  intros. rewrite <- iota_A_6'_aux. auto.
Defined.

Program Definition iota_B_6' P f0 f1 f2 f3 f4 f5 f6 f7 b1 b2 Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_6' b1 b2)) ->
  Q (f6 b1 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b1) b2 (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b2)).
Proof.
  intros. auto.
Defined.

Program Definition iota_A_7' P f0 f1 f2 f3 f4 f5 f6 f7 i a Q
: Q (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_A_7' i a)) ->
  Q (f7 i a (dep_elim_A' P f0 f1 f2 f3 f4 f5 f6 f7 a)).
Proof.
  intros. induction a; apply X.
Defined.

Program Definition iota_B_7' P f0 f1 f2 f3 f4 f5 f6 f7 i b Q
: Q (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 (dep_constr_B_7' i b)) ->
  Q (f7 i b (dep_elim_B' P f0 f1 f2 f3 f4 f5 f6 f7 b)).
Proof.
  intros. auto.
Defined.

Program Definition f' : A' -> B'.
Proof.
  intros a. apply dep_elim_A' with (P := fun _ => B'); intros.
  - apply (dep_constr_B_0' i).
  - apply (dep_constr_B_1' b).
  - apply (dep_constr_B_2' X X0).
  - apply (dep_constr_B_3' z).
  - apply (dep_constr_B_4' X X0).
  - apply (dep_constr_B_5' X X0).
  - apply (dep_constr_B_6' X X0).
  - apply (dep_constr_B_7' i X).
  - apply a.
Defined.

Program Definition g' : B' -> A'.
Proof.
  intros b. apply dep_elim_B' with (P := fun _ => A'); intros.
  - apply (dep_constr_A_0' i).
  - apply (dep_constr_A_1' b0).
  - apply (dep_constr_A_2' X X0).
  - apply (dep_constr_A_3' z).
  - apply (dep_constr_A_4' X X0).
  - apply (dep_constr_A_5' X X0).
  - apply (dep_constr_A_6' X X0).
  - apply (dep_constr_A_7' i X).
  - apply b.
Defined.

Save equivalence A' B' { promote = f'; forget = g' }.
Configure Lift A' B' {
  constrs_a = dep_constr_A_0' dep_constr_A_1' dep_constr_A_2' dep_constr_A_3' dep_constr_A_4' dep_constr_A_5' dep_constr_A_6' dep_constr_A_7';
  constrs_b = dep_constr_B_0' dep_constr_B_1' dep_constr_B_2' dep_constr_B_3' dep_constr_B_4' dep_constr_B_5' dep_constr_B_6' dep_constr_B_7';
  elim_a = dep_elim_A';
  elim_b = dep_elim_B';
  eta_a = eta_A';
  eta_b = eta_B';
  iota_a = iota_A_0' iota_A_1' iota_A_2' iota_A_3' iota_A_4' iota_A_5' iota_A_6' iota_A_7';
  iota_b = iota_B_0' iota_B_1' iota_B_2' iota_B_3' iota_B_4' iota_B_5' iota_B_6' iota_B_7'
}.

(*
 * But writing functions and proofs this way isn't any easier.
 * We can backport from the fast version to show equivalent terms exist,
 * at least, but nobody would ever want to write these directly.
 *)
Preprocess Module Manual as Manual'.
Repair Module B' A' in Manual' as Backported.
Print Backported.identity.
Print Backported.free_vars.
(* there may be a different configuration that gets you there and isn't this hard, but I don't know it *)


(* -*- coding: utf-8 -*- *)
(************************************************************************)
(*         *   The Coq Proof Assistant / The Coq Development Team       *)
(*  v      *   INRIA, CNRS and contributors - Copyright 1999-2018       *)
(* <O___,, *       (see CREDITS file for the list of authors)           *)
(*   \VV/  **************************************************************)
(*    //   *    This file is distributed under the terms of the         *)
(*         *     GNU Lesser General Public License Version 2.1          *)
(*         *     (see LICENSE file for the text of the license)         *)
(************************************************************************)

(* File Eqdep.v created by Christine Paulin-Mohring in Coq V5.6, May 1992 *)
(* Abstraction with respect to the eq_rect_eq axiom and creation of
   EqdepFacts.v by Hugo Herbelin, Mar 2006 *)

(** This file axiomatizes the invariance by substitution of reflexive
    equality proofs [[Streicher93]] and exports its consequences, such
    as the injectivity of the projection of the dependent pair.

    [[Streicher93]] T. Streicher, Semantical Investigations into
    Intensional Type Theory, Habilitationsschrift, LMU München, 1993.
*)

Require Export EqdepFacts.

Module Eq_rect_eq.

Axiom eq_rect_eq :
  forall (U:Type) (p:U) (Q:U -> Type) (x:Q p) (h:p = p), x = eq_rect p Q x p h.

End Eq_rect_eq.

Module EqdepTheory := EqdepTheory(Eq_rect_eq).
Export EqdepTheory.

(** Exported hints *)

Hint Resolve eq_dep_eq: eqdep.
Hint Resolve inj_pair2 inj_pairT2: eqdep.


(** * Definition of grammar for expressions involving parentheses and plus *)
Require Import Fiat.Parsers.ContextFreeGrammar.Notations.

Definition plus_expr_pregrammar : pregrammar Ascii.ascii :=
  [[[ "expr" ::== "pexpr" || "pexpr" "+" "expr";;
      "pexpr" ::== "number" || "(" "expr" ")";;
      "number" ::== [0-9] || [0-9] "number"
  ]]].

Definition plus_expr_grammar : grammar Ascii.ascii := plus_expr_pregrammar.


(* *********************************************************************)
(*                                                                     *)
(*              The Compcert verified compiler                         *)
(*                                                                     *)
(*          Xavier Leroy, INRIA Paris-Rocquencourt                     *)
(*                                                                     *)
(*  Copyright Institut National de Recherche en Informatique et en     *)
(*  Automatique.  All rights reserved.  This file is distributed       *)
(*  under the terms of the INRIA Non-Commercial License Agreement.     *)
(*                                                                     *)
(* *********************************************************************)

(** Operators and addressing modes.  The abstract syntax and dynamic
  semantics for the CminorSel, RTL, LTL and Mach languages depend on the
  following types, defined in this library:
- [condition]:  boolean conditions for conditional branches;
- [operation]: arithmetic and logical operations;
- [addressing]: addressing modes for load and store operations.

  These types are PowerPC-specific and correspond roughly to what the
  processor can compute in one instruction.  In other terms, these
  types reflect the state of the program after instruction selection.
  For a processor-independent set of operations, see the abstract
  syntax and dynamic semantics of the Cminor language.
*)

Require Import BoolEqual.
Require Import Coqlib.
Require Import AST.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Globalenvs.
Require Import Events.

Set Implicit Arguments.
Local Transparent Archi.ptr64.

(** Conditions (boolean-valued operators). *)

Inductive condition : Type :=
  | Ccomp: comparison -> condition      (**r signed integer comparison *)
  | Ccompu: comparison -> condition     (**r unsigned integer comparison *)
  | Ccompimm: comparison -> int -> condition (**r signed integer comparison with a constant *)
  | Ccompuimm: comparison -> int -> condition  (**r unsigned integer comparison with a constant *)
  | Ccompf: comparison -> condition     (**r floating-point comparison *)
  | Cnotcompf: comparison -> condition  (**r negation of a floating-point comparison *)
  | Cmaskzero: int -> condition         (**r test [(arg & constant) == 0] *)
  | Cmasknotzero: int -> condition.     (**r test [(arg & constant) != 0] *)

(** Arithmetic and logical operations.  In the descriptions, [rd] is the
  result of the operation and [r1], [r2], etc, are the arguments. *)

Inductive operation : Type :=
  | Omove: operation                    (**r [rd = r1] *)
  | Ointconst: int -> operation         (**r [rd] is set to the given integer constant *)
  | Ofloatconst: float -> operation     (**r [rd] is set to the given float constant *)
  | Osingleconst: float32 -> operation  (**r [rd] is set to the given float constant *)
  | Oaddrsymbol: ident -> ptrofs -> operation (**r [rd] is set to the the address of the symbol plus the offset *)
  | Oaddrstack: ptrofs -> operation        (**r [rd] is set to the stack pointer plus the given offset *)
(*c Integer arithmetic: *)
  | Ocast8signed: operation             (**r [rd] is 8-bit sign extension of [r1] *)
  | Ocast16signed: operation            (**r [rd] is 16-bit sign extension of [r1] *)
  | Oadd: operation                     (**r [rd = r1 + r2] *)
  | Oaddimm: int -> operation           (**r [rd = r1 + n] *)
  | Oaddsymbol: ident -> ptrofs -> operation (**r [rd = addr(id + ofs) + r1] *)
  | Osub: operation                     (**r [rd = r1 - r2] *)
  | Osubimm: int -> operation           (**r [rd = n - r1] *)
  | Omul: operation                     (**r [rd = r1 * r2] *)
  | Omulimm: int -> operation           (**r [rd = r1 * n] *)
  | Omulhs: operation                   (**r [rd = high part of r1 * r2, signed] *)
  | Omulhu: operation                   (**r [rd = high part of r1 * r2, unsigned] *)
  | Odiv: operation                     (**r [rd = r1 / r2] (signed) *)
  | Odivu: operation                    (**r [rd = r1 / r2] (unsigned) *)
  | Oand: operation                     (**r [rd = r1 & r2] *)
  | Oandimm: int -> operation           (**r [rd = r1 & n] *)
  | Oor: operation                      (**r [rd = r1 | r2] *)
  | Oorimm: int -> operation            (**r [rd = r1 | n] *)
  | Oxor: operation                     (**r [rd = r1 ^ r2] *)
  | Oxorimm: int -> operation           (**r [rd = r1 ^ n] *)
  | Onot: operation                     (**r [rd = ~r1] *)
  | Onand: operation                    (**r [rd = ~(r1 & r2)] *)
  | Onor: operation                     (**r [rd = ~(r1 | r2)] *)
  | Onxor: operation                    (**r [rd = ~(r1 ^ r2)] *)
  | Oandc: operation                    (**r [rd = r1 & ~r2] *)
  | Oorc: operation                     (**r [rd = r1 | ~r2] *)
  | Oshl: operation                     (**r [rd = r1 << r2] *)
  | Oshr: operation                     (**r [rd = r1 >> r2] (signed) *)
  | Oshrimm: int -> operation           (**r [rd = r1 >> n] (signed) *)
  | Oshrximm: int -> operation          (**r [rd = r1 / 2^n] (signed) *)
  | Oshru: operation                    (**r [rd = r1 >> r2] (unsigned) *)
  | Orolm: int -> int -> operation      (**r rotate left and mask *)
  | Oroli: int -> int -> operation      (**r rotate left and insert *)
(*c Floating-point arithmetic: *)
  | Onegf: operation                    (**r [rd = - r1] *)
  | Oabsf: operation                    (**r [rd = abs(r1)] *)
  | Oaddf: operation                    (**r [rd = r1 + r2] *)
  | Osubf: operation                    (**r [rd = r1 - r2] *)
  | Omulf: operation                    (**r [rd = r1 * r2] *)
  | Odivf: operation                    (**r [rd = r1 / r2] *)
  | Onegfs: operation                   (**r [rd = - r1] *)
  | Oabsfs: operation                   (**r [rd = abs(r1)] *)
  | Oaddfs: operation                   (**r [rd = r1 + r2] *)
  | Osubfs: operation                   (**r [rd = r1 - r2] *)
  | Omulfs: operation                   (**r [rd = r1 * r2] *)
  | Odivfs: operation                   (**r [rd = r1 / r2] *)
  | Osingleoffloat: operation           (**r [rd] is [r1] truncated to single-precision float *)
  | Ofloatofsingle: operation           (**r [rd] is [r1] extended to double-precision float *)
(*c Conversions between int and float: *)
  | Ointoffloat: operation              (**r [rd = signed_int_of_float(r1)] *)
  | Ointuoffloat: operation             (**r [rd = unsigned_int_of_float(r1)] (PPC64 only) *)
  | Ofloatofint: operation              (**r [rd = float_of_signed_int(r1)] (PPC64 only) *)
  | Ofloatofintu: operation             (**r [rd = float_of_unsigned_int(r1)] (PPC64 only *)
  | Ofloatofwords: operation            (**r [rd = float_of_words(r1,r2)] *)
(*c Manipulating 64-bit integers: *)
  | Omakelong: operation                (**r [rd = r1 << 32 | r2] *)
  | Olowlong: operation                 (**r [rd = low-word(r1)] *)
  | Ohighlong: operation                (**r [rd = high-word(r1)] *)
(*c Boolean tests: *)
  | Ocmp: condition -> operation.       (**r [rd = 1] if condition holds, [rd = 0] otherwise. *)

(** Addressing modes.  [r1], [r2], etc, are the arguments to the
  addressing. *)

Inductive addressing: Type :=
  | Aindexed: int -> addressing         (**r Address is [r1 + offset] *)
  | Aindexed2: addressing               (**r Address is [r1 + r2] *)
  | Aglobal: ident -> ptrofs -> addressing (**r Address is [symbol + offset] *)
  | Abased: ident -> ptrofs -> addressing (**r Address is [symbol + offset + r1] *)
  | Ainstack: ptrofs -> addressing.        (**r Address is [stack_pointer + offset] *)

(** Comparison functions (used in module [CSE]). *)

Definition eq_condition (x y: condition) : {x=y} + {x<>y}.
Proof.
  generalize Int.eq_dec; intro.
  assert (forall (x y: comparison), {x=y}+{x<>y}). decide equality.
  decide equality.
Defined.

Definition beq_operation: forall (x y: operation), bool.
  generalize Int.eq_dec Ptrofs.eq_dec ident_eq Float.eq_dec Float32.eq_dec  eq_condition; boolean_equality.
Defined.

Definition eq_operation (x y: operation): {x=y} + {x<>y}.
Proof.
  decidable_equality_from beq_operation.
Defined.

Definition eq_addressing (x y: addressing) : {x=y} + {x<>y}.
Proof.
  generalize Int.eq_dec Ptrofs.eq_dec ident_eq; intro.
  decide equality.
Defined.

Global Opaque eq_condition eq_addressing eq_operation.

(** * Evaluation functions *)

(** Evaluation of conditions, operators and addressing modes applied
  to lists of values.  Return [None] when the computation can trigger an
  error, e.g. integer division by zero.  [eval_condition] returns a boolean,
  [eval_operation] and [eval_addressing] return a value. *)

Definition eval_condition (cond: condition) (vl: list val) (m: mem): option bool :=
  match cond, vl with
  | Ccomp c, v1 :: v2 :: nil => Val.cmp_bool c v1 v2
  | Ccompu c, v1 :: v2 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 v2
  | Ccompimm c n, v1 :: nil => Val.cmp_bool c v1 (Vint n)
  | Ccompuimm c n, v1 :: nil => Val.cmpu_bool (Mem.valid_pointer m) c v1 (Vint n)
  | Ccompf c, v1 :: v2 :: nil => Val.cmpf_bool c v1 v2
  | Cnotcompf c, v1 :: v2 :: nil => option_map negb (Val.cmpf_bool c v1 v2)
  | Cmaskzero n, v1 :: nil => Val.maskzero_bool v1 n
  | Cmasknotzero n, v1 :: nil => option_map negb (Val.maskzero_bool v1 n)
  | _, _ => None
  end.

Definition eval_operation
             (F V: Type) (genv: Genv.t F V) (sp: val)
             (op: operation) (vl: list val) (m: mem): option val :=
  match op, vl with
  | Omove, v1::nil => Some v1
  | Ointconst n, nil => Some (Vint n)
  | Ofloatconst n, nil => Some (Vfloat n)
  | Osingleconst n, nil => Some (Vsingle n)
  | Oaddrsymbol s ofs, nil => Some (Genv.symbol_address genv s ofs)
  | Oaddrstack ofs, nil => Some (Val.offset_ptr sp ofs)
  | Ocast8signed, v1::nil => Some (Val.sign_ext 8 v1)
  | Ocast16signed, v1::nil => Some (Val.sign_ext 16 v1)
  | Oadd, v1::v2::nil => Some (Val.add v1 v2)
  | Oaddimm n, v1::nil => Some (Val.add v1 (Vint n))
  | Oaddsymbol s ofs, v1::nil => Some (Val.add (Genv.symbol_address genv s ofs) v1)
  | Osub, v1::v2::nil => Some (Val.sub v1 v2)
  | Osubimm n, v1::nil => Some (Val.sub (Vint n) v1)
  | Omul, v1::v2::nil => Some (Val.mul v1 v2)
  | Omulimm n, v1::nil => Some (Val.mul v1 (Vint n))
  | Omulhs, v1::v2::nil => Some (Val.mulhs v1 v2)
  | Omulhu, v1::v2::nil => Some (Val.mulhu v1 v2)
  | Odiv, v1::v2::nil => Val.divs v1 v2
  | Odivu, v1::v2::nil => Val.divu v1 v2
  | Oand, v1::v2::nil => Some(Val.and v1 v2)
  | Oandimm n, v1::nil => Some (Val.and v1 (Vint n))
  | Oor, v1::v2::nil => Some(Val.or v1 v2)
  | Oorimm n, v1::nil => Some (Val.or v1 (Vint n))
  | Oxor, v1::v2::nil => Some(Val.xor v1 v2)
  | Oxorimm n, v1::nil => Some (Val.xor v1 (Vint n))
  | Onot, v1::nil => Some(Val.notint v1)
  | Onand, v1::v2::nil => Some (Val.notint (Val.and v1 v2))
  | Onor, v1::v2::nil => Some (Val.notint (Val.or v1 v2))
  | Onxor, v1::v2::nil => Some (Val.notint (Val.xor v1 v2))
  | Oandc, v1::v2::nil => Some (Val.and v1 (Val.notint v2))
  | Oorc, v1::v2::nil => Some (Val.or v1 (Val.notint v2))
  | Oshl, v1::v2::nil => Some (Val.shl v1 v2)
  | Oshr, v1::v2::nil => Some (Val.shr v1 v2)
  | Oshrimm n, v1::nil => Some (Val.shr v1 (Vint n))
  | Oshrximm n, v1::nil => Val.shrx v1 (Vint n)
  | Oshru, v1::v2::nil => Some (Val.shru v1 v2)
  | Orolm amount mask, v1::nil => Some (Val.rolm v1 amount mask)
  | Oroli amount mask, v1::v2::nil =>
      Some(Val.or (Val.and v1 (Vint (Int.not mask))) (Val.rolm v2 amount mask))
  | Onegf, v1::nil => Some(Val.negf v1)
  | Oabsf, v1::nil => Some(Val.absf v1)
  | Oaddf, v1::v2::nil => Some(Val.addf v1 v2)
  | Osubf, v1::v2::nil => Some(Val.subf v1 v2)
  | Omulf, v1::v2::nil => Some(Val.mulf v1 v2)
  | Odivf, v1::v2::nil => Some(Val.divf v1 v2)
  | Onegfs, v1::nil => Some(Val.negfs v1)
  | Oabsfs, v1::nil => Some(Val.absfs v1)
  | Oaddfs, v1::v2::nil => Some(Val.addfs v1 v2)
  | Osubfs, v1::v2::nil => Some(Val.subfs v1 v2)
  | Omulfs, v1::v2::nil => Some(Val.mulfs v1 v2)
  | Odivfs, v1::v2::nil => Some(Val.divfs v1 v2)
  | Osingleoffloat, v1::nil => Some(Val.singleoffloat v1)
  | Ofloatofsingle, v1::nil => Some(Val.floatofsingle v1)
  | Ointoffloat, v1::nil => Val.intoffloat v1
  | Ointuoffloat, v1::nil => Val.intuoffloat v1
  | Ofloatofint, v1::nil => Val.floatofint v1
  | Ofloatofintu, v1::nil => Val.floatofintu v1
  | Ofloatofwords, v1::v2::nil => Some(Val.floatofwords v1 v2)
  | Omakelong, v1::v2::nil => Some(Val.longofwords v1 v2)
  | Olowlong, v1::nil => Some(Val.loword v1)
  | Ohighlong, v1::nil => Some(Val.hiword v1)
  | Ocmp c, _ => Some(Val.of_optbool (eval_condition c vl m))
  | _, _ => None
  end.

Definition eval_addressing
    (F V: Type) (genv: Genv.t F V) (sp: val)
    (addr: addressing) (vl: list val) : option val :=
  match addr, vl with
  | Aindexed n, v1::nil => Some (Val.add v1 (Vint n))
  | Aindexed2, v1::v2::nil => Some (Val.add v1 v2)
  | Aglobal s ofs, nil => Some (Genv.symbol_address genv s ofs)
  | Abased s ofs, v1::nil => Some (Val.add (Genv.symbol_address genv s ofs) v1)
  | Ainstack ofs, nil => Some(Val.offset_ptr sp ofs)
  | _, _ => None
  end.

Remark eval_addressing_Ainstack:
  forall (F V: Type) (genv: Genv.t F V) sp ofs,
  eval_addressing genv sp (Ainstack ofs) nil = Some (Val.offset_ptr sp ofs).
Proof.
  intros. reflexivity.
Qed.

Remark eval_addressing_Ainstack_inv:
  forall (F V: Type) (genv: Genv.t F V) sp ofs vl v,
  eval_addressing genv sp (Ainstack ofs) vl = Some v -> vl = nil /\ v = Val.offset_ptr sp ofs.
Proof.
  unfold eval_addressing; intros; destruct vl; inv H; auto.
Qed.

Ltac FuncInv :=
  match goal with
  | H: (match ?x with nil => _ | _ :: _ => _ end = Some _) |- _ =>
      destruct x; simpl in H; try discriminate; FuncInv
  | H: (match ?v with Vundef => _ | Vint _ => _ | Vlong _ => _ | Vfloat _ => _ | Vptr _ _ => _ end = Some _) |- _ =>
      destruct v; simpl in H; try discriminate; FuncInv
  | H: (Some _ = Some _) |- _ =>
      injection H; intros; clear H; FuncInv
  | _ =>
      idtac
  end.

(** * Static typing of conditions, operators and addressing modes. *)

Definition type_of_condition (c: condition) : list typ :=
  match c with
  | Ccomp _ => Tint :: Tint :: nil
  | Ccompu _ => Tint :: Tint :: nil
  | Ccompimm _ _ => Tint :: nil
  | Ccompuimm _ _ => Tint :: nil
  | Ccompf _ => Tfloat :: Tfloat :: nil
  | Cnotcompf _ => Tfloat :: Tfloat :: nil
  | Cmaskzero _ => Tint :: nil
  | Cmasknotzero _ => Tint :: nil
  end.

Definition type_of_operation (op: operation) : list typ * typ :=
  match op with
  | Omove => (nil, Tint)   (* treated specially *)
  | Ointconst _ => (nil, Tint)
  | Ofloatconst f => (nil, Tfloat)
  | Osingleconst f => (nil, Tsingle)
  | Oaddrsymbol _ _ => (nil, Tint)
  | Oaddrstack _ => (nil, Tint)
  | Ocast8signed => (Tint :: nil, Tint)
  | Ocast16signed => (Tint :: nil, Tint)
  | Oadd => (Tint :: Tint :: nil, Tint)
  | Oaddimm _ => (Tint :: nil, Tint)
  | Oaddsymbol _ _ => (Tint :: nil, Tint)
  | Osub => (Tint :: Tint :: nil, Tint)
  | Osubimm _ => (Tint :: nil, Tint)
  | Omul => (Tint :: Tint :: nil, Tint)
  | Omulimm _ => (Tint :: nil, Tint)
  | Omulhs => (Tint :: Tint :: nil, Tint)
  | Omulhu => (Tint :: Tint :: nil, Tint)
  | Odiv => (Tint :: Tint :: nil, Tint)
  | Odivu => (Tint :: Tint :: nil, Tint)
  | Oand => (Tint :: Tint :: nil, Tint)
  | Oandimm _ => (Tint :: nil, Tint)
  | Oor => (Tint :: Tint :: nil, Tint)
  | Oorimm _ => (Tint :: nil, Tint)
  | Oxor => (Tint :: Tint :: nil, Tint)
  | Oxorimm _ => (Tint :: nil, Tint)
  | Onot => (Tint :: nil, Tint)
  | Onand => (Tint :: Tint :: nil, Tint)
  | Onor => (Tint :: Tint :: nil, Tint)
  | Onxor => (Tint :: Tint :: nil, Tint)
  | Oandc => (Tint :: Tint :: nil, Tint)
  | Oorc => (Tint :: Tint :: nil, Tint)
  | Oshl => (Tint :: Tint :: nil, Tint)
  | Oshr => (Tint :: Tint :: nil, Tint)
  | Oshrimm _ => (Tint :: nil, Tint)
  | Oshrximm _ => (Tint :: nil, Tint)
  | Oshru => (Tint :: Tint :: nil, Tint)
  | Orolm _ _ => (Tint :: nil, Tint)
  | Oroli _ _ => (Tint :: Tint :: nil, Tint)
  | Onegf => (Tfloat :: nil, Tfloat)
  | Oabsf => (Tfloat :: nil, Tfloat)
  | Oaddf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Osubf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Omulf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Odivf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Onegfs => (Tsingle :: nil, Tsingle)
  | Oabsfs => (Tsingle :: nil, Tsingle)
  | Oaddfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Osubfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Omulfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Odivfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Osingleoffloat => (Tfloat :: nil, Tsingle)
  | Ofloatofsingle => (Tsingle :: nil, Tfloat)
  | Ointoffloat => (Tfloat :: nil, Tint)
  | Ointuoffloat => (Tfloat :: nil, Tint)
  | Ofloatofint => (Tint :: nil, Tfloat)
  | Ofloatofintu => (Tint :: nil, Tfloat)
  | Ofloatofwords => (Tint :: Tint :: nil, Tfloat)
  | Omakelong => (Tint :: Tint :: nil, Tlong)
  | Olowlong => (Tlong :: nil, Tint)
  | Ohighlong => (Tlong :: nil, Tint)
  | Ocmp c => (type_of_condition c, Tint)
  end.

Definition type_of_addressing (addr: addressing) : list typ :=
  match addr with
  | Aindexed _ => Tint :: nil
  | Aindexed2 => Tint :: Tint :: nil
  | Aglobal _ _ => nil
  | Abased _ _ => Tint :: nil
  | Ainstack _ => nil
  end.

(** Weak type soundness results for [eval_operation]:
  the result values, when defined, are always of the type predicted
  by [type_of_operation]. *)

Section SOUNDNESS.

Variable A V: Type.
Variable genv: Genv.t A V.

Lemma type_of_operation_sound:
  forall op vl sp v m,
  op <> Omove ->
  eval_operation genv sp op vl m = Some v ->
  Val.has_type v (snd (type_of_operation op)).
Proof with (try exact I; try reflexivity).
  intros.
  destruct op; simpl in H0; FuncInv; subst; simpl.
  congruence.
  exact I.
  auto.
  auto.
  unfold Genv.symbol_address. destruct (Genv.find_symbol genv i)...
  destruct sp...
  destruct v0...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0...
  unfold Genv.symbol_address. destruct (Genv.find_symbol genv i)... destruct v0...
  destruct v0; destruct v1... simpl. destruct (eq_block b b0)...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1; simpl in *; inv H0.
    destruct (Int.eq i0 Int.zero
         || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2...
  destruct v0; destruct v1; simpl in *; inv H0. destruct (Int.eq i0 Int.zero); inv H2...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...
  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...
  destruct v0; simpl... destruct (Int.ltu i Int.iwordsize)...
  destruct v0; simpl in *; inv H0. destruct (Int.ltu i (Int.repr 31)); inv H2...
  destruct v0; destruct v1; simpl... destruct (Int.ltu i0 Int.iwordsize)...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0...
  destruct v0; simpl in H0; inv H0. destruct (Float.to_int f); inv H2...
  destruct v0; simpl in H0; inv H0. destruct (Float.to_intu f); inv H2...
  destruct v0; simpl in H0; inv H0...
  destruct v0; simpl in H0; inv H0...
  destruct v0; destruct v1...
  destruct v0; destruct v1...
  destruct v0...
  destruct v0...
  destruct (eval_condition c vl m); simpl... destruct b...
Qed.

End SOUNDNESS.

(** * Manipulating and transforming operations *)

(** Recognition of move operations. *)

Definition is_move_operation
    (A: Type) (op: operation) (args: list A) : option A :=
  match op, args with
  | Omove, arg :: nil => Some arg
  | _, _ => None
  end.

Lemma is_move_operation_correct:
  forall (A: Type) (op: operation) (args: list A) (a: A),
  is_move_operation op args = Some a ->
  op = Omove /\ args = a :: nil.
Proof.
  intros until a. unfold is_move_operation; destruct op;
  try (intros; discriminate).
  destruct args. intros; discriminate.
  destruct args. intros. intuition congruence.
  intros; discriminate.
Qed.

(** [negate_condition cond] returns a condition that is logically
  equivalent to the negation of [cond]. *)

Definition negate_condition (cond: condition): condition :=
  match cond with
  | Ccomp c => Ccomp(negate_comparison c)
  | Ccompu c => Ccompu(negate_comparison c)
  | Ccompimm c n => Ccompimm (negate_comparison c) n
  | Ccompuimm c n => Ccompuimm (negate_comparison c) n
  | Ccompf c => Cnotcompf c
  | Cnotcompf c => Ccompf c
  | Cmaskzero n => Cmasknotzero n
  | Cmasknotzero n => Cmaskzero n
  end.

Lemma eval_negate_condition:
  forall cond vl m,
  eval_condition (negate_condition cond) vl m = option_map negb (eval_condition cond vl m).
Proof.
  intros. destruct cond; simpl.
  repeat (destruct vl; auto). apply Val.negate_cmp_bool.
  repeat (destruct vl; auto). apply Val.negate_cmpu_bool.
  repeat (destruct vl; auto). apply Val.negate_cmp_bool.
  repeat (destruct vl; auto). apply Val.negate_cmpu_bool.
  repeat (destruct vl; auto).
  repeat (destruct vl; auto). destruct (Val.cmpf_bool c v v0); auto. destruct b; auto.
  repeat (destruct vl; auto).
  repeat (destruct vl; auto). destruct (Val.maskzero_bool v i) as [[]|]; auto.
Qed.

(** Shifting stack-relative references.  This is used in [Stacking]. *)

Definition shift_stack_addressing (delta: Z) (addr: addressing) :=
  match addr with
  | Ainstack ofs => Ainstack (Ptrofs.add (Ptrofs.repr delta) ofs)
  | _ => addr
  end.

Definition shift_stack_operation (delta: Z) (op: operation) :=
  match op with
  | Oaddrstack ofs => Oaddrstack (Ptrofs.add (Ptrofs.repr delta) ofs)
  | _ => op
  end.

Lemma type_shift_stack_addressing:
  forall delta addr, type_of_addressing (shift_stack_addressing delta addr) = type_of_addressing addr.
Proof.
  intros. destruct addr; auto.
Qed.

Lemma type_shift_stack_operation:
  forall delta op, type_of_operation (shift_stack_operation delta op) = type_of_operation op.
Proof.
  intros. destruct op; auto.
Qed.

Lemma eval_shift_stack_addressing:
  forall F V (ge: Genv.t F V) sp addr vl delta,
  eval_addressing ge (Vptr sp Ptrofs.zero) (shift_stack_addressing delta addr) vl =
  eval_addressing ge (Vptr sp (Ptrofs.repr delta)) addr vl.
Proof.
  intros. destruct addr; simpl; auto.
  rewrite Ptrofs.add_zero_l; auto.
Qed.

Lemma eval_shift_stack_operation:
  forall F V (ge: Genv.t F V) sp op vl m delta,
  eval_operation ge (Vptr sp Ptrofs.zero) (shift_stack_operation delta op) vl m =
  eval_operation ge (Vptr sp (Ptrofs.repr delta)) op vl m.
Proof.
  intros. destruct op; simpl; auto.
  rewrite Ptrofs.add_zero_l; auto.
Qed.

(** Offset an addressing mode [addr] by a quantity [delta], so that
  it designates the pointer [delta] bytes past the pointer designated
  by [addr].  May be undefined, in which case [None] is returned. *)

Definition offset_addressing (addr: addressing) (delta: Z) : option addressing :=
  match addr with
  | Aindexed n => Some(Aindexed (Int.add n (Int.repr delta)))
  | Aindexed2 => None
  | Aglobal s n => Some(Aglobal s (Ptrofs.add n (Ptrofs.repr delta)))
  | Abased s n => Some(Abased s (Ptrofs.add n (Ptrofs.repr delta)))
  | Ainstack n => Some(Ainstack (Ptrofs.add n (Ptrofs.repr delta)))
  end.

Lemma eval_offset_addressing:
  forall (F V: Type) (ge: Genv.t F V) sp addr args delta addr' v,
  offset_addressing addr delta = Some addr' ->
  eval_addressing ge sp addr args = Some v ->
  eval_addressing ge sp addr' args = Some(Val.add v (Vint (Int.repr delta))).
Proof.
  intros.
  assert (D: Ptrofs.repr delta = Ptrofs.of_int (Int.repr delta)) by (symmetry; auto with ptrofs).
  destruct addr; simpl in H; inv H; simpl in *; FuncInv; subst.
- rewrite Val.add_assoc; auto.
- unfold Genv.symbol_address. destruct (Genv.find_symbol ge i); auto. rewrite D; auto.
- unfold Genv.symbol_address. destruct (Genv.find_symbol ge i); auto.
  rewrite Val.add_assoc. rewrite Val.add_permut. rewrite Val.add_commut.
  simpl. rewrite D. auto.
- destruct sp; simpl; auto. rewrite Ptrofs.add_assoc, D. auto.
Qed.

(** Operations that are so cheap to recompute that CSE should not factor them out. *)

Definition is_trivial_op (op: operation) : bool :=
  match op with
  | Omove => true
  | Ointconst _ => true
  | Oaddrsymbol _ _ => true
  | Oaddrstack _ => true
  | _ => false
  end.

(** Operations that depend on the memory state. *)

Definition op_depends_on_memory (op: operation) : bool :=
  match op with
  | Ocmp (Ccompu _) => true
  | Ocmp (Ccompuimm _ _) => true
  | _ => false
  end.

Lemma op_depends_on_memory_correct:
  forall (F V: Type) (ge: Genv.t F V) sp op args m1 m2,
  op_depends_on_memory op = false ->
  eval_operation ge sp op args m1 = eval_operation ge sp op args m2.
Proof.
  intros until m2. destruct op; simpl; try congruence. unfold eval_condition.
  destruct c; simpl; auto; try discriminate.
Qed.

(** Global variables mentioned in an operation or addressing mode *)

Definition globals_operation (op: operation) : list ident :=
  match op with
  | Oaddrsymbol s ofs => s :: nil
  | Oaddsymbol s ofs => s :: nil
  | _ => nil
  end.

Definition globals_addressing (addr: addressing) : list ident :=
  match addr with
  | Aglobal s n => s :: nil
  | Abased s n => s :: nil
  | _ => nil
  end.

(** * Invariance and compatibility properties. *)

(** [eval_operation] and [eval_addressing] depend on a global environment
  for resolving references to global symbols.  We show that they give
  the same results if a global environment is replaced by another that
  assigns the same addresses to the same symbols. *)

Section GENV_TRANSF.

Variable F1 F2 V1 V2: Type.
Variable ge1: Genv.t F1 V1.
Variable ge2: Genv.t F2 V2.
Hypothesis agree_on_symbols:
  forall (s: ident), Genv.find_symbol ge2 s = Genv.find_symbol ge1 s.

Remark symbol_address_preserved:
  forall s ofs, Genv.symbol_address ge2 s ofs = Genv.symbol_address ge1 s ofs.
Proof.
  unfold Genv.symbol_address; intros. rewrite agree_on_symbols; auto.
Qed.

Lemma eval_operation_preserved:
  forall sp op vl m,
  eval_operation ge2 sp op vl m = eval_operation ge1 sp op vl m.
Proof.
  intros. destruct op; simpl; auto; rewrite symbol_address_preserved; auto.
Qed.

Lemma eval_addressing_preserved:
  forall sp addr vl,
  eval_addressing ge2 sp addr vl = eval_addressing ge1 sp addr vl.
Proof.
  intros. destruct addr; simpl; auto; rewrite symbol_address_preserved; auto.
Qed.

End GENV_TRANSF.

(** Compatibility of the evaluation functions with value injections. *)

Section EVAL_COMPAT.

Variable F1 F2 V1 V2: Type.
Variable ge1: Genv.t F1 V1.
Variable ge2: Genv.t F2 V2.
Variable f: meminj.

Variable m1: mem.
Variable m2: mem.

Hypothesis valid_pointer_inj:
  forall b1 ofs b2 delta,
  f b1 = Some(b2, delta) ->
  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->
  Mem.valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.

Hypothesis weak_valid_pointer_inj:
  forall b1 ofs b2 delta,
  f b1 = Some(b2, delta) ->
  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->
  Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.

Hypothesis weak_valid_pointer_no_overflow:
  forall b1 ofs b2 delta,
  f b1 = Some(b2, delta) ->
  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->
  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.max_unsigned.

Hypothesis valid_different_pointers_inj:
  forall b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,
  b1 <> b2 ->
  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->
  Mem.valid_pointer m1 b2 (Ptrofs.unsigned ofs2) = true ->
  f b1 = Some (b1', delta1) ->
  f b2 = Some (b2', delta2) ->
  b1' <> b2' \/
  Ptrofs.unsigned (Ptrofs.add ofs1 (Ptrofs.repr delta1)) <> Ptrofs.unsigned (Ptrofs.add ofs2 (Ptrofs.repr delta2)).

Ltac InvInject :=
  match goal with
  | [ H: Val.inject _ (Vint _) _ |- _ ] =>
      inv H; InvInject
  | [ H: Val.inject _ (Vfloat _) _ |- _ ] =>
      inv H; InvInject
  | [ H: Val.inject _ (Vsingle _) _ |- _ ] =>
      inv H; InvInject
  | [ H: Val.inject _ (Vptr _ _) _ |- _ ] =>
      inv H; InvInject
  | [ H: Val.inject_list _ nil _ |- _ ] =>
      inv H; InvInject
  | [ H: Val.inject_list _ (_ :: _) _ |- _ ] =>
      inv H; InvInject
  | _ => idtac
  end.

Lemma eval_condition_inj:
  forall cond vl1 vl2 b,
  Val.inject_list f vl1 vl2 ->
  eval_condition cond vl1 m1 = Some b ->
  eval_condition cond vl2 m2 = Some b.
Proof.
  intros. destruct cond; simpl in H0; FuncInv; InvInject; simpl; auto.
  inv H3; inv H2; simpl in H0; inv H0; auto.
  eauto 3 using Val.cmpu_bool_inject, Mem.valid_pointer_implies.
  inv H3; simpl in H0; inv H0; auto.
  eauto 3 using Val.cmpu_bool_inject, Mem.valid_pointer_implies.
  inv H3; inv H2; simpl in H0; inv H0; auto.
  inv H3; inv H2; simpl in H0; inv H0; auto.
  inv H3; try discriminate; auto.
  inv H3; try discriminate; auto.
Qed.

Ltac TrivialExists :=
  match goal with
  | [ |- exists v2, Some ?v1 = Some v2 /\ Val.inject _ _ v2 ] =>
      exists v1; split; auto
  | _ => idtac
  end.

Lemma eval_operation_inj:
  forall op sp1 vl1 sp2 vl2 v1,
  (forall id ofs,
      In id (globals_operation op) ->
      Val.inject f (Genv.symbol_address ge1 id ofs) (Genv.symbol_address ge2 id ofs)) ->
  Val.inject f sp1 sp2 ->
  Val.inject_list f vl1 vl2 ->
  eval_operation ge1 sp1 op vl1 m1 = Some v1 ->
  exists v2, eval_operation ge2 sp2 op vl2 m2 = Some v2 /\ Val.inject f v1 v2.
Proof.
  intros until v1; intros GL; intros. destruct op; simpl in H1; simpl; FuncInv; InvInject; TrivialExists.
  apply GL; simpl; auto.
  apply Val.offset_ptr_inject; auto.
  inv H4; simpl; auto.
  inv H4; simpl; auto.
  apply Val.add_inject; auto.
  apply Val.add_inject; auto.
  apply Val.add_inject; auto. apply GL; simpl; auto.
  apply Val.sub_inject; auto.
  inv H4; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H3; simpl in H1; inv H1. simpl.
    destruct (Int.eq i0 Int.zero
         || Int.eq i (Int.repr Int.min_signed) && Int.eq i0 Int.mone); inv H2. TrivialExists.
  inv H4; inv H3; simpl in H1; inv H1. simpl.
    destruct (Int.eq i0 Int.zero); inv H2. TrivialExists.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.
  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.
  inv H4; simpl; auto. destruct (Int.ltu i Int.iwordsize); auto.
  inv H4; simpl in *; inv H1. destruct (Int.ltu i (Int.repr 31)); inv H2. econstructor; eauto.
  inv H4; inv H2; simpl; auto. destruct (Int.ltu i0 Int.iwordsize); auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; simpl; auto.
  inv H4; simpl in H1; inv H1. simpl. destruct (Float.to_int f0); simpl in H2; inv H2.
  exists (Vint i); auto.
  inv H4; simpl in H1; inv H1. simpl. destruct (Float.to_intu f0); simpl in H2; inv H2.
  exists (Vint i); auto.
  inv H4; simpl in H1; inv H1; simpl. TrivialExists.
  inv H4; simpl in H1; inv H1; simpl. TrivialExists.
  inv H4; inv H2; simpl; auto.
  inv H4; inv H2; simpl; auto.
  inv H4; simpl; auto.
  inv H4; simpl; auto.
  subst. destruct (eval_condition c vl1 m1) eqn:?.
  exploit eval_condition_inj; eauto. intros EQ; rewrite EQ.
  destruct b; simpl; constructor.
  simpl; constructor.
Qed.

Lemma eval_addressing_inj:
  forall addr sp1 vl1 sp2 vl2 v1,
  (forall id ofs,
      In id (globals_addressing addr) ->
      Val.inject f (Genv.symbol_address ge1 id ofs) (Genv.symbol_address ge2 id ofs)) ->
  Val.inject f sp1 sp2 ->
  Val.inject_list f vl1 vl2 ->
  eval_addressing ge1 sp1 addr vl1 = Some v1 ->
  exists v2, eval_addressing ge2 sp2 addr vl2 = Some v2 /\ Val.inject f v1 v2.
Proof.
  intros. destruct addr; simpl in H2; simpl; FuncInv; InvInject; TrivialExists;
    auto using Val.add_inject, Val.offset_ptr_inject.
  apply H; simpl; auto.
  apply Val.add_inject; auto. apply H; simpl; auto.
Qed.

End EVAL_COMPAT.

(** Compatibility of the evaluation functions with the ``is less defined'' relation over values. *)

Section EVAL_LESSDEF.

Variable F V: Type.
Variable genv: Genv.t F V.

Remark valid_pointer_extends:
  forall m1 m2, Mem.extends m1 m2 ->
  forall b1 ofs b2 delta,
  Some(b1, 0) = Some(b2, delta) ->
  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->
  Mem.valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.
Proof.
  intros. inv H0. rewrite Ptrofs.add_zero. eapply Mem.valid_pointer_extends; eauto.
Qed.

Remark weak_valid_pointer_extends:
  forall m1 m2, Mem.extends m1 m2 ->
  forall b1 ofs b2 delta,
  Some(b1, 0) = Some(b2, delta) ->
  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->
  Mem.weak_valid_pointer m2 b2 (Ptrofs.unsigned (Ptrofs.add ofs (Ptrofs.repr delta))) = true.
Proof.
  intros. inv H0. rewrite Ptrofs.add_zero. eapply Mem.weak_valid_pointer_extends; eauto.
Qed.

Remark weak_valid_pointer_no_overflow_extends:
  forall m1 b1 ofs b2 delta,
  Some(b1, 0) = Some(b2, delta) ->
  Mem.weak_valid_pointer m1 b1 (Ptrofs.unsigned ofs) = true ->
  0 <= Ptrofs.unsigned ofs + Ptrofs.unsigned (Ptrofs.repr delta) <= Ptrofs.max_unsigned.
Proof.
  intros. inv H. rewrite Zplus_0_r. apply Ptrofs.unsigned_range_2.
Qed.

Remark valid_different_pointers_extends:
  forall m1 b1 ofs1 b2 ofs2 b1' delta1 b2' delta2,
  b1 <> b2 ->
  Mem.valid_pointer m1 b1 (Ptrofs.unsigned ofs1) = true ->
  Mem.valid_pointer m1 b2 (Ptrofs.unsigned ofs2) = true ->
  Some(b1, 0) = Some (b1', delta1) ->
  Some(b2, 0) = Some (b2', delta2) ->
  b1' <> b2' \/
  Ptrofs.unsigned(Ptrofs.add ofs1 (Ptrofs.repr delta1)) <> Ptrofs.unsigned(Ptrofs.add ofs2 (Ptrofs.repr delta2)).
Proof.
  intros. inv H2; inv H3. auto.
Qed.

Lemma eval_condition_lessdef:
  forall cond vl1 vl2 b m1 m2,
  Val.lessdef_list vl1 vl2 ->
  Mem.extends m1 m2 ->
  eval_condition cond vl1 m1 = Some b ->
  eval_condition cond vl2 m2 = Some b.
Proof.
  intros. eapply eval_condition_inj with (f := fun b => Some(b, 0)) (m1 := m1).
  apply valid_pointer_extends; auto.
  apply weak_valid_pointer_extends; auto.
  apply weak_valid_pointer_no_overflow_extends; auto.
  apply valid_different_pointers_extends; auto.
  rewrite <- val_inject_list_lessdef. eauto. auto.
Qed.

Lemma eval_operation_lessdef:
  forall sp op vl1 vl2 v1 m1 m2,
  Val.lessdef_list vl1 vl2 ->
  Mem.extends m1 m2 ->
  eval_operation genv sp op vl1 m1 = Some v1 ->
  exists v2, eval_operation genv sp op vl2 m2 = Some v2 /\ Val.lessdef v1 v2.
Proof.
  intros. rewrite val_inject_list_lessdef in H.
  assert (exists v2 : val,
          eval_operation genv sp op vl2 m2 = Some v2
          /\ Val.inject (fun b => Some(b, 0)) v1 v2).
  eapply eval_operation_inj with (m1 := m1) (sp1 := sp).
  apply valid_pointer_extends; auto.
  apply weak_valid_pointer_extends; auto.
  apply weak_valid_pointer_no_overflow_extends; auto.
  apply valid_different_pointers_extends; auto.
  intros. rewrite <- val_inject_lessdef; auto.
  rewrite <- val_inject_lessdef; auto.
  eauto. auto.
  destruct H2 as [v2 [A B]]. exists v2; split; auto. rewrite val_inject_lessdef; auto.
Qed.

Lemma eval_addressing_lessdef:
  forall sp addr vl1 vl2 v1,
  Val.lessdef_list vl1 vl2 ->
  eval_addressing genv sp addr vl1 = Some v1 ->
  exists v2, eval_addressing genv sp addr vl2 = Some v2 /\ Val.lessdef v1 v2.
Proof.
  intros. rewrite val_inject_list_lessdef in H.
  assert (exists v2 : val,
          eval_addressing genv sp addr vl2 = Some v2
          /\ Val.inject (fun b => Some(b, 0)) v1 v2).
  eapply eval_addressing_inj with (sp1 := sp).
  intros. rewrite <- val_inject_lessdef; auto.
  rewrite <- val_inject_lessdef; auto.
  eauto. auto.
  destruct H1 as [v2 [A B]]. exists v2; split; auto. rewrite val_inject_lessdef; auto.
Qed.

End EVAL_LESSDEF.

(** Compatibility of the evaluation functions with memory injections. *)

Section EVAL_INJECT.

Variable F V: Type.
Variable genv: Genv.t F V.
Variable f: meminj.
Hypothesis globals: meminj_preserves_globals genv f.
Variable sp1: block.
Variable sp2: block.
Variable delta: Z.
Hypothesis sp_inj: f sp1 = Some(sp2, delta).

Remark symbol_address_inject:
  forall id ofs, Val.inject f (Genv.symbol_address genv id ofs) (Genv.symbol_address genv id ofs).
Proof.
  intros. unfold Genv.symbol_address. destruct (Genv.find_symbol genv id) eqn:?; auto.
  exploit (proj1 globals); eauto. intros.
  econstructor; eauto. rewrite Ptrofs.add_zero; auto.
Qed.

Lemma eval_condition_inject:
  forall cond vl1 vl2 b m1 m2,
  Val.inject_list f vl1 vl2 ->
  Mem.inject f m1 m2 ->
  eval_condition cond vl1 m1 = Some b ->
  eval_condition cond vl2 m2 = Some b.
Proof.
  intros. eapply eval_condition_inj with (f := f) (m1 := m1); eauto.
  intros; eapply Mem.valid_pointer_inject_val; eauto.
  intros; eapply Mem.weak_valid_pointer_inject_val; eauto.
  intros; eapply Mem.weak_valid_pointer_inject_no_overflow; eauto.
  intros; eapply Mem.different_pointers_inject; eauto.
Qed.

Lemma eval_addressing_inject:
  forall addr vl1 vl2 v1,
  Val.inject_list f vl1 vl2 ->
  eval_addressing genv (Vptr sp1 Ptrofs.zero) addr vl1 = Some v1 ->
  exists v2,
     eval_addressing genv (Vptr sp2 Ptrofs.zero) (shift_stack_addressing delta addr) vl2 = Some v2
  /\ Val.inject f v1 v2.
Proof.
  intros.
  rewrite eval_shift_stack_addressing.
  eapply eval_addressing_inj with (sp1 := Vptr sp1 Ptrofs.zero); eauto.
  intros. apply symbol_address_inject.
  econstructor; eauto. rewrite Ptrofs.add_zero_l; auto.
Qed.

Lemma eval_operation_inject:
  forall op vl1 vl2 v1 m1 m2,
  Val.inject_list f vl1 vl2 ->
  Mem.inject f m1 m2 ->
  eval_operation genv (Vptr sp1 Ptrofs.zero) op vl1 m1 = Some v1 ->
  exists v2,
     eval_operation genv (Vptr sp2 Ptrofs.zero) (shift_stack_operation delta op) vl2 m2 = Some v2
  /\ Val.inject f v1 v2.
Proof.
  intros.
  rewrite eval_shift_stack_operation. simpl.
  eapply eval_operation_inj with (sp1 := Vptr sp1 Ptrofs.zero) (m1 := m1); eauto.
  intros; eapply Mem.valid_pointer_inject_val; eauto.
  intros; eapply Mem.weak_valid_pointer_inject_val; eauto.
  intros; eapply Mem.weak_valid_pointer_inject_no_overflow; eauto.
  intros; eapply Mem.different_pointers_inject; eauto.
  intros. apply symbol_address_inject.
  econstructor; eauto. rewrite Ptrofs.add_zero_l; auto.
Qed.

End EVAL_INJECT.

(** * Masks for rotate and mask instructions *)

(** Recognition of integers that are acceptable as immediate operands
  to the [rlwim] PowerPC instruction.  These integers are of the form
  [000011110000] or [111100001111], that is, a run of one bits
  surrounded by zero bits, or conversely.  We recognize these integers by
  running the following automaton on the bits.  The accepting states are
  2, 3, 4, 5, and 6.
<<
               0          1          0
              / \        / \        / \
              \ /        \ /        \ /
        -0--> [1] --1--> [2] --0--> [3]
       /
     [0]
       \
        -1--> [4] --0--> [5] --1--> [6]
              / \        / \        / \
              \ /        \ /        \ /
               1          0          1
>>
*)

Inductive rlw_state: Type :=
  | RLW_S0 : rlw_state
  | RLW_S1 : rlw_state
  | RLW_S2 : rlw_state
  | RLW_S3 : rlw_state
  | RLW_S4 : rlw_state
  | RLW_S5 : rlw_state
  | RLW_S6 : rlw_state
  | RLW_Sbad : rlw_state.

Definition rlw_transition (s: rlw_state) (b: bool) : rlw_state :=
  match s, b with
  | RLW_S0, false => RLW_S1
  | RLW_S0, true  => RLW_S4
  | RLW_S1, false => RLW_S1
  | RLW_S1, true  => RLW_S2
  | RLW_S2, false => RLW_S3
  | RLW_S2, true  => RLW_S2
  | RLW_S3, false => RLW_S3
  | RLW_S3, true  => RLW_Sbad
  | RLW_S4, false => RLW_S5
  | RLW_S4, true  => RLW_S4
  | RLW_S5, false => RLW_S5
  | RLW_S5, true  => RLW_S6
  | RLW_S6, false => RLW_Sbad
  | RLW_S6, true  => RLW_S6
  | RLW_Sbad, _ => RLW_Sbad
  end.

Definition rlw_accepting (s: rlw_state) : bool :=
  match s with
  | RLW_S0 => false
  | RLW_S1 => false
  | RLW_S2 => true
  | RLW_S3 => true
  | RLW_S4 => true
  | RLW_S5 => true
  | RLW_S6 => true
  | RLW_Sbad => false
  end.

Fixpoint is_rlw_mask_rec (n: nat) (s: rlw_state) (x: Z) {struct n} : bool :=
  match n with
  | O =>
      rlw_accepting s
  | S m =>
      is_rlw_mask_rec m (rlw_transition s (Z.odd x)) (Z.div2 x)
  end.

Definition is_rlw_mask (x: int) : bool :=
  is_rlw_mask_rec Int.wordsize RLW_S0 (Int.unsigned x).