Require Import Coq.Lists.List.
Import ListNotations.

Require Import Tactics.
Require Import Axioms.
Require Import Sigma.
Require Import Equality.
Require Import Sequence.
Require Import Relation.
Require Import Ordinal.
Require Import Syntax.
Require Import SimpSub.
Require Import Dynamic.
Require Import Ofe.
Require Import Uniform.
Require Import Intensional.
Require Import Candidate.
Require Import System.
Require Import Semantics.
Require Import SemanticsKnot.
Require Import Judgement.
Require Import Hygiene.
Require Import ProperClosed.
Require Import ProperFun.
Require Import Shut.

Require Import Equivalence.
Require Import SemanticsSimple.
Require Import Equivalences.
Require Import SoundHyp.
Require Import SoundSubstitution.
Require Import ProperEquiv.
Require Import Defined.
Require Import PageCode.
Require Import PageType.
Require Import Subsumption.

Local Ltac prove_hygiene :=
  repeat (first [ apply hygiene_shift_permit
                | apply hygiene_auto; cbn; repeat2 split; auto
                ]);
  eauto using hygiene_weaken, clo_min, hygiene_shift', hygiene_subst1;
  try (apply hygiene_var; cbn; auto; done).

Lemma lvinterp_nzero :
  lvinterp nzero (fin 0).
Proof.
exists 0.
split; auto.
exact natinterp_nzero.
Qed.

Definition zeropg : page :=
  mk_page (fin 0) (fin 0) (fin 0) (le_ord_zero _) (le_ord_zero _) (le_ord_refl _).

Lemma pginterp_nzero :
  pginterp nzero zeropg.
Proof.
exists (fin 0).
do2 3 split; auto.
exact lvinterp_nzero.
Qed.

Lemma sound_voidtp_formation :
  forall G,
    pseq G (deq voidtp voidtp (univ nzero)).
Proof.
cut
  (forall G, seq G (deq voidtp voidtp (univ nzero))).
  {
  intros Hsound G.
  exists 0; intros j Hj.
  simpsub.
  apply Hsound.
  }
intros G.
rewrite -> seq_univ.
intros i s s' Hs.
exists zeropg, (iubase (void_urel stop)).
simpsub.
do2 5 split; auto using pginterp_nzero;
apply interp_eval_refl; apply interp_void.
Qed.

Lemma sound_voidtp_elim_pre :
  forall G m n p q a,
    hygiene (ctxpred G) p
    -> hygiene (ctxpred G) q
    -> hygiene (ctxpred G) a
    -> seq G (deq m n voidtp)
    -> seq G (deq p q a).
Proof.
intros G m n p q a Hclp Hclq Hcla Hseq.
invertc Hseq; intro Hseq.
apply seq_i.
intros i s s' Hs.
so (Hseq _#3 Hs) as (R & Hvoid & _ & Hinh & _).
invert (basic_value_inv _#6 value_voidtp Hvoid).
intros <-.
destruct Hinh.
Qed.

Lemma sound_voidtp_elim :
  forall G m n p q a,
    pseq G (deq m n voidtp)
    -> pseq G (deq p q a).
Proof.
intros G m n p q a (i1 & Hseq).
so (shut_term _ G p) as (i2 & Hclp).
so (shut_term _ G q) as (i3 & Hclq).
so (shut_term _ G a) as (i4 & Hcla).
so (upper_bound_all 4 i1 i2 i3 i4) as (i & Hi1 & Hi2 & Hi3 & Hi4 & _).
exists i.
intros j Hj.
eapply sound_voidtp_elim_pre; eauto using le_trans.
Qed.

Lemma sound_unittp_kind_formation :
  forall G lv,
    pseq G (deq lv lv pagetp)
    -> pseq G (deq unittp unittp (kuniv lv)).
Proof.
intros G lv.
revert G.
refine (seq_pseq 0 1 [] _ _ _); cbn.
intros G Hseqlv.
rewrite -> seq_eqkind.
invertc Hseqlv; intro Hseqlv.
intros i s s' Hs.
so (Hseqlv _#3 Hs) as (R & Hpagetp & _ & Hlv & _).
so (interp_pagetp_invert _#7 Hpagetp Hlv) as (pg & Hlvl & Hlvr).
exists pg, qone, (iubase (unit_urel stop i)), (pginterp_lt_top _ _ Hlvl).
simpsub.
do2 9 split; auto;
try (apply kinterp_eval_refl; apply interp_kunit);
apply interp_eval_refl; apply interp_unit.
Qed.

Lemma sound_unittp_formation :
  forall G,
    pseq G (deq unittp unittp (univ nzero)).
Proof.
refine (seq_pseq 0 0 _ _); cbn.
intros G.
rewrite -> seq_univ.
intros i s s' Hs.
exists zeropg, (iubase (unit_urel stop i)).
simpsub.
do2 5 split; auto using pginterp_nzero;
apply interp_eval_refl; apply interp_unit.
Qed.

Lemma sound_unittp_intro_pre :
  forall G,
    seq G (deq triv triv unittp).
Proof.
intros G.
apply seq_i.
intros i s s' Hs.
exists (iubase (unit_urel stop i)).
simpsub.
do2 2 split; try (apply interp_eval_refl; apply interp_unit).
assert (rel (unit_urel stop i) i triv triv) as H.
  {
  do2 5 split; auto using star_refl; prove_hygiene.
  }
auto.
Qed.

Lemma sound_unittp_intro :
  forall G,
    pseq G (deq triv triv unittp).
Proof.
refine (seq_pseq 0 0 _ _); cbn.
intros G.
apply sound_unittp_intro_pre.
Qed.

Lemma sound_unittp_eta :
  forall G p,
    pseq G (deq p p unittp)
    -> pseq G (deq p triv unittp).
Proof.
intros G p.
revert G.
refine (seq_pseq 0 1 [] _ _ _); cbn.
intros G Hseq.
invertc Hseq; intro Hseq.
apply seq_i.
intros i s s' Hs.
so (Hseq _#3 Hs) as (R & Hunitl & Hunitr & Hp & _).
simpsubin Hunitl.
simpsubin Hunitr.
invert (basic_value_inv _#6 value_unittp Hunitl).
intros <-.
exists (iubase (unit_urel stop i)).
do2 4 split; auto.
  {
  simpsub.
  apply unit_urel_triv; auto.
  }

  {
  simpsub.
  destruct Hp as (_ & _ & Hclsp & _ & Hsteps & _).
  do2 5 split; auto using star_refl; try prove_hygiene.
  }
Qed.

Lemma sound_unittp_eta_hyp :
  forall G1 G2 m n b,
    pseq (substctx (dot triv id) G2 ++ G1) (deq m n (subst (under (length G2) (dot triv id)) b))
    -> pseq (G2 ++ hyp_tm unittp :: G1) (deq (subst (under (length G2) sh1) m) (subst (under (length G2) sh1) n) b).
Proof.
intros G1 G2 m n b Hseq.
eapply sound_property_eta_hyp; eauto.
intros s pg z i R H.
simpsubin H.
invert (basic_value_inv _#6 value_unittp H).
intros <-.
do 3 eexists.
reflexivity.
Qed.

Lemma sound_booltp_formation :
  forall G,
    pseq G (deq booltp booltp (univ nzero)).
Proof.
refine (seq_pseq 0 0 _ _).
cbn.
intros G.
rewrite -> seq_univ.
intros i s s' Hs.
exists zeropg, (iubase (bool_urel stop i)).
simpsub.
do2 5 split; auto using pginterp_nzero;
apply interp_eval_refl; apply interp_bool.
Qed.

Lemma sound_booltp_intro_btrue :
  forall G,
    pseq G (deq btrue btrue booltp).
Proof.
refine (seq_pseq 0 0 _ _).
intros G.
apply seq_i.
intros i s s' Hs.
exists (iubase (bool_urel stop i)).
simpsub.
do2 2 split;
try (apply interp_eval_refl; apply interp_bool).
assert (rel (bool_urel stop i) i btrue btrue) as H.
  {
  do2 3 split; auto; try prove_hygiene.
  left.
  split; apply star_refl.
  }
auto.
Qed.

Lemma sound_booltp_intro_bfalse :
  forall G,
    pseq G (deq bfalse bfalse booltp).
Proof.
refine (seq_pseq 0 0 _ _).
intros G.
apply seq_i.
intros i s s' Hs.
exists (iubase (bool_urel stop i)).
simpsub.
do2 2 split;
try (apply interp_eval_refl; apply interp_bool).
assert (rel (bool_urel stop i) i bfalse bfalse) as H.
  {
  do2 3 split; auto; try prove_hygiene.
  right.
  split; apply star_refl.
  }
auto.
Qed.

Lemma sound_booltp_elim_pre :
  forall G m n p q r s a,
    hygiene (ctxpred G) a
    -> hygiene (ctxpred G) m
    -> hygiene (ctxpred G) n
    -> hygiene (ctxpred G) p
    -> hygiene (ctxpred G) q
    -> hygiene (ctxpred G) r
    -> hygiene (ctxpred G) s
    -> seq G (deq m n booltp)
    -> seq G (deq p q (subst1 btrue a))
    -> seq G (deq r s (subst1 bfalse a))
    -> seq G (deq (bite m p r) (bite n q s) (subst1 m a)).
Proof.
intros G m n p q r t a Hcla Hclm Hcln Hclp Hclq Hclr Hclt Hseqmn Hseqpq Hseqrt.
invertc Hseqmn; intro Hseqmn.
invertc Hseqpq; intro Hseqpq.
invertc Hseqrt; intro Hseqrt.
apply seq_i.
intros i s s' Hs.
so (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').
so (Hseqmn _#3 Hs) as (R & Hbool & _ & Hm & Hn & Hmn).
simpsubin Hbool.
invert (basic_value_inv _#6 value_booltp Hbool).
intros <-.
destruct Hm as (_ & _ & _ & H).
destruct H as [(Hstepsml & Hstepsmr) | (Hstepsml & Hstepsmr)].
  {
  destruct Hn as (_ & _ & _ & H).
  destruct H as [(Hstepsnl & Hstepsnr) | (_ & Hstepsnr)].
  2:{
    exfalso.
    destruct Hmn as (_ & _ & _ & H).
    destruct H as [(_ & Hstepsnr') | (Hstepsml' & _)].
      {
      so (determinism_eval _#4 (conj Hstepsnr value_bfalse) (conj Hstepsnr' value_btrue)) as Heq.
      discriminate Heq.
      }

      {
      so (determinism_eval _#4 (conj Hstepsml value_btrue) (conj Hstepsml' value_bfalse)) as Heq.
      discriminate Heq.
      }
    }
  assert (forall (x y z : sterm),
            star step x btrue
            -> equiv y (bite x y z)) as Hequiv.
    {
    intros x y z Hsteps.
    apply equiv_symm.
    eapply equiv_trans.
      {
      apply equiv_bite; [| apply equiv_refl ..].
      apply steps_equiv; eauto.
      }
    apply steps_equiv; apply star_one.
    apply step_bite2.
    }
  so (Hseqpq _#3 Hs) as (A & Hal & Har & Hp & Hq & Hpq).
  exists A.
  do2 4 split.
    {
    simpsub.
    eapply basic_equiv; eauto.
      {
      eapply hygiene_subst; eauto.
      intros j Hj.
      destruct j as [| j].
        {
        simpsub.
        eapply subst_closub; eauto.
        }
      simpsub.
      cbn in Hj.
      replace (project s j) with (subst s (var j)) by (simpsub; reflexivity).
      eapply subst_closub; eauto.
      apply hygiene_var.
      rewrite -> ctxpred_length in Hj |- *.
      omega.
      }

      {
      simpsub.
      apply equiv_funct; auto using equiv_refl.
      apply equivsub_dot; auto using equivsub_refl.
      apply equiv_symm.
      eapply steps_equiv; eauto.
      }
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
      {
      eapply hygiene_subst; eauto.
      intros j Hj.
      destruct j as [| j].
        {
        simpsub.
        eapply subst_closub; eauto.
        }
      simpsub.
      cbn in Hj.
      replace (project s' j) with (subst s' (var j)) by (simpsub; reflexivity).
      eapply subst_closub; eauto.
      apply hygiene_var.
      rewrite -> ctxpred_length in Hj |- *.
      omega.
      }

      {
      simpsub.
      apply equiv_funct; auto using equiv_refl.
      apply equivsub_dot; auto using equivsub_refl.
      apply equiv_symm.
      eapply steps_equiv; eauto.
      }
    }

    {
    simpsub.
    refine (urel_equiv _#7 _ _ _ _ Hp); try (prove_hygiene; eapply subst_closub; eauto).
    }

    {
    simpsub.
    refine (urel_equiv _#7 _ _ _ _ Hq); try (prove_hygiene; eapply subst_closub; eauto).
    }

    {
    simpsub.
    refine (urel_equiv _#7 _ _ _ _ Hpq); try (prove_hygiene; eapply subst_closub; eauto).
    }
  }

  {
  destruct Hn as (_ & _ & _ & H).
  destruct H as [(_ & Hstepsnr) | (Hstepsnl & Hstepsnr)].
    {
    exfalso.
    destruct Hmn as (_ & _ & _ & H).
    destruct H as [(Hstepsml' & _) | (_ & Hstepsnr')].
      {
      so (determinism_eval _#4 (conj Hstepsml value_bfalse) (conj Hstepsml' value_btrue)) as Heq.
      discriminate Heq.
      }

      {
      so (determinism_eval _#4 (conj Hstepsnr value_btrue) (conj Hstepsnr' value_bfalse)) as Heq.
      discriminate Heq.
      }
    }
  assert (forall (x y z : sterm),
            star step x bfalse
            -> equiv z (bite x y z)) as Hequiv.
    {
    intros x y z Hsteps.
    apply equiv_symm.
    eapply equiv_trans.
      {
      apply equiv_bite; [| apply equiv_refl ..].
      apply steps_equiv; eauto.
      }
    apply steps_equiv; apply star_one.
    apply step_bite3.
    }
  so (Hseqrt _#3 Hs) as (A & Hal & Har & Hp & Hq & Hpq).
  exists A.
  do2 4 split.
    {
    simpsub.
    eapply basic_equiv; eauto.
      {
      eapply hygiene_subst; eauto.
      intros j Hj.
      destruct j as [| j].
        {
        simpsub.
        eapply subst_closub; eauto.
        }
      simpsub.
      cbn in Hj.
      replace (project s j) with (subst s (var j)) by (simpsub; reflexivity).
      eapply subst_closub; eauto.
      apply hygiene_var.
      rewrite -> ctxpred_length in Hj |- *.
      omega.
      }

      {
      simpsub.
      apply equiv_funct; auto using equiv_refl.
      apply equivsub_dot; auto using equivsub_refl.
      apply equiv_symm.
      eapply steps_equiv; eauto.
      }
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
      {
      eapply hygiene_subst; eauto.
      intros j Hj.
      destruct j as [| j].
        {
        simpsub.
        eapply subst_closub; eauto.
        }
      simpsub.
      cbn in Hj.
      replace (project s' j) with (subst s' (var j)) by (simpsub; reflexivity).
      eapply subst_closub; eauto.
      apply hygiene_var.
      rewrite -> ctxpred_length in Hj |- *.
      omega.
      }

      {
      simpsub.
      apply equiv_funct; auto using equiv_refl.
      apply equivsub_dot; auto using equivsub_refl.
      apply equiv_symm.
      eapply steps_equiv; eauto.
      }
    }

    {
    simpsub.
    refine (urel_equiv _#7 _ _ _ _ Hp); try (prove_hygiene; eapply subst_closub; eauto).
    }

    {
    simpsub.
    refine (urel_equiv _#7 _ _ _ _ Hq); try (prove_hygiene; eapply subst_closub; eauto).
    }

    {
    simpsub.
    refine (urel_equiv _#7 _ _ _ _ Hpq); try (prove_hygiene; eapply subst_closub; eauto).
    }
  }
Qed.

Lemma sound_booltp_elim :
  forall G m n p q r s a,
    pseq G (deq m n booltp)
    -> pseq G (deq p q (subst1 btrue a))
    -> pseq G (deq r s (subst1 bfalse a))
    -> pseq G (deq (bite m p r) (bite n q s) (subst1 m a)).
Proof.
intros G m n p q r t a (i1, Hmn) (i2, Hpq) (i3, Hrt).
so (shut_term _ G m) as (i4, Hclm).
so (shut_term _ G n) as (i5, Hcln).
so (shut_term _ G p) as (i6, Hclp).
so (shut_term _ G q) as (i7, Hclq).
so (shut_term _ G r) as (i8, Hclr).
so (shut_term _ G t) as (i9, Hclt).
so (shut_term _ G a) as (i10, Hcla).
so (upper_bound_all 10 i1 i2 i3 i4 i5 i6 i7 i8 i9 i10) as (i & Hi1 & Hi2 & Hi3 & Hi4 & Hi5 & Hi6 & Hi7 & Hi8 & Hi9 & Hi10 & _).
exists i; intros j Hj.
eapply sound_booltp_elim_pre; eauto using le_trans.
Qed.

Lemma sound_booltp_elim_eqtype_pre :
  forall G m n p q r s,
    hygiene (ctxpred G) m
    -> hygiene (ctxpred G) n
    -> hygiene (ctxpred G) p
    -> hygiene (ctxpred G) q
    -> hygiene (ctxpred G) r
    -> hygiene (ctxpred G) s
    -> seq G (deq m n booltp)
    -> seq G (deqtype p q)
    -> seq G (deqtype r s)
    -> seq G (deqtype (bite m p r) (bite n q s)).
Proof.
intros G m n p q r t Hclm Hcln Hclp Hclq Hclr Hclt Hseqmn Hseqpq Hseqrt.
rewrite -> seq_eqtype in Hseqpq, Hseqrt |- *.
invertc Hseqmn; intro Hseqmn.
intros i s s' Hs.
so (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').
so (Hseqmn _#3 Hs) as (R & Hbool & _ & Hm & Hn & Hmn).
simpsubin Hbool.
invert (basic_value_inv _#6 value_booltp Hbool).
intros <-.
destruct Hm as (_ & _ & _ & H).
destruct H as [(Hstepsml & Hstepsmr) | (Hstepsml & Hstepsmr)].
  {
  destruct Hn as (_ & _ & _ & H).
  destruct H as [(Hstepsnl & Hstepsnr) | (_ & Hstepsnr)].
  2:{
    exfalso.
    destruct Hmn as (_ & _ & _ & H).
    destruct H as [(_ & Hstepsnr') | (Hstepsml' & _)].
      {
      so (determinism_eval _#4 (conj Hstepsnr value_bfalse) (conj Hstepsnr' value_btrue)) as Heq.
      discriminate Heq.
      }

      {
      so (determinism_eval _#4 (conj Hstepsml value_btrue) (conj Hstepsml' value_bfalse)) as Heq.
      discriminate Heq.
      }
    }
  assert (forall (x y z : sterm),
            star step x btrue
            -> equiv y (bite x y z)) as Hequiv.
    {
    intros x y z Hsteps.
    apply equiv_symm.
    eapply equiv_trans.
      {
      apply equiv_bite; [| apply equiv_refl ..].
      apply steps_equiv; eauto.
      }
    apply steps_equiv; apply star_one.
    apply step_bite2.
    }
  so (Hseqpq _#3 Hs) as (P & Hpl & Hpr & Hql & Hqr).
  exists P.
  do2 3 split.
    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }
  }

  {
  destruct Hn as (_ & _ & _ & H).
  destruct H as [(_ & Hstepsnr) | (Hstepsnl & Hstepsnr)].
    {
    exfalso.
    destruct Hmn as (_ & _ & _ & H).
    destruct H as [(Hstepsml' & _) | (_ & Hstepsnr')].
      {
      so (determinism_eval _#4 (conj Hstepsml value_bfalse) (conj Hstepsml' value_btrue)) as Heq.
      discriminate Heq.
      }

      {
      so (determinism_eval _#4 (conj Hstepsnr value_btrue) (conj Hstepsnr' value_bfalse)) as Heq.
      discriminate Heq.
      }
    }
  assert (forall (x y z : sterm),
            star step x bfalse
            -> equiv z (bite x y z)) as Hequiv.
    {
    intros x y z Hsteps.
    apply equiv_symm.
    eapply equiv_trans.
      {
      apply equiv_bite; [| apply equiv_refl ..].
      apply steps_equiv; eauto.
      }
    apply steps_equiv; apply star_one.
    apply step_bite3.
    }
  so (Hseqrt _#3 Hs) as (R & Hrl & Hrr & Htl & Htr).
  exists R.
  do2 3 split.
    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }

    {
    simpsub.
    eapply basic_equiv; eauto.
    prove_hygiene; eapply hygiene_subst; eauto.
    }
  }
Qed.

Lemma sound_booltp_elim_eqtype :
  forall G m n p q r s,
    pseq G (deq m n booltp)
    -> pseq G (deqtype p q)
    -> pseq G (deqtype r s)
    -> pseq G (deqtype (bite m p r) (bite n q s)).
Proof.
intros G m n p q r t (i1, Hmn) (i2, Hpq) (i3, Hrt).
so (shut_term _ G m) as (i4, Hclm).
so (shut_term _ G n) as (i5, Hcln).
so (shut_term _ G p) as (i6, Hclp).
so (shut_term _ G q) as (i7, Hclq).
so (shut_term _ G r) as (i8, Hclr).
so (shut_term _ G t) as (i9, Hclt).
so (upper_bound_all 9 i1 i2 i3 i4 i5 i6 i7 i8 i9) as (i & Hi1 & Hi2 & Hi3 & Hi4 & Hi5 & Hi6 & Hi7 & Hi8 & Hi9 & _).
exists i; intros j Hj.
eapply sound_booltp_elim_eqtype_pre; eauto using le_trans.
Qed.

Lemma equivsub_under_dot :
  forall object i (b : @term object) s,
    hygiene clo b
    -> star step (project s i) b
    -> equivsub (compose (under i (compose (dot b id) sh1)) s) s.
Proof.
intros object i b s Hclb Hsteps.
simpsub.
intro j.
rewrite -> project_compose.
so (lt_eq_lt_dec j i) as [[Hlt | Heq] | Hlt].
  {
  rewrite -> project_under_lt; auto.
  simpsub.
  apply equiv_refl.
  }

  {
  subst j.
  rewrite -> project_under_eq.
  simpsub.
  rewrite -> (subst_into_closed _ _ b); auto.
  apply equiv_symm.
  apply steps_equiv.
  exact Hsteps.
  }

  {
  rewrite -> project_under_geq; [| omega].
  replace (j - i) with (S (j - i - 1)) by omega.
  simpsub.
  replace (i + (1 + (j - i - 1))) with j by omega.
  apply equiv_refl.
  }
Qed.

Lemma sound_booltp_eta_hyp_pre :
  forall G1 G2 m n p q a,
    hygiene (ctxpred (substctx (dot btrue id) G2 ++ G1)) m
    -> hygiene (ctxpred (substctx (dot btrue id) G2 ++ G1)) n
    -> hygiene (ctxpred (substctx (dot bfalse id) G2 ++ G1)) p
    -> hygiene (ctxpred (substctx (dot bfalse id) G2 ++ G1)) q
    -> hygiene (ctxpred (G2 ++ hyp_tm booltp :: G1)) a
    -> seq (substctx (dot btrue id) G2 ++ G1) (deq m n (subst (under (length G2) (dot btrue id)) a))
    -> seq (substctx (dot bfalse id) G2 ++ G1) (deq p q (subst (under (length G2) (dot bfalse id)) a))
    -> seq (G2 ++ cons (hyp_tm booltp) G1)
         (deq
            (bite (var (length G2))
               (subst (under (length G2) sh1) m)
               (subst (under (length G2) sh1) p))
            (bite (var (length G2))
               (subst (under (length G2) sh1) n)
               (subst (under (length G2) sh1) q))
            a).
Proof.
intros G1 G2 m n p q a Hclm Hcln Hclp Hclq Hcla Hseqmn Hseqpq.
apply seq_i.
invertc Hseqmn; intro Hseqmn.
invertc Hseqpq; intro Hseqpq.
intros i s s' Hs.
assert (index (length G2) (G2 ++ hyp_tm booltp :: G1)%list (hyp_tm booltp)) as Hindex.
  {
  replace (length G2) with (0 + length G2) by omega.
  apply index_app_right.
  apply index_0.
  }
so (seqctx_index _#6 (pwctx_impl_seqctx _#4 Hs) Hindex) as Hhyp.
simpsubin Hhyp.
set (x := project s (length G2)) in Hhyp.
set (y := project s' (length G2)) in Hhyp.
invertc Hhyp.
intros R Hbool _ Hxy.
invert (basic_value_inv _#6 value_booltp Hbool).
intros <-.
clear Hbool Hindex.
destruct Hxy as (_ & Hclx & Hcly & Hxy).
assert (exists b,
          hygiene clo b
          /\ star step x b
          /\ star step y b
          /\ (forall j, rel (bool_urel stop j) j b b)
          /\ forall s s',
               pwctx i s s' (substctx (dot b id) G2 ++ G1)
               -> exists A,
                    interp toppg true i (subst s (subst (under (length G2) (dot b id)) a)) A
                    /\ interp toppg false i (subst s' (subst (under (length G2) (dot b id)) a)) A
                    /\ rel (den A) i (bite x (subst s m) (subst s p)) (bite y (subst s' m) (subst s' p))
                    /\ rel (den A) i (bite x (subst s n) (subst s q)) (bite y (subst s' n) (subst s' q))
                    /\ rel (den A) i (bite x (subst s m) (subst s p)) (bite y (subst s' n) (subst s' q))) as H.
  {
  destruct Hxy as [(Hstepsx & Hstepsy) | (Hstepsx & Hstepsy)].
    {
    exists btrue.
    do2 4 split; auto; try prove_hygiene.
      {
      intro j.
      do2 3 split; auto; try prove_hygiene.
      left; auto using star_refl.
      }

      {
      intros t t' Ht.
      so (pwctx_impl_closub _#4 Ht) as (Hclt & Hclt').
      rewrite -> ctxpred_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.
      rewrite -> app_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.
      rewrite -> length_substctx in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.
      so (Hseqmn i t t' Ht) as (R & Hl & Hr & Hm & Hn & Hmn).
      exists R.
      assert (forall z z', equiv z (bite x z z')) as Hequivx.
        {
        intros z z'.
        apply equiv_symm.
        apply steps_equiv.
        eapply star_trans.
          {
          apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.
          exact Hstepsx.
          }
        apply star_one.
        apply step_bite2.
        }
      assert (forall z z', equiv z (bite y z z')) as Hequivy.
        {
        intros z z'.
        apply equiv_symm.
        apply steps_equiv.
        eapply star_trans.
          {
          apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.
          exact Hstepsy.
          }
        apply star_one.
        apply step_bite2.
        }
      do2 4 split; auto.
        {
        refine (urel_equiv _#7 _ _ _ _ Hm); try prove_hygiene; eauto using subst_closub.
        }

        {
        refine (urel_equiv _#7 _ _ _ _ Hn); try prove_hygiene; eauto using subst_closub.
        }

        {
        refine (urel_equiv _#7 _ _ _ _ Hmn); try prove_hygiene; eauto using subst_closub.
        }
      }
    }

    {
    exists bfalse.
    do2 4 split; auto; try prove_hygiene.
      {
      intro j.
      do2 3 split; auto; try prove_hygiene.
      right; auto using star_refl.
      }

      {
      intros t t' Ht.
      so (pwctx_impl_closub _#4 Ht) as (Hclt & Hclt').
      rewrite -> ctxpred_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.
      rewrite -> app_length in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.
      rewrite -> length_substctx in Hclt, Hclt', Hclm, Hcln, Hclp, Hclq.
      so (Hseqpq i t t' Ht) as (R & Hl & Hr & Hp & Hq & Hpq).
      exists R.
      assert (forall z z', equiv z' (bite x z z')) as Hequivx.
        {
        intros z z'.
        apply equiv_symm.
        apply steps_equiv.
        eapply star_trans.
          {
          apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.
          exact Hstepsx.
          }
        apply star_one.
        apply step_bite3.
        }
      assert (forall z z', equiv z' (bite y z z')) as Hequivy.
        {
        intros z z'.
        apply equiv_symm.
        apply steps_equiv.
        eapply star_trans.
          {
          apply (star_map' _ _ (fun zz => bite zz _ _)); auto using step_bite1.
          exact Hstepsy.
          }
        apply star_one.
        apply step_bite3.
        }
      do2 4 split; auto.
        {
        refine (urel_equiv _#7 _ _ _ _ Hp); try prove_hygiene; eauto using subst_closub.
        }

        {
        refine (urel_equiv _#7 _ _ _ _ Hq); try prove_hygiene; eauto using subst_closub.
        }

        {
        refine (urel_equiv _#7 _ _ _ _ Hpq); try prove_hygiene; eauto using subst_closub.
        }
      }
    }
  }
clear Hclm Hcln Hclp Hclq Hseqmn Hseqpq Hxy.
destruct H as (b & Hclb & Hpb & Hqb & Hrelb & Hseq).
exploit (subst_pwctx G1 G2 booltp b i s s' (iubase (bool_urel stop i))) as Ht; auto.
  {
  intros j u u' Hu.
  exists (iubase (bool_urel stop j)).
  simpsub.
  do2 2 split.
    {
    apply interp_eval_refl.
    apply interp_bool.
    }

    {
    apply interp_eval_refl.
    apply interp_bool.
    }

    {
    rewrite -> !(subst_into_closed _ _ b); auto.
    apply Hrelb.
    }
  }

  {
  apply interp_eval_refl.
  apply interp_bool.
  }

  {
  apply interp_eval_refl.
  apply interp_bool.
  }

  {
  rewrite -> !(subst_into_closed _ _ b); auto.
  apply Hrelb.
  }

  {
  rewrite -> !(subst_into_closed _ _ b); auto.
  apply (urel_equiv_1 _#3 b); auto.
    {
    apply equiv_symm.
    apply steps_equiv; auto.
    }

    {
    apply Hrelb.
    }
  }
set (t := compose (under (length G2) sh1) s) in Ht.
set (t' := compose (under (length G2) sh1) s') in Ht.
so (Hseq _ _ Ht) as (A & Hal & Har & Hm & Hn & Hmn).
clear Hseq.
so (pwctx_impl_closub _#4 Hs) as (Hcls & Hcls').
exists A.
simpsub.
do2 4 split; auto.
  {
  eapply basic_equiv; eauto.
    {
    eapply subst_closub; eauto.
    }
  simpsub.
  unfold t.
  rewrite <- compose_assoc.
  rewrite <- compose_under.
  apply equiv_funct; auto using equiv_refl.
  apply equivsub_under_dot; auto.
 }

  {
  eapply basic_equiv; eauto.
    {
    eapply subst_closub; eauto.
    }
  simpsub.
  apply equiv_funct; auto using equiv_refl.
  unfold t'.
  rewrite <- compose_assoc.
  rewrite <- compose_under.
  apply equivsub_under_dot; auto.
  }
Qed.

Lemma sound_booltp_eta_hyp :
  forall G1 G2 m n p q a,
    pseq (substctx (dot btrue id) G2 ++ G1) (deq m n (subst (under (length G2) (dot btrue id)) a))
    -> pseq (substctx (dot bfalse id) G2 ++ G1) (deq p q (subst (under (length G2) (dot bfalse id)) a))
    -> pseq (G2 ++ cons (hyp_tm booltp) G1)
         (deq
            (bite (var (length G2))
               (subst (under (length G2) sh1) m)
               (subst (under (length G2) sh1) p))
            (bite (var (length G2))
               (subst (under (length G2) sh1) n)
               (subst (under (length G2) sh1) q))
            a).
Proof.
intros G1 G2 m n p q a (i1, Hmn) (i2, Hpq).
so (shut_term _ (substctx (dot btrue id) G2 ++ G1) m) as (i3, Hclm).
so (shut_term _ (substctx (dot btrue id) G2 ++ G1) n) as (i4, Hcln).
so (shut_term _ (substctx (dot bfalse id) G2 ++ G1) p) as (i5, Hclp).
so (shut_term _ (substctx (dot bfalse id) G2 ++ G1) q) as (i6, Hclq).
so (shut_term _ (G2 ++ hyp_tm booltp :: G1) a) as (i7, Hcla).
so (upper_bound_all 7 i1 i2 i3 i4 i5 i6 i7) as (i & Hi1 & Hi2 & Hi3 & Hi4 & Hi5 & Hi6 & Hi7 & _).
exists i; intros j Hj.
autorewrite with canonlist.
apply sound_booltp_eta_hyp_pre; finish_pseq j.
Qed.


Require Import Sem SimProg Skeleton Mod ModSem SimMod SimModSem SimSymb SimMem Sound SimSymb.
Require Import Simulation Ctypes Cop Ctyping Csyntax Clight.
Require SimMemId SimMemExt SimMemInj.
Require SoundTop UnreachC.
Require SimSymbId SimSymbDrop.
Require Import CoqlibC.
Require Import ValuesC.
Require Import LinkingC.
Require Import MapsC.
Require Import AxiomsC.
Require Import Ord.
Require Import MemoryC.
Require Import SmallstepC.
Require Import Events.
Require Import Preservation.
Require Import Integers.
Require Import LocationsC Conventions.

Require Import MatchSimModSem.
Require Import mktac.
Require Import IntegersC.
Require Import IdSimExtra ClightC.

Set Implicit Arguments.

Local Opaque Z.mul Z.add Z.sub Z.div.

Lemma clight_step_readonly se ge st0 st1 tr
      (STEP: step se ge (function_entry2 ge) st0 tr st1):
    Mem.unchanged_on (loc_not_writable (get_mem st0)) (get_mem st0) (get_mem st1).
Proof.
  inv STEP; ss; try refl; try (by eapply mem_free_list_readonly; eauto); try (by eapply external_call_readonly; eauto).
  - inv H2.
    + unfold Mem.storev in *. eapply mem_store_readonly; eauto.
    + eapply Mem.storebytes_unchanged_on; eauto. ii. unfold loc_not_writable in *.
      eapply H9. eapply Mem.perm_cur. eapply Mem.storebytes_range_perm; eauto.
  - inv H. eapply alloc_variables_unchanged_on; eauto.
Qed.

Definition match_env (j: meminj) (env_src env_tgt: env) :=
  forall id,
    (<<MAPPED: exists blk_src blk_tgt ty,
        (<<INJ: j blk_src = Some (blk_tgt, 0)>>) /\
        (<<BLKSRC: env_src ! id = Some (blk_src, ty)>>) /\
        (<<BLKTGT: env_tgt ! id = Some (blk_tgt, ty)>>)>>) \/
    (<<NOTMAPPED:
       (<<BLKSRC: env_src ! id = None>>) /\
       (<<BLKTGT: env_tgt ! id = None>>)>>).

Definition match_temp_env (j: meminj) (tenv_src tenv_tgt: temp_env) :=
  forall id,
    option_rel (Val.inject j) (tenv_src ! id) (tenv_tgt ! id).

Inductive match_cont (j: meminj): cont -> cont -> Prop :=
| match_Kstop:
    match_cont j Kstop Kstop
| match_Kseq
    stmt K_src K_tgt
    (CONT: match_cont j K_src K_tgt):
    match_cont j (Kseq stmt K_src) (Kseq stmt K_tgt)
| match_Kloop1
    stmt0 stmt1 K_src K_tgt
    (CONT: match_cont j K_src K_tgt):
    match_cont j (Kloop1 stmt0 stmt1 K_src) (Kloop1 stmt0 stmt1 K_tgt)
| match_Kloop2
    stmt0 stmt1 K_src K_tgt
    (CONT: match_cont j K_src K_tgt):
    match_cont j (Kloop2 stmt0 stmt1 K_src) (Kloop2 stmt0 stmt1 K_tgt)
| match_Kswitch
    K_src K_tgt
    (CONT: match_cont j K_src K_tgt):
    match_cont j (Kswitch K_src) (Kswitch K_tgt)
| match_Kcall
    id fn env_src env_tgt tenv_src tenv_tgt K_src K_tgt
    (ENV: match_env j env_src env_tgt)
    (TENV: match_temp_env j tenv_src tenv_tgt)
    (CONT: match_cont j K_src K_tgt):
    match_cont j (Kcall id fn env_src tenv_src K_src) (Kcall id fn env_tgt tenv_tgt K_tgt).

Inductive match_states_clight_internal:
  state -> state -> meminj -> mem -> mem -> Prop :=
| match_State
    fn stmt K_src K_tgt env_src env_tgt tenv_src tenv_tgt m_src m_tgt j
    (ENV: match_env j env_src env_tgt)
    (TENV: match_temp_env j tenv_src tenv_tgt)
    (CONT: match_cont j K_src K_tgt):
    match_states_clight_internal
      (State fn stmt K_src env_src tenv_src m_src)
      (State fn stmt K_tgt env_tgt tenv_tgt m_tgt)
      j m_src m_tgt
| match_Callstate
    fptr_src fptr_tgt ty args_src args_tgt K_src K_tgt m_src m_tgt j
    (INJ: Val.inject j fptr_src fptr_tgt)
    (VALS: Val.inject_list j args_src args_tgt)
    (CONT: match_cont j K_src K_tgt):
    match_states_clight_internal
      (Callstate fptr_src ty args_src K_src m_src)
      (Callstate fptr_tgt ty args_tgt K_tgt m_tgt)
      j m_src m_tgt
| match_Returnstate
    retv_src retv_tgt K_src K_tgt m_src m_tgt j
    (INJ: Val.inject j retv_src retv_tgt)
    (CONT: match_cont j K_src K_tgt):
    match_states_clight_internal
      (Returnstate retv_src K_src m_src)
      (Returnstate retv_tgt K_tgt m_tgt)
      j m_src m_tgt.

Inductive match_states_clight
  : unit -> state -> state -> SimMemInj.t' -> Prop :=
| match_states_clight_intro
    st_src st_tgt j m_src m_tgt sm0
    (MWFSRC: m_src = sm0.(SimMemInj.src))
    (MWFTGT: m_tgt = sm0.(SimMemInj.tgt))
    (MWFINJ: j = sm0.(SimMemInj.inj))
    (MATCHST: match_states_clight_internal st_src st_tgt j m_src m_tgt)
    (MWF: SimMemInj.wf' sm0):
    match_states_clight tt st_src st_tgt sm0.

Section CLIGHTINJ.

  Variable se_src se_tgt: Senv.t.
  Variable ge_src ge_tgt: genv.
  Hypothesis CENV: genv_cenv ge_src = genv_cenv ge_tgt.

  Definition function_entry_inject
             (function_entry: genv -> function -> list val -> mem -> env -> temp_env -> mem -> Prop) :=
      forall fn vs_src vs_tgt sm0 env_src tenv_src m_src1
        (MWF: SimMemInj.wf' sm0)
        (VALS: Val.inject_list sm0.(SimMemInj.inj) vs_src vs_tgt)
        (ENTRY: function_entry ge_src fn vs_src sm0.(SimMemInj.src) env_src tenv_src m_src1),
      exists env_tgt tenv_tgt sm1,
        (<<MEMSRC: SimMemInj.src sm1 = m_src1>>) /\
        (<<MWF: SimMemInj.wf' sm1>>) /\
        (<<ENV: match_env sm1.(SimMemInj.inj) env_src env_tgt>>) /\
        (<<TENV: match_temp_env sm1.(SimMemInj.inj) tenv_src tenv_tgt>>) /\
        (<<MLE: SimMemInj.le' sm0 sm1>>) /\
        (<<ENTRY: function_entry ge_tgt fn vs_tgt sm0.(SimMemInj.tgt) env_tgt tenv_tgt sm1.(SimMemInj.tgt)>>).

  Lemma alloc_variables_inject sm0 idl e_src0 e_tgt0 e_src1 m_src1
        (ALLOC: alloc_variables ge_src e_src0 (SimMemInj.src sm0) idl e_src1 m_src1)
        (ENV: match_env (SimMemInj.inj sm0) e_src0 e_tgt0)
        (MWF: SimMemInj.wf' sm0):
      exists e_tgt1 sm1,
        (<<MEMSRC: SimMemInj.src sm1 = m_src1>>) /\
        (<<MWF: SimMemInj.wf' sm1>>) /\
        (<<MLE: SimMemInj.le' sm0 sm1>>) /\
        (<<ENV: match_env (SimMemInj.inj sm1) e_src1 e_tgt1>>) /\
        (<<ALLOC: alloc_variables ge_tgt e_tgt0 (SimMemInj.tgt sm0) idl e_tgt1 (SimMemInj.tgt sm1)>>).
  Proof.
    revert sm0 MWF e_src0 e_tgt0 e_src1 m_src1 ENV ALLOC. induction idl.
    - i. inv ALLOC. esplits; eauto; try refl. econs.
    - i. inv ALLOC.
      exploit SimMemInj.alloc_parallel; eauto; try refl. i. des. clarify.
      exploit IHidl; eauto.
      { instantiate (1:=PTree.set id (blk_tgt, ty) e_tgt0).
        ii. repeat rewrite PTree.gsspec. des_ifs.
        - left. esplits; eauto.
        - destruct (ENV id0).
          + des. left. inv MLE. esplits; cycle 1; eauto.
          + right. eauto. }
      i. des. clarify. esplits; eauto; try etrans; eauto. econs; eauto. rewrite <- CENV. auto.
  Qed.

 Lemma assign_loc_inject ce ty sm0 blk_src blk_tgt ofs_src ofs_tgt v_src v_tgt m_src1
        (ASSIGN: assign_loc ce ty sm0.(SimMemInj.src) blk_src ofs_src v_src m_src1)
        (INJ: Val.inject sm0.(SimMemInj.inj) (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt))
        (VAL: Val.inject sm0.(SimMemInj.inj) v_src v_tgt)
        (MWF: SimMemInj.wf' sm0):
      exists sm1,
        (<<ASSIGN: assign_loc ce ty sm0.(SimMemInj.tgt) blk_tgt ofs_tgt v_tgt sm1.(SimMemInj.tgt)>>) /\
        (<<MEMSRC: SimMemInj.src sm1 = m_src1>>) /\
        (<<MWF: SimMemInj.wf' sm1>>) /\
        (<<MLE: SimMemInj.le' sm0 sm1>>).
  Proof.
    cinv MWF. inv ASSIGN.
    - exploit SimMemInj.storev_mapped; eauto. i. des. clarify. esplits; eauto. econs 1; eauto.
    - destruct (zeq (sizeof ce ty) 0).
      + cinv VAL. cinv INJ.
        assert (bytes = nil).
        { exploit (Mem.loadbytes_empty (SimMemInj.src sm0) b' (Ptrofs.unsigned ofs') (sizeof ce ty)).
          omega. congruence. } subst.
        destruct (Mem.range_perm_storebytes (SimMemInj.tgt sm0) blk_tgt (Ptrofs.unsigned (Ptrofs.add ofs_src (Ptrofs.repr delta0))) nil)
          as [tm' SB].
        { simpl. red; intros; omegaContradiction. }
        eexists (SimMemInj.mk _ tm' _ _ _ _ _ _ _); ss. esplits; cycle 3; eauto.
        * econs; ss; eauto; try (eapply Mem.storebytes_unchanged_on; eauto; i; ss; omega);
            try (ii; eapply Mem.perm_storebytes_2; eauto); try (econs; i; des; clarify).
       * econs 2; eauto; i; try omegaContradiction.
          { rewrite e; right; omega. }
          { apply Mem.loadbytes_empty. omega. }
        * inv MWF. econs; ss; eauto; try (erewrite Mem.nextblock_storebytes; eauto).
          { eapply Mem.storebytes_empty_inject; eauto. }
          { unfold SimMemInj.src_private, SimMemInj.valid_blocks, Mem.valid_block. ss.
            erewrite Mem.nextblock_storebytes; eauto. }
          { ii. exploit TGTEXT0; eauto.
            unfold SimMemInj.tgt_private, SimMemInj.valid_blocks, Mem.valid_block, loc_out_of_reach. ss.
            erewrite (@Mem.nextblock_storebytes _ _ _ _ _ SB). i.
            des_safe. split; eauto. ii.
            eapply H5; eauto. eapply Mem.perm_storebytes_2; eauto. }
      + assert (SZPOS: sizeof ce ty > 0).
        { generalize (sizeof_pos ce ty); omega. }
        cinv VAL. cinv INJ.
        assert (RPSRC: Mem.range_perm (SimMemInj.src sm0) b' (Ptrofs.unsigned ofs') (Ptrofs.unsigned ofs' + sizeof ce ty) Cur Nonempty).
        { eapply Mem.range_perm_implies; try eapply perm_any_N. eapply Mem.loadbytes_range_perm; eauto. }
        assert (RPDST: Mem.range_perm (SimMemInj.src sm0) blk_src (Ptrofs.unsigned ofs_src) (Ptrofs.unsigned ofs_src + sizeof ce ty) Cur Nonempty).
        { replace (sizeof ce ty) with (Z.of_nat (List.length bytes)).
          - eapply Mem.range_perm_implies; try eapply perm_any_N. eapply Mem.storebytes_range_perm; eauto.
          - exploit Mem.loadbytes_length; try apply H3; eauto. intros LEN.
            rewrite LEN. rewrite Z2Nat.id; try omega. }
        assert (PSRC: Mem.perm (SimMemInj.src sm0) b' (Ptrofs.unsigned ofs') Cur Nonempty) by (apply RPSRC; omega).
        assert (PDST: Mem.perm (SimMemInj.src sm0) blk_src (Ptrofs.unsigned ofs_src) Cur Nonempty) by (apply RPDST; omega).
        exploit Mem.address_inject; try apply PSRC; eauto. intros EQ1.
        exploit Mem.address_inject; try apply PDST; eauto. intros EQ2.
        exploit Mem.loadbytes_inject; eauto. intros [bytes2 [A B]].
        exploit SimMemInjC.storebytes_mapped; eauto. i. des_safe.
        exists sm1. splits; auto. econs 2; try rewrite EQ1; try rewrite EQ2; eauto.
        * intros; eapply Mem.aligned_area_inject with (m := SimMemInj.src sm0); eauto.
          { apply alignof_blockcopy_1248. }
          { apply sizeof_alignof_blockcopy_compat. }
        * intros; eapply Mem.aligned_area_inject with (m := SimMemInj.src sm0); eauto.
          { apply alignof_blockcopy_1248. }
          { apply sizeof_alignof_blockcopy_compat. }
        *  eapply Mem.disjoint_or_equal_inject with (m := SimMemInj.src sm0); eauto; apply Mem.range_perm_max with Cur; auto.
  Qed.

  Lemma call_cont_match j K_src K_tgt
        (MATCH: match_cont j K_src K_tgt):
      match_cont j (call_cont K_src) (call_cont K_tgt).
  Proof.
    revert K_tgt MATCH. induction K_src; ss; i; inv MATCH; ss; eauto; econs; eauto.
  Qed.

  Lemma match_env_incr j0 j1
        (INCR: inject_incr j0 j1):
      match_env j0 <2= match_env j1.
  Proof.
    ii. destruct (PR id).
    - des. left. esplits; eauto.
    - des. right. esplits; eauto.
  Qed.

  Lemma match_temp_env_incr j0 j1
        (INCR: inject_incr j0 j1):
      match_temp_env j0 <2= match_temp_env j1.
  Proof.
    ii. destruct (PR id); econs. eapply val_inject_incr; eauto.
  Qed.

  Lemma match_cont_incr j0 j1
        (INCR: inject_incr j0 j1):
      match_cont j0 <2= match_cont j1.
  Proof.
    ii. revert INCR. induction PR; i; econs; eauto; try by (eapply match_expr_incr; eauto).
    - eapply match_env_incr; eauto.
    - eapply match_temp_env_incr; eauto.
  Qed.

  Lemma bind_parameters_inject e_src e_tgt sm0 idl vargs_src vargs_tgt m_src1
        (BIND: bind_parameters ge_src e_src (SimMemInj.src sm0) idl vargs_src m_src1)
        (ENV: match_env (SimMemInj.inj sm0) e_src e_tgt)
        (MWF: SimMemInj.wf' sm0)
        (VALS: Val.inject_list (SimMemInj.inj sm0) vargs_src vargs_tgt):
      exists sm1,
        (<<MEMSRC: SimMemInj.src sm1 = m_src1>>) /\
        (<<MWF: SimMemInj.wf' sm1>>) /\
        (<<MLE: SimMemInj.le' sm0 sm1>>) /\
        (<<BIND: bind_parameters ge_tgt e_tgt (SimMemInj.tgt sm0) idl vargs_tgt (SimMemInj.tgt sm1)>>).
  Proof.
    revert sm0 ENV vargs_src vargs_tgt m_src1 MWF VALS BIND. induction idl.
    - i. inv BIND. inv VALS. esplits; eauto; try refl. econs.
    - i. inv BIND. inv VALS.
      destruct (ENV id); des; clarify.
      exploit assign_loc_inject; eauto. i. des. clarify.
      exploit IHidl; try apply H6; eauto.
      { inv MLE. eapply match_env_incr; eauto. }
      { inv MLE. eapply val_inject_list_incr; eauto. }
      i. des. esplits; eauto; try etrans; eauto. econs; eauto. rewrite CENV in *. auto.
  Qed.

  Lemma set_match_temp_env j id v_src v_tgt tenv_src tenv_tgt
        (TENV: match_temp_env j tenv_src tenv_tgt)
        (VAL: Val.inject j v_src v_tgt):
      match_temp_env j (PTree.set id v_src tenv_src) (PTree.set id v_tgt tenv_tgt).
  Proof.
    ii. repeat rewrite PTree.gsspec. des_ifs. econs; eauto.
  Qed.

  Lemma bind_parameter_temps_inject tenv_src0 tenv_tgt0 tenv_src1
        j idl vargs_src vargs_tgt
        (BIND: bind_parameter_temps idl vargs_src tenv_src0 = Some tenv_src1)
        (TENV: match_temp_env j tenv_src0 tenv_tgt0)
        (VALS: Val.inject_list j vargs_src vargs_tgt):
      exists tenv_tgt1,
        (<<BIND: bind_parameter_temps idl vargs_tgt tenv_tgt0 = Some tenv_tgt1>>) /\
        (<<TENV: match_temp_env j tenv_src1 tenv_tgt1>>).
  Proof.
    revert tenv_src0 tenv_tgt0 tenv_src1 vargs_src BIND TENV vargs_tgt VALS.
    induction idl; i; ss; des_ifs_safe; inv VALS; eauto.
    exploit IHidl; eauto. eapply set_match_temp_env; eauto.
  Qed.

  Lemma create_undef_temps_match j l:
      match_temp_env j (create_undef_temps l) (create_undef_temps l).
  Proof.
    induction l; ss.
    - ii. repeat rewrite PTree.gempty. econs.
    - ii. des_ifs. rewrite PTree.gsspec. des_ifs. econs. eauto.
  Qed.

  Lemma function_entry1_inject: function_entry_inject function_entry1.
  Proof.
    ii. inv ENTRY.
    exploit alloc_variables_inject; eauto.
    { instantiate (1:=empty_env). ii. right. unfold empty_env. repeat rewrite PTree.gempty. auto. }
    i. des. clarify.
    exploit bind_parameters_inject; eauto.
    { cinv MLE. eapply val_inject_list_incr; eauto. } i. des.
    esplits; eauto; try (by etrans; eauto); try by (econs; eauto).
    - cinv MLE. cinv MLE0. eapply match_env_incr; eauto.
    - eapply create_undef_temps_match.
  Qed.

  Lemma function_entry2_inject: function_entry_inject function_entry2.
  Proof.
    ii. inv ENTRY.
    exploit alloc_variables_inject; eauto.
    { instantiate (1:=empty_env). ii. right.
      unfold empty_env. repeat rewrite PTree.gempty. auto. }
    i. des. clarify.
    exploit bind_parameter_temps_inject; eauto.
    { eapply create_undef_temps_match. } i. des.
    esplits; eauto; try (econs; eauto). cinv MLE. eapply match_temp_env_incr; eauto.
  Qed.

  Variable function_entry: genv -> function -> list val -> mem -> env -> temp_env -> mem -> Prop.
  Hypothesis FUNCTIONENTRY: function_entry_inject function_entry.

  Lemma deref_loc_inject j ty m_src m_tgt blk_src blk_tgt ofs_src ofs_tgt v_src
        (DEREF: deref_loc ty m_src blk_src ofs_src v_src)
        (INJECT: Mem.inject j m_src m_tgt)
        (VAL: Val.inject j (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt)):
      exists v_tgt,
        (<<DEREF: deref_loc ty m_tgt blk_tgt ofs_tgt v_tgt>>) /\
        (<<VAL: Val.inject j v_src v_tgt>>).
  Proof.
    inv DEREF; try (by esplits; eauto; econs; eauto).
    exploit Mem.loadv_inject; eauto. i. des. esplits; eauto. econs 1; eauto.
  Qed.

  Lemma eval_expr_lvalue_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt
        (GENV: meminj_match_globals eq ge_src ge_tgt j):
      (forall exp v_src
          (EVAL: eval_expr ge_src env_src tenv_src m_src exp v_src),
          forall (ENV: match_env j env_src env_tgt)
            (TENV: match_temp_env j tenv_src tenv_tgt)
            (INJECT: Mem.inject j m_src m_tgt),
          exists v_tgt,
            (<<EVAL: eval_expr ge_tgt env_tgt tenv_tgt m_tgt exp v_tgt>>) /\
            (<<INJ: Val.inject j v_src v_tgt>>)) /\
      (forall exp blk_src ofs_src
          (EVAL: eval_lvalue ge_src env_src tenv_src m_src exp blk_src ofs_src),
          forall (ENV: match_env j env_src env_tgt)
            (TENV: match_temp_env j tenv_src tenv_tgt)
            (INJECT: Mem.inject j m_src m_tgt),
          exists blk_tgt ofs_tgt,
            (<<EVAL: eval_lvalue ge_tgt env_tgt tenv_tgt m_tgt exp blk_tgt ofs_tgt>>) /\
            (<<INJ: Val.inject j (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt)>>)).
  Proof.
    apply eval_expr_lvalue_ind; i; try (by esplits; eauto; econs; eauto).
    - cinv (TENV id); rewrite H in *; clarify. esplits; eauto. econs 5; eauto.
    - exploit H0; eauto. i. des. esplits; eauto. econs 6; eauto.
    - exploit H0; eauto. i. des. exploit sem_unary_operation_inject; eauto. i. des.
      esplits; eauto. econs 7; eauto.
    - exploit H0; eauto. i. des. exploit H2; eauto. i. des.
      exploit sem_binary_operation_inject; eauto. i. des.
      esplits; eauto. econs 8; eauto. rewrite <- CENV. auto.
    - exploit H0; eauto. i. des. exploit sem_cast_inject; eauto. i. des.
      esplits; eauto. econs 9; eauto.
    - esplits; eauto. rewrite CENV. econs 10; eauto.
    - esplits; eauto. rewrite CENV. econs 11; eauto.
    - exploit H0; eauto. i. des. exploit deref_loc_inject; eauto. i. des.
      esplits; eauto. econs 12; eauto.
    - cinv (ENV id); des; rewrite H in *; clarify. esplits; eauto. econs 1; eauto.
    - cinv (ENV id); des; rewrite H in *; clarify. inv GENV. exploit SYMBLE; eauto. i. des.
      esplits; eauto. econs 2; eauto.
    - exploit H0; eauto. i. des. cinv INJ. esplits; eauto. econs 3; eauto.
    - exploit H0; eauto. i. des. cinv INJ. rewrite CENV in *. esplits.
      + econs 4; eauto.
      + econs; eauto. repeat rewrite Ptrofs.add_assoc. f_equal. apply Ptrofs.add_commut.
    - exploit H0; eauto. i. des. cinv INJ. rewrite CENV in *. esplits; eauto. econs 5; eauto.
  Qed.

  Lemma eval_expr_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt exp v_src
        (EVAL: eval_expr ge_src env_src tenv_src m_src exp v_src)
        (GENV: meminj_match_globals eq ge_src ge_tgt j)
        (ENV: match_env j env_src env_tgt)
        (TENV: match_temp_env j tenv_src tenv_tgt)
        (INJECT: Mem.inject j m_src m_tgt):
      exists v_tgt,
        (<<EVAL: eval_expr ge_tgt env_tgt tenv_tgt m_tgt exp v_tgt>>) /\
        (<<INJ: Val.inject j v_src v_tgt>>).
  Proof.
    exploit eval_expr_lvalue_inject; eauto. i. des. eauto.
  Qed.

  Lemma eval_exprlist_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt tys
        exps vs_src
        (EVALS: eval_exprlist ge_src env_src tenv_src m_src exps tys vs_src)
        (GENV: meminj_match_globals eq ge_src ge_tgt j)
        (ENV: match_env j env_src env_tgt)
        (TENV: match_temp_env j tenv_src tenv_tgt)
        (INJECT: Mem.inject j m_src m_tgt):
      exists vs_tgt,
        (<<EVALS: eval_exprlist ge_tgt env_tgt tenv_tgt m_tgt exps tys vs_tgt>>) /\
        (<<INJ: Val.inject_list j vs_src vs_tgt>>).
  Proof.
    revert tys vs_src EVALS ENV TENV INJECT. induction exps; i.
    - inv EVALS. exists []. esplits; eauto. econs; eauto.
    - inv EVALS. exploit IHexps; eauto. i. des.
      exploit eval_expr_inject; eauto. i. des.
      exploit sem_cast_inject; eauto. i. des.
      exists (tv :: vs_tgt). esplits; eauto. econs; eauto.
  Qed.

  Lemma eval_lvalue_inject j env_src env_tgt tenv_src tenv_tgt m_src m_tgt exp blk_src ofs_src
        (EVAL: eval_lvalue ge_src env_src tenv_src m_src exp blk_src ofs_src)
        (GENV: meminj_match_globals eq ge_src ge_tgt j)
        (ENV: match_env j env_src env_tgt)
        (TENV: match_temp_env j tenv_src tenv_tgt)
        (INJECT: Mem.inject j m_src m_tgt):
      exists blk_tgt ofs_tgt,
        (<<EVAL: eval_lvalue ge_tgt env_tgt tenv_tgt m_tgt exp blk_tgt ofs_tgt>>) /\
        (<<INJ: Val.inject j (Vptr blk_src ofs_src) (Vptr blk_tgt ofs_tgt)>>).
  Proof.
    exploit eval_expr_lvalue_inject; eauto. i. des. eauto.
  Qed.

  Definition match_loc j (loc_src loc_tgt: block * Z * Z): Prop :=
    match loc_src with
    | (blk_src, lo_src, hi_src) =>
      match loc_tgt with
      | (blk_tgt, lo_tgt, hi_tgt) =>
        exists delta,
        (<<DELTA: j blk_src = Some (blk_tgt, delta)>>) /\
        (<<LO: lo_src + delta = lo_tgt>>) /\
        (<<HI: hi_src + delta = hi_tgt>>)
      end
    end.

  Lemma free_list_inject_parallel
        sm0 locs_src locs_tgt m_src1
        (MWF: SimMemInj.wf' sm0)
        (LOCS: list_forall2 (match_loc (SimMemInj.inj sm0)) locs_src locs_tgt)
        (FREE: Mem.free_list (SimMemInj.src sm0) locs_src = Some m_src1):
      exists sm1,
        (<<MEMSRC: SimMemInj.src sm1 = m_src1>>) /\
        (<<MWF: SimMemInj.wf' sm1>>) /\
        (<<MLE: SimMemInj.le' sm0 sm1>>) /\
        (<<FREE: Mem.free_list (SimMemInj.tgt sm0) locs_tgt = Some (SimMemInj.tgt sm1)>>).
  Proof.
    revert sm0 locs_tgt m_src1 MWF LOCS FREE. induction locs_src; ss.
    - i. clarify. inv LOCS. esplits; eauto. refl.
    - i. inv LOCS. unfold match_loc in H1. des_ifs. des. clarify. ss.
      exploit SimMemInj.free_parallel; eauto. i. des. clarify.
      exploit IHlocs_src; eauto.
      { eapply list_forall2_imply; eauto. i. unfold match_loc in *. des_ifs. des. inv MLE. esplits; eauto. }
      i. des. clarify. esplits; eauto; etrans; eauto. rewrite FREETGT. eauto.
  Qed.

  Lemma blocks_of_env_match j e_src e_tgt
        (ENV: match_env j e_src e_tgt):
      list_forall2 (match_loc j) (blocks_of_env ge_src e_src) (blocks_of_env ge_tgt e_tgt).
  Proof.
    set (R:=(fun (d_src d_tgt: block * type) =>
               let (b_src, t_src) := d_src in
               let (b_tgt, t_tgt) := d_tgt in
               (<<INJ: j b_src = Some (b_tgt, 0)>>) /\
               (<<TYSAME: t_src = t_tgt>>))).
    exploit PTree.elements_canonical_order.
    - instantiate (1:=R). instantiate (1:=e_tgt). instantiate (1:=e_src).
      i. destruct (ENV i); des; clarify. esplits; eauto. ss.
    - i. destruct (ENV i); des; clarify. esplits; eauto. ss.
    - intros ALL. unfold blocks_of_env. revert ALL.
      generalize (PTree.elements e_tgt). generalize (PTree.elements e_src).
      induction l; ss; i.
      + inv ALL. econs.
      + inv ALL. ss. econs; eauto. unfold block_of_binding. des_ifs; ss; des; clarify.
        esplits; eauto. rewrite CENV. zsimpl. auto.
  Qed.

  Scheme statement_ind2 := Induction for statement Sort Prop
    with labeled_statements_ind2 := Induction for labeled_statements Sort Prop.
  Combined Scheme statement_labeled_statements_ind from statement_ind2, labeled_statements_ind2.

  Lemma find_label_label_ls_match_none j lbl:
      (forall stmt,
          forall K_src0 K_tgt0
                 (LABEL: find_label lbl stmt K_src0 = None)
                 (CONT: match_cont j K_src0 K_tgt0),
            find_label lbl stmt K_tgt0 = None) /\
      (forall ls,
          forall K_src0 K_tgt0
                 (LABEL: find_label_ls lbl ls K_src0 = None)
                 (CONT: match_cont j K_src0 K_tgt0),
            find_label_ls lbl ls K_tgt0 = None).
  Proof.
    eapply statement_labeled_statements_ind; ss; i; try (by des_ifs_safe; erewrite H; eauto; econs; eauto).
    - des_ifs_safe. erewrite H; try econs; eauto. erewrite H0; try econs; eauto.
  Qed.

  Lemma find_label_match_none j lbl stmt K_src0 K_tgt0
        (LABEL: find_label lbl stmt K_src0 = None)
        (CONT: match_cont j K_src0 K_tgt0):
      find_label lbl stmt K_tgt0 = None.
  Proof.
    eapply find_label_label_ls_match_none; eauto.
  Qed.

  Lemma find_label_label_ls_match j lbl:
      (forall stmt K_src0 K_tgt0 stmt' K_src1
          (LABEL: find_label lbl stmt K_src0 = Some (stmt', K_src1))
          (CONT: match_cont j K_src0 K_tgt0),
          exists K_tgt1,
            (<<LABEL: find_label lbl stmt K_tgt0 = Some (stmt', K_tgt1)>>) /\
            (<<CONT: match_cont j K_src1 K_tgt1>>)) /\
      (forall ls K_src0 K_tgt0 stmt' K_src1
          (LABEL: find_label_ls lbl ls K_src0 = Some (stmt', K_src1))
          (CONT: match_cont j K_src0 K_tgt0),
          exists K_tgt1,
            (<<LABEL: find_label_ls lbl ls K_tgt0 = Some (stmt', K_tgt1)>>) /\
            (<<CONT: match_cont j K_src1 K_tgt1>>)).
  Proof.
    eapply statement_labeled_statements_ind; ss; i.
    - destruct (find_label lbl s (Kseq s0 K_src0)) eqn:LABEL0.
      + clarify. exploit H; eauto.
        { econs; eauto. } i. des.
        rewrite LABEL. esplits; eauto.
      + exploit H0; eauto. i. des.
        exploit find_label_match_none; eauto.
        { econs; eauto. } intros LABEL2.
        rewrite LABEL1. rewrite LABEL2. esplits; eauto.
    - destruct (find_label lbl s K_src0) eqn:LABEL0.
      + clarify. exploit H; eauto. i. des. rewrite LABEL. esplits; eauto.
      + exploit find_label_match_none; eauto. intros LABEL1. rewrite LABEL1. exploit H0; eauto.
    - destruct (find_label lbl s (Kloop1 s s0 K_src0)) eqn:LABEL0.
      + clarify. exploit H; eauto.
        { econs; eauto. } i. des.
        rewrite LABEL. esplits; eauto.
      + exploit find_label_match_none; eauto.
        { econs; eauto. }
        intros LABEL1. rewrite LABEL1. exploit H0; eauto. econs; eauto.
    - exploit H; eauto. econs; eauto.
    - des_ifs.
      + esplits; eauto.
      + exploit H; eauto.
    - destruct (find_label lbl s (Kseq (seq_of_labeled_statement l) K_src0)) eqn:LABEL0.
      + clarify. exploit H; eauto.
        { econs; eauto. } i. des.
        rewrite LABEL. esplits; eauto.
      + exploit find_label_match_none; eauto.
        { econs; eauto. }
        intros LABEL1. rewrite LABEL1. exploit H0; eauto.
  Qed.

  Lemma find_label_match j lbl stmt K_src0 K_tgt0 stmt' K_src1
        (LABEL: find_label lbl stmt K_src0 = Some (stmt', K_src1))
        (CONT: match_cont j K_src0 K_tgt0):
      exists K_tgt1,
        (<<LABEL: find_label lbl stmt K_tgt0 = Some (stmt', K_tgt1)>>) /\
        (<<CONT: match_cont j K_src1 K_tgt1>>).
  Proof.
    eapply find_label_label_ls_match; eauto.
  Qed.

  Lemma clight_step_preserve_injection
        u st_src0 st_tgt0 st_src1 sm0 tr
        (SYMBOLS: symbols_inject (SimMemInj.inj sm0) se_src se_tgt)
        (GENV: meminj_match_globals eq ge_src ge_tgt (SimMemInj.inj sm0))
        (MATCH: match_states_clight u st_src0 st_tgt0 sm0)
        (STEP: step se_src ge_src (function_entry ge_src) st_src0 tr st_src1):
      exists st_tgt1 sm1,
        (<<STEP: step se_tgt ge_tgt (function_entry ge_tgt) st_tgt0 tr st_tgt1>>) /\
        (<<MATCH: match_states_clight u st_src1 st_tgt1 sm1>>) /\
        (<<MLE: SimMemInj.le' sm0 sm1>>).
  Proof.
    inv STEP; inv MATCH; inv MATCHST; try (by inv CONT; esplits; try refl; do 3 (econs; eauto)).
    - cinv MWF. exploit eval_expr_inject; eauto. i. des.
      exploit eval_lvalue_inject; eauto. i. des.
      exploit sem_cast_inject; eauto. i. des.
      exploit assign_loc_inject; eauto. i. des.
      rewrite CENV in *. esplits; eauto; econs; eauto. cinv MLE. econs; eauto.
      + eapply match_env_incr; eauto.
      + eapply match_temp_env_incr; eauto.
      + eapply match_cont_incr; eauto.

    - cinv MWF. exploit eval_expr_inject; eauto. i. des. esplits; try refl; econs; eauto.
      econs; eauto. eapply set_match_temp_env; eauto.

    - cinv MWF. exploit eval_exprlist_inject; eauto. i. des.
      exploit eval_expr_inject; eauto. i. des. esplits; try refl; do 3 (econs; eauto).

    - cinv MWF. exploit eval_exprlist_inject; eauto. i. des.
      exploit external_call_mem_inject_gen; eauto. i. des.
      exploit SimMemInjC.parallel_gen; eauto.
      { ii. eapply external_call_max_perm; eauto. }
      { ii. eapply external_call_max_perm; eauto. }
      i. des. esplits; eauto.
      + econs 4; eauto.
      + cinv MLE. econs; eauto. econs; eauto.
        * eapply match_env_incr; eauto.
        * unfold set_opttemp. des_ifs.
          { eapply set_match_temp_env; eauto. eapply match_temp_env_incr; eauto. }
          { eapply match_temp_env_incr; eauto. }
        * eapply match_cont_incr; eauto.

    - esplits; try refl; do 3 (econs; eauto).

    - cinv MWF. exploit eval_expr_inject; eauto. i. des.
      exploit bool_val_inject; eauto. i. esplits; try refl; do 2 (econs; eauto).

    - esplits; try refl; do 3 (econs; eauto).

    - exploit free_list_inject_parallel; eauto.
      { eapply blocks_of_env_match; eauto. } i. des.
      esplits; try econs 15; eauto. econs; eauto. clarify. econs; eauto. eapply call_cont_match; eauto.
      cinv MLE. eapply match_cont_incr; eauto.

    - cinv MWF. exploit eval_expr_inject; eauto. i. des.
      exploit sem_cast_inject; eauto. i. des.
      exploit free_list_inject_parallel; eauto.
      { eapply blocks_of_env_match; eauto. } i. des.
      esplits; try econs 16; eauto. econs; eauto. clarify. econs; eauto.
      + cinv MLE. eapply val_inject_incr; eauto.
      + eapply call_cont_match; eauto. cinv MLE. eapply match_cont_incr; eauto.

    - cinv MWF. exploit free_list_inject_parallel; eauto.
      { eapply blocks_of_env_match; eauto. } i. des.
      esplits; eauto.
      + econs 17; eauto. unfold is_call_cont in *. destruct CONT; clarify.
      + econs; eauto. clarify. econs; eauto. cinv MLE. eapply match_cont_incr; eauto.

    - cinv MWF. exploit eval_expr_inject; eauto. i. des.
      assert (SWITCH: sem_switch_arg v_tgt (typeof a) = Some n).
      { unfold sem_switch_arg in *. inv INJ; ss; clarify; des_ifs. }
      esplits; try refl; do 3 (econs; eauto).

    - exploit find_label_match; eauto.
      { eapply call_cont_match; eauto. } i. des.
      esplits; try refl; do 2 (econs; eauto).

    - exploit match_globals_find_funct; eauto. intros FPTRTGT.
      exploit FUNCTIONENTRY; eauto. i. des.
      esplits; try econs 23; eauto. econs; eauto. clarify. econs; eauto.
      cinv MLE. eapply match_cont_incr; eauto.

    - cinv MWF. exploit match_globals_find_funct; eauto. intros FPTRTGT.
      exploit external_call_mem_inject_gen; eauto. i. des.
      exploit SimMemInjC.parallel_gen; eauto.
      { ii. eapply external_call_max_perm; eauto. }
      { ii. eapply external_call_max_perm; eauto. }
      i. des. esplits; try econs 24; eauto.
      cinv MLE. econs; eauto. econs; eauto. eapply match_cont_incr; eauto.

    - inv CONT. esplits; try refl; econs; eauto. clarify. econs; eauto. destruct optid; ss.
      eapply set_match_temp_env; eauto.
  Qed.

  Lemma clight_step_preserve_injection2
        st_src0 st_tgt0 st_src1 j0 m_src0 m_tgt0 tr
        (SYMBOLS: symbols_inject j0 se_src se_tgt)
        (GENV: meminj_match_globals eq ge_src ge_tgt j0)
        (INJECT: Mem.inject j0 m_src0 m_tgt0)
        (MATCH: match_states_clight_internal st_src0 st_tgt0 j0 m_src0 m_tgt0)
        (STEP: step se_src ge_src (function_entry ge_src) st_src0 tr st_src1):
      exists st_tgt1 m_src1 m_tgt1 j1 ,
        (<<STEP: step se_tgt ge_tgt (function_entry ge_tgt) st_tgt0 tr st_tgt1>>) /\
        (<<MATCH: match_states_clight_internal st_src1 st_tgt1 j1 m_src1 m_tgt1>>) /\
        (<<INJECT: Mem.inject j1 m_src1 m_tgt1>>) /\
        (<<INCR: inject_incr j0 j1>>) /\
        (<<SEP: inject_separated j0 j1 m_src0 m_tgt0>>) /\
        (<<UNCHSRC: Mem.unchanged_on (loc_unmapped j0) m_src0 m_src1>>) /\
        (<<UNCHTGT: Mem.unchanged_on (loc_out_of_reach j0 m_src0) m_tgt0 m_tgt1>>) /\
        (<<MAXSRC: forall b ofs
            (VALID: Mem.valid_block m_src0 b),
            <<MAX: Mem.perm m_src1 b ofs Max <1= Mem.perm m_src0 b ofs Max>> >>) /\
        (<<MAXTGT: forall b ofs
            (VALID: Mem.valid_block m_tgt0 b),
            <<MAX: Mem.perm m_tgt1 b ofs Max <1= Mem.perm m_tgt0 b ofs Max>> >>).
  Proof.
    set (sm:=SimMemInj.mk
               m_src0 m_tgt0 j0
               (loc_unmapped j0 /2\ SimMemInj.valid_blocks m_src0)
               (loc_out_of_reach j0 m_src0 /2\ SimMemInj.valid_blocks m_tgt0)
               (Mem.nextblock m_src0)
               (Mem.nextblock m_tgt0) 1%positive 1%positive).
    assert (SYMBINJ: symbols_inject (SimMemInj.inj sm) se_src se_tgt) by eauto.
    exploit clight_step_preserve_injection; eauto; ss.
    - econs; eauto. econs; ss; eauto; try refl; try xomega.
    - i. des. destruct sm1.
      inv MATCH0. inv MLE. inv MWF. ss. esplits; eauto; try (eapply Mem.unchanged_on_implies; eauto; ii; ss).
      + inv FROZEN. ii. exploit NEW_IMPLIES_OUTSIDE; eauto. i. des.
        unfold Mem.valid_block. clear - OUTSIDE_SRC OUTSIDE_TGT. xomega.
  Qed.

End CLIGHTINJ.


(** * Induction: Proof by Induction *)

(** The next line imports all of our definitions from the
    previous chapter. *)

Require Export begriffs_Basics.

(** For it to work, you need to use [coqc] to compile [Basics.v]
    into [Basics.vo].  (This is like making a .class file from a .java
    file, or a .o file from a .c file.)

    Here are two ways to compile your code:

     - CoqIDE:

         Open [Basics.v].
         In the "Compile" menu, click on "Compile Buffer".

     - Command line:

         Run [coqc Basics.v]

    *)

(* ###################################################################### *)
(** * Naming Cases *)

(** The fact that there is no explicit command for moving from
    one branch of a case analysis to the next can make proof scripts
    rather hard to read.  In larger proofs, with nested case analyses,
    it can even become hard to stay oriented when you're sitting with
    Coq and stepping through the proof.  (Imagine trying to remember
    that the first five subgoals belong to the inner case analysis and
    the remaining seven cases are what remains of the outer one...)
    Disciplined use of indentation and comments can help, but a better
    way is to use the [Case] tactic. *)

(* [Case] is not built into Coq: we need to define it ourselves.
    There is no need to understand how it works -- you can just skip
    over the definition to the example that follows.  It uses some
    facilities of Coq that we have not discussed -- the string
    library (just for the concrete syntax of quoted strings) and the
    [Ltac] command, which allows us to declare custom tactics.  Kudos
    to Aaron Bohannon for this nice hack! *)

Require String. Open Scope string_scope.

Ltac move_to_top x :=
  match reverse goal with
  | H : _ |- _ => try move x after H
  end.

Tactic Notation "assert_eq" ident(x) constr(v) :=
  let H := fresh in
  assert (x = v) as H by reflexivity;
  clear H.

Tactic Notation "Case_aux" ident(x) constr(name) :=
  first [
    set (x := name); move_to_top x
  | assert_eq x name; move_to_top x
  | fail 1 "because we are working on a different case" ].

Tactic Notation "Case" constr(name) := Case_aux Case name.
Tactic Notation "SCase" constr(name) := Case_aux SCase name.
Tactic Notation "SSCase" constr(name) := Case_aux SSCase name.
Tactic Notation "SSSCase" constr(name) := Case_aux SSSCase name.
Tactic Notation "SSSSCase" constr(name) := Case_aux SSSSCase name.
Tactic Notation "SSSSSCase" constr(name) := Case_aux SSSSSCase name.
Tactic Notation "SSSSSSCase" constr(name) := Case_aux SSSSSSCase name.
Tactic Notation "SSSSSSSCase" constr(name) := Case_aux SSSSSSSCase name.
(** Here's an example of how [Case] is used.  Step through the
   following proof and observe how the context changes. *)

Theorem andb_true_elim1 : forall b c : bool,
  andb b c = true -> b = true.
Proof.
  intros b c H.
  destruct b.
  Case "b = true".  (* <----- here *)
    reflexivity.
  Case "b = false".  (* <---- and here *)
    rewrite <- H.
    reflexivity.
Qed.

(** [Case] does something very straightforward: It simply adds a
    string that we choose (tagged with the identifier "Case") to the
    context for the current goal.  When subgoals are generated, this
    string is carried over into their contexts.  When the last of
    these subgoals is finally proved and the next top-level goal
    becomes active, this string will no longer appear in the context
    and we will be able to see that the case where we introduced it is
    complete.  Also, as a sanity check, if we try to execute a new
    [Case] tactic while the string left by the previous one is still
    in the context, we get a nice clear error message.

    For nested case analyses (e.g., when we want to use a [destruct]
    to solve a goal that has itself been generated by a [destruct]),
    there is an [SCase] ("subcase") tactic. *)

(** **** Exercise: 2 stars (andb_true_elim2) *)
(** Prove [andb_true_elim2], marking cases (and subcases) when
    you use [destruct]. *)

Theorem andb_true_elim2 : forall b c : bool,
  andb b c = true -> c = true.
Proof.
  intros b c H.
  destruct c.
  Case "c = true".
    reflexivity.
  Case "c = false".
    rewrite <- H.
    destruct b.
    SCase "b = true".
      reflexivity.
    SCase "b = false".
      reflexivity.
Qed.

(** [] *)

(** There are no hard and fast rules for how proofs should be
    formatted in Coq -- in particular, where lines should be broken
    and how sections of the proof should be indented to indicate their
    nested structure.  However, if the places where multiple subgoals
    are generated are marked with explicit [Case] tactics placed at
    the beginning of lines, then the proof will be readable almost no
    matter what choices are made about other aspects of layout.

    This is a good place to mention one other piece of (possibly
    obvious) advice about line lengths.  Beginning Coq users sometimes
    tend to the extremes, either writing each tactic on its own line
    or entire proofs on one line.  Good style lies somewhere in the
    middle.  In particular, one reasonable convention is to limit
    yourself to 80-character lines.  Lines longer than this are hard
    to read and can be inconvenient to display and print.  Many
    editors have features that help enforce this. *)

(* ###################################################################### *)
(** * Proof by Induction *)

(** We proved in the last chapter that [0] is a neutral element
    for [+] on the left using a simple argument.  The fact that it is
    also a neutral element on the _right_... *)

Theorem plus_0_r_firsttry : forall n:nat,
  n + 0 = n.

(** ... cannot be proved in the same simple way.  Just applying
  [reflexivity] doesn't work: the [n] in [n + 0] is an arbitrary
  unknown number, so the [match] in the definition of [+] can't be
  simplified.  *)

Proof.
  intros n.
  simpl. (* Does nothing! *)
Abort.

(** And reasoning by cases using [destruct n] doesn't get us much
   further: the branch of the case analysis where we assume [n = 0]
   goes through, but in the branch where [n = S n'] for some [n'] we
   get stuck in exactly the same way.  We could use [destruct n'] to
   get one step further, but since [n] can be arbitrarily large, if we
   try to keep on like this we'll never be done. *)

Theorem plus_0_r_secondtry : forall n:nat,
  n + 0 = n.
Proof.
  intros n. destruct n as [| n'].
  Case "n = 0".
    reflexivity. (* so far so good... *)
  Case "n = S n'".
    simpl.       (* ...but here we are stuck again *)
Abort.

(** To prove such facts -- indeed, to prove most interesting
    facts about numbers, lists, and other inductively defined sets --
    we need a more powerful reasoning principle: _induction_.

    Recall (from high school) the principle of induction over natural
    numbers: If [P(n)] is some proposition involving a natural number
    [n] and we want to show that P holds for _all_ numbers [n], we can
    reason like this:
         - show that [P(O)] holds;
         - show that, for any [n'], if [P(n')] holds, then so does
           [P(S n')];
         - conclude that [P(n)] holds for all [n].

    In Coq, the steps are the same but the order is backwards: we
    begin with the goal of proving [P(n)] for all [n] and break it
    down (by applying the [induction] tactic) into two separate
    subgoals: first showing [P(O)] and then showing [P(n') -> P(S
    n')].  Here's how this works for the theorem we are trying to
    prove at the moment: *)

Theorem plus_0_r : forall n:nat, n + 0 = n.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".     reflexivity.
  Case "n = S n'".  simpl. rewrite -> IHn'. reflexivity.  Qed.

(** Like [destruct], the [induction] tactic takes an [as...]
    clause that specifies the names of the variables to be introduced
    in the subgoals.  In the first branch, [n] is replaced by [0] and
    the goal becomes [0 + 0 = 0], which follows by simplification.  In
    the second, [n] is replaced by [S n'] and the assumption [n' + 0 =
    n'] is added to the context (with the name [IHn'], i.e., the
    Induction Hypothesis for [n']).  The goal in this case becomes [(S
    n') + 0 = S n'], which simplifies to [S (n' + 0) = S n'], which in
    turn follows from the induction hypothesis. *)

Theorem minus_diag : forall n,
  minus n n = 0.
Proof.
  (* WORKED IN CLASS *)
  intros n. induction n as [| n'].
  Case "n = 0".
    simpl. reflexivity.
  Case "n = S n'".
    simpl. rewrite -> IHn'. reflexivity.  Qed.

(** **** Exercise: 2 stars (basic_induction) *)

(** Prove the following lemmas using induction. You might need
    previously proven results. *)

Theorem mult_0_r : forall n:nat,
  n * 0 = 0.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".  simpl. reflexivity.
  Case "n = S n'".
    simpl.  rewrite -> IHn'. reflexivity. Qed.

Theorem plus_n_Sm : forall n m : nat,
  S (n + m) = n + (S m).
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    simpl. reflexivity.
  Case "n = S n'".
    intros m. simpl. rewrite IHn'. reflexivity.
Qed.

Theorem plus_comm : forall n m : nat,
  n + m = m + n.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    simpl. intros m. rewrite plus_0_r. reflexivity.
  Case "n = S n'".
    intros m. rewrite <- plus_n_Sm.
    simpl. rewrite IHn'. reflexivity.
Qed.

Theorem plus_assoc : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  intros n. induction n as [| n'].
  Case "n = 0".
    simpl. reflexivity.
  Case "n = S n'".
    intros m p.
    simpl. rewrite -> IHn'. reflexivity.
Qed.

(** **** Exercise: 2 stars (double_plus) *)

(** Consider the following function, which doubles its argument: *)

Fixpoint double (n:nat) :=
  match n with
  | 0 => 0
  | S n' => S (S (double n'))
  end.

(** Use induction to prove this simple fact about [double]: *)

Lemma double_plus : forall n, double n = n + n .
Proof.
  intros n. induction n as [| n'].
  Case "n = 0". simpl. reflexivity.
  Case "n = S n'".
    simpl. rewrite IHn'.
           rewrite plus_n_Sm. reflexivity.
Qed.

(** **** Exercise: 1 star (destruct_induction) *)
(** Briefly explain the difference between the tactics
    [destruct] and [induction].

(* FILL IN HERE *)

*)
(** [] *)

(* ###################################################################### *)
(** * Proofs Within Proofs *)

(** In Coq, as in informal mathematics, large proofs are very
    often broken into a sequence of theorems, with later proofs
    referring to earlier theorems.  Occasionally, however, a proof
    will need some miscellaneous fact that is too trivial (and of too
    little general interest) to bother giving it its own top-level
    name.  In such cases, it is convenient to be able to simply state
    and prove the needed "sub-theorem" right at the point where it is
    used.  The [assert] tactic allows us to do this.  For example, our
    earlier proof of the [mult_0_plus] theorem referred to a previous
    theorem named [plus_O_n].  We can also use [assert] to state and
    prove [plus_O_n] in-line: *)

Theorem mult_0_plus' : forall n m : nat,
  (0 + n) * m = n * m.
Proof.
  intros n m.
  assert (H: 0 + n = n).
    Case "Proof of assertion". reflexivity.
  rewrite -> H.
  reflexivity.  Qed.

(** The [assert] tactic introduces two sub-goals.  The first is
    the assertion itself; by prefixing it with [H:] we name the
    assertion [H].  (Note that we could also name the assertion with
    [as] just as we did above with [destruct] and [induction], i.e.,
    [assert (0 + n = n) as H].  Also note that we mark the proof of
    this assertion with a [Case], both for readability and so that,
    when using Coq interactively, we can see when we're finished
    proving the assertion by observing when the ["Proof of assertion"]
    string disappears from the context.)  The second goal is the same
    as the one at the point where we invoke [assert], except that, in
    the context, we have the assumption [H] that [0 + n = n].  That
    is, [assert] generates one subgoal where we must prove the
    asserted fact and a second subgoal where we can use the asserted
    fact to make progress on whatever we were trying to prove in the
    first place. *)

(** Actually, [assert] will turn out to be handy in many sorts of
    situations.  For example, suppose we want to prove that [(n + m)
    + (p + q) = (m + n) + (p + q)]. The only difference between the
    two sides of the [=] is that the arguments [m] and [n] to the
    first inner [+] are swapped, so it seems we should be able to
    use the commutativity of addition ([plus_comm]) to rewrite one
    into the other.  However, the [rewrite] tactic is a little stupid
    about _where_ it applies the rewrite.  There are three uses of
    [+] here, and it turns out that doing [rewrite -> plus_comm]
    will affect only the _outer_ one. *)

Theorem plus_rearrange_firsttry : forall n m p q : nat,
  (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.

  assert (H: n + m = m + n).
    rewrite -> plus_comm. reflexivity.
  rewrite H. reflexivity.
Qed.

(** To get [plus_comm] to apply at the point where we want it, we can
    introduce a local lemma stating that [n + m = m + n] (for
    the particular [m] and [n] that we are talking about here), prove
    this lemma using [plus_comm], and then use this lemma to do the
    desired rewrite. *)

Theorem plus_rearrange : forall n m p q : nat,
  (n + m) + (p + q) = (m + n) + (p + q).
Proof.
  intros n m p q.
  assert (H: n + m = m + n).
    Case "Proof of assertion".
    rewrite -> plus_comm. reflexivity.
  rewrite -> H. reflexivity.  Qed.

(** **** Exercise: 4 stars (mult_comm) *)
(** Use [assert] to help prove this theorem.  You shouldn't need to
    use induction. *)

Theorem plus_swap : forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  intros m n p.
  assert (H: n + (m + p) = (n + m) + p).
    rewrite plus_assoc. reflexivity.
  assert (K: m + (n + p) = (m + n) + p).
    rewrite plus_assoc. reflexivity.
  rewrite H. rewrite K.
  assert (L: m + n = n + m).
    rewrite plus_comm. reflexivity.
  rewrite L. reflexivity.
Qed.

(** Now prove commutativity of multiplication.  (You will probably
    need to define and prove a separate subsidiary theorem to be used
    in the proof of this one.)  You may find that [plus_swap] comes in
    handy. *)

Theorem mult_1_r : forall n : nat,
  n * 1 = n.
Proof.
  induction n as [| n'].
  Case "base". simpl. reflexivity.
  Case "step". simpl. rewrite IHn'. reflexivity.
Qed.

Theorem mult_Sm : forall m n : nat,
  n * S m = n + n * m.
Proof.
  intros m n.
  induction n as [| n'].
    Case "base". simpl. reflexivity.
    Case "step". simpl. rewrite IHn'.
      rewrite plus_swap. reflexivity.
Qed.

Theorem mult_comm : forall m n : nat,
 m * n = n * m.
Proof.
  intros m n.
  induction m as [| m'].
    Case "base". rewrite mult_0_r. simpl. reflexivity.
    Case "step". simpl. rewrite mult_Sm. rewrite IHm'.
      reflexivity.
Qed.

(** **** Exercise: 2 stars, optional (evenb_n__oddb_Sn) *)

(** Prove the following simple fact: *)

Theorem evenb_n__oddb_Sn : forall n : nat,
  evenb n = negb (evenb (S n)).
Proof.
  intros n.
  induction n as [| n'].
    Case "base". simpl. reflexivity.
    Case "step". simpl.
      rewrite IHn'. rewrite negb_involutive.

      destruct n' as [| c].
      SCase "n' = 0". simpl. reflexivity.
      SCase "n' = S c". simpl. reflexivity.
Qed.

(* ###################################################################### *)
(** * More Exercises *)

(** **** Exercise: 3 stars, optional (more_exercises) *)
(** Take a piece of paper.  For each of the following theorems, first
    _think_ about whether (a) it can be proved using only
    simplification and rewriting, (b) it also requires case
    analysis ([destruct]), or (c) it also requires induction.  Write
    down your prediction.  Then fill in the proof.  (There is no need
    to turn in your piece of paper; this is just to encourage you to
    reflect before hacking!) *)

Theorem ble_nat_refl : forall n:nat,
  true = ble_nat n n.
Proof.
  intros n.
  induction n as [| n'].
    Case "base". simpl. reflexivity.
    Case "step". simpl. rewrite IHn'. reflexivity.
Qed.

Theorem zero_nbeq_S : forall n:nat,
  beq_nat 0 (S n) = false.
Proof.
  intros n.
  destruct n as [| n'].
    Case "0". simpl. reflexivity.
    Case "S n'". simpl. reflexivity.
Qed.

Theorem andb_false_r : forall b : bool,
  andb b false = false.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem plus_ble_compat_l : forall n m p : nat,
  ble_nat n m = true -> ble_nat (p + n) (p + m) = true.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem S_nbeq_0 : forall n:nat,
  beq_nat (S n) 0 = false.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem mult_1_l : forall n:nat, 1 * n = n.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem all3_spec : forall b c : bool,
    orb
      (andb b c)
      (orb (negb b)
               (negb c))
  = true.
Proof.
  (* FILL IN HERE *) Admitted.

Theorem mult_plus_distr_r : forall n m p : nat,
  (n + m) * p = (n * p) + (m * p).
Proof.
  (* FILL IN HERE *) Admitted.

Theorem mult_assoc : forall n m p : nat,
  n * (m * p) = (n * m) * p.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, optional (beq_nat_refl) *)
(** Prove the following theorem.  Putting [true] on the left-hand side
of the equality may seem odd, but this is how the theorem is stated in
the standard library, so we follow suit.  Since rewriting
works equally well in either direction, we will have no
problem using the theorem no matter which way we state it. *)

Theorem beq_nat_refl : forall n : nat,
  true = beq_nat n n.
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 2 stars, optional (plus_swap') *)
(** The [replace] tactic allows you to specify a particular subterm to
   rewrite and what you want it rewritten to.  More precisely,
   [replace (t) with (u)] replaces (all copies of) expression [t] in
   the goal by expression [u], and generates [t = u] as an additional
   subgoal. This is often useful when a plain [rewrite] acts on the wrong
   part of the goal.

   Use the [replace] tactic to do a proof of [plus_swap'], just like
   [plus_swap] but without needing [assert (n + m = m + n)].
*)

Theorem plus_swap' : forall n m p : nat,
  n + (m + p) = m + (n + p).
Proof.
  (* FILL IN HERE *) Admitted.
(** [] *)

(** **** Exercise: 3 stars (binary_commute) *)
(** Recall the [increment] and [binary-to-unary] functions that you
    wrote for the [binary] exercise in the [Basics] chapter.  Prove
    that these functions commute -- that is, incrementing a binary
    number and then converting it to unary yields the same result as
    first converting it to unary and then incrementing.

    (Before you start working on this exercise, please copy the
    definitions from your solution to the [binary] exercise here so
    that this file can be graded on its own.  If you find yourself
    wanting to change your original definitions to make the property
    easier to prove, feel free to do so.) *)

(* FILL IN HERE *)
(** [] *)

(** **** Exercise: 5 stars, advanced (binary_inverse) *)
(** This exercise is a continuation of the previous exercise about
    binary numbers.  You will need your definitions and theorems from
    the previous exercise to complete this one.

    (a) First, write a function to convert natural numbers to binary
        numbers.  Then prove that starting with any natural number,
        converting to binary, then converting back yields the same
        natural number you started with.

    (b) You might naturally think that we should also prove the
        opposite direction: that starting with a binary number,
        converting to a natural, and then back to binary yields the
        same number we started with.  However, it is not true!
        Explain what the problem is.

    (c) Define a function [normalize] from binary numbers to binary
        numbers such that for any binary number b, converting to a
        natural and then back to binary yields [(normalize b)].  Prove
        it.

    Again, feel free to change your earlier definitions if this helps
    here.
*)

(* FILL IN HERE *)
(** [] *)

(* ###################################################################### *)
(** * Advanced Material *)

(** ** Formal vs. Informal Proof *)

(** "Informal proofs are algorithms; formal proofs are code." *)

(** The question of what, exactly, constitutes a "proof" of a
    mathematical claim has challenged philosophers for millenia.  A
    rough and ready definition, though, could be this: a proof of a
    mathematical proposition [P] is a written (or spoken) text that
    instills in the reader or hearer the certainty that [P] is true.
    That is, a proof is an act of communication.

    Now, acts of communication may involve different sorts of readers.
    On one hand, the "reader" can be a program like Coq, in which case
    the "belief" that is instilled is a simple mechanical check that
    [P] can be derived from a certain set of formal logical rules, and
    the proof is a recipe that guides the program in performing this
    check.  Such recipes are _formal_ proofs.

    Alternatively, the reader can be a human being, in which case the
    proof will be written in English or some other natural language,
    thus necessarily _informal_.  Here, the criteria for success are
    less clearly specified.  A "good" proof is one that makes the
    reader believe [P].  But the same proof may be read by many
    different readers, some of whom may be convinced by a particular
    way of phrasing the argument, while others may not be.  One reader
    may be particularly pedantic, inexperienced, or just plain
    thick-headed; the only way to convince them will be to make the
    argument in painstaking detail.  But another reader, more familiar
    in the area, may find all this detail so overwhelming that they
    lose the overall thread.  All they want is to be told the main
    ideas, because it is easier to fill in the details for themselves.
    Ultimately, there is no universal standard, because there is no
    single way of writing an informal proof that is guaranteed to
    convince every conceivable reader.  In practice, however,
    mathematicians have developed a rich set of conventions and idioms
    for writing about complex mathematical objects that, within a
    certain community, make communication fairly reliable.  The
    conventions of this stylized form of communication give a fairly
    clear standard for judging proofs good or bad.

    Because we are using Coq in this course, we will be working
    heavily with formal proofs.  But this doesn't mean we can ignore
    the informal ones!  Formal proofs are useful in many ways, but
    they are _not_ very efficient ways of communicating ideas between
    human beings. *)

(** For example, here is a proof that addition is associative: *)

Theorem plus_assoc' : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof. intros n m p. induction n as [| n']. reflexivity.
  simpl. rewrite -> IHn'. reflexivity.  Qed.

(** Coq is perfectly happy with this as a proof.  For a human,
    however, it is difficult to make much sense of it.  If you're used
    to Coq you can probably step through the tactics one after the
    other in your mind and imagine the state of the context and goal
    stack at each point, but if the proof were even a little bit more
    complicated this would be next to impossible.  Instead, a
    mathematician might write it something like this: *)
(** - _Theorem_: For any [n], [m] and [p],
      n + (m + p) = (n + m) + p.
    _Proof_: By induction on [n].

    - First, suppose [n = 0].  We must show
        0 + (m + p) = (0 + m) + p.
      This follows directly from the definition of [+].

    - Next, suppose [n = S n'], where
        n' + (m + p) = (n' + m) + p.
      We must show
        (S n') + (m + p) = ((S n') + m) + p.
      By the definition of [+], this follows from
        S (n' + (m + p)) = S ((n' + m) + p),
      which is immediate from the induction hypothesis. [] *)

(** The overall form of the proof is basically similar.  This is
    no accident: Coq has been designed so that its [induction] tactic
    generates the same sub-goals, in the same order, as the bullet
    points that a mathematician would write.  But there are
    significant differences of detail: the formal proof is much more
    explicit in some ways (e.g., the use of [reflexivity]) but much
    less explicit in others (in particular, the "proof state" at any
    given point in the Coq proof is completely implicit, whereas the
    informal proof reminds the reader several times where things
    stand). *)

(** Here is a formal proof that shows the structure more
    clearly: *)

Theorem plus_assoc'' : forall n m p : nat,
  n + (m + p) = (n + m) + p.
Proof.
  intros n m p. induction n as [| n'].
  Case "n = 0".
    reflexivity.
  Case "n = S n'".
    simpl. rewrite -> IHn'. reflexivity.   Qed.

(** **** Exercise: 2 stars, advanced (plus_comm_informal) *)
(** Translate your solution for [plus_comm] into an informal proof. *)

(** Theorem: Addition is commutative.

    Proof: (* FILL IN HERE *)
[]
*)

(** **** Exercise: 2 stars, optional (beq_nat_refl_informal) *)
(** Write an informal proof of the following theorem, using the
    informal proof of [plus_assoc] as a model.  Don't just
    paraphrase the Coq tactics into English!

    Theorem: [true = beq_nat n n] for any [n].

    Proof: (* FILL IN HERE *)
[]
 *)

(* $Date: 2013-07-17 16:19:11 -0400 (Wed, 17 Jul 2013) $ *)


Require Import SpecDeps.
Require Import RData.
Require Import EventReplay.
Require Import MoverTypes.
Require Import Constants.
Require Import CommonLib.
Require Import TableWalk.Spec.
Require Import AbsAccessor.Spec.

Local Open Scope Z_scope.

Section Spec.

  Definition data_create_spec (g_rd: Pointer) (data_addr: Z64) (map_addr: Z64) (g_data': Pointer) (g_src: Pointer) (adt: RData) : option (RData * Z64) :=
    match map_addr, data_addr with
    | VZ64 map_addr, VZ64 data_addr =>
      rely is_int64 map_addr; rely is_int64 data_addr;
      let idx0 := __addr_to_idx map_addr 0 in
      let idx1 := __addr_to_idx map_addr 1 in
      let idx2 := __addr_to_idx map_addr 2 in
      let idx3 := __addr_to_idx map_addr 3 in
      let ret_idx := idx3 in
      rely (peq (base g_rd) ginfo_loc);
      rely (peq (base g_data') ginfo_loc);
      rely (peq (base g_src) ginfo_loc);
      rely prop_dec ((buffer (priv adt)) @ SLOT_RD = None);
      rely prop_dec ((buffer (priv adt)) @ SLOT_TABLE = None);
      rely prop_dec ((buffer (priv adt)) @ SLOT_DELEGATED = None);
      rely prop_dec ((buffer (priv adt)) @ SLOT_NS = None);
      let rd_gidx := (offset g_rd) in
      let data_gidx := offset g_data' in
      let src_gidx := offset g_src in
      let grd := (gs (share adt)) @ rd_gidx in
      rely prop_dec (__addr_to_gidx data_addr = data_gidx);
      rely (g_tag (ginfo grd) =? GRANULE_STATE_RD);
      rely prop_dec (glock grd = Some CPU_ID);
      let root_gidx := (g_rtt (gnorm grd)) in
      rely is_gidx rd_gidx; rely is_gidx root_gidx; rely is_gidx src_gidx; rely is_gidx data_gidx;
      when adt == query_oracle adt;
      (* hold root lock *)
      let adt := adt {log: EVT CPU_ID (ACQ root_gidx) :: log adt} in
      let groot := (gs (share adt)) @ root_gidx in
      rely (tbl_level (gaux groot) =? 0);
      rely prop_dec (glock groot = None);
      rely (g_tag (ginfo groot) =? GRANULE_STATE_TABLE);
      rely (gtype groot =? GRANULE_STATE_TABLE);
      (* walk deeper root *)
      let entry0 := (g_data (gnorm groot)) @ idx0 in
      rely is_int64 entry0;
      let phys0 := __entry_to_phys entry0 3 in
      let lv1_gidx := __addr_to_gidx phys0 in
      if (__entry_is_table entry0) && (GRANULE_ALIGNED phys0) && (is_gidx lv1_gidx) then
        (* level 1 valid, hold level 1 lock *)
        let adt := adt {log: EVT CPU_ID (REL root_gidx groot {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv1_gidx) :: log adt} in
        let glv1 := (gs (share adt)) @ lv1_gidx in
        rely prop_dec (glock glv1 = None);
        rely (tbl_level (gaux glv1) =? 1);
        (* walk deeper level 1 *)
        rely (g_tag (ginfo glv1) =? GRANULE_STATE_TABLE);
        rely (gtype glv1 =? GRANULE_STATE_TABLE);
        let entry1 := (g_data (gnorm glv1)) @ idx1 in
        rely is_int64 entry1;
        let phys1 := __entry_to_phys entry1 3 in
        let lv2_gidx := __addr_to_gidx phys1 in
        if (__entry_is_table entry1) && (GRANULE_ALIGNED phys1) && (is_gidx lv2_gidx) then
          (* level 2 valid, hold level 2 lock *)
          when adt == query_oracle adt;
          let adt := adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv2_gidx) :: log adt} in
          let glv2 := (gs (share adt)) @ lv2_gidx in
          rely (tbl_level (gaux glv2) =? 2);
          rely prop_dec (glock glv2 = None);
          (* walk deeper level 2 *)
          rely (g_tag (ginfo glv2) =? GRANULE_STATE_TABLE);
          rely (gtype glv2 =? GRANULE_STATE_TABLE);
          let entry2 := (g_data (gnorm glv2)) @ idx2 in
          rely is_int64 entry2;
          let phys2 := __entry_to_phys entry2 3 in
          let lv3_gidx := __addr_to_gidx phys2 in
          if (__entry_is_table entry2) && (GRANULE_ALIGNED phys2) && (is_gidx lv3_gidx) then
            (* level 2 valid, hold level 2 lock *)
            when adt == query_oracle adt;
            let adt := adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: EVT CPU_ID (ACQ lv3_gidx) :: log adt} in
            let glv3 := (gs (share adt)) @ lv3_gidx in
            rely prop_dec (glock glv3 = None);
            rely (tbl_level (gaux glv3) =? 3);
            let adt :=  adt {priv: (priv adt) {wi_llt: lv3_gidx} {wi_index: idx3}} in
            (* create data *)
            let llt_gidx := lv3_gidx in
            let idx := idx3 in
            let gn_llt := (gs (share adt)) @ llt_gidx in
            let gn_data := (gs (share adt)) @ data_gidx in
            let gn_src := (gs (share adt)) @ src_gidx in
            rely (g_tag (ginfo gn_llt) =? GRANULE_STATE_TABLE);
            rely (gtype gn_llt =? GRANULE_STATE_TABLE);
            rely (gtype gn_data =? GRANULE_STATE_DELEGATED);
            rely (g_tag (ginfo gn_src) =? GRANULE_STATE_NS);
            rely (gtype gn_src =? GRANULE_STATE_NS);
            rely prop_dec (glock gn_data = Some CPU_ID);
            rely (tbl_level (gaux gn_data) =? 0);
            let llt_pte := (g_data (gnorm gn_llt)) @ idx in
            rely is_int64 llt_pte;
            if PTE_TO_IPA_STATE llt_pte =? IPA_STATE_VACANT then
              let e := EVT CPU_ID (COPY_NS src_gidx (READ_DATA data_gidx)) in
              let gdata' := gn_data {gnorm: (gnorm gn_data) {g_data: g_data (gnorm gn_src)}}
                                    {gaux: mkAuxillaryVars 0 0 map_addr} in
              let pte_val := Z.lor (IPA_STATE_TO_PTE IPA_STATE_ABSENT) data_addr in
              let llt' := (g_data (gnorm gn_llt)) # idx == pte_val in
              let gllt' := gn_llt {ginfo : (ginfo gn_llt) {g_refcount : g_refcount (ginfo gn_llt) + 1}}
                                  {gnorm: (gnorm gn_llt) {g_data: llt'}} in
              let cp := EVT CPU_ID (COPY_NS src_gidx (READ_DATA data_gidx)) in
              Some (adt {log: EVT CPU_ID (REL llt_gidx gllt' {glock: Some CPU_ID}) :: cp :: log adt}
                        {share : (share adt) {gs : ((gs (share adt)) # data_gidx == gdata') # llt_gidx == gllt'}},
                    VZ64 0)
            else Some (adt {log: EVT CPU_ID (REL llt_gidx gn_llt {glock: Some CPU_ID}) :: log adt}, VZ64 1)
          else
            (* level 3 invalid *)
            Some (adt {log: EVT CPU_ID (REL lv2_gidx glv2 {glock: Some CPU_ID}) :: log adt}
                      {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)
        else
          (* level 2 invalid *)
          Some (adt {log: EVT CPU_ID (REL lv1_gidx glv1 {glock: Some CPU_ID}) :: log adt}
                    {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)
      else
        (* level 1 invalid *)
        Some (adt {log: EVT CPU_ID (REL root_gidx groot {glock: Some CPU_ID}) :: log adt}
                  {priv: (priv adt) {wi_llt: 0} {wi_index: ret_idx}}, VZ64 1)
    end.

End Spec.