Require Export vsSahlq_instant19.

Open Scope type_scope.

Lemma hopeful4_REV'_withex'_FULL : forall lP xn phi1 phi2,
  vsSahlq_ante phi1 = true ->
  uniform_pos phi2  ->
  is_in_pred_l (preds_in (ST (mimpl phi1 phi2) (Var xn))) lP = true ->
  existsT2 (lx : list FOvariable) (atm : SecOrder),
    (AT atm = true) *
    ((existsT rel,
      REL rel = true /\
      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir (replace_pred_l (list_closed_allFO (implSO
    (conjSO rel atm)
    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)
    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) lP) (Var (new_FOv_pp_pre2 atm)))) <->
  SOturnst W Iv Ip Ir (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP)) +

     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir (replace_pred_l (list_closed_allFO (implSO atm
    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)
    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l atm lP) (Var (new_FOv_pp_pre2 atm)))) <->
  SOturnst W Iv Ip Ir (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP))).
Proof.
  intros lP xn phi1 phi2 Hvs Hun Hin0.
  destruct (vsS_preprocessing_Step1_pre_againTRY'_withex' _ _ (Var xn) Hvs Hun)
    as [lv [atm [HAT [Hex [ [rel [HREL [Hin SOt]]]  | [Hin SOt]  ]]]]].
    exists lv. exists atm.
    apply pair. assumption.
    left. exists rel. apply conj. assumption.
    apply conj. assumption.
    intros W Iv Ip Ir.
split; intros H.
    apply hopeful3_REV with (alpha := (ST (mimpl phi1 phi2) (Var xn))) in H ;
      try assumption.
        apply lem_f3; assumption.
      apply uni_pos__SO. assumption.
      apply SOQFree_ST.

      apply att_allFO_x_ST.
      apply att_exFO_x_ST.
      apply closed_except_ST.
      apply x_occ_in_alpha_instant_cons_empty'.
        apply x_occ_in_alpha_ST.

      assert (is_in_pred_l
          (preds_in (implSO (conjSO rel atm) (ST phi2 (Var xn))))
          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.
        simpl. apply is_in_pred_l_2app.
        apply Hin. apply is_in_pred_l_refl.
      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).

      apply ex_P_occ_in_alpha_ST.

        apply hopeful3 with (alpha := (ST (mimpl phi1 phi2) (Var xn)));
      try assumption.
      apply uni_pos__SO. assumption.
      apply SOQFree_ST.

      apply att_allFO_x_ST.
      apply att_exFO_x_ST.
      apply closed_except_ST.
      apply x_occ_in_alpha_instant_cons_empty'.
        apply x_occ_in_alpha_ST.

      assert (is_in_pred_l
          (preds_in (implSO (conjSO rel atm) (ST phi2 (Var xn))))
          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.
        simpl. apply is_in_pred_l_2app.
        apply Hin. apply is_in_pred_l_refl.
      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).

      apply ex_P_occ_in_alpha_ST.

    exists lv. exists atm.
    apply pair. assumption.
    right.
    apply conj. assumption.
    intros W Iv Ip Ir.
split; intros H.
    apply hopeful3_REV_atm with (alpha := (ST (mimpl phi1 phi2) (Var xn))) in H;
      try assumption.
      apply lem_f3; assumption.

      apply uni_pos__SO. assumption.
      apply SOQFree_ST.

      apply att_allFO_x_ST.
      apply att_exFO_x_ST.
      apply closed_except_ST.
      apply x_occ_in_alpha_instant_cons_empty'.
        apply x_occ_in_alpha_ST.

      assert (is_in_pred_l
          (preds_in (implSO atm (ST phi2 (Var xn))))
          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.
        simpl. apply is_in_pred_l_2app.
        apply Hin. apply is_in_pred_l_refl.
      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).

      apply ex_P_occ_in_alpha_ST.

    apply hopeful3_atm with (alpha := (ST (mimpl phi1 phi2) (Var xn)));
      try assumption.
      apply uni_pos__SO. assumption.
      apply SOQFree_ST.

      apply att_allFO_x_ST.
      apply att_exFO_x_ST.
      apply closed_except_ST.
      apply x_occ_in_alpha_instant_cons_empty'.
        apply x_occ_in_alpha_ST.

      assert (is_in_pred_l
          (preds_in (implSO atm (ST phi2 (Var xn))))
          (preds_in (implSO (ST phi1 (Var xn)) (ST phi2 (Var xn)))) = true) as HH1.
        simpl. apply is_in_pred_l_2app.
        apply Hin. apply is_in_pred_l_refl.
      apply (is_in_pred_l_trans _ _ _ HH1 Hin0).

      apply ex_P_occ_in_alpha_ST.
Defined.

Lemma hopeful4_REV'_withex'_FULL_allFO : forall lP xn phi1 phi2,
  vsSahlq_ante phi1 = true ->
  uniform_pos phi2  ->
  is_in_pred_l (preds_in (ST (mimpl phi1 phi2) (Var xn))) lP = true ->
  existsT2 lx atm,
    (AT atm = true) *
    ((existsT rel,
      REL rel = true /\
      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO
    (conjSO rel atm)
    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)
    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) lP) (Var (new_FOv_pp_pre2 atm))))) <->
  SOturnst W Iv Ip Ir (allFO (Var xn) (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP))) +

     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO atm
    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)
    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l atm lP) (Var (new_FOv_pp_pre2 atm))))) <->
  SOturnst W Iv Ip Ir (allFO (Var xn) (list_closed_SO (ST (mimpl phi1 phi2) (Var xn)) lP)))).
Proof.
  intros lP xn phi1 phi2 H1 H2 H3.
  destruct (hopeful4_REV'_withex'_FULL lP xn phi1 phi2 H1 H2 H3) as [lx [atm [Hat [ [rel [Hrel [Hin SOt]]]| [Hin SOt] ]]]];
  exists lx; exists atm; apply pair; try assumption; [left | right].
    exists rel. apply conj. assumption. apply conj. assumption.
    intros.
    apply equiv_allFO with (W := W) (Iv := Iv) (Ip := Ip) (Ir := Ir) (x := (Var xn)) in SOt.
    assumption.

    apply conj. assumption. intros.
    apply equiv_allFO with (W := W) (Iv := Iv) (Ip := Ip) (Ir := Ir) (x := (Var xn)) in SOt.
    assumption.
Defined.

Lemma hopeful4_REV'_withex'_FULL_allFO_in : forall lP xn phi1 phi2,
  vsSahlq_ante phi1 = true ->
  uniform_pos phi2  ->
  is_in_pred_l (preds_in (ST (mimpl phi1 phi2) (Var xn))) lP = true ->
  existsT2 lx atm,
    (AT atm = true) *
    ((existsT rel,
      REL rel = true /\
      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO
    (conjSO rel atm)
    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)
    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) lP) (Var (new_FOv_pp_pre2 atm))))) <->
  SOturnst W Iv Ip Ir (list_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn))) lP)) +

     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO atm
    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)
    lP (list_Var (length lP) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l atm lP) (Var (new_FOv_pp_pre2 atm))))) <->
  SOturnst W Iv Ip Ir (list_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn))) lP))).
Proof.
  intros lP xn phi1 phi2 H1 H2 H3.
  destruct (hopeful4_REV'_withex'_FULL_allFO lP xn phi1 phi2 H1 H2 H3) as [lx [atm [Hat [ [rel [Hrel [Hin SOt]]]| [Hin SOt] ]]]];
  exists lx; exists atm; apply pair; try assumption; [left | right].
    exists rel. apply conj. assumption. apply conj. assumption.
    intros. split; intros HH. apply equiv_list_closed_SO_allFO.
      apply SOt. assumption.

      apply equiv_list_closed_SO_allFO in HH. apply SOt. assumption.

    apply conj. assumption. intros.
    split; intros HH. apply equiv_list_closed_SO_allFO.
      apply SOt. assumption.

      apply equiv_list_closed_SO_allFO in HH. apply SOt. assumption.
Defined.

Lemma vsSahlq_full_SO_pre : forall xn phi1 phi2,
  vsSahlq_ante phi1 = true ->
  uniform_pos phi2  ->
  existsT2 lx atm,
    (AT atm = true) *
    ((existsT rel,
      REL rel = true /\
      is_in_pred_l (preds_in (conjSO rel atm)) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,

  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO
    (conjSO rel atm)
    (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))) (Var xn)))))) lx)
    (preds_in (ST (mimpl phi1 phi2) (Var xn))) (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l (conjSO rel atm) (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm))))) <->
  SOturnst W Iv Ip Ir (uni_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn))))) +

     (is_in_pred_l (preds_in atm) (preds_in (ST phi1 (Var xn))) = true /\
forall W Iv Ip Ir,

  SOturnst W Iv Ip Ir (allFO (Var xn) (replace_pred_l (list_closed_allFO (implSO atm
    (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))
      (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))
      (rev_seq (S (max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))
        (length       (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn)))))) lx)
    (preds_in (ST (mimpl phi1 phi2) (Var xn))) (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm)))
    (vsS_syn_l (FOv_att_P_l atm (preds_in (ST (mimpl phi1 phi2) (Var xn)))) (Var (new_FOv_pp_pre2 atm))))) <->
  SOturnst W Iv Ip Ir (uni_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn)))))).
Proof.
  intros xn phi1 phi2 H1 H2. unfold uni_closed_SO in *. unfold uni_closed_SO.
  apply hopeful4_REV'_withex'_FULL_allFO_in; try assumption.
  simpl. apply is_in_pred_l_refl.
Defined.

Lemma vsSahlq_full_SO : forall xn phi1 phi2,
  vsSahlq_ante phi1 = true ->
  uniform_pos phi2  ->
  existsT (alpha : SecOrder),
is_unary_predless alpha = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir alpha <->
  SOturnst W Iv Ip Ir (uni_closed_SO (allFO (Var xn) (ST (mimpl phi1 phi2) (Var xn)))).
Proof.
  intros xn phi1 phi2 H1 H2.
  destruct (vsSahlq_full_SO_pre xn phi1 phi2 H1 H2) as  [lx [atm [Hat [[rel [Hrel [Hin SOt]]]| [Hin SOt] ]]]].
    exists (allFO (Var xn) (replace_pred_l
           (list_closed_allFO
              (implSO (conjSO rel atm)
                 (newnew_pre (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn)))
                    (rem_FOv
                       (FOvars_in (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn))))
                       (Var xn))
                    (rev_seq
                       (S (Nat.max (max_FOv (implSO (conjSO rel atm) (ST phi2 (Var xn)))) xn))
                       (length
                          (rem_FOv
                             (FOvars_in
                                (instant_cons_empty' (conjSO rel atm) (ST phi2 (Var xn))))
                             (Var xn)))))) lx) (preds_in (ST (mimpl phi1 phi2) (Var xn)))
           (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn))))
              (Var (new_FOv_pp_pre2 atm)))
           (vsS_syn_l (FOv_att_P_l (conjSO rel atm) (preds_in (ST (mimpl phi1 phi2) (Var xn))))
              (Var (new_FOv_pp_pre2 atm))))).
      apply conj.
apply is_un_predless_corresp; assumption.

      apply SOt.

    exists (allFO (Var xn) (replace_pred_l
           (list_closed_allFO
              (implSO atm
                 (newnew_pre (instant_cons_empty' atm (ST phi2 (Var xn)))
                    (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn)))) (Var xn))
                    (rev_seq (S (Nat.max (max_FOv (implSO atm (ST phi2 (Var xn)))) xn))
                       (length
                          (rem_FOv (FOvars_in (instant_cons_empty' atm (ST phi2 (Var xn))))
                             (Var xn)))))) lx) (preds_in (ST (mimpl phi1 phi2) (Var xn)))
           (list_Var (length (preds_in (ST (mimpl phi1 phi2) (Var xn))))
              (Var (new_FOv_pp_pre2 atm)))
           (vsS_syn_l (FOv_att_P_l atm (preds_in (ST (mimpl phi1 phi2) (Var xn))))
              (Var (new_FOv_pp_pre2 atm))))).
      apply conj.
apply is_un_predless_corresp_atm; assumption.
      apply SOt.
Defined.

Theorem vsSahlq_full_Modal_sep : forall phi1 phi2,
  vsSahlq_ante phi1 = true ->
  uniform_pos phi2  ->
  existsT (alpha : SecOrder),
is_unary_predless alpha = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir alpha <->
  mturnst_frame W Ir (mimpl phi1 phi2).
Proof.
  intros phi1 phi2 H1 H2.
  destruct (vsSahlq_full_SO 0 phi1 phi2 H1 H2) as [alpha [Hun SOt]].
  exists alpha. apply conj. assumption.
  intros. split; intros HH.
    apply (correctness_ST _ _ (Var 0) Iv Ip).
    apply SOt. assumption.

    apply SOt.
    apply (correctness_ST _ _ (Var 0) Iv Ip).
    assumption.
Defined.

Theorem vsSahlq_full_Modal : forall phi,
  vsSahlq phi ->
  existsT (alpha : SecOrder),
is_unary_predless alpha = true /\
forall W Iv Ip Ir,
  SOturnst W Iv Ip Ir alpha <->
  mturnst_frame W Ir phi.
Proof.
  intros phi H. destruct phi; try contradiction.
  simpl in H. case_eq (vsSahlq_ante phi1); intros Hs;
    rewrite Hs in *. 2 : contradiction.
  apply vsSahlq_full_Modal_sep; assumption.
Defined.

(* Print All Dependencies vsSahlq_full_Modal. *)


Require Import Rel.Definitions.
Require Import Rel.BasicFacts.
Require Import Rel.Monotone.
Require Import Util.Postfix.
Require Import Lang.BindingsFacts.
Set Implicit Arguments.

Ltac bind_let :=
  match goal with
  | [ |- ?n ⊨ 𝓣⟦ ?Ξ ⊢ ?T # ?E ⟧ _ _ _ _ _ _ _ _
              (tm_let ?t₁ ?s₁) (tm_let ?t₂ ?s₂) ] =>
    replace (tm_let t₁ s₁)
    with (ktx_plug (ktx_let ktx_hole s₁) t₁) by reflexivity ;
    replace (tm_let t₂ s₂)
    with (ktx_plug (ktx_let ktx_hole s₂) t₂) by reflexivity
  end.

Section section_ccompat_tm_app_let.

Context (EV LV : Set).
Context (Ξ : XEnv EV LV).
Context (δ₁ δ₂ : EV → eff0) (δ : EV → IRel 𝓤_Sig).
Context (ρ₁ ρ₂ : LV → lbl0) (ρ : LV → IRel 𝓣_Sig).
Context (S T : ty ∅ EV LV ∅) (E : eff ∅ EV LV ∅).

Lemma ccompat_tm_let n ξ₁ ξ₂ s₁ s₂ t₁ t₂ :
  n ⊨ 𝓣⟦ Ξ ⊢ S # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ s₁ s₂ → (
  n ⊨ ∀ᵢ ξ₁' ξ₂' (_ : postfix ξ₁ ξ₁') (_ : postfix ξ₂ ξ₂'),
      ∀ᵢ v₁ v₂,
      𝓥⟦ Ξ ⊢ S ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' v₁ v₂ ⇒
      𝓣⟦ Ξ ⊢ T # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁' ξ₂' (V_subst_tm v₁ t₁) (V_subst_tm v₂ t₂)
  ) →
  n ⊨ 𝓣⟦ Ξ ⊢ T # E ⟧ δ₁ δ₂ δ ρ₁ ρ₂ ρ ξ₁ ξ₂ (tm_let s₁ t₁) (tm_let s₂ t₂).
Proof.
intros Hs Ht.
bind_let.
eapply plug0 with (ξ₁ := ξ₁) (ξ₂ := ξ₂) ;
  [crush|crush| |apply postfix_refl|apply postfix_refl|exact Hs].
iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;
iintro v₁ ; iintro v₂ ; iintro Hv.
simpl ktx_plug.
eapply 𝓣_step_r ; [ apply step_let | ].
eapply 𝓣_step_l ; [ apply step_let | ].
iintro_later.

ielim_vars Ht ; [ | eassumption | eassumption ].
iespecialize Ht ; ispecialize Ht ; [ eassumption | ].
apply Ht.
Qed.

End section_ccompat_tm_app_let.

Section section_compat_tm_let.

Context (EV LV V : Set).
Context (Ξ : XEnv EV LV).
Context (Γ : V → ty ∅ EV LV ∅).
Context (S T : ty ∅ EV LV ∅).
Context (E : eff ∅ EV LV ∅).

Hint Resolve postfix_trans postfix_refl.

Lemma compat_ktx_let n T' E' K₁ K₂ t₁ t₂ :
  n ⊨ ⟦ Ξ Γ ⊢ K₁ ≼ˡᵒᵍ K₂ : T' # E' ⇢ S # E ⟧ →
  n ⊨ ⟦ Ξ (env_ext Γ S) ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E ⟧ →
  n ⊨ ⟦ Ξ Γ ⊢ (ktx_let K₁ t₁) ≼ˡᵒᵍ (ktx_let K₂ t₂) : T' # E' ⇢ T # E ⟧.
Proof.
intros HK Ht.
iintro ξ₁ ; iintro ξ₂ ;
iintro δ₁ ; iintro δ₂ ; iintro δ ;
iintro ρ₁ ; iintro ρ₂ ; iintro ρ ;
iintro γ₁ ; iintro γ₂.
iintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.
iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂'.
iintro r₁ ; iintro r₂ ; iintro Hr.

iespecialize HK.
ispecialize HK ; [ eassumption | ].
ispecialize HK ; [ eassumption | ].
ispecialize HK ; [ eassumption | ].
ispecialize HK ; [ eassumption | ].
ielim_vars HK ; [ | eassumption | eassumption ].
iespecialize HK ; ispecialize HK ; [ apply Hr | ].

simpl ktx_plug.
eapply ccompat_tm_let ; [ apply HK | ].
iintro ξ₁'' ; iintro ξ₂'' ; iintro Hξ₁'' ; iintro Hξ₂'' ;
iintro v₁ ; iintro v₂ ; iintro Hv.
ispecialize Ht ξ₁'' ; ispecialize Ht ξ₂'' ;
ispecialize Ht δ₁ ; ispecialize Ht δ₂ ; ispecialize Ht δ ;
ispecialize Ht ρ₁ ; ispecialize Ht ρ₂ ; ispecialize Ht ρ.
ispecialize Ht (env_ext γ₁ v₁) ; ispecialize Ht (env_ext γ₂ v₂).
iespecialize Ht.
ispecialize Ht.
{ iintro_prop ; eapply 𝜩_monotone ; eauto. }
ispecialize Ht.
{ eapply δ_is_closed_monotone ; eauto. }
ispecialize Ht.
{ iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto. }
ispecialize Ht.
{ iintro x ; destruct x ; simpl ; [ assumption | ].
  iespecialize Hγ ; eapply 𝓥_monotone ; [ | | apply Hγ ] ; eauto.
}
repeat erewrite V_bind_bind_tm ; try apply Ht.
{ intro x ; destruct x ; simpl ; [ reflexivity | ].
  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.
}
{ intro x ; destruct x ; simpl ; [ reflexivity | ].
  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.
}
Qed.

Lemma compat_tm_let n t₁ t₂ s₁ s₂ :
n ⊨ ⟦ Ξ (env_ext Γ S) ⊢ t₁ ≼ˡᵒᵍ t₂ : T # E ⟧ →
n ⊨ ⟦ Ξ Γ ⊢ s₁ ≼ˡᵒᵍ s₂ : S # E ⟧ →
n ⊨ ⟦ Ξ Γ ⊢ (tm_let s₁ t₁) ≼ˡᵒᵍ (tm_let s₂ t₂) : T # E ⟧.
Proof.
intros Ht Hs.
iintro ξ₁ ; iintro ξ₂ ;
iintro δ₁ ; iintro δ₂ ; iintro δ ;
iintro ρ₁ ; iintro ρ₂ ; iintro ρ ;
iintro γ₁ ; iintro γ₂.
iintro Hξ ; iintro Hδ ; iintro Hρ ; iintro Hγ.

iespecialize Hs.
ispecialize Hs ; [ eassumption | ].
ispecialize Hs ; [ eassumption | ].
ispecialize Hs ; [ eassumption | ].
ispecialize Hs ; [ eassumption | ].
simpl subst_tm.
eapply ccompat_tm_let ; [ apply Hs | ].

iintro ξ₁' ; iintro ξ₂' ; iintro Hξ₁' ; iintro Hξ₂' ;
iintro v₁ ; iintro v₂ ; iintro Hv.
ispecialize Ht ξ₁' ; ispecialize Ht ξ₂' ;
ispecialize Ht δ₁ ; ispecialize Ht δ₂ ; ispecialize Ht δ ;
ispecialize Ht ρ₁ ; ispecialize Ht ρ₂ ; ispecialize Ht ρ.
ispecialize Ht (env_ext γ₁ v₁) ; ispecialize Ht (env_ext γ₂ v₂).
iespecialize Ht.
ispecialize Ht.
{ iintro_prop ; eapply 𝜩_monotone ; eauto. }
ispecialize Ht.
{ eapply δ_is_closed_monotone ; eauto. }
ispecialize Ht.
{ iintro_prop ; eapply ρ₁ρ₂_are_closed_monotone ; eauto. }
ispecialize Ht.
{ iintro x ; destruct x ; simpl ; [ assumption | ].
  iespecialize Hγ ; eapply 𝓥_monotone ; [ | | apply Hγ ] ; eauto.
}
repeat erewrite V_bind_bind_tm ; try apply Ht.
{ intro x ; destruct x ; simpl ; [ reflexivity | ].
  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.
}
{ intro x ; destruct x ; simpl ; [ reflexivity | ].
  erewrite V_bind_map_val, V_bind_val_id, V_map_val_id ; reflexivity.
}

Qed.

End section_compat_tm_let.


Require Import bedrock2.NotationsCustomEntry.

Import Syntax Syntax.Coercions BinInt String List List.ListNotations.
Local Open Scope string_scope. Local Open Scope Z_scope. Local Open Scope list_scope.

Definition memswap := func! (x, y, n) {
  while n {
    vx = load1(x);
    vy = load1(y);
    store1(x, vy);
    store1(y, vx);

    x = x + $1;
    y = y + $1;
    n = n - $1;
    $(cmd.unset "vx");
    $(cmd.unset "vy")
  }
}.

Require Import bedrock2.WeakestPrecondition bedrock2.Semantics bedrock2.ProgramLogic.
Require Import coqutil.Word.Interface coqutil.Word.Bitwidth.
Require Import coqutil.Map.Interface bedrock2.Map.SeparationLogic.
Require Import bedrock2.ZnWords.
Import Coq.Init.Byte coqutil.Byte.
Local Notation string := String.string.

(*Require Import bedrock2.ptsto_bytes.*)
Local Notation "xs $@ a" := (Array.array ptsto (word.of_Z 1) a xs) (at level 10, format "xs $@ a").
Local Notation "m =* P" := ((P%sep) m) (at level 70, only parsing) (* experiment*).

Section WithParameters.
  Context {width} {BW: Bitwidth width}.
  Context {word: word.word width} {mem: map.map word byte} {locals: map.map string word}.
  Context {ext_spec: ExtSpec}.
  Import ProgramLogic.Coercions.

  Global Instance spec_of_memswap : spec_of "memswap" :=
    fnspec! "memswap" (x y n : word) / (xs ys : list byte) (R : mem -> Prop),
    { requires t m := m =* xs$@x * ys$@y * R /\
                      length xs = n :>Z /\ length ys = n :>Z;
      ensures t' m := m =* ys$@x * xs$@y * R /\ t=t' }.

  Context {word_ok: word.ok word} {mem_ok: map.ok mem} {locals_ok : map.ok locals}
    {env : map.map string (list string * list string * Syntax.cmd)} {env_ok : map.ok env}
    {ext_spec_ok : ext_spec.ok ext_spec}.

  Import coqutil.Tactics.letexists coqutil.Tactics.Tactics coqutil.Tactics.autoforward.
  Import coqutil.Word.Properties coqutil.Map.Properties.

  Local Ltac ZnWords := destruct width_cases; bedrock2.ZnWords.ZnWords.
  Lemma memswap_ok : program_logic_goal_for_function! memswap.
  Proof.
    repeat straightline.

    refine ((Loops.tailrec
      (HList.polymorphic_list.cons _
      (HList.polymorphic_list.cons _
      (HList.polymorphic_list.cons _
      HList.polymorphic_list.nil)))
      ["x";"y";"n"])
      (fun (v:nat) xs ys R t m x y n => PrimitivePair.pair.mk (
        m =* xs$@x * ys$@y * R /\ length xs = n :>Z /\ length ys = n :>Z /\ v = n :>Z)
      (fun                 T M (X Y N : word) => t = T /\ M =* ys$@x * xs$@y * R))
      lt
      _ _ _ _ _ _ _ _);
      (* TODO wrap this into a tactic with the previous refine *)
      cbn [HList.hlist.foralls HList.tuple.foralls
           HList.hlist.existss HList.tuple.existss
           HList.hlist.apply  HList.tuple.apply
           HList.hlist
           List.repeat Datatypes.length
           HList.polymorphic_list.repeat HList.polymorphic_list.length
           PrimitivePair.pair._1 PrimitivePair.pair._2] in *.
      { cbv [Loops.enforce]; cbn.
        subst l.
        repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split.
        { exact eq_refl. }
        { eapply map.map_ext; intros k.
          repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]).
          repeat (destruct String.eqb; trivial). } }
      { eapply Wf_nat.lt_wf. }
      { cbn; ssplit; try ecancel_assumption; eauto. }
      { intros ?v ?xs ?ys ?R ?t ?m ?x ?y ?n.
        repeat straightline.
        cbn in localsmap.
        eexists n0; split; cbv [expr expr_body localsmap get].
        { rewrite ?Properties.map.get_put_dec. exists n0; cbn. auto. }
        split; cycle 1.
        { intros Ht; rewrite Ht in *.
          intuition idtac; destruct xs0, ys0; cbn in *; try discriminate; try ecancel_assumption; eauto. }

        intros Ht.
        destruct xs0 as [|hxs xs0] in *, ys0 as [|hys ys0] in *;
          cbn [length Array.array] in *; try (cbn in *; congruence); [];

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.

        repeat straightline.
        letexists; split.
        { rewrite ?Properties.map.get_put_dec; exact eq_refl. }
        repeat straightline.

        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }
        repeat straightline.

        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0. rewrite ?Properties.map.get_put_dec; exact eq_refl. }
        repeat straightline.

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0 l1. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }

        repeat straightline.
        eapply WeakestPreconditionProperties.dexpr_expr.
        letexists; split.
        { subst l l0 l1 l2. rewrite ?Properties.map.get_put_dec; cbn. exact eq_refl. }

        eexists _, _, _.
        split.
        { cbv [Loops.enforce l l0 l1 l2]; cbn.
          repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec; cbn); split.
          { exact eq_refl. }
          { eapply map.map_ext; intros k.
            repeat (rewrite ?map.get_put_dec, ?map.get_remove_dec, ?map.get_empty; cbn -[String.eqb]).
            repeat (destruct String.eqb; trivial). } }
        eexists _, _, _, (length xs0); split; ssplit; try ecancel_assumption; try ZnWords.
        split.
        { cbn in *; ZnWords. }
        intuition idtac; repeat straightline_cleanup.
        subst v0 v1 v2 v3.
        pose proof byte.unsigned_range hxs.
        pose proof byte.unsigned_range hys.
        use_sep_assumption.
        rewrite !word.unsigned_of_Z_nowrap, !byte.of_Z_unsigned by ZnWords.
        cancel. }

      intuition idtac. cbn. eauto.
  Qed.
End WithParameters.


(******************************************************************************)
(** * Domains of the Power memory model *)
(******************************************************************************)

Require Import Classical List Relations Peano_dec Omega.
Require Import Hahn.
Require Import Basic Power_Events Power_Model.

Set Implicit Arguments.

Section Power_Locations.

Variable G : power_execution.

(* Basic *)
Notation "'acts'" := G.(acts).
Notation "'lab'" := G.(lab).
Notation "'sb'" := G.(sb).
Notation "'rf'" := G.(rf).
Notation "'mo'" := G.(mo).
Notation "'rmw'" := G.(rmw).
Notation "'data'" := G.(data).
Notation "'addr'" := G.(addr).
Notation "'ctrl'" := G.(ctrl).
Notation "'ctrl_isync'" := G.(ctrl_isync).
(* Events *)
Notation "'E'" := G.(E).
Notation "'R'" := G.(R).
Notation "'W'" := G.(W).
Notation "'F_sync'" := G.(F_sync).
Notation "'F_lwsync'" := G.(F_lwsync).
Notation "'RW'" := G.(RW).
Notation "'_WF'" := G.(_WF).
Notation "'F'" := G.(F).
(* Relations *)
Notation "'same_loc'" := G.(same_loc).
Notation "'deps'" := G.(deps).
Notation "'rb'" := G.(rb).
Notation "'rdw'" := G.(rdw).
Notation "'detour'" := G.(detour).
Notation "'ii0'" := G.(ii0).
Notation "'ci0'" := G.(ci0).
Notation "'cc0'" := G.(cc0).
Notation "'ii'" := G.(ii).
Notation "'ic'" := G.(ic).
Notation "'ci'" := G.(ci).
Notation "'cc'" := G.(cc).
Notation "'L'" := G.(L).
Notation "'Li'" := G.(Li).
Notation "'ii_alt'" := G.(ii_alt).
Notation "'ic_alt'" := G.(ic_alt).
Notation "'ci_alt'" := G.(ci_alt).
Notation "'cc_alt'" := G.(cc_alt).
Notation "'ppo'" := G.(ppo).
Notation "'sync'" := G.(sync).
Notation "'lwsync'" := G.(lwsync).
Notation "'fence'" := G.(fence).
Notation "'hb'" := G.(hb).
Notation "'prop1'" := G.(prop1).
Notation "'prop2'" := G.(prop2).
Notation "'prop'" := G.(prop).
Notation "'psbloc'" := G.(psbloc).
Notation "'eco'" := G.(eco).
(* Well-formed axioms *)
Notation "'WfDEPS'" := G.(WfDEPS).
Notation "'WfACTS'" := G.(WfACTS).
Notation "'WfSB'" := G.(WfSB).
Notation "'WfRF'" := G.(WfRF).
Notation "'WfMO'" := G.(WfMO).
Notation "'WfRMW'" := G.(WfRMW).
Notation "'Wf'" := G.(Wf).
(* Consistency *)
Notation "'PowerConsistent'" := G.(PowerConsistent).
(* Notation *)
Notation "'restrict_location'" := G.(restrict_location).
Notation "s ⌇ x" := (restrict_location s x) (at level 1).
Notation "rel |loc" := (rel ∩ same_loc) (at level 1).
Notation "a ∙" := (a ∩ same_thread) (at level 1, format "a ∙").
Notation "a ∘" := (a \ same_thread) (at level 1, format "a ∘").

Hypothesis WF: Wf.

Lemma rf_loc a b (RF: rf a b) : loc lab a = loc lab b.
Proof. by cdes WF; cdes WF_RF; apply RF_LOC. Qed.

Lemma mo_loc a b (MO: mo a b) : loc lab a = loc lab b.
Proof. by cdes WF; cdes WF_MO; apply MO_LOC. Qed.

Lemma rmw_loc a b (RMW: rmw a b) : loc lab a = loc lab b.
Proof. by cdes WF; cdes WF_RMW; apply RMW_LOC. Qed.

Lemma rb_loc a b (RB: rb a b) : loc lab a = loc lab b.
Proof.
  unfold Power_Model.rb in RB.
  unfolder in RB. destruct RB as [z [RF MO]].
  apply rf_loc in RF.
  apply mo_loc in MO.
  congruence.
Qed.

Hint Resolve rf_loc mo_loc rmw_loc rb_loc : locations.

Lemma eco_loc a b (ECO: eco a b) : loc lab a = loc lab b.
Proof.
  unfold Power_Model.eco in ECO; unfolder in ECO.
  desf; eauto with locations;
  (apply mo_loc in ECO + apply rb_loc in ECO);
  apply rf_loc in ECO0; congruence.
Qed.

Lemma Wa_implies_some_loc a (WA: W a) : loc lab a <> None.
Proof.
  unfold Power_Model.W, is_w in WA.
  remember (lab a) as l.
  destruct l; try contradiction.
  unfold loc.
  rewrite <- Heql.
  red; ins.
Qed.

Lemma writes_same_loc_implies_mo (CON: PowerConsistent) a b l
  (WA: (restrict_location W l) a) (WB: (restrict_location W l) b)
  (ACTA: In a acts) (ACTB: In b acts) (NEQ: a <> b) :
    mo a b \/ mo b a.
Proof.
  cdes WF; cdes WF_MO; clear - WF CON WA WB ACTA ACTB NEQ MO_ACT MO_LOC MO_TOT.
  assert (l <> None).
    by unfold Power_Model.restrict_location in *; desf; apply Wa_implies_some_loc.
  apply not_none_implies_some in H. desc.
  apply MO_TOT with x; splits; unfold Power_Model.restrict_location in *; desf; eauto.
Qed.

Lemma RW_has_loc a : RW a -> loc lab a <> None.
Proof.
  repeat autounfold with type_unfold; unfold set_union, is_r, is_w.
  ins; desf; unfold Power_Events.loc; desf.
Qed.

End Power_Locations.

(* Export Hints *)
Hint Resolve rf_loc mo_loc rmw_loc rb_loc eco_loc : locations.


(* seplog (c) AIST 2005-2013. R. Affeldt, N. Marti, et al. GNU GPLv3. *)
(* seplog (c) AIST 2014-2018. R. Affeldt et al. GNU GPLv3. *)
Require Import machine_int.
Import MachineInt.
Require Import mips_cmd.
Import expr_m.
Require Import multi_is_zero_u_prg pick_sign_prg copy_s_u_prg multi_lt_prg.
Require Import multi_zero_s_prg multi_sub_u_u_prg multi_add_u_u_prg copy_s_s_prg.

Local Open Scope mips_cmd_scope.

(** z <- x - y with z, x signed and y unsigned *)
Definition multi_sub_s_s_u0 rk rz rx ry a0 a1 a2 a3 a4 ret X Z :=
  lw Z four16 rz ;
  lw X four16 rx ;
  pick_sign rx a0 a1 ;
  If_bgez a1 Then (* 0 <= x ? *)
    If_beq a1, r0 Then (* x = 0 ? *)
      copy_s_u rk rz ry a0 a1 a2 a3 ;
      addiu a3 r0 zero16 ; (* no overflow *)
      subu a0 r0 rk ;
      sw a0 zero16 rz
    Else (* 0 < x *) (* NB: a1 = 1 *)
      multi_lt rk ry X a0 a1 ret a2 a3 a4 ;
      If_beq ret, r0 Then (* ry >= X ? *)
        If_beq a2, r0 Then (* Y = X *)
          multi_zero_s rz ; (* fix size *)
          addiu a3 r0 zero16 (* no overflow *)
        Else (* Y > X *)
          multi_sub_u_u rk ry X Z a0 a1 a2 a3 a4 ret;
          subu a0 r0 rk ;
          sw a0 zero16 rz (* fix size *)
      Else (* ry < X *)
        multi_sub_u_u rk X ry Z a0 a1 a2 a3 a4 ret;
        sw rk zero16 rz (* fix size *)
  Else (* x < 0 *)
    addiu a3 r0 one16 ;
    multi_add_u_u rk a3 X ry Z a0 a1 a2 ;
    mflo a3 ;
    subu a0 r0 rk ;
    sw a0 zero16 rz.

Definition multi_sub_s_s_u rk rz rx ry a0 a1 a2 a3 a4 ret X Z :=
  multi_is_zero_u rk ry a0 a1 a2 ;
  If_bne a2 , r0 Then (* y = 0 ? *)
    addiu a3 r0 zero16 (* no overflow *) ;
    copy_s_s rk rz rx a0 a1 a2 ret a4
  Else (* y <> 0 *)
    multi_sub_s_s_u0 rk rz rx ry a0 a1 a2 a3 a4 ret X Z.


Require Export DACandMAC.
Set Implicit Arguments.
Unset Strict Implicit.

Section Stat.

Variable s : SFSstate.

(*********************************************************************)
(*                             stat                                  *)
(*********************************************************************)

(*This operation outputs the UNIX security information stored in the *)
(*ACL of a given object. Note that in our model the only precondition*)
(*for this operation is that the user has DAC read                   *)
(*access to the object and not, as in the standar UNIX, execute      *)
(*access.                                                            *)

(*This function computes object's mode from the object's ACL by      *)
(*owner, group and AllGrp in UsersReaders, UsersWriters,             *)
(*GroupReaders and GroupWriters.                                     *)

Parameter comp_mode : AccessCtrlListData -> PERMS.

(*This record stores the security attributes present in a            *)
(*conventinoal i-node.                                               *)

Record stat_struct : Set := stat_fields
  {st_mode : PERMS; st_uid : SUBJECT; st_gid : GRPNAME}.

Inductive stat (u : SUBJECT) (o : OBJECT) :
SFSstate -> Exc stat_struct -> Prop :=
    StatOK :
      PreDACRead s u o ->
      stat u o s
        match facl (acl s) o with
        | None => None (A:=stat_struct)
        | Some y => Some (stat_fields (comp_mode y) (owner y) (group y))
        end.

End Stat.


(** * LogRel.AlgorithmicTypingProperties: properties of algorithmic typing. *)
From LogRel.AutoSubst Require Import core unscoped Ast Extra.
From LogRel Require Import Utils BasicAst Notations Context NormalForms Weakening UntypedReduction
  GenericTyping DeclarativeTyping DeclarativeInstance AlgorithmicTyping DeclarativeSubst TypeConstructorsInj BundledAlgorithmicTyping AlgorithmicConvProperties.
From LogRel Require Import LogicalRelation Validity Fundamental.
From LogRel.LogicalRelation Require Import Escape.
From LogRel.Substitution Require Import Properties Escape.

Import DeclarativeTypingProperties AlgorithmicTypingData BundledTypingData BundledIntermediateData IntermediateTypingProperties.

(** ** Completeness of algorithmic conversion *)
(** We use the intermediate instance derived in AlgorithmicConvProperties to get this result,
using the fundamental lemma. *)

Lemma algo_conv_complete Γ A B :
  [Γ |-[de] A ≅ B] ->
  [Γ |-[al] A ≅ B].
Proof.
  now intros [HΓ ? _ []%escapeEq]%Fundamental.
Qed.

(** ** Instance *)
(** Equipped with this equivalence, we easily derive our third instance. *)

Module AlgorithmicTypingProperties.
  Export BundledTypingData AlgorithmicConvProperties.

  #[local] Ltac intros_bn :=
    intros ;
    repeat match goal with | H : context [bn] |- _ => destruct H end ;
    econstructor ; try assumption.

  #[export, refine] Instance WfCtxAlgProperties : WfContextProperties (ta := bn) := {}.
  Proof.
    1-8: intros_bn.
    - now do 2 constructor.
    - constructor ; tea.
      now apply typing_sound.
    - now intros ? [].
  Qed.

  #[export, refine] Instance WfTypeAlgProperties : WfTypeProperties (ta := bn) := {}.
  Proof.
    - intros_bn.
      now eapply algo_typing_wk.
    - now intros * [? ?%typing_sound].
    - intros_bn.
      now econstructor.
    - intros_bn.
      now econstructor.
    - intros_bn.
      now econstructor.
    - intros_bn.
      now econstructor.
    - intros_bn.
      do 2 econstructor ; tea.
      now apply algo_conv_complete.
  Qed.

  #[export, refine] Instance TypingAlgProperties : TypingProperties (ta := bn) := {}.
  Proof.
    - intros_bn.
      + now eapply algo_typing_wk.
      + gen_typing.
    - intros * [?? ?%typing_sound] ; tea.
      now econstructor.
    - intros_bn.
      + now econstructor.
      + constructor.
        now eapply in_ctx_wf.
    - intros_bn.
      + do 2 econstructor ; tea.
        all: now eapply (redty_red (ta := de)), red_ty_compl_univ_r.
      + now do 2 econstructor.
    - intros_bn.
      + now econstructor.
      + econstructor ; tea.
        2: econstructor.
        all: boundary.
    - intros * [? ? ? (?&?&[])%red_ty_compl_prod_r] [].
      esplit ; tea.
      + do 2 econstructor ; tea.
        1: now eapply (redty_red (ta := de)).
        eapply algo_conv_complete.
        now etransitivity.
      + eapply typing_subst1 ; tea.
        econstructor.
        now eapply inf_conv_decl.
    - intros_bn.
      1: now econstructor.
      now do 2 econstructor.
    - intros_bn.
      1: now econstructor.
      now do 2 econstructor.
    - intros_bn.
      + do 2 econstructor ; tea.
        now eapply (redty_red (ta := de)), red_ty_compl_nat_r.
      + now do 2 econstructor.
    - intros_bn.
      1: econstructor ; tea.
      + econstructor ; tea.
        now eapply (redty_red (ta := de)), red_ty_compl_nat_r.
      + econstructor ; tea.
        now eapply algo_conv_complete.
      + econstructor ; tea.
        now eapply algo_conv_complete.
      + econstructor.
        eapply typing_subst1.
        1: eauto using inf_conv_decl.
        now eapply typing_sound.
    - intros_bn.
      1: econstructor.
      gen_typing.
    - intros_bn.
      1: econstructor ; tea.
      + econstructor ; tea.
        now eapply (redty_red (ta := de)), red_ty_compl_empty_r.
      + econstructor.
        eapply typing_subst1.
        1: eauto using inf_conv_decl.
        now eapply typing_sound.
    - intros_bn.
      1: eassumption.
      etransitivity ; tea.
      symmetry.
      eapply RedConvTyC, subject_reduction_type ; tea.
      now eapply typing_sound.
    - intros_bn.
      1: eassumption.
      etransitivity ; tea.
      now eapply conv_sound in bun_conv_ty.
  Qed.

  #[export, refine] Instance OneStepRedTermAlgProperties :
    OneStepRedTermProperties (ta := bn) := {}.
  Proof.
    intros_bn.
    2: econstructor.
    econstructor ; tea.
    - econstructor.
      1: now do 2 econstructor.
      econstructor ; tea.
      now eapply algo_conv_complete.
    - eapply typing_subst1 ; tea.
      econstructor.
      now eapply inf_conv_decl.
    - intros * HP Hz Hs.
      assert [|-[de] Γ] by (destruct Hz ; boundary).
      split ; tea.
      + eapply ty_natElim ; tea.
        econstructor ; tea.
        1: econstructor.
        now do 2 econstructor.
      + now constructor.
    - intros * HP Hz Hs [].
      assert [|-[de] Γ] by (destruct Hz ; boundary).
      split ; tea.
      + eapply ty_natElim ; tea.
        econstructor.
        * eassumption.
        * do 2 econstructor ; tea.
          now eapply (redty_red (ta := de)), red_ty_compl_nat_r.
        * now do 2 econstructor.
      + constructor.
  Qed.

  #[export, refine] Instance RedTermAlgProperties :
    RedTermProperties (ta := bn) := {}.
  Proof.
    - intros_bn.
      2: now apply credalg_wk.
      econstructor ; tea.
      1: now eapply algo_typing_wk.
      now eapply typing_wk.
    - intros * [? []].
      eapply subject_reduction ; tea.
      now eapply inf_conv_decl.
    - now intros * [].
    - intros * [] ; constructor; tea; now econstructor.
    - intros_bn.
      + eapply red_ty_compl_prod_r in bun_inf_conv_conv0 as (?&?&[]).
        econstructor ; tea.
        1: econstructor.
        * econstructor ; tea.
          now eapply (redty_red (ta := de)).
        * econstructor ; tea.
          eapply algo_conv_complete.
          now etransitivity.
        * eapply typing_subst1 ; tea.
          econstructor.
          now eapply inf_conv_decl.
      + clear -bun_red_tm.
        induction bun_red_tm ; econstructor.
        2: eassumption.
        now econstructor.
    - intros * [] [] [] [] [] ?.
      assert [Γ |-[al] n ▹h tNat].
      {
        econstructor ; tea.
        now eapply (redty_red (ta := de)), red_ty_compl_nat_r.
      }
      split ; tea.
      1: econstructor ; tea.
      1: econstructor ; tea.
      + econstructor ; tea.
        now eapply algo_conv_complete.
      + econstructor ; tea.
        now eapply algo_conv_complete.
      + econstructor.
        eapply typing_subst1.
        all: eapply typing_sound ; tea.
        2: now econstructor.
        econstructor ; tea.
        now eapply algo_conv_complete.
      + clear -bun_red_tm.
        induction bun_red_tm.
        1: now constructor.
        econstructor ; tea.
        now econstructor.
    - intros * [] [] [] ?.
      assert [Γ |-[al] n ▹h tEmpty].
      {
        econstructor ; tea.
        now eapply (redty_red (ta := de)), red_ty_compl_empty_r.
      }
      split ; tea.
      1: econstructor ; tea.
      1: econstructor ; tea.
      + econstructor.
        eapply typing_subst1.
        all: eapply typing_sound ; tea.
        2: now econstructor.
        econstructor ; tea.
        now eapply algo_conv_complete.
      + clear -bun_red_tm.
        induction bun_red_tm.
        1: now constructor.
        econstructor ; tea.
        now econstructor.
    - intros_bn.
      eapply conv_sound in bun_conv_ty ; tea.
      econstructor ; tea.
      now etransitivity.
    - intros_bn.
      all: now econstructor.
    - red. intros_bn.
      2: now etransitivity.
      now econstructor.
  Qed.

  #[export, refine] Instance RedTypeAlgProperties :
    RedTypeProperties (ta := bn) := {}.
  Proof.
    - intros_bn.
      1: now apply algo_typing_wk.
      now apply credalg_wk.
    - intros * [].
      eapply subject_reduction_type ; tea.
      now eapply typing_sound.
    - now intros_bn.
    - intros_bn.
      do 2 econstructor ; tea.
      now eapply algo_conv_complete.
    - intros_bn.
      now econstructor.
    - red. intros_bn.
      now etransitivity.
  Qed.

  Export UntypedValues.WeakValuesProperties.

  #[export] Instance AlgorithmicTypingProperties : GenericTypingProperties bn _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ := {}.

End AlgorithmicTypingProperties.

Import AlgorithmicTypingProperties.

Corollary algo_typing_complete Γ A t :
  [Γ |-[de] t : A] ->
  [Γ |-[bn] t : A].
Proof.
  now intros [_ _ ?%escapeTm]%(Fundamental (ta := bn)).
Qed.


(** Example from Ernst-Murray CAV 2019, done without locks, proven directly. *)
From iris.base_logic Require Import invariants.
From iris_ni.logrel Require Import types.
From iris_ni.program_logic Require Import dwp heap_lang_lifting.
From iris.proofmode Require Import proofmode.
From iris.heap_lang Require Import lang proofmode.
From iris_ni.proofmode Require Import dwp_tactics.
From iris_ni.logrel Require Import interp.
From iris_ni.examples Require Import lock par various (* for oneshot *).
From iris.algebra Require Import auth agree csum frac excl cmra.

(** * The example program.
Note that a record

   { is_classified: ref bool;
     data : ref τ }

is modeled by a tuple

   (is_classified, data)
**)
Definition thread1 : val :=
  rec: "loop" "out" "rec" :=
    let: "is_classified" := Fst "rec" in
    let: "data" := Snd "rec" in
    (if: ~ !"is_classified"
     then "out" <- !"data"
     else #());;
    "loop" "out" "rec".

Definition thread2 : val :=
  λ: "rec", let: "is_classified" := Fst "rec" in
            let: "data" := Snd "rec" in
            "data" <- #0;;
            "is_classified" <- #false.

Definition prog : val := λ: "out" "secret",
  let: "rec" := (ref #true, ref "secret") in
  thread1 "out" "rec" ||| thread2 "rec".

(** * Ghost state *)
Definition rec : Type := loc * loc.
Inductive state :=
| Classified
| Intermediate
| Declassified.

Canonical Structure stateO := leibnizO state.
Instance state_inhabited : Inhabited state := populate Declassified.

Definition stateR := authR (optionUR (exclR stateO)).
Class stateG Σ := StateG {
   state_stateG :> inG Σ stateR;
}.

Definition classified := Excl' Classified.
Definition intermediate := Excl' Intermediate.
Definition declassified := Excl' Declassified.

Section helper_lemmas.
  Context `{!stateG Σ, !oneshotG Σ}.

  (* Helper lemmas *)
  Lemma Some_None_not_included {A : cmra} (x : A) :
    ¬ Some x ≼ None.
  Proof.
    rewrite option_included. intros [?|Hfoo]; simplify_eq/=.
    destruct Hfoo as [a [b [? [? ?]]]]. simplify_eq/=.
  Qed.

  Lemma current_state γ s1 s2  :
    own γ (◯ Some s2 : stateR) -∗ own γ (● Some s1 : stateR) -∗ ⌜s1 = s2⌝.
  Proof.
    iIntros "Hf Ha".
    iPoseProof (own_valid_2 with "Ha Hf") as "H".
    iDestruct "H" as %[Hfoo Hh]%auth_both_valid_discrete. iPureIntro.
    revert Hfoo. rewrite Some_included.
    intros [Hfoo|Hfoo]; eauto.
    + by unfold_leibniz.
    + exfalso. eapply (exclusive_included _ _ Hfoo). done.
  Qed.

  Lemma excl_change_state (s2 s1 : state) γ :
    own γ (● Excl' s1 : stateR) -∗ own γ (◯ Excl' s1 : stateR) ==∗
    own γ (● Excl' s2 : stateR) ∗ own γ (◯ Excl' s2 : stateR).
  Proof.
    apply bi.wand_intro_r. rewrite - !own_op.
    apply own_update. apply auth_update.
    apply option_local_update.
    apply exclusive_local_update. done.
  Qed.

End helper_lemmas.

(** * Ghost state theory *)
Section ghost_state.
  Context `{!stateG Σ, !oneshotG Σ}.

  (* Preorder on states *)
  Definition state_leq (s1 s2 : state) :=
    match s1, s2 with
    | Classified,   _            => true
    | _,            Declassified => true
    | Intermediate, Intermediate => true
    | _,            _            => false
    end.

  Definition in_state γ (s : state) :=
    match s with
    | Classified   => own γ.1 (● classified : stateR)   ∗ pending γ.2
    | Intermediate => own γ.1 (● intermediate : stateR) ∗ pending γ.2
    | Declassifed  => own γ.1 (● declassified : stateR) ∗ shot γ.2
    end%I.

  Definition state_token γ (s : state) :=
    match s with
    | Classified   => own γ.1 (◯ classified : stateR)
    | Intermediate => own γ.1 (◯ intermediate : stateR)
    | Declassifed  => shot γ.2
    end%I.

  Lemma in_state_agree γ s1 s2 :
    in_state γ s1 -∗ state_token γ s2 -∗ ⌜s1 = s2⌝.
  Proof.
    rewrite /in_state /state_token.
    destruct s1, s2; first
       [ by iIntros "? ?"; iPureIntro; eauto
       | iIntros "[Ha _] Hf"; iExFalso;
         iDestruct (current_state with "Hf Ha") as %Hfoo;
         simplify_eq/=
       | iIntros "[_ H1] H2"; iExFalso;
         iApply (shot_not_pending with "H2 H1") ].
  Qed.

  Global Instance declassified_token_persistent γ :
    Persistent (state_token γ Declassified).
  Proof. apply _. Qed.

  Lemma state_change γ s1 s2 :
    state_leq s1 s2 →
    in_state γ s1 -∗ state_token γ s1 ==∗ in_state γ s2 ∗ state_token γ s2.
  Proof.
    rewrite /in_state /state_token. iIntros (Hleq).
    destruct s1, s2; first
      [ by iIntros "[$ $] $"
      | iIntros "[Ha $] Hf"; iApply (excl_change_state with "Ha Hf")
      | exfalso; by simplify_eq/=
      | idtac ].
    - iIntros "[Ha H] Hf".
      iMod (shoot with "H") as "#$".
      by iMod (excl_change_state with "Ha Hf") as "[$ _]".
    - iIntros "[Ha H] Hf".
      iMod (shoot with "H") as "#$".
      by iMod (excl_change_state with "Ha Hf") as "[$ _]".
  Qed.

End ghost_state.

Section proof.
  Context `{!heapDG Σ, !spawnG Σ, !stateG Σ, !oneshotG Σ}.

  (* The invariant guarantees the monotonicity of the declassification. *)
  Definition inv_body (r1 r2 : rec) γ γs ξ :=
    (* in the state CLASSIFIED *)
    ((∃ v1 v2, in_state (γ, γs) Classified ∗ r1.1 ↦ₗ #true ∗ r2.1 ↦ᵣ #true
                   ∗ r1.2 ↦ₗ v1 ∗ r2.2 ↦ᵣ v2 ∗ ⟦ tint High ⟧ ξ v1 v2)
   ∨ (* in the state INTERMEDIATE *)
     (∃ v, in_state (γ, γs) Intermediate ∗ r1.1 ↦ₗ #true ∗ r2.1 ↦ #true
               ∗ r1.2 ↦ₗ v ∗ r2.2 ↦ᵣ v ∗ ⟦ tint Low ⟧ ξ v v)
   ∨ (* in the state DECLASSIFIED *)
     (∃ v, in_state (γ, γs) Declassified ∗ state_token (γ, γs) Declassified ∗ r1.1 ↦ₗ #false ∗ r2.1 ↦ #false
               ∗ r1.2 ↦ₗ v ∗ r2.2 ↦ᵣ v ∗ ⟦ tint Low ⟧ ξ v v))%I.

  Definition N := nroot.@"example".

  Definition I (rec1 rec2 : val) γ ξ :=
    (∃ (i1 i2 d1 d2 : loc), ⌜rec1 = (#i1, #d1)%V⌝ ∗ ⌜rec2 = (#i2, #d2)%V⌝ ∗
        inv N (inv_body (i1,d1) (i2,d2) γ.1 γ.2 ξ))%I.

  Lemma thread1_spec γ out1 rec1 out2 rec2 ξ :
    ⟦ tref (tint Low) ⟧ ξ out1 out2 -∗
    I rec1 rec2 γ ξ -∗
    DWP thread1 out1 rec1 & thread1 out2 rec2 : ⟦ tunit ⟧ ξ.
  Proof.
    iIntros "#Hout".
    iDestruct 1 as (ri1 ri2 rd1 rd2 -> ->) "#Hinv".
    iLöb as "IH". dwp_rec. dwp_pures.
    dwp_bind (!_)%E (!_)%E.
    iApply dwp_atomic.
    iInv N as "[Hst|[Hst|Hst]]" "Hcl"; iModIntro.
    - (* We are still in the CLASSIFIED state *)
      iDestruct "Hst" as (v1 v2) "(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
      iApply (dwp_load with "Hi1 Hi2"). iIntros "Hi1 Hi2". iNext.
      iMod ("Hcl" with "[-]") as "_".
      { iNext. iLeft. eauto with iFrame. }
      iModIntro. dwp_pures. by iApply "IH".
    - (* We are in the INTERMEDIATE state *)
      iDestruct "Hst" as (v) "(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
      iApply (dwp_load with "Hi1 Hi2"). iIntros "Hi1 Hi2". iNext.
      iMod ("Hcl" with "[-]") as "_".
      { iNext. iRight. iLeft. eauto with iFrame. }
      iModIntro. dwp_pures. by iApply "IH".
    - (* We are in the DECLASSIFIED state *)
      iDestruct "Hst" as (v) "(Hstate & #Hdecl & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
      iApply (dwp_load with "Hi1 Hi2"). iIntros "Hi1 Hi2". iNext.
      iMod ("Hcl" with "[-]") as "_".
      { iNext. iRight. iRight. eauto with iFrame. }
      iModIntro. dwp_pures. clear v.
      dwp_bind (_ <- _)%E (_ <- _)%E.
      iApply (dwp_wand _ _ _ (⟦ tunit ⟧ ξ)); last first.
      { iIntros (??) "_". dwp_pures.
        by iApply "IH". }
      dwp_bind (! _)%E (! _)%E.
      iApply dwp_atomic.
      iInv N as "[Hst|[Hst|Hst]]" "Hcl"; iModIntro.
      + (* We *cannot* be in the CLASSIFIED state *)
        iDestruct "Hst" as (v1 v2) "(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
        iExFalso. iDestruct (in_state_agree with "Hstate Hdecl") as %foo.
        simplify_eq/=.
      + (* We *cannot* be in the INTERMEDIATE state *)
        iDestruct "Hst" as (v) "(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & #Hv)".
        iExFalso. iDestruct (in_state_agree with "Hstate Hdecl") as %foo.
        simplify_eq/=.
      + (* Still in the DECLASSIFIED state *)
        iDestruct "Hst" as (v) "(Hstate & _ & Hi1 & Hi2 & Hd1 & Hd2 & #Hv)".
        iApply (dwp_load with "Hd1 Hd2"). iIntros "Hd1 Hd2". iNext.
        iMod ("Hcl" with "[-]") as "_".
        { iNext. iRight. iRight. eauto with iFrame. }
        iModIntro. iApply logrel_store; first solve_ndisj; by iApply dwp_value.
  Qed.

  Lemma thread2_spec γ rec1 rec2 ξ :
    I rec1 rec2 γ ξ -∗
    state_token γ Classified -∗
    DWP thread2 rec1 & thread2 rec2 : ⟦ tunit ⟧ ξ.
  Proof.
    iDestruct 1 as (ri1 ri2 rd1 rd2 -> ->) "#Hinv".
    iIntros "Hstt".
    dwp_rec. dwp_pures.
    dwp_bind (_ <- _)%E (_ <- _)%E.
    iApply dwp_atomic.
    iInv N as "[Hst|[Hst|Hst]]" "Hcl"; iModIntro.
    - (* We are still in the CLASSIFIED state *)
      iDestruct "Hst" as (v1 v2) "(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
      iApply (dwp_store with "Hd1 Hd2"). iIntros "Hd1 Hd2". iNext.
      iMod (state_change _ _ Intermediate with "Hstate Hstt") as "[Hstate Hstt]";
        first done.
      iMod ("Hcl" with "[-Hstt]") as "_".
      { iNext. iRight. iLeft. iExists #0. iFrame.
        rewrite interp_eq. iExists 0,0. eauto with iFrame. } clear v1 v2.
      iModIntro. dwp_pures. iApply dwp_atomic.
      iInv N as "[Hst|[Hst|Hst]]" "Hcl"; iModIntro.
      + (* CLASSIFIED state --> impossible *)
        iDestruct "Hst" as (v1 v2) "(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
        iDestruct (in_state_agree with "Hstate Hstt") as %Hfoo.
        exfalso. naive_solver.
      + (* INTERMEDIATE state *)
        iDestruct "Hst" as (v) "(Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
        iApply (dwp_store with "Hi1 Hi2"). iIntros "Hi1 Hi2". iNext.
        iMod (state_change _ _ Declassified with "Hstate Hstt") as "[Hstate Hstt]";
          first done.
        iMod ("Hcl" with "[-]") as "_".
        { iNext. iRight. iRight. eauto with iFrame.  }
        iModIntro. eauto with iFrame.
      + (* DECLASSIFIED state. In this case it is actually impossible
           in the program, but we don't account for that in the proof.
           Instead we can just keep calm and carry on. *)
        iDestruct "Hst" as (v) "(>Hstate & Hdecl & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
        iApply (dwp_store with "Hi1 Hi2"). iIntros "Hi1 Hi2". iNext.
        iMod ("Hcl" with "[-]") as "_".
        { iNext. iRight. iRight. eauto with iFrame.  }
        iModIntro. eauto with iFrame.
    - (* INTERMEDIATE state --> impossible *)
      iDestruct "Hst" as (v) "(>Hstate & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
      destruct γ as [γ γs].
      iDestruct (in_state_agree with "Hstate Hstt") as %Hfoo.
      exfalso. naive_solver.
    - (* DECLASSIFIED state --> impossible *)
      iDestruct "Hst" as (v) "(>Hstate & _ & Hi1 & Hi2 & Hd1 & Hd2 & Hv)".
      destruct γ as [γ γs].
      iDestruct (in_state_agree with "Hstate Hstt") as %Hfoo.
      exfalso. naive_solver.
  Qed.

  Lemma proof out1 out2 dat1 dat2 ξ :
    ⟦ tref (tint Low) ⟧ ξ out1 out2 -∗
    ⟦ tint High ⟧ ξ dat1 dat2 -∗
    DWP (prog out1 dat1) & (prog out2 dat2) : ⟦ tprod tunit tunit ⟧ ξ.
  Proof.
    iIntros "#Hout #Hdat".
    dwp_rec. dwp_pures.

    dwp_bind (ref _)%E (ref _)%E.
    iApply dwp_alloc. iIntros (rd1 rd2) "Hrd1 Hrd2". iNext.

    dwp_bind (ref _)%E (ref _)%E.
    iApply dwp_alloc. iIntros (is_classified1 is_classified2) "Hc1 Hc2". iNext.

    iMod new_pending as (γs) "Hstt".
    iMod (own_alloc (● classified ⋅ ◯ classified)) as (γ) "Hst".
    { by apply (auth_both_valid_2 classified). }
    rewrite own_op.
    iDestruct "Hst" as "[Hstate Htoken]".
    iMod (inv_alloc N _
           (inv_body (is_classified1,rd1) (is_classified2,rd2) γ γs ξ) with "[-Htoken]")
      as "#Hinv".
    { iNext. iLeft. iExists _,_. eauto with iFrame. }
    dwp_pures.
    iApply (dwp_par (⟦ tunit ⟧ ξ) (⟦ tunit ⟧ ξ) with "[] [Htoken]").
    - (* Thread 1 *) iApply (thread1_spec (γ,γs) with "Hout []").
      iExists _,_,_,_. repeat iSplit; eauto.
    - (* Thread 2 *) iApply (thread2_spec (γ,γs) with "[] Htoken").
      iExists _,_,_,_. repeat iSplit; eauto.
    - (* Finally *)
      iIntros (???? [-> ->] [-> ->]).
      iNext. iExists _,_,_,_; eauto with iFrame.
  Qed.

End proof.


Require Import Raft.

Require Import CommonDefinitions.

Section TermsAndIndicesFromOneLogInterface.
  Context {orig_base_params : BaseParams}.
  Context {one_node_params : OneNodeParams orig_base_params}.
  Context {raft_params : RaftParams orig_base_params}.

  Definition terms_and_indices_from_one_log (net : network) : Prop :=
    forall h,
      terms_and_indices_from_one (log (nwState net h)).

  Definition terms_and_indices_from_one_log_nw (net : network) : Prop :=
    forall p t leaderId prevLogIndex prevLogTerm entries leaderCommit,
      In p (nwPackets net) ->
      pBody p = AppendEntries t leaderId prevLogIndex prevLogTerm entries leaderCommit ->
      terms_and_indices_from_one entries.

  Class terms_and_indices_from_one_log_interface : Prop := {
    terms_and_indices_from_one_log_invariant : forall net,
      raft_intermediate_reachable net ->
      terms_and_indices_from_one_log net;
    terms_and_indices_from_one_log_nw_invariant : forall net,
      raft_intermediate_reachable net ->
      terms_and_indices_from_one_log_nw net
  }.
End TermsAndIndicesFromOneLogInterface.


Require Import RefProofDeps.
Require Import RData.
Require Import EventReplay.
Require Import MoverTypes.
Require Import Constants.
Require Import CommonLib.
Require Import RefTactics.
Require Import AbsAccessor.Spec.
Require Import CtxtSwitchAux.Specs.save_sysreg_state.
Require Import CtxtSwitchAux.LowSpecs.save_sysreg_state.
Require Import CtxtSwitchAux.RefProof.RefRel.

Local Open Scope string_scope.
Local Open Scope Z_scope.
Local Opaque Z.add Z.mul Z.div Z.shiftl Z.shiftr Z.land Z.lor.

Section Refine.

  Hint Unfold
       sysreg_read_spec
       set_rec_sysregs_spec
    .

  Lemma save_sysreg_state_spec_exists:
    forall habd habd'  labd rec
           (Hspec: save_sysreg_state_spec rec habd = Some habd')
            (Hrel: relate_RData habd labd),
    exists labd', save_sysreg_state_spec0 rec labd = Some labd' /\ relate_RData habd' labd'.
  Proof.
    Local Opaque ptr_eq get_reg set_reg.
    intros. destruct Hrel. destruct rec.
    unfold save_sysreg_state_spec, save_sysreg_state_spec0 in *.
    unfold set_rec_sysregs_spec, sysreg_read_spec.
    autounfold in Hspec. simpl in *.
    hsimpl_hyp Hspec; inv Hspec; simpl_query_oracle; extract_prop_dec. autounfold in *.
    destruct regs_is_int64_dec in C3; [|inversion C3].
    unfold Assertion. unfold buffer_loc. grewrite.
    unfold ref_accessible in *. unfold GRANULE_STATE_REC. autounfold in *.
    repeat (rewrite e; grewrite; simpl;
            repeat rewrite ZMap.gss; simpl_update_reg; repeat rewrite ZMap.set2; repeat simpl_field;
            simpl; grewrite; simpl).
    eexists; split. reflexivity. constructor.
    repeat (simpl_update_reg; simpl; repeat simpl_field).
    reflexivity.
  Qed.

End Refine.


(* *********************************************************************)
(*                                                                     *)
(*              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.     *)
(*                                                                     *)
(* *********************************************************************)

(** Correctness proof for x86 generation: main proof. *)

Require Import Coqlib.
Require Import Errors.
Require Import AST.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import Memory.
Require Import Events.
Require Import Globalenvs.
Require Import Smallstep.
Require Import Op.
Require Import Locations.
Require Import Mach.
Require Import Conventions.
Require Import Asm.
Require Import Asmgen.
Require Import Asmgenproof0.
Require Import Asmgenproof1.

Section PRESERVATION.

Variable prog: Mach.program.
Variable tprog: Asm.program.
Hypothesis TRANSF: transf_program prog = Errors.OK tprog.

Let ge := Genv.globalenv prog.
Let tge := Genv.globalenv tprog.

Lemma symbols_preserved:
  forall id, Genv.find_symbol tge id = Genv.find_symbol ge id.
Proof.
  intros. unfold ge, tge.
  apply Genv.find_symbol_transf_partial with transf_fundef.
  exact TRANSF.
Qed.

Lemma functions_translated:
  forall b f,
  Genv.find_funct_ptr ge b = Some f ->
  exists tf, Genv.find_funct_ptr tge b = Some tf /\ transf_fundef f = Errors.OK tf.
Proof
  (Genv.find_funct_ptr_transf_partial transf_fundef _ TRANSF).

Lemma functions_transl:
  forall fb f tf,
  Genv.find_funct_ptr ge fb = Some (Internal f) ->
  transf_function f = OK tf ->
  Genv.find_funct_ptr tge fb = Some (Internal tf).
Proof.
  intros. exploit functions_translated; eauto. intros [tf' [A B]].
  monadInv B. rewrite H0 in EQ; inv EQ; auto.
Qed.

Lemma varinfo_preserved:
  forall b, Genv.find_var_info tge b = Genv.find_var_info ge b.
Proof.
  intros. unfold ge, tge.
  apply Genv.find_var_info_transf_partial with transf_fundef.
  exact TRANSF.
Qed.

(** * Properties of control flow *)

Lemma transf_function_no_overflow:
  forall f tf,
  transf_function f = OK tf -> list_length_z tf <= Int.max_unsigned.
Proof.
  intros. monadInv H. destruct (zlt (list_length_z x) Int.max_unsigned); monadInv EQ0.
  rewrite list_length_z_cons. omega.
Qed.

Lemma exec_straight_exec:
  forall fb f c ep tf tc c' rs m rs' m',
  transl_code_at_pc ge (rs PC) fb f c ep tf tc ->
  exec_straight tge tf tc rs m c' rs' m' ->
  plus step tge (State rs m) E0 (State rs' m').
Proof.
  intros. inv H.
  eapply exec_straight_steps_1; eauto.
  eapply transf_function_no_overflow; eauto.
  eapply functions_transl; eauto.
Qed.

Lemma exec_straight_at:
  forall fb f c ep tf tc c' ep' tc' rs m rs' m',
  transl_code_at_pc ge (rs PC) fb f c ep tf tc ->
  transl_code f c' ep' = OK tc' ->
  exec_straight tge tf tc rs m tc' rs' m' ->
  transl_code_at_pc ge (rs' PC) fb f c' ep' tf tc'.
Proof.
  intros. inv H.
  exploit exec_straight_steps_2; eauto.
  eapply transf_function_no_overflow; eauto.
  eapply functions_transl; eauto.
  intros [ofs' [PC' CT']].
  rewrite PC'. constructor; auto.
Qed.

(** The following lemmas show that the translation from Mach to Asm
  preserves labels, in the sense that the following diagram commutes:
<<
                          translation
        Mach code ------------------------ Asm instr sequence
            |                                          |
            | Mach.find_label lbl       find_label lbl |
            |                                          |
            v                                          v
        Mach code tail ------------------- Asm instr seq tail
                          translation
>>
  The proof demands many boring lemmas showing that Asm constructor
  functions do not introduce new labels.

  In passing, we also prove a "is tail" property of the generated Asm code.
*)

Section TRANSL_LABEL.

Remark mk_mov_label:
  forall rd rs k c, mk_mov rd rs k = OK c -> tail_nolabel k c.
Proof.
  unfold mk_mov; intros.
  destruct rd; try discriminate; destruct rs; TailNoLabel.
Qed.
Hint Resolve mk_mov_label: labels.

Remark mk_shrximm_label:
  forall n k c, mk_shrximm n k = OK c -> tail_nolabel k c.
Proof.
  intros. monadInv H; TailNoLabel.
Qed.
Hint Resolve mk_shrximm_label: labels.

Remark mk_intconv_label:
  forall f r1 r2 k c, mk_intconv f r1 r2 k = OK c ->
  (forall r r', nolabel (f r r')) ->
  tail_nolabel k c.
Proof.
  unfold mk_intconv; intros. TailNoLabel.
Qed.
Hint Resolve mk_intconv_label: labels.

Remark mk_smallstore_label:
  forall f addr r k c, mk_smallstore f addr r k = OK c ->
  (forall r addr, nolabel (f r addr)) ->
  tail_nolabel k c.
Proof.
  unfold mk_smallstore; intros. TailNoLabel.
Qed.
Hint Resolve mk_smallstore_label: labels.

Remark loadind_label:
  forall base ofs ty dst k c,
  loadind base ofs ty dst k = OK c ->
  tail_nolabel k c.
Proof.
  unfold loadind; intros. destruct ty.
  TailNoLabel.
  destruct (preg_of dst); TailNoLabel.
  discriminate.
  TailNoLabel.
Qed.

Remark storeind_label:
  forall base ofs ty src k c,
  storeind src base ofs ty k = OK c ->
  tail_nolabel k c.
Proof.
  unfold storeind; intros. destruct ty.
  TailNoLabel.
  destruct (preg_of src); TailNoLabel.
  discriminate.
  TailNoLabel.
Qed.

Remark mk_setcc_base_label:
  forall xc rd k,
  tail_nolabel k (mk_setcc_base xc rd k).
Proof.
  intros. destruct xc; simpl; destruct (ireg_eq rd EAX); TailNoLabel.
Qed.

Remark mk_setcc_label:
  forall xc rd k,
  tail_nolabel k (mk_setcc xc rd k).
Proof.
  intros. unfold mk_setcc. destruct (low_ireg rd).
  apply mk_setcc_base_label.
  eapply tail_nolabel_trans. apply mk_setcc_base_label. TailNoLabel.
Qed.

Remark mk_jcc_label:
  forall xc lbl' k,
  tail_nolabel k (mk_jcc xc lbl' k).
Proof.
  intros. destruct xc; simpl; TailNoLabel.
Qed.

Remark transl_cond_label:
  forall cond args k c,
  transl_cond cond args k = OK c ->
  tail_nolabel k c.
Proof.
  unfold transl_cond; intros.
  destruct cond; TailNoLabel.
  destruct (Int.eq_dec i Int.zero); TailNoLabel.
  destruct c0; simpl; TailNoLabel.
  destruct c0; simpl; TailNoLabel.
Qed.

Remark transl_op_label:
  forall op args r k c,
  transl_op op args r k = OK c ->
  tail_nolabel k c.
Proof.
  unfold transl_op; intros. destruct op; TailNoLabel.
  destruct (Int.eq_dec i Int.zero); TailNoLabel.
  destruct (Float.eq_dec f Float.zero); TailNoLabel.
  eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_setcc_label.
Qed.

Remark transl_load_label:
  forall chunk addr args dest k c,
  transl_load chunk addr args dest k = OK c ->
  tail_nolabel k c.
Proof.
  intros. monadInv H. destruct chunk; TailNoLabel.
Qed.

Remark transl_store_label:
  forall chunk addr args src k c,
  transl_store chunk addr args src k = OK c ->
  tail_nolabel k c.
Proof.
  intros. monadInv H. destruct chunk; TailNoLabel.
Qed.

Lemma transl_instr_label:
  forall f i ep k c,
  transl_instr f i ep k = OK c ->
  match i with Mlabel lbl => c = Plabel lbl :: k | _ => tail_nolabel k c end.
Proof.
Opaque loadind.
  unfold transl_instr; intros; destruct i; TailNoLabel.
  eapply loadind_label; eauto.
  eapply storeind_label; eauto.
  eapply loadind_label; eauto.
  eapply tail_nolabel_trans; eapply loadind_label; eauto.
  eapply transl_op_label; eauto.
  eapply transl_load_label; eauto.
  eapply transl_store_label; eauto.
  destruct s0; TailNoLabel.
  destruct s0; TailNoLabel.
  eapply tail_nolabel_trans. eapply transl_cond_label; eauto. eapply mk_jcc_label.
Qed.

Lemma transl_instr_label':
  forall lbl f i ep k c,
  transl_instr f i ep k = OK c ->
  find_label lbl c = if Mach.is_label lbl i then Some k else find_label lbl k.
Proof.
  intros. exploit transl_instr_label; eauto.
  destruct i; try (intros [A B]; apply B).
  intros. subst c. simpl. auto.
Qed.

Lemma transl_code_label:
  forall lbl f c ep tc,
  transl_code f c ep = OK tc ->
  match Mach.find_label lbl c with
  | None => find_label lbl tc = None
  | Some c' => exists tc', find_label lbl tc = Some tc' /\ transl_code f c' false = OK tc'
  end.
Proof.
  induction c; simpl; intros.
  inv H. auto.
  monadInv H. rewrite (transl_instr_label' lbl _ _ _ _ _ EQ0).
  generalize (Mach.is_label_correct lbl a).
  destruct (Mach.is_label lbl a); intros.
  subst a. simpl in EQ. exists x; auto.
  eapply IHc; eauto.
Qed.

Lemma transl_find_label:
  forall lbl f tf,
  transf_function f = OK tf ->
  match Mach.find_label lbl f.(Mach.fn_code) with
  | None => find_label lbl tf = None
  | Some c => exists tc, find_label lbl tf = Some tc /\ transl_code f c false = OK tc
  end.
Proof.
  intros. monadInv H. destruct (zlt (list_length_z x) Int.max_unsigned); inv EQ0.
  simpl. eapply transl_code_label; eauto. rewrite transl_code'_transl_code in EQ; eauto.
Qed.

End TRANSL_LABEL.

(** A valid branch in a piece of Mach code translates to a valid ``go to''
  transition in the generated PPC code. *)

Lemma find_label_goto_label:
  forall f tf lbl rs m c' b ofs,
  Genv.find_funct_ptr ge b = Some (Internal f) ->
  transf_function f = OK tf ->
  rs PC = Vptr b ofs ->
  Mach.find_label lbl f.(Mach.fn_code) = Some c' ->
  exists tc', exists rs',
    goto_label tf lbl rs m = Next rs' m
  /\ transl_code_at_pc ge (rs' PC) b f c' false tf tc'
  /\ forall r, r <> PC -> rs'#r = rs#r.
Proof.
  intros. exploit (transl_find_label lbl f tf); eauto. rewrite H2.
  intros [tc [A B]].
  exploit label_pos_code_tail; eauto. instantiate (1 := 0).
  intros [pos' [P [Q R]]].
  exists tc; exists (rs#PC <- (Vptr b (Int.repr pos'))).
  split. unfold goto_label. rewrite P. rewrite H1. auto.
  split. rewrite Pregmap.gss. constructor; auto.
  rewrite Int.unsigned_repr. replace (pos' - 0) with pos' in Q.
  auto. omega.
  generalize (transf_function_no_overflow _ _ H0). omega.
  intros. apply Pregmap.gso; auto.
Qed.

(** Existence of return addresses *)

Lemma return_address_exists:
  forall f sg ros c, is_tail (Mcall sg ros :: c) f.(Mach.fn_code) ->
  exists ra, return_address_offset f c ra.
Proof.
  intros. eapply Asmgenproof0.return_address_exists; eauto.
- intros. exploit transl_instr_label; eauto.
  destruct i; try (intros [A B]; apply A). intros. subst c0. repeat constructor.
- intros. monadInv H0.
  destruct (zlt (list_length_z x) Int.max_unsigned); inv EQ0.
  rewrite transl_code'_transl_code in EQ.
  exists x; exists true; split; auto. unfold fn_code. repeat constructor.
- exact transf_function_no_overflow.
Qed.

(** * Proof of semantic preservation *)

(** Semantic preservation is proved using simulation diagrams
  of the following form.
<<
           st1 --------------- st2
            |                   |
           t|                  *|t
            |                   |
            v                   v
           st1'--------------- st2'
>>
  The invariant is the [match_states] predicate below, which includes:
- The PPC code pointed by the PC register is the translation of
  the current Mach code sequence.
- Mach register values and PPC register values agree.
*)

Inductive match_states: Mach.state -> Asm.state -> Prop :=
  | match_states_intro:
      forall s fb sp c ep ms m m' rs f tf tc
        (STACKS: match_stack ge s)
        (FIND: Genv.find_funct_ptr ge fb = Some (Internal f))
        (MEXT: Mem.extends m m')
        (AT: transl_code_at_pc ge (rs PC) fb f c ep tf tc)
        (AG: agree ms sp rs)
        (DXP: ep = true -> rs#EDX = parent_sp s),
      match_states (Mach.State s fb sp c ms m)
                   (Asm.State rs m')
  | match_states_call:
      forall s fb ms m m' rs
        (STACKS: match_stack ge s)
        (MEXT: Mem.extends m m')
        (AG: agree ms (parent_sp s) rs)
        (ATPC: rs PC = Vptr fb Int.zero)
        (ATLR: rs RA = parent_ra s),
      match_states (Mach.Callstate s fb ms m)
                   (Asm.State rs m')
  | match_states_return:
      forall s ms m m' rs
        (STACKS: match_stack ge s)
        (MEXT: Mem.extends m m')
        (AG: agree ms (parent_sp s) rs)
        (ATPC: rs PC = parent_ra s),
      match_states (Mach.Returnstate s ms m)
                   (Asm.State rs m').

Lemma exec_straight_steps:
  forall s fb f rs1 i c ep tf tc m1' m2 m2' sp ms2,
  match_stack ge s ->
  Mem.extends m2 m2' ->
  Genv.find_funct_ptr ge fb = Some (Internal f) ->
  transl_code_at_pc ge (rs1 PC) fb f (i :: c) ep tf tc ->
  (forall k c (TR: transl_instr f i ep k = OK c),
   exists rs2,
       exec_straight tge tf c rs1 m1' k rs2 m2'
    /\ agree ms2 sp rs2
    /\ (it1_is_parent ep i = true -> rs2#EDX = parent_sp s)) ->
  exists st',
  plus step tge (State rs1 m1') E0 st' /\
  match_states (Mach.State s fb sp c ms2 m2) st'.
Proof.
  intros. inversion H2. subst. monadInv H7.
  exploit H3; eauto. intros [rs2 [A [B C]]].
  exists (State rs2 m2'); split.
  eapply exec_straight_exec; eauto.
  econstructor; eauto. eapply exec_straight_at; eauto.
Qed.

Lemma exec_straight_steps_goto:
  forall s fb f rs1 i c ep tf tc m1' m2 m2' sp ms2 lbl c',
  match_stack ge s ->
  Mem.extends m2 m2' ->
  Genv.find_funct_ptr ge fb = Some (Internal f) ->
  Mach.find_label lbl f.(Mach.fn_code) = Some c' ->
  transl_code_at_pc ge (rs1 PC) fb f (i :: c) ep tf tc ->
  it1_is_parent ep i = false ->
  (forall k c (TR: transl_instr f i ep k = OK c),
   exists jmp, exists k', exists rs2,
       exec_straight tge tf c rs1 m1' (jmp :: k') rs2 m2'
    /\ agree ms2 sp rs2
    /\ exec_instr tge tf jmp rs2 m2' = goto_label tf lbl rs2 m2') ->
  exists st',
  plus step tge (State rs1 m1') E0 st' /\
  match_states (Mach.State s fb sp c' ms2 m2) st'.
Proof.
  intros. inversion H3. subst. monadInv H9.
  exploit H5; eauto. intros [jmp [k' [rs2 [A [B C]]]]].
  generalize (functions_transl _ _ _ H7 H8); intro FN.
  generalize (transf_function_no_overflow _ _ H8); intro NOOV.
  exploit exec_straight_steps_2; eauto.
  intros [ofs' [PC2 CT2]].
  exploit find_label_goto_label; eauto.
  intros [tc' [rs3 [GOTO [AT' OTH]]]].
  exists (State rs3 m2'); split.
  eapply plus_right'.
  eapply exec_straight_steps_1; eauto.
  econstructor; eauto.
  eapply find_instr_tail. eauto.
  rewrite C. eexact GOTO.
  traceEq.
  econstructor; eauto.
  apply agree_exten with rs2; auto with asmgen.
  congruence.
Qed.

(** We need to show that, in the simulation diagram, we cannot
  take infinitely many Mach transitions that correspond to zero
  transitions on the PPC side.  Actually, all Mach transitions
  correspond to at least one Asm transition, except the
  transition from [Mach.Returnstate] to [Mach.State].
  So, the following integer measure will suffice to rule out
  the unwanted behaviour. *)

Definition measure (s: Mach.state) : nat :=
  match s with
  | Mach.State _ _ _ _ _ _ => 0%nat
  | Mach.Callstate _ _ _ _ => 0%nat
  | Mach.Returnstate _ _ _ => 1%nat
  end.

(** This is the simulation diagram.  We prove it by case analysis on the Mach transition. *)

Theorem step_simulation:
  forall S1 t S2, Mach.step return_address_offset ge S1 t S2 ->
  forall S1' (MS: match_states S1 S1'),
  (exists S2', plus step tge S1' t S2' /\ match_states S2 S2')
  \/ (measure S2 < measure S1 /\ t = E0 /\ match_states S2 S1')%nat.
Proof.
  induction 1; intros; inv MS.

- (* Mlabel *)
  left; eapply exec_straight_steps; eauto; intros.
  monadInv TR. econstructor; split. apply exec_straight_one. simpl; eauto. auto.
  split. apply agree_nextinstr; auto. simpl; congruence.

- (* Mgetstack *)
  unfold load_stack in H.
  exploit Mem.loadv_extends; eauto. intros [v' [A B]].
  rewrite (sp_val _ _ _ AG) in A.
  left; eapply exec_straight_steps; eauto. intros. simpl in TR.
  exploit loadind_correct; eauto. intros [rs' [P [Q R]]].
  exists rs'; split. eauto.
  split. eapply agree_set_mreg; eauto. congruence.
  simpl; congruence.

- (* Msetstack *)
  unfold store_stack in H.
  assert (Val.lessdef (rs src) (rs0 (preg_of src))). eapply preg_val; eauto.
  exploit Mem.storev_extends; eauto. intros [m2' [A B]].
  left; eapply exec_straight_steps; eauto.
  rewrite (sp_val _ _ _ AG) in A. intros. simpl in TR.
  exploit storeind_correct; eauto. intros [rs' [P Q]].
  exists rs'; split. eauto.
  split. eapply agree_undef_regs; eauto.
  simpl; intros. rewrite Q; auto with asmgen.
Local Transparent destroyed_by_setstack.
  destruct ty; simpl; intuition congruence.

- (* Mgetparam *)
  assert (f0 = f) by congruence; subst f0.
  unfold load_stack in *.
  exploit Mem.loadv_extends. eauto. eexact H0. auto.
  intros [parent' [A B]]. rewrite (sp_val _ _ _ AG) in A.
  exploit lessdef_parent_sp; eauto. clear B; intros B; subst parent'.
  exploit Mem.loadv_extends. eauto. eexact H1. auto.
  intros [v' [C D]].
Opaque loadind.
  left; eapply exec_straight_steps; eauto; intros.
  assert (DIFF: negb (mreg_eq dst DX) = true -> IR EDX <> preg_of dst).
    intros. change (IR EDX) with (preg_of DX). red; intros.
    unfold proj_sumbool in H1. destruct (mreg_eq dst DX); try discriminate.
    elim n. eapply preg_of_injective; eauto.
  destruct ep; simpl in TR.
(* EDX contains parent *)
  exploit loadind_correct. eexact TR.
  instantiate (2 := rs0). rewrite DXP; eauto.
  intros [rs1 [P [Q R]]].
  exists rs1; split. eauto.
  split. eapply agree_set_mreg. eapply agree_set_mreg; eauto. congruence. auto.
  simpl; intros. rewrite R; auto.
(* EDX does not contain parent *)
  monadInv TR.
  exploit loadind_correct. eexact EQ0. eauto. intros [rs1 [P [Q R]]]. simpl in Q.
  exploit loadind_correct. eexact EQ. instantiate (2 := rs1). rewrite Q. eauto.
  intros [rs2 [S [T U]]].
  exists rs2; split. eapply exec_straight_trans; eauto.
  split. eapply agree_set_mreg. eapply agree_set_mreg; eauto. congruence. auto.
  simpl; intros. rewrite U; auto.

- (* Mop *)
  assert (eval_operation tge sp op rs##args m = Some v).
    rewrite <- H. apply eval_operation_preserved. exact symbols_preserved.
  exploit eval_operation_lessdef. eapply preg_vals; eauto. eauto. eexact H0.
  intros [v' [A B]]. rewrite (sp_val _ _ _ AG) in A.
  left; eapply exec_straight_steps; eauto; intros. simpl in TR.
  exploit transl_op_correct; eauto. intros [rs2 [P [Q R]]].
  assert (S: Val.lessdef v (rs2 (preg_of res))) by (eapply Val.lessdef_trans; eauto).
  exists rs2; split. eauto.
  split. eapply agree_set_undef_mreg; eauto.
  simpl; congruence.

- (* Mload *)
  assert (eval_addressing tge sp addr rs##args = Some a).
    rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.
  exploit eval_addressing_lessdef. eapply preg_vals; eauto. eexact H1.
  intros [a' [A B]]. rewrite (sp_val _ _ _ AG) in A.
  exploit Mem.loadv_extends; eauto. intros [v' [C D]].
  left; eapply exec_straight_steps; eauto; intros. simpl in TR.
  exploit transl_load_correct; eauto. intros [rs2 [P [Q R]]].
  exists rs2; split. eauto.
  split. eapply agree_set_undef_mreg; eauto. congruence.
  simpl; congruence.

- (* Mstore *)
  assert (eval_addressing tge sp addr rs##args = Some a).
    rewrite <- H. apply eval_addressing_preserved. exact symbols_preserved.
  exploit eval_addressing_lessdef. eapply preg_vals; eauto. eexact H1.
  intros [a' [A B]]. rewrite (sp_val _ _ _ AG) in A.
  assert (Val.lessdef (rs src) (rs0 (preg_of src))). eapply preg_val; eauto.
  exploit Mem.storev_extends; eauto. intros [m2' [C D]].
  left; eapply exec_straight_steps; eauto.
  intros. simpl in TR.
  exploit transl_store_correct; eauto. intros [rs2 [P Q]].
  exists rs2; split. eauto.
  split. eapply agree_undef_regs; eauto.
  simpl; congruence.

- (* Mcall *)
  assert (f0 = f) by congruence.  subst f0.
  inv AT.
  assert (NOOV: list_length_z tf <= Int.max_unsigned).
    eapply transf_function_no_overflow; eauto.
  destruct ros as [rf|fid]; simpl in H; monadInv H5.
+ (* Indirect call *)
  assert (rs rf = Vptr f' Int.zero).
    destruct (rs rf); try discriminate.
    revert H; predSpec Int.eq Int.eq_spec i Int.zero; intros; congruence.
  assert (rs0 x0 = Vptr f' Int.zero).
    exploit ireg_val; eauto. rewrite H5; intros LD; inv LD; auto.
  generalize (code_tail_next_int _ _ _ _ NOOV H6). intro CT1.
  assert (TCA: transl_code_at_pc ge (Vptr fb (Int.add ofs Int.one)) fb f c false tf x).
    econstructor; eauto.
  exploit return_address_offset_correct; eauto. intros; subst ra.
  left; econstructor; split.
  apply plus_one. eapply exec_step_internal. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. eauto.
  econstructor; eauto.
  econstructor; eauto.
  eapply agree_sp_def; eauto.
  simpl. eapply agree_exten; eauto. intros. Simplifs.
  Simplifs. rewrite <- H2. auto.
+ (* Direct call *)
  generalize (code_tail_next_int _ _ _ _ NOOV H6). intro CT1.
  assert (TCA: transl_code_at_pc ge (Vptr fb (Int.add ofs Int.one)) fb f c false tf x).
    econstructor; eauto.
  exploit return_address_offset_correct; eauto. intros; subst ra.
  left; econstructor; split.
  apply plus_one. eapply exec_step_internal. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. unfold symbol_offset. rewrite symbols_preserved. rewrite H. eauto.
  econstructor; eauto.
  econstructor; eauto.
  eapply agree_sp_def; eauto.
  simpl. eapply agree_exten; eauto. intros. Simplifs.
  Simplifs. rewrite <- H2. auto.

- (* Mtailcall *)
  assert (f0 = f) by congruence.  subst f0.
  inv AT.
  assert (NOOV: list_length_z tf <= Int.max_unsigned).
    eapply transf_function_no_overflow; eauto.
  rewrite (sp_val _ _ _ AG) in *. unfold load_stack in *.
  exploit Mem.loadv_extends. eauto. eexact H1. auto. simpl. intros [parent' [A B]].
  exploit Mem.loadv_extends. eauto. eexact H2. auto. simpl. intros [ra' [C D]].
  exploit lessdef_parent_sp; eauto. intros. subst parent'. clear B.
  exploit lessdef_parent_ra; eauto. intros. subst ra'. clear D.
  exploit Mem.free_parallel_extends; eauto. intros [m2' [E F]].
  destruct ros as [rf|fid]; simpl in H; monadInv H7.
+ (* Indirect call *)
  assert (rs rf = Vptr f' Int.zero).
    destruct (rs rf); try discriminate.
    revert H; predSpec Int.eq Int.eq_spec i Int.zero; intros; congruence.
  assert (rs0 x0 = Vptr f' Int.zero).
    exploit ireg_val; eauto. rewrite H7; intros LD; inv LD; auto.
  generalize (code_tail_next_int _ _ _ _ NOOV H8). intro CT1.
  left; econstructor; split.
  eapply plus_left. eapply exec_step_internal. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG). rewrite E. eauto.
  apply star_one. eapply exec_step_internal.
  transitivity (Val.add rs0#PC Vone). auto. rewrite <- H4. simpl. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. eauto. traceEq.
  econstructor; eauto.
  apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.
  eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.
  Simplifs. rewrite Pregmap.gso; auto.
  generalize (preg_of_not_SP rf). rewrite (ireg_of_eq _ _ EQ1). congruence.
+ (* Direct call *)
  generalize (code_tail_next_int _ _ _ _ NOOV H8). intro CT1.
  left; econstructor; split.
  eapply plus_left. eapply exec_step_internal. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG). rewrite E. eauto.
  apply star_one. eapply exec_step_internal.
  transitivity (Val.add rs0#PC Vone). auto. rewrite <- H4. simpl. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. eauto. traceEq.
  econstructor; eauto.
  apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.
  eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.
  rewrite Pregmap.gss. unfold symbol_offset. rewrite symbols_preserved. rewrite H. auto.

- (* Mbuiltin *)
  inv AT. monadInv H3.
  exploit functions_transl; eauto. intro FN.
  generalize (transf_function_no_overflow _ _ H2); intro NOOV.
  exploit external_call_mem_extends'; eauto. eapply preg_vals; eauto.
  intros [vres' [m2' [A [B [C D]]]]].
  left. econstructor; split. apply plus_one.
  eapply exec_step_builtin. eauto. eauto.
  eapply find_instr_tail; eauto.
  eapply external_call_symbols_preserved'; eauto.
  exact symbols_preserved. exact varinfo_preserved.
  eauto.
  econstructor; eauto.
  instantiate (2 := tf); instantiate (1 := x).
  unfold nextinstr_nf, nextinstr. rewrite Pregmap.gss.
  rewrite undef_regs_other. rewrite set_pregs_other_2. rewrite undef_regs_other_2.
  rewrite <- H0. simpl. econstructor; eauto.
  eapply code_tail_next_int; eauto.
  rewrite preg_notin_charact. intros. auto with asmgen.
  rewrite preg_notin_charact. intros. auto with asmgen.
  auto with asmgen.
  simpl; intros. intuition congruence.
  apply agree_nextinstr_nf. eapply agree_set_mregs; auto.
  eapply agree_undef_regs; eauto. intros; apply undef_regs_other_2; auto.
  congruence.

- (* Mannot *)
  inv AT. monadInv H4.
  exploit functions_transl; eauto. intro FN.
  generalize (transf_function_no_overflow _ _ H3); intro NOOV.
  exploit annot_arguments_match; eauto. intros [vargs' [P Q]].
  exploit external_call_mem_extends'; eauto.
  intros [vres' [m2' [A [B [C D]]]]].
  left. econstructor; split. apply plus_one.
  eapply exec_step_annot. eauto. eauto.
  eapply find_instr_tail; eauto. eauto.
  eapply external_call_symbols_preserved'; eauto.
  exact symbols_preserved. exact varinfo_preserved.
  eapply match_states_intro with (ep := false); eauto with coqlib.
  unfold nextinstr. rewrite Pregmap.gss.
  rewrite <- H1; simpl. econstructor; eauto.
  eapply code_tail_next_int; eauto.
  apply agree_nextinstr. auto.
  congruence.

- (* Mgoto *)
  assert (f0 = f) by congruence. subst f0.
  inv AT. monadInv H4.
  exploit find_label_goto_label; eauto. intros [tc' [rs' [GOTO [AT2 INV]]]].
  left; exists (State rs' m'); split.
  apply plus_one. econstructor; eauto.
  eapply functions_transl; eauto.
  eapply find_instr_tail; eauto.
  simpl; eauto.
  econstructor; eauto.
  eapply agree_exten; eauto with asmgen.
  congruence.

- (* Mcond true *)
  assert (f0 = f) by congruence. subst f0.
  exploit eval_condition_lessdef. eapply preg_vals; eauto. eauto. eauto. intros EC.
  left; eapply exec_straight_steps_goto; eauto.
  intros. simpl in TR.
  destruct (transl_cond_correct tge tf cond args _ _ rs0 m' TR)
  as [rs' [A [B C]]].
  rewrite EC in B.
  destruct (testcond_for_condition cond); simpl in *.
(* simple jcc *)
  exists (Pjcc c1 lbl); exists k; exists rs'.
  split. eexact A.
  split. eapply agree_exten; eauto.
  simpl. rewrite B. auto.
(* jcc; jcc *)
  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;
  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.
  destruct b1.
  (* first jcc jumps *)
  exists (Pjcc c1 lbl); exists (Pjcc c2 lbl :: k); exists rs'.
  split. eexact A.
  split. eapply agree_exten; eauto.
  simpl. rewrite TC1. auto.
  (* second jcc jumps *)
  exists (Pjcc c2 lbl); exists k; exists (nextinstr rs').
  split. eapply exec_straight_trans. eexact A.
  eapply exec_straight_one. simpl. rewrite TC1. auto. auto.
  split. eapply agree_exten; eauto.
  intros; Simplifs.
  simpl. rewrite eval_testcond_nextinstr. rewrite TC2.
  destruct b2; auto || discriminate.
(* jcc2 *)
  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;
  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.
  destruct (andb_prop _ _ H3). subst.
  exists (Pjcc2 c1 c2 lbl); exists k; exists rs'.
  split. eexact A.
  split. eapply agree_exten; eauto.
  simpl. rewrite TC1; rewrite TC2; auto.

- (* Mcond false *)
  exploit eval_condition_lessdef. eapply preg_vals; eauto. eauto. eauto. intros EC.
  left; eapply exec_straight_steps; eauto. intros. simpl in TR.
  destruct (transl_cond_correct tge tf cond args _ _ rs0 m' TR)
  as [rs' [A [B C]]].
  rewrite EC in B.
  destruct (testcond_for_condition cond); simpl in *.
(* simple jcc *)
  econstructor; split.
  eapply exec_straight_trans. eexact A.
  apply exec_straight_one. simpl. rewrite B. eauto. auto.
  split. apply agree_nextinstr. eapply agree_exten; eauto.
  simpl; congruence.
(* jcc ; jcc *)
  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;
  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.
  destruct (orb_false_elim _ _ H1); subst.
  econstructor; split.
  eapply exec_straight_trans. eexact A.
  eapply exec_straight_two. simpl. rewrite TC1. eauto. auto.
  simpl. rewrite eval_testcond_nextinstr. rewrite TC2. eauto. auto. auto.
  split. apply agree_nextinstr. apply agree_nextinstr. eapply agree_exten; eauto.
  simpl; congruence.
(* jcc2 *)
  destruct (eval_testcond c1 rs') as [b1|] eqn:TC1;
  destruct (eval_testcond c2 rs') as [b2|] eqn:TC2; inv B.
  exists (nextinstr rs'); split.
  eapply exec_straight_trans. eexact A.
  apply exec_straight_one. simpl.
  rewrite TC1; rewrite TC2.
  destruct b1. simpl in *. subst b2. auto. auto.
  auto.
  split. apply agree_nextinstr. eapply agree_exten; eauto.
  rewrite H1; congruence.

- (* Mjumptable *)
  assert (f0 = f) by congruence. subst f0.
  inv AT. monadInv H6.
  exploit functions_transl; eauto. intro FN.
  generalize (transf_function_no_overflow _ _ H5); intro NOOV.
  exploit find_label_goto_label; eauto.
  intros [tc' [rs' [A [B C]]]].
  exploit ireg_val; eauto. rewrite H. intros LD; inv LD.
  left; econstructor; split.
  apply plus_one. econstructor; eauto.
  eapply find_instr_tail; eauto.
  simpl. rewrite <- H9. unfold Mach.label in H0; unfold label; rewrite H0. eauto.
  econstructor; eauto.
Transparent destroyed_by_jumptable.
  simpl. eapply agree_exten; eauto. intros. rewrite C; auto with asmgen.
  congruence.

- (* Mreturn *)
  assert (f0 = f) by congruence. subst f0.
  inv AT.
  assert (NOOV: list_length_z tf <= Int.max_unsigned).
    eapply transf_function_no_overflow; eauto.
  rewrite (sp_val _ _ _ AG) in *. unfold load_stack in *.
  exploit Mem.loadv_extends. eauto. eexact H0. auto. simpl. intros [parent' [A B]].
  exploit lessdef_parent_sp; eauto. intros. subst parent'. clear B.
  exploit Mem.loadv_extends. eauto. eexact H1. auto. simpl. intros [ra' [C D]].
  exploit lessdef_parent_ra; eauto. intros. subst ra'. clear D.
  exploit Mem.free_parallel_extends; eauto. intros [m2' [E F]].
  monadInv H6.
  exploit code_tail_next_int; eauto. intro CT1.
  left; econstructor; split.
  eapply plus_left. eapply exec_step_internal. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. rewrite C. rewrite A. rewrite <- (sp_val _ _ _ AG). rewrite E. eauto.
  apply star_one. eapply exec_step_internal.
  transitivity (Val.add rs0#PC Vone). auto. rewrite <- H3. simpl. eauto.
  eapply functions_transl; eauto. eapply find_instr_tail; eauto.
  simpl. eauto. traceEq.
  constructor; auto.
  apply agree_set_other; auto. apply agree_nextinstr. apply agree_set_other; auto.
  eapply agree_change_sp; eauto. eapply parent_sp_def; eauto.

- (* internal function *)
  exploit functions_translated; eauto. intros [tf [A B]]. monadInv B.
  generalize EQ; intros EQ'. monadInv EQ'. rewrite transl_code'_transl_code in EQ0.
  destruct (zlt (list_length_z x0) Int.max_unsigned); inversion EQ1. clear EQ1.
  unfold store_stack in *.
  exploit Mem.alloc_extends. eauto. eauto. apply Zle_refl. apply Zle_refl.
  intros [m1' [C D]].
  exploit Mem.storev_extends. eexact D. eexact H1. eauto. eauto.
  intros [m2' [F G]].
  exploit Mem.storev_extends. eexact G. eexact H2. eauto. eauto.
  intros [m3' [P Q]].
  left; econstructor; split.
  apply plus_one. econstructor; eauto.
  subst x; simpl.
  rewrite Int.unsigned_zero. simpl. eauto.
  simpl. rewrite C. simpl in F. rewrite (sp_val _ _ _ AG) in F. rewrite F.
  simpl in P. rewrite ATLR. rewrite P. eauto.
  econstructor; eauto.
  unfold nextinstr. rewrite Pregmap.gss. repeat rewrite Pregmap.gso; auto with asmgen.
  rewrite ATPC. simpl. constructor; eauto.
  subst x. unfold fn_code. eapply code_tail_next_int. rewrite list_length_z_cons. omega.
  constructor.
  apply agree_nextinstr. eapply agree_change_sp; eauto.
Transparent destroyed_at_function_entry.
  apply agree_undef_regs with rs0; eauto.
  simpl; intros. apply Pregmap.gso; auto with asmgen. tauto.
  congruence.
  intros. Simplifs. eapply agree_sp; eauto.

- (* external function *)
  exploit functions_translated; eauto.
  intros [tf [A B]]. simpl in B. inv B.
  exploit extcall_arguments_match; eauto.
  intros [args' [C D]].
  exploit external_call_mem_extends'; eauto.
  intros [res' [m2' [P [Q [R S]]]]].
  left; econstructor; split.
  apply plus_one. eapply exec_step_external; eauto.
  eapply external_call_symbols_preserved'; eauto.
  exact symbols_preserved. exact varinfo_preserved.
  econstructor; eauto.
  unfold loc_external_result.
  apply agree_set_other; auto. apply agree_set_mregs; auto.

- (* return *)
  inv STACKS. simpl in *.
  right. split. omega. split. auto.
  econstructor; eauto. rewrite ATPC; eauto. congruence.
Qed.

Lemma transf_initial_states:
  forall st1, Mach.initial_state prog st1 ->
  exists st2, Asm.initial_state tprog st2 /\ match_states st1 st2.
Proof.
  intros. inversion H. unfold ge0 in *.
  econstructor; split.
  econstructor.
  eapply Genv.init_mem_transf_partial; eauto.
  replace (symbol_offset (Genv.globalenv tprog) (prog_main tprog) Int.zero)
     with (Vptr fb Int.zero).
  econstructor; eauto.
  constructor.
  apply Mem.extends_refl.
  split. auto. simpl. unfold Vzero; congruence. intros. rewrite Regmap.gi. auto.
  unfold symbol_offset.
  rewrite (transform_partial_program_main _ _ TRANSF).
  rewrite symbols_preserved.
  unfold ge; rewrite H1. auto.
Qed.

Lemma transf_final_states:
  forall st1 st2 r,
  match_states st1 st2 -> Mach.final_state st1 r -> Asm.final_state st2 r.
Proof.
  intros. inv H0. inv H. constructor. auto.
  compute in H1. inv H1.
  generalize (preg_val _ _ _ AX AG). rewrite H2. intros LD; inv LD. auto.
Qed.

Theorem transf_program_correct:
  forward_simulation (Mach.semantics return_address_offset prog) (Asm.semantics tprog).
Proof.
  eapply forward_simulation_star with (measure := measure).
  eexact symbols_preserved.
  eexact transf_initial_states.
  eexact transf_final_states.
  exact step_simulation.
Qed.

End PRESERVATION.