Ltac remove_unrelevant_last_txn :=
  repeat match goal with
  | [H: context[trace_tid_last ?tid ((?tid0, _) :: ?t) = _] |-_] =>
      unfold trace_tid_last in H; inversion H;
      destruct (Nat.eq_dec tid tid0); subst
  | [H: context[hd _
       (map snd
          (if ?tid0 =? ?tid0
           then (?tid0, ?x) :: trace_filter_tid ?tid0 ?t
           else trace_filter_tid ?tid0 ?t)) = ?y] |-_] =>
      rewrite <- beq_nat_refl in H; simpl in H; inversion H
  | [H: context[?tid <> ?tid0] |-_] =>
      apply not_eq_sym in H; apply Nat.eqb_neq in H
end.

Lemma seq_list_commit tid t:
  sto_trace t ->
  trace_tid_last tid t = seq_point
  -> In tid (seq_list t).
Proof.
  intros.
  induction H; simpl; try discriminate.
  1, 3, 4, 6-8, 10: remove_unrelevant_last_txn; rewrite n in H3; apply IHsto_trace in H3; auto.
  1, 2: remove_unrelevant_last_txn; rewrite n in H4; apply IHsto_trace in H4; auto.
  remove_unrelevant_last_txn.
  apply in_or_app. right. simpl. auto.
  remove_unrelevant_last_txn.
  rewrite n in H4.
  apply IHsto_trace in H4.
  apply in_or_app. left. auto.
Qed.

Lemma trace_seqlist_seqpoint t tid:
  In (tid, seq_point) t
  -> In tid (seq_list t).
Proof.
  intros.
  functional induction seq_list t.
  inversion H.
  destruct (Nat.eq_dec tid tid0); subst; apply in_or_app.
  right. simpl. auto.
  left. apply IHl. apply in_inv in H. destruct H.
  inversion H. apply Nat.eq_sym in H1. contradiction. auto.
  all: destruct (Nat.eq_dec tid tid0); subst; apply IHl; apply in_inv in H; destruct H; try inversion H; auto.
Qed.

Lemma seq_list_no_two_seqpoint t tid:
  sto_trace ((tid, seq_point) :: t)
  -> ~ In (tid, seq_point) t.
Proof.
  intros.
  assert (sto_trace t). { apply sto_trace_app with (tid0 := tid) (action0 := seq_point). auto. }
  inversion H.
  intuition.

  all: unfold trace_no_seq_points in H4; apply in_split in H6;
  destruct H6; destruct H6;
  rewrite H6 in H4; simpl in H4;
  rewrite trace_filter_tid_app in H4;
  simpl in H4;
  rewrite <-beq_nat_refl in H4;
  rewrite map_app in H4;
  rewrite Forall_app in H4;
  destruct H4; simpl in H7;
  apply Forall_inv in H7; simpl in H7; auto.
Qed.


Require Export Fiat.Common.Coq__8_4__8_5__Compat.
Require Import
        Coq.Strings.String
        Coq.Arith.Mult
        Coq.Vectors.Vector.

Require Import
        Fiat.Common.SumType
        Fiat.Common.BoundedLookup
        Fiat.Common.ilist
        Fiat.Common.DecideableEnsembles
        Fiat.Common.IterateBoundedIndex
        Fiat.Common.Tactics.CacheStringConstant
        Fiat.Computation
        Fiat.Narcissus.Common.Specs
        Fiat.Narcissus.Common.ComposeOpt
        Fiat.Narcissus.Formats.WordOpt
        Fiat.Narcissus.Formats.NatOpt
        Fiat.Narcissus.Formats.StringOpt
        Fiat.Narcissus.Formats.EnumOpt
        Fiat.Narcissus.Formats.FixListOpt
        Fiat.Narcissus.Formats.SumTypeOpt
        Fiat.Narcissus.Formats.DomainNameOpt
        Fiat.Narcissus.Formats.Vector
        Fiat.Narcissus.BinLib.AlignedByteString
        Fiat.Narcissus.BinLib.AlignWord
        Fiat.Narcissus.BinLib.AlignedDecoders
        Fiat.Narcissus.BinLib.AlignedEncodeMonad
        Fiat.Narcissus.BinLib.AlignedDecodeMonad
        Fiat.Narcissus.BinLib.AlignedList
        Fiat.Narcissus.BaseFormats.

Require Import
        Bedrock.Word.

Section AlignedList.

  Context {cache : Cache}.
  Context {cacheAddNat : CacheAdd cache nat}.

  Definition bytebuffer_of_bytebuffer_range {sz: nat} (from: nat) (len: nat) (v: ByteBuffer.t sz) : { n : _ & ByteBuffer.t n } :=
    let l := List.firstn len (List.skipn from (Vector.to_list v)) in
    existT ByteBuffer.t _ (Vector.of_list l).

  Definition ByteBufferAlignedDecodeM {m : nat} (len: nat) : @AlignedDecodeM cache {n : _ & ByteBuffer.t n} m :=
    fun (v: ByteBuffer.t m) idx env =>
      let lastidx := idx + len in
      if Coq.Init.Nat.leb lastidx m then
        Some ((bytebuffer_of_bytebuffer_range idx len v, lastidx, addD env (8 * len)))
      else
        None.

  Variable addD_addD_plus :
    forall (ce : CacheDecode) (n m : nat), addD (addD ce n) m = addD ce (n + m).
  Variable addD_0 :
    forall ce, addD ce 0 = ce.

  Lemma nth_opt_some
    : forall sz (v : ByteBuffer.t sz) idx,
      lt idx sz
      -> exists b, nth_opt v idx = Some b.
  Proof.
    induction v; simpl; intros.
    - inversion H.
    - destruct idx; simpl.
      + unfold nth_opt; simpl; eauto.
      + apply_in_hyp lt_S_n.
        unfold nth_opt; simpl; eauto.
  Qed.

  Lemma nth_opt_None
    : forall sz (v : ByteBuffer.t sz) idx,
      le sz idx
      -> nth_opt v idx = None.
  Proof.
    induction v; simpl; intros.
    - destruct idx; simpl; try reflexivity.
    - inversion H; subst.
      + eapply IHv; eauto.
      + eapply IHv; Omega.omega.
  Qed.

  Lemma AlignedDecodeByteBufferM {C : Type}
        (n : nat)
    : forall (t : { n : _ & ByteBuffer.t n } -> DecodeM (C * _) ByteString)
        (t' : { n : _ & ByteBuffer.t n } -> forall {numBytes}, AlignedDecodeM C numBytes),
      (forall b, DecodeMEquivAlignedDecodeM (t b) (@t' b))
      -> DecodeMEquivAlignedDecodeM
          (fun v cd => `(b, bs, cd') <- decode_bytebuffer n v cd;
                      t b bs cd')
          (fun numBytes => b <- ByteBufferAlignedDecodeM n;
                          t' b)%AlignedDecodeM%list.
  Proof.
    intros.
    eapply DecodeMEquivAlignedDecodeM_trans with
        (bit_decoder1 := (fun v cd => `(l, bs, cd') <- decode_list decode_word n v cd;
                                      t (existT ByteBuffer.t _ (ByteBuffer.of_list l)) bs cd'))
        (byte_decoder1 := (fun numBytes => l <- ListAlignedDecodeM (fun numBytes : nat => GetCurrentByte) n;
                                           fun v idx cd =>
                                             if (Coq.Init.Nat.leb idx numBytes) then
                                               t' (existT ByteBuffer.t _ (ByteBuffer.of_list l)) _ v idx cd
                                             else None
                          )%AlignedDecodeM%list).
    - eapply AlignedDecodeListM; eauto using AlignedDecodeCharM.
      intros; repeat (eapply conj; intros).
      + simpl; destruct (Coq.Init.Nat.leb n0 (numBytes_hd)) eqn: ? ;
          repeat apply_in_hyp Compare_dec.leb_complete;
          repeat apply_in_hyp Compare_dec.leb_complete_conv;
          try Omega.omega; simpl; eauto.
        pattern numBytes_hd, v; apply caseS; simpl; intros.
        rewrite (proj1 (H _)); reflexivity.
      + eapply H in H0; eauto.
      + rewrite (proj1 (proj2 (proj2 (H _)) _ _ _)) in H0; rewrite H0;
          find_if_inside; reflexivity.
      + destruct (Coq.Init.Nat.leb 0 n0) eqn: ? ;
        repeat apply_in_hyp Compare_dec.leb_complete;
          repeat apply_in_hyp Compare_dec.leb_complete_conv;
          try Omega.omega; simpl; eauto.
        apply (proj2 (proj2 (H _)) _ _ _) in H0; eauto.
      + destruct (Coq.Init.Nat.leb 0 n0) eqn: ? ;
        repeat apply_in_hyp Compare_dec.leb_complete;
          repeat apply_in_hyp Compare_dec.leb_complete_conv;
          try Omega.omega; simpl; eauto.
        eapply H; eauto.
      + eapply H; eauto.
    - clear t' H; revert t; induction n; simpl; intros.
      + reflexivity.
      + unfold decode_bytebuffer.
        destruct (decode_Vector decode_word (S n) b cd) as [ [ [? ?] ? ] | ] eqn: ?; simpl.
        * unfold decode_Vector in Heqo.
          destruct (decode_word b cd) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.
          fold (decode_Vector (decode_word (sz := 8)) n b1 c0) in Heqo.
          rewrite DecodeBindOpt2_assoc; simpl.
          erewrite IHn with (t := fun l => t (existT ByteBuffer.t _ (ByteBuffer.cons w (projT2 l)))).
          unfold decode_bytebuffer.
          destruct (decode_Vector decode_word n b1 c0) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.
          injections.
          reflexivity.
        * unfold decode_Vector in Heqo.
          destruct (decode_word b cd) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.
          fold (decode_Vector (decode_word (sz := 8)) n b0 c) in Heqo.
          rewrite DecodeBindOpt2_assoc; simpl.
          erewrite IHn with (t := fun l => t (existT ByteBuffer.t _ (ByteBuffer.cons w (projT2 l)))).
          unfold decode_bytebuffer.
          destruct (decode_Vector decode_word n b0 c) as [ [ [? ?] ?]  | ]; simpl in *; eauto; try discriminate.
    - intros n0 v idx; generalize t'; revert addD_addD_plus addD_0 n0 idx v. clear; induction n; simpl; intros.
      + eapply AlignedDecodeMEquiv_trans. eapply ReturnAlignedDecodeM_LeftUnit.
        unfold AlignedDecodeMEquiv, ByteBufferAlignedDecodeM, BindAlignedDecodeM; simpl; intros.
        rewrite <- plus_n_O; find_if_inside; simpl; eauto.
        unfold bytebuffer_of_bytebuffer_range; simpl.
        simpl; rewrite addD_0; reflexivity.
      + eapply AlignedDecodeMEquiv_trans.
        eapply BindAlignedDecodeM_assoc.
        eapply AlignedDecodeMEquiv_trans.
        { instantiate (1 := (a <- GetCurrentByte;
                             l <- ListAlignedDecodeM (fun numBytes : nat => GetCurrentByte) n;
                             (fun (v0 : ByteBuffer.t n0) (idx0 : nat) (cd : CacheDecode) =>
                                if Coq.Init.Nat.leb idx0 n0
                                then t' (existT ByteBuffer.t (| (a :: l) |) (ByteBuffer.of_list (a :: l))) n0 v0 idx0 cd
                                else None))%AlignedDecodeM).
          intros ? ? ?; f_equal; apply functional_extensionality; intros.
          unfold AlignedDecodeMEquiv, ByteBufferAlignedDecodeM, BindAlignedDecodeM in *; simpl in *; intros.
          repeat (apply functional_extensionality; intros).
          destruct (ListAlignedDecodeM (fun numBytes : nat => GetCurrentByte) n x0 x1 x2); simpl; eauto.
        }
        unfold AlignedDecodeMEquiv, ByteBufferAlignedDecodeM, BindAlignedDecodeM in *; simpl in *; intros.
        unfold GetCurrentByte at 1.
        destruct (Coq.Init.Nat.leb (idx0 + S n) n0) as [ | ] eqn: ?; simpl;
          repeat apply_in_hyp Compare_dec.leb_complete;
          repeat apply_in_hyp Compare_dec.leb_complete_conv;
          try Omega.omega; simpl; eauto.
        * destruct (nth_opt_some _ v0 idx0); try Omega.omega;
            rewrite H; simpl.
          pose proof (fun t' => IHn addD_addD_plus addD_0 _ (S idx0) v0 t' (addD c0 8)).
          rewrite (Compare_dec.leb_correct (S idx0 + n) n0) in H0 by Omega.omega;
            simpl in H0.
          pose proof (H0 (fun n => t' (existT ByteBuffer.t (S (projT1 n)) (Vector.cons _ x _ (projT2 n))))).
          cbv beta in H1.
          simpl projT1 at 1 in H1; simpl projT2 at 1 in H1.
          simpl projT1 at 1 in H1.
          unfold ByteBuffer.of_list in *; simpl.
          revert Heqb H.
          rewrite H1, addD_addD_plus; clear; intros.
          unfold bytebuffer_of_bytebuffer_range.
          unfold projT1; unfold projT2.
          f_equal; eauto.
          2: f_equal; Omega.omega.
          replace ((skipn idx0 (to_list v0))) with (x :: (skipn (S idx0) (to_list v0)));
            auto.
          generalize n0 v0 H; clear.
          induction idx0; destruct v0; intros.
          -- compute in H; discriminate.
          -- compute in H; injections; reflexivity.
          -- compute in H; discriminate.
          -- unfold nth_opt in H; simpl in H;
               apply_in_hyp IHidx0.
             unfold to_list at 1; fold (@to_list _ n v0).
             replace (skipn (S (S idx0)) (h :: to_list v0)) with
                 (skipn (S idx0) (to_list v0)) by reflexivity.
             rewrite H; reflexivity.
        * destruct (nth_opt v0 idx0); simpl; eauto.
          assert (Coq.Init.Nat.leb (S idx0 + n) n0 = false)
            by (apply Compare_dec.leb_correct_conv; Omega.omega).
          pose proof (fun t' => IHn addD_addD_plus addD_0 _ (S idx0) v0 t' (addD c0 8)).
          rewrite H in H0; simpl in H0.
          pose proof (H0 (fun n => t' (existT ByteBuffer.t (S (projT1 n)) (Vector.cons _ c1 _ (projT2 n))))).
          erewrite <- H1 at -1.
          f_equal; apply functional_extensionality; intro.
  Qed.

  Fixpoint buffer_blit_buffer' {sz1 sz2} start (src: ByteBuffer.t sz1) (dst: ByteBuffer.t sz2) :=
    match src with
    | Vector.nil => dst
    | Vector.cons h _ t => buffer_blit_buffer' (S start) t (set_nth' dst start h)
    end.

  Definition buffer_blit_buffer {sz1 sz2} start (src: ByteBuffer.t sz1) (dst: ByteBuffer.t sz2) :=
    let idx' := start + sz1 in
    if Coq.Init.Nat.leb idx' sz2 then
      Some (buffer_blit_buffer' start src dst, idx')
    else None.

  Definition AlignedEncodeByteBuffer
    : forall sz, AlignedEncodeM (S := { n : _ & ByteBuffer.t n }) sz :=
    fun sz2 (dst: ByteBuffer.t sz2) idx src env =>
      let '(existT len src) := src in
      match buffer_blit_buffer idx src dst with
      | Some (v', idx') => Some (v', idx', addE env (8 * len))
      | None => None
      end.

  Variable addE_addE_plus :
    forall (ce : CacheFormat) (n m : nat), addE (addE ce n) m = addE ce (n + m).
  Variable addE_0 :
    forall ce, addE ce 0 = ce.

  Lemma CorrectAlignedEncoderForFormatByteBuffer
    (encode_word_OK : forall (a : word (1 * 8)) (l : list (word (1 * 8))) (env : CacheFormat)
              (tenv' tenv'' : ByteString * CacheFormat),
            format_word a env ∋ tenv' ->
            format_list format_word l (snd tenv') ∋ tenv'' ->
            exists tenv3 tenv4 : ByteString * CacheFormat,
              projT1 (CorrectAlignedEncoderForFormatNChar addE_addE_plus addE_0) a env = Some tenv3 /\
              format_list format_word l (snd tenv3) ∋ tenv4)
    : CorrectAlignedEncoder format_bytebuffer AlignedEncodeByteBuffer.
  Proof.
    eapply refine_CorrectAlignedEncoder
      with (format' := fun s env => format_list format_word (ByteBuffer.to_list (projT2 s)) env);
      [ | eapply CorrectAlignedEncoder_morphism with
              (encode := fun sz v idx w c => AlignedEncodeList (@SetCurrentByte _ _) sz v idx (ByteBuffer.to_list (projT2 w)) c)].
    - intros [? ?]; clear; split.
      + revert env; induction t; simpl; intros.
        * reflexivity.
        * unfold format_bytebuffer in *; simpl in *; apply refine_under_bind; intros.
          unfold Bind2; rewrite IHt; reflexivity.
      + unfold format_bytebuffer, Bind2 in *.
        intros; intro; eapply (H v).
        clear H; revert env v H0; induction t; simpl; intros.
        * eapply H0.
        * unfold Bind2 in *.
          computes_to_inv.
          computes_to_econstructor; eauto.
          computes_to_econstructor; eauto.
          rewrite H0''; eauto.
    - apply EquivFormat_reflexive.
    - intros ? ? ? [n t]; revert sz v idx; induction t.
      + simpl; intros.
        unfold buffer_blit_buffer.
        destruct (Coq.Init.Nat.leb (idx + 0) sz) eqn: ?; intros.
        * eapply PeanoNat.Nat.leb_le in Heqb.
          rewrite (proj2 (PeanoNat.Nat.ltb_lt idx (S sz))) by Omega.omega.
          unfold ReturnAlignedEncodeM.
          simpl. rewrite <- (addE_0 c) at 2.
          simpl; repeat f_equal; try Omega.omega.
        * eapply PeanoNat.Nat.leb_gt in Heqb.
          rewrite (proj2 (PeanoNat.Nat.ltb_ge idx (S sz))) by Omega.omega.
          reflexivity.
      + simpl; intros.
        unfold buffer_blit_buffer.
        destruct (Coq.Init.Nat.leb (idx + (S n)) sz) eqn: ?; intros.
        * eapply PeanoNat.Nat.leb_le in Heqb.
          unfold SetCurrentByte at 1.
          rewrite (proj2 (PeanoNat.Nat.ltb_lt idx sz)) by Omega.omega; simpl.
          rewrite <- IHt.
          simpl.
          unfold buffer_blit_buffer.
          destruct (Coq.Init.Nat.leb (S idx + n) sz) eqn: ?; intros.
          eapply PeanoNat.Nat.leb_le in Heqb0; simpl;
            rewrite addE_addE_plus; repeat (f_equal; try Omega.omega).
          eapply PeanoNat.Nat.leb_gt in Heqb0; Omega.omega.
        * eapply PeanoNat.Nat.leb_gt in Heqb.
          unfold SetCurrentByte at 1.
          destruct (PeanoNat.Nat.ltb idx sz) eqn: ? ; simpl; auto.
          rewrite <- IHt.
          unfold AlignedEncodeByteBuffer, buffer_blit_buffer.
          destruct (Coq.Init.Nat.leb (S idx + n) sz) eqn: ? ; simpl; auto.
          eapply PeanoNat.Nat.leb_le in Heqb0;
            eapply PeanoNat.Nat.leb_le in Heqb1; Omega.omega.
    - eexists (fun s env => _); repeat apply conj; intros;
        try eapply ((projT2 (CorrectAlignedEncoderForFormatList
                               _ _
                               (CorrectAlignedEncoderForFormatNChar (sz := 1) addE_addE_plus addE_0) encode_word_OK))); eauto.
      pose proof (proj2 (proj2 ((projT2 (CorrectAlignedEncoderForFormatList
                                           _ _
                                           (CorrectAlignedEncoderForFormatNChar (sz := 1) addE_addE_plus addE_0) encode_word_OK))))).
      unfold EncodeMEquivAlignedEncodeM in *; intros ? [? ?] ?; simpl in *.
      intuition.
      eapply H; eauto.
      eapply (proj1 (proj2 (H _ _ _))); eauto.
      eapply (proj1 (proj2 (proj2 (H _ _ _)))); eauto.
      eapply (proj2 (proj2 (proj2 (H _ _ _)))); eauto.
  Qed.

End AlignedList.


From ITree Require Import ITree.
From SimpleIO Require Import SimpleIO.

#[global]
Instance MonadIter_IO : MonadIter IO :=
  fun _ _ f =>
    IO.fix_io (fun self x =>
      IO.bind (f x) (fun y =>
      match y with
      | inl x' => self x'
      | inr r => IO.ret r
      end)).

(** Interpret [itree E] into [IO] given an interpreter of [E].
    This is literally a specialization of [interp]. *)
Definition interp_io {E} : (E ~> IO) -> (itree E ~> IO) :=
  interp.
Arguments interp_io {E} h [T] t.

(** Interpret [itree IO] into [IO]. *)
Definition interp_io' : itree IO ~> IO :=
  interp (E := IO) (M := IO) (fun T (e : IO T) => e).
Arguments interp_io' [T] t.

(** Interpret [itree void1] into [IO]. *)
Definition interp_io_ : itree void1 ~> IO :=
  interp (M := IO) (elim_void1 (E := IO)).
Arguments interp_io_ [T] t.


(* Disable notation conflict warnings *)
Set Warnings "-notation-overridden".

From mathcomp.ssreflect
Require Import ssreflect ssrnat prime ssrbool eqtype.

Require Import Core.
Require Import FV.
Require Import Proofs.Axioms.
Require Import Proofs.ContainerProofs.
Require Import Proofs.VarSet.
Require Import Proofs.VarSetFSet.
Require Import Proofs.Var.

Require Import Coq.Lists.List.
Require Import Coq.Bool.Bool.

Require Import GHC.Base.
Require Import Proofs.Prelude.
Import GHC.Base.ManualNotations.

Require Import Coq.Classes.Morphisms.

Set Bullet Behavior "Strict Subproofs".

(** * Well-formedness of [FV]s. *)

(* A FV is well formed when it is denoted by some VarSet vs. *)

Lemma RespectsVar_const_true : RespectsVar (const true).
Proof. move => x1 x2 Eq. reflexivity. Qed.
Hint Resolve RespectsVar_const_true.
Lemma RespectsVar_andb f0 f:
  RespectsVar f0 -> RespectsVar f ->
  RespectsVar (fun v : Var => f0 v && f v).
Proof.
  move => r1 r2 x1 x2 Eq.
  erewrite r1; eauto.
  erewrite r2; eauto.
Qed.

Reserved Notation "A ⊢ B" (at level 70, no associativity).

Inductive Denotes : VarSet -> FV -> Prop :=
| DenotesVarSet : forall vs fv,
    (forall f in_scope vs' l,
        RespectsVar f ->
        extendVarSetList emptyVarSet l [=] vs' ->
        extendVarSetList emptyVarSet (fst (fv f in_scope (l, vs'))) [=]
        Tuple.snd (fv f in_scope (l, vs')) /\
        Tuple.snd (fv f in_scope (l, vs')) [=]
        unionVarSet (minusVarSet (filterVarSet f vs) in_scope) vs') ->
    vs ⊢ fv
where "A ⊢ B" := (Denotes A B).

Theorem Denotes_fvVarSet : forall m fv f in_scope l vs,
    m ⊢ fv ->
    RespectsVar f ->
    extendVarSetList emptyVarSet l [=] vs ->
    Tuple.snd (fv f in_scope (l, vs)) [=]
    unionVarSet (minusVarSet (filterVarSet f m) in_scope) vs.
Proof.
  move => m fv f in_scope l vs [vs' fv' H0] H1 H2.
  specialize (H0 f in_scope vs l H1 H2); subst.
  destruct fv'.
  move: H0 => [h0 h1].
  auto.
Qed.

Lemma Denotes_Equal vs1 vs2 f : vs1 [=] vs2 -> Denotes vs1 f -> Denotes vs2 f.
Proof.
  move => Eqx.
  move=> h. inversion h. subst.
  constructor.
  move => f0 in_scope vs' l RV EX.
  specialize (H f0 in_scope vs' l RV EX).
  move: H => [h0 h1].
  split. done.
  rewrite h1.
  f_equiv.
  f_equiv.
  apply filterVarSet_equal; eauto.
Qed.

Require Import Coq.Classes.Morphisms.
Instance Denotes_m : Proper (Equal ==> Logic.eq ==> iff) Denotes.
Proof.
  move=> vs1 vs2 EqV f0 f EqF. rewrite EqF.
  split; apply Denotes_Equal; try done.
  symmetry. auto.
Qed.

Definition WF_fv (fv : FV) : Prop := exists vs, vs ⊢ fv.

Ltac unfold_WF :=
  repeat match goal with
  | [ H : WF_fv ?fv |- _] =>
    let vs := fresh "vs" in
    let Hd := fresh "Hdenotes" in
    inversion H as [vs Hd]; inversion Hd; subst; clear H
  | [ |- WF_fv ?fv ] =>
    unfold WF_fv
  end.

(* We show that the various operations on FVs produce well-formed FVs. *)

Lemma emptyVarSet_emptyFV : Denotes emptyVarSet emptyFV.
Proof.
  constructor; intros; subst.
  unfold emptyFV.
  unfold Tuple.fst, Tuple.snd.
  hs_simpl.
  split; auto.
  reflexivity.
Qed.

Lemma empty_FV_WF :
  WF_fv emptyFV.
Proof.
  unfold WF_fv. exists emptyVarSet. eapply emptyVarSet_emptyFV.
Qed.

Lemma unitVarSet_unitFV x : Denotes (unitVarSet x) (unitFV x).
Proof.
  constructor; intros; subst.
  unfold fst, snd.
  unfold unitFV.
  destruct elemVarSet eqn:E1;
  destruct (f x) eqn:FX;
  hs_simpl; split; auto.
  - rewrite -> filterSingletonTrue; try done.
    rewrite elemVarSet_minusVarSetTrue; try done.
    hs_simpl.
    reflexivity.
  - rewrite filterSingletonFalse; try done.
    hs_simpl.
    reflexivity.
  - elim In: (elemVarSet x vs') => //.
    hs_simpl.
    rewrite <- H0.
    rewrite extendVarSetList_extendVarSet_iff.
    reflexivity.
  - rewrite filterSingletonTrue; try done.
    rewrite elemVarSet_minusVarSetFalse; try done.
    elim E2: (elemVarSet x vs').
    hs_simpl.
    set_b_iff.
    rewrite add_equal; try done.
    hs_simpl.
    reflexivity.
  - elim E2: (elemVarSet x vs'); done.
  - rewrite filterSingletonFalse; try done.
    hs_simpl.
    elim E2: (elemVarSet x vs'); done.
Qed.

Lemma unit_FV_WF :
  forall x, WF_fv (unitFV x).
Proof.
  move=>x. unfold WF_fv.
  exists (unitVarSet x).
  eapply unitVarSet_unitFV.
Qed.

Lemma filterVarSet_filterFV f vs x :
  Proper ((fun x0 y : Var => x0 == y) ==> Logic.eq) f ->
  Denotes vs x -> Denotes (filterVarSet f vs) (filterFV f x).
Proof.
  move => p D.
  constructor. move=> f0 in_scope vs' l h0 h1.
  inversion D.
  unfold filterFV.
  specialize (H (fun v : Var => f0 v && f v) in_scope vs' l ltac:(eauto using RespectsVar_andb)).
  destruct H. auto.
  rewrite H.
  rewrite H2.
  rewrite <- filterVarSet_comp.
  split; reflexivity.
Qed.

Lemma filter_FV_WF : forall f x,
    RespectsVar f ->
    WF_fv x -> WF_fv (filterFV f x).
Proof.
  intros. unfold_WF.
  exists (filterVarSet f vs).
  eapply filterVarSet_filterFV; auto.
Qed.

Lemma delVarSet_delFV vs v fv :
  Denotes vs fv -> Denotes (delVarSet vs v) (delFV v fv).
Proof.
  move=> H. inversion H.
  constructor; intros. unfold delFV.
  specialize (H0 f (extendVarSet in_scope v) vs' l H3 H4).
  destruct H0. intuition. rewrite H5.
  destruct (fv f (extendVarSet in_scope v)) as [l0 h0] eqn:h.
  simpl in *.
  apply union_equal_1.
  move => x.
  unfold VarSetFSet.In.
  rewrite !elemVarSet_minusVarSet.
  split.
  - move=> /andP [h1 h2].
    apply /andP.
    hs_simpl in h2.
    rewrite negb_or in h2.
    move: h2 => /andP.
    move => [h3 h4].
    intuition.
    rewrite elemVarSet_filterVarSet in h1 => //.
    rewrite elemVarSet_filterVarSet => // .
    apply /andP.
    move: h1 => /andP [h1 h2].
    rewrite elemVarSet_delVarSet.
    split; auto.
    apply /andP. split; auto.
  - move=> /andP [h1 h2].
    apply /andP.

    rewrite elemVarSet_filterVarSet in h1 => //.
    move: h1 => /andP. move => [h3 h4].
    elim hf: (f x); rewrite hf in h3; try done; clear h3.
    rewrite elemVarSet_delVarSet in h4.
    induction (v GHC.Base.== x) eqn:ev.
    + done.
    + move: h4 => /andP. move => [h5 h6].
      rewrite elemVarSet_filterVarSet => //.
      rewrite elemVarSet_extendVarSet.
      rewrite hf.
      rewrite ev.
      rewrite h6.
      done.
Qed.

Lemma del_FV_WF : forall fv v,
    WF_fv fv -> WF_fv (delFV v fv).
Proof.
  intros. unfold_WF.
  exists (delVarSet vs v).
  eapply delVarSet_delFV. auto.
Qed.

Lemma unionVarSet_unionFV vs vs' fv fv' :
  Denotes vs fv -> Denotes vs' fv' -> Denotes (unionVarSet vs vs') (unionFV fv' fv).
Proof.
  move=> H H1. inversion H. inversion H1. subst.
  constructor.
  move=> f in_scope vs1 l h h0.
  unfold unionFV.
  specialize (H0 f in_scope vs1 l h h0).  move: H0 => [h1 h2].
  remember (fv f in_scope (l, vs1)) as vs_mid.
  specialize (H4 f in_scope (Tuple.snd vs_mid) (Tuple.fst vs_mid) h h1); move: H4 => [h3 h4].
  replace vs_mid with (Tuple.fst vs_mid, Tuple.snd vs_mid); [| destruct vs_mid; reflexivity].
  intuition.
  remember (fv' f in_scope (Tuple.fst vs_mid, Tuple.snd vs_mid)) as vs_fin.
  rewrite h4.
  rewrite h2.
  rewrite <- union_assoc.
  apply union_equal_1.
  rewrite -> unionVarSet_minusVarSet.
  rewrite unionVarSet_filterVarSet => //.
  f_equiv.
  apply filterVarSet_equal; try done.
  set_b_iff. rewrite union_sym.
  reflexivity.
Qed.

Lemma union_FV_WF : forall fv fv',
    WF_fv fv -> WF_fv fv' -> WF_fv (unionFV fv fv').
Proof.
  intros. unfold_WF.
  exists (unionVarSet vs vs0).
  eapply unionVarSet_unionFV; eauto.
Qed.

Lemma mapUnionFV_nil A f :
  mapUnionFV f (nil : list A) = emptyFV.
Proof.
  simpl.
  unfold emptyFV.
  reflexivity.
Qed.
Hint Rewrite mapUnionFV_nil : hs_simpl.

Lemma mapUnionFV_cons A f (x : A) xs :
  mapUnionFV f (x :: xs) = unionFV (mapUnionFV f xs) (f x).
Proof.
  simpl.
  unfold unionFV.
  reflexivity.
Qed.
Hint Rewrite mapUnionFV_cons : hs_simpl.

Lemma map_union_FV_WF : forall A f (ls : list A),
    (forall e, In e ls -> WF_fv (f e)) ->
    WF_fv (mapUnionFV f ls).
Proof.
  induction ls.
  - intros.
    exists emptyVarSet.
    hs_simpl.
    eapply emptyVarSet_emptyFV.
  -  move=> h. simpl in h.
    assert (h0 : forall e : A, In e ls -> WF_fv (f e)). { intros. apply h. tauto. }
    apply IHls in h0.
    assert (WF_fv (f a)). { apply h; tauto. }
    hs_simpl.
    move: h0 => [vs D].
    move: H => [vs' D'].
    eexists.
    eapply unionVarSet_unionFV; eauto.
Qed.

Lemma unions_FV_WF : forall fvs,
    (forall fv, In fv fvs -> WF_fv fv) ->
    WF_fv (unionsFV fvs).
Proof.
  apply map_union_FV_WF.
Qed.

Lemma mkFVs_FV_WF : forall vs,
    WF_fv (mkFVs vs).
Proof.
  intros. apply map_union_FV_WF; intros. apply unit_FV_WF.
Qed.

Hint Resolve unit_FV_WF.
Hint Resolve empty_FV_WF.
Hint Resolve union_FV_WF.
Hint Resolve unions_FV_WF.
Hint Resolve del_FV_WF.
Hint Resolve mkFVs_FV_WF.

(** * Some other theroems about [FV]s. *)

Lemma union_empty_l : forall fv, FV.unionFV FV.emptyFV fv = fv.
Proof. reflexivity. Qed.

Lemma union_empty_r : forall fv, FV.unionFV fv FV.emptyFV = fv.
Proof. reflexivity. Qed.

Lemma DenotesfvVarSet vs fv :
  Denotes vs fv -> fvVarSet fv [=] vs.
Proof.
  move => [vs0 fv0 h1].
  unfold fvVarSet, op_z2218U__, fvVarListVarSet, Tuple.snd.
  specialize (h1 (const true) emptyVarSet emptyVarSet nil ltac:(eauto)).
  destruct h1.
  rewrite extendVarSetList_nil.
  reflexivity.
  remember (fv0 (const true) emptyVarSet (nil, emptyVarSet)) as tup.
  replace tup with (Tuple.fst tup, Tuple.snd tup); [| destruct tup; reflexivity].
  rewrite H0.
  hs_simpl.
  reflexivity.
Qed.

Lemma Denotes_inj1 vs1 vs2 fv : Denotes vs1 fv -> Denotes vs2 fv -> vs1 [=] vs2.
Proof.
  move => h1. inversion h1.
  move => h2. inversion h2.
  subst.
  set in_scope := emptyVarSet.
  assert (h : extendVarSetList emptyVarSet nil [=] emptyVarSet).
  { rewrite <- mkVarSet_extendVarSetList. reflexivity. }
  specialize (H (const true) in_scope emptyVarSet nil ltac:(auto) h).
  specialize (H2 (const true) in_scope emptyVarSet nil ltac:(auto) h).
  move: H => [h3 h4].
  move: H2 => [h5 h6].
  remember (fv (const true) emptyVarSet (nil,emptyVarSet)) as tup1.
  replace tup1 with (Tuple.fst tup1, Tuple.snd tup1); [| destruct tup1; reflexivity].
  remember (fv (const true) emptyVarSet (nil,emptyVarSet)) as tup2.
  replace tup2 with (Tuple.fst tup2, Tuple.snd tup2); [| destruct tup2; reflexivity].
  hs_simpl in h4.
  hs_simpl in h6.
  rewrite <- h4.
  rewrite <- h6.
  reflexivity.
Qed.

Lemma unionVarSet_same vs : unionVarSet vs vs [=] vs.
Proof. set_b_iff. fsetdec. Qed.
Hint Rewrite unionVarSet_same : hs_simpl.

Lemma delVarSet_fvVarSet: forall fv x,
    WF_fv fv ->
    delVarSet (fvVarSet fv) x [=] fvVarSet (delFV x fv).
Proof.
  move => fv x [vs D].
  move: (delVarSet_delFV _ x _ D) => h1.
  move: (DenotesfvVarSet _ _ h1) => h2.
  move: (DenotesfvVarSet _ _ D) => h3.
  rewrite h3.
  rewrite h2.
  reflexivity.
Qed.

(* --------------------------------------- *)

Lemma mapUnionVarSet_mapUnionFV A (ps : list A)
      (f1 :  A -> VarSet) (f2 : A -> FV.FV) :
  Forall2 Denotes (map f1 ps) (map f2 ps) ->
  Denotes  (mapUnionVarSet f1 ps) (FV.mapUnionFV f2 ps).
Proof.
  elim: ps => [|p ps IH]; unfold mapUnionVarSet; simpl.
  hs_simpl.
  - move=>h. constructor; intros; subst.
    unfold Tuple.fst, Tuple.snd.
    hs_simpl.
    split; auto.
    reflexivity.
  - hs_simpl.
    move=>h. inversion h. subst.
    unfold mapUnionVarSet in IH.
    specialize (IH H4). clear H4.
    move: (unionVarSet_unionFV _ _ _ _ H2 IH) => h0.
    unfold FV.unionFV in h0.
    auto.
Qed.

Lemma unionsFV_cons fv fvs :
  FV.unionsFV (fv :: fvs) =
  FV.unionFV (FV.unionsFV fvs) fv.
Proof.
  repeat unfold FV.unionsFV, FV.unionFV.
  rewrite mapUnionFV_cons.
  unfold FV.unionFV.
  simpl.
  reflexivity.
Qed.

Lemma unionsVarSet_unionsFV vss fvs:
   Forall2 Denotes vss fvs ->
   Denotes (Foldable.foldr unionVarSet emptyVarSet vss) (FV.unionsFV fvs).
Proof.
  elim.
  - hs_simpl.
    unfold FV.unionsFV, FV.mapUnionFV.
    constructor; intros; subst.
    unfold Tuple.fst, Tuple.snd.
    hs_simpl.
    split; auto.
    reflexivity.
  - move => vs fv vss1 fvs1 D1 D2 IH.
    hs_simpl.
    move: (unionVarSet_unionFV _ _ _ _ D1 IH) => h0.
    rewrite unionsFV_cons.
    auto.
Qed.


(** MetaType.v *)
From Babel Require Import TerminalDogma
                          ExtraDogma.Extensionality
                          SetFacility
                          POrderFacility.

From Babel Require Import Ranko
                            ExtensionalityCharacter
                            ClassicalCharacter.

From Babel Require Export MetaLanguage.Notations
                            Parity.

From Coq Require Import Relations Classical.

Set Implicit Arguments.
Unset Strict Implicit.
Unset Printing Implicit Defensive.

(****************************************)
(*                                      *)
(*       DMT                            *)
(*       (Deduction Metatype)           *)
(*                                      *)
(****************************************)

Module DMT.
Section ClassDef.

Record mixin_of (T : iType) := Mixin {
    ded_sys : T -> T -> Prop;
}.

Notation class_of := mixin_of (only parsing).

Record type := Pack {
    sort : iType;
    class : class_of sort;
}.

End ClassDef.

Module Exports.

#[reversible]
Coercion sort : type >-> iType.

Coercion class : type >-> mixin_of.

Notation dMT := type.
Notation DMT s m := (@Pack s m).
Notation Dsys := ded_sys.

Notation " ax ⊢ P ⇒ Q " := ((Dsys ax) P Q) : MetaLan_scope.

End Exports.
End DMT.
Export DMT.Exports.

(****************************************)
(*                                      *)
(*       cpoDMT                         *)
(*       (cpo with Deduction Metatype)  *)
(*                                      *)
(****************************************)

Module CpoDMT.

Section ClassDef.

Record mixin_of (T : iType)
        (b_cpo : CPO.class_of T) (b_dMT : DMT.mixin_of T)
        (bcpo := CPO T b_cpo) (bdMT := DMT T b_dMT):= Mixin {

    ded_iffP : forall (P Q : bcpo),
        P ⊑ Q   <->   bdMT ⊢ P ⇒ Q;
}.

Record class_of (T : iType) := Class {
    b_cpo : CPO.class_of T;
    b_dMT : DMT.mixin_of T;
    mixin : mixin_of b_cpo b_dMT;
}.

Record type := Pack {
    sort : iType;
    class : class_of sort;
}.

Local Coercion sort : type >-> iType.
Local Coercion class : type >-> class_of.

Variable (cT : type).

Definition pack (T : iType) (b_cpo : CPO.class_of T) (b_dMT : DMT.mixin_of T)
    (m : mixin_of b_cpo b_dMT) : type := @Pack T (Class m).

Definition to_cpo : cpo := CPO cT (b_cpo cT).
Definition to_dMT : dMT := DMT cT (b_dMT cT).

End ClassDef.

Module Exports.

#[reversible]
Coercion sort : type >-> iType.
Coercion to_cpo : type >-> cpo.
Coercion to_dMT : type >-> dMT.
Coercion class : type >-> class_of.

Notation cpoDMT := type.
Notation CpoDMT T m := (@pack T _ _ m).

End Exports.

End CpoDMT.
Export CpoDMT.Exports.

(****************************************)
(*                                      *)
(*       BaseMT                         *)
(*       (Basic Metatype)               *)
(*                                      *)
(****************************************)
Module BaseMT.

Section ClassDef.

Record mixin_of (FType BType : iType) := Mixin {
    SVal : clattice;
    sat_eval : BType -> FType -> SVal;
}.

Notation class_of := mixin_of (only parsing).

(** This acts as the basic rules of this program world. *)
Record type := Pack {
    fType : iType;
    bType : iType;
    class : class_of fType bType;
}.

Local Coercion class : type >-> mixin_of.

End ClassDef.

Module Exports.

Coercion class : type >-> mixin_of.

Notation baseMT := type.
Notation BaseMT fT bT m := (@Pack fT bT m).

Notation FType := fType.
Notation BType := bType.
Notation SVal := SVal.

Notation " P ∙ s " := (sat_eval (class _) P s) : MetaLan_scope.
Notation " P ∙ s :> mT" := (sat_eval (class mT) P s)
    (only parsing): MetaLan_scope.
Notation " ⌈ x ⇒ y ⌉ " := (forall P, P ∙ x ⊑ P ∙ y) : MetaLan_scope.
Notation " ⌈ x ⇒ y ⌉ :> mT " := (forall P, P ∙ x :> mT ⊑ P ∙ y :> mT)
    (only parsing): MetaLan_scope.

End Exports.
End BaseMT.
Export BaseMT.Exports.

(** How to do parity transformation? *)
Definition Parity_Trans : baseMT -> baseMT :=
    fun b =>
    {|
        BaseMT.fType := BType b;
        BaseMT.bType := FType b;
        BaseMT.class := {|
            BaseMT.SVal := SVal b;
            BaseMT.sat_eval := fun bt ft => BaseMT.sat_eval b ft bt;
        |};
    |}.

Definition parity_trans_involutive :
    forall b : baseMT, Parity_Trans (Parity_Trans b) = b.
Proof. move => [] ? ? [] => //=. Qed.

Section BaseMT_Theories.

Variable (mT : baseMT).

(** Definition of two kinds of correctness *)
Definition correct
    (x : FType mT) (f : BType mT -> BType mT) (y : FType mT) : Prop :=
        forall P, P ∙ x ⊑ (f P)∙ y.

(** Extensionality *)
Definition sat_eq : FType mT -> FType mT -> Prop :=
    fun x y => forall P, P ∙ x = P ∙ y.

(** Proof of equivalence relation. *)
Lemma sat_eq_refl :
    reflexive _ sat_eq.
Proof. by rewrite /sat_eq.  Qed.

Lemma sat_eq_trans :
    transitive _ sat_eq.
Proof.
    rewrite /transitive => P Q R.
    rewrite /sat_eq => HPQ HQR x.
    rewrite -HQR. apply HPQ.
Qed.

Lemma sat_eq_symm :
    symmetric _ sat_eq.
Proof.
    rewrite /symmetric => P Q.
    rewrite /sat_eq => H x. by rewrite H.
Qed.

Add Relation _ sat_eq
    reflexivity proved by sat_eq_refl
    symmetry proved by sat_eq_symm
    transitivity proved by sat_eq_trans
    as sat_eq_rel.

(** Morphism between extensional equivalence and correctness *)
Add Morphism correct
    with signature sat_eq ==> eq ==> sat_eq ==> iff
        as correct_mor.
Proof.
    move => P Q HPQ f R S HRS.
    rewrite /correct. split.
    - move => H s. rewrite -(HPQ s) -(HRS (f s)). by apply H.
    - move => H s. rewrite (HPQ s) (HRS (f s)). by apply H.
Qed.

(** Injection and Equivalence *)
(** IMPORTANT : this is actually the ability of distinguish of [Asn] or [Stt]. *)
Definition sat_eval_inj :=
    forall (x y : FType mT), sat_eq x y -> x = y.

End BaseMT_Theories.

Notation " ⊨ { P } f { Q } " := (@correct _ P f Q) : MetaLan_scope.
Notation " ⊨ [ x ] g [ y ] " := (@correct _ x g y) : MetaLan_scope.
Notation " P '=FD' Q " := (@sat_eq _ P Q) : MetaLan_scope.

(****************************************)
(*                                      *)
(*       cpoMT                          *)
(*       (CPO Metatype)                 *)
(*                                      *)
(****************************************)

Module CpoMT.

Section ClassDef.

Record mixin_of (fType bType : iType)
            (b : BaseMT.mixin_of fType bType)
            (b_cpo : CPO.class_of fType)
            (base := BaseMT _ _ b) (bcpo := CPO _ b_cpo)
        := Mixin {

    sat_eval_monotonicity : forall (x y : bcpo), x ⊑ y <-> ⌈ x ⇒ y ⌉ :> base;
}.

Record class_of (fType bType : iType) := Class {
    base : BaseMT.mixin_of fType bType;
    base_cpo : CPO.class_of fType;
    mixin : mixin_of base base_cpo;
}.

Record type := Pack {
    fType : iType;
    bType : iType;
    class : class_of fType bType;
}.

Local Coercion class : type >-> class_of.

Definition to_baseMT (c : type) : baseMT :=
    BaseMT _ _ (base c).

Definition fType_cpo (c : type) : cpo := CPO _ (base_cpo c).

Lemma sat_eval_monotonicity_wrap (cT : type) :
    forall (x y : (fType_cpo cT)), x ⊑ y <-> ⌈ x ⇒ y ⌉ :> (to_baseMT cT).
Proof. apply sat_eval_monotonicity. by apply (class cT). Qed.

End ClassDef.

Module Exports.

Coercion class : type >-> class_of.
Coercion mixin : class_of >-> mixin_of.

Coercion to_baseMT : type >-> baseMT.

Notation FType_cpo := fType_cpo.
Notation Sat_eval_monotonicity := sat_eval_monotonicity_wrap.

Notation cpoMT := type.
Notation CpoMT fT bT m := (@Pack fT bT (Class m)).

End Exports.
End CpoMT.

Export CpoMT.Exports.

Section CpoMT_Theories.

Variable (mT : cpoMT).

Add Morphism (@ord_op (FType_cpo mT))
    with signature (@sat_eq mT) ==> (@sat_eq mT) ==> iff
        as fType_le_mor.
Proof.
    move => x y Hxy r s Hrs.
    rewrite /correct. rewrite !Sat_eval_monotonicity.
    split.
    - move => H P. rewrite -Hxy -Hrs. by apply H.
    - move => H P. rewrite Hxy Hrs. by apply H.
Qed.

Lemma cpoMT_sat_eval_inj : sat_eval_inj mT.
Proof.
    rewrite /sat_eval_inj => x y Hxy.
    apply (@poset_antisym (FType_cpo mT)).
    all: apply Sat_eval_monotonicity => P; rewrite Hxy; by reflexivity.
Qed.

End CpoMT_Theories.

(****************************************)
(*                                      *)
(*       CLatticeMT                     *)
(*                                      *)
(*       (Complete Lattice)             *)
(****************************************)

Module CLatticeMT.

Section ClassDef.

Record mixin_of (fType bType: iType)
        (b : CpoMT.class_of fType bType) (b_cl : CLattice.class_of fType)
        (mT := CpoMT fType bType b) (cl := CLattice fType b_cl)
            := Mixin {

    sat_eval_join_mor :
        forall (X : 𝒫(cl)) (P : BType mT),
          P ∙ (⊔ᶜˡ X) = ⊔ᶜˡ { P ∙ s, s | s ∈ X };
}.

Record class_of (fType bType : iType) := Class {
    b_cpoMT : CpoMT.class_of fType bType;
    b_cl : CLattice.class_of fType;
    mixin : mixin_of b_cpoMT b_cl;
}.

Record type := Pack {
    fType : iType;
    bType : iType;
    class : class_of fType bType;
}.

Local Coercion class : type >-> class_of.

Definition to_cpoMT (cT : type) : cpoMT := CpoMT _ _ (b_cpoMT cT).
Definition FType_clattice (cT : type) : clattice := CLattice _ (b_cl cT).

Lemma sat_eval_join_mor_wrap (cT : type) :
    forall (X : 𝒫(FType_clattice cT)) (P : BType (to_cpoMT cT)),
        P ∙ (⊔ᶜˡ X) = ⊔ᶜˡ { P ∙ s, s | s ∈ X }.
Proof. apply sat_eval_join_mor. apply (mixin cT). Qed.

End ClassDef.

Module Exports.

Coercion to_cpoMT : type >-> cpoMT.
Coercion class : type >-> class_of.

Notation FType_clattice := FType_clattice.
Canonical FType_clattice.

Notation Sat_eval_join_mor := sat_eval_join_mor_wrap.

Notation cLatticeMT := type.
Notation CLatticeMT fT bT m := (@Pack fT bT (Class m)).

End Exports.
End CLatticeMT.

Export CLatticeMT.Exports.


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

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

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

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

Set Implicit Arguments.

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

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

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

Inductive operation : Type :=
  | Omove: operation                    (**r [rd = r1] *)
  | Ointconst: int -> operation         (**r [rd] is set to the given integer constant *)
  | Ofloatconst: float -> operation     (**r [rd] is set to the given float constant *)
  | Osingleconst: float32 -> operation  (**r [rd] is set to the given float constant *)
  | Oaddrsymbol: ident -> ptrofs -> operation (**r [rd] is set to the the address of the symbol plus the offset *)
  | Oaddrstack: ptrofs -> operation     (**r [rd] is set to the stack pointer plus the given offset *)
(*c Integer arithmetic: *)
  | Ocast8signed: operation             (**r [rd] is 8-bit sign extension of [r1] *)
  | Ocast16signed: operation            (**r [rd] is 16-bit sign extension of [r1] *)
  | Oadd: operation                     (**r [rd = r1 + r2] *)
  | Oaddimm: int -> operation           (**r [rd = r1 + n] *)
  | Oaddsymbol: ident -> ptrofs -> operation (**r [rd = addr(id + ofs) + r1] *)
  | Osub: operation                     (**r [rd = r1 - r2] *)
  | Osubimm: int -> operation           (**r [rd = n - r1] *)
  | Omul: operation                     (**r [rd = r1 * r2] *)
  | Omulimm: int -> operation           (**r [rd = r1 * n] *)
  | Omulhs: operation                   (**r [rd = high part of r1 * r2, signed] *)
  | Omulhu: operation                   (**r [rd = high part of r1 * r2, unsigned] *)
  | Odiv: operation                     (**r [rd = r1 / r2] (signed) *)
  | Odivu: operation                    (**r [rd = r1 / r2] (unsigned) *)
  | Oand: operation                     (**r [rd = r1 & r2] *)
  | Oandimm: int -> operation           (**r [rd = r1 & n] *)
  | Oor: operation                      (**r [rd = r1 | r2] *)
  | Oorimm: int -> operation            (**r [rd = r1 | n] *)
  | Oxor: operation                     (**r [rd = r1 ^ r2] *)
  | Oxorimm: int -> operation           (**r [rd = r1 ^ n] *)
  | Onot: operation                     (**r [rd = ~r1] *)
  | Onand: operation                    (**r [rd = ~(r1 & r2)] *)
  | Onor: operation                     (**r [rd = ~(r1 | r2)] *)
  | Onxor: operation                    (**r [rd = ~(r1 ^ r2)] *)
  | Oandc: operation                    (**r [rd = r1 & ~r2] *)
  | Oorc: operation                     (**r [rd = r1 | ~r2] *)
  | Oshl: operation                     (**r [rd = r1 << r2] *)
  | Oshr: operation                     (**r [rd = r1 >> r2] (signed) *)
  | Oshrimm: int -> operation           (**r [rd = r1 >> n] (signed) *)
  | Oshrximm: int -> operation          (**r [rd = r1 / 2^n] (signed) *)
  | Oshru: operation                    (**r [rd = r1 >> r2] (unsigned) *)
  | Orolm: int -> int -> operation      (**r rotate left and mask *)
  | Oroli: int -> int -> operation      (**r rotate left and insert *)
(*c PPC64 64-bit integer arithmetic: *)
  | Olongconst: int64 -> operation      (**r [rd] is set to the given int64 constant *)
  | Ocast32signed: operation            (**r [rd] is 64-bit sign extension of [r1] *)
  | Ocast32unsigned: operation          (**r [rd] is 64-bit zero extension of [r1] *)
  | Oaddl: operation                    (**r [rd = r1 + r2] *)
  | Oaddlimm: int64 -> operation        (**r [rd = r1 + n] *)
  | Osubl: operation                    (**r [rd = r1 - r2] *)
  | Onegl: operation                    (**r [rd = - r1] *)
  | Omull: operation                    (**r [rd = r1 * r2] *)
  | Omullhs: operation                  (**r [rd = high part of r1 * r2, signed] *)
  | Omullhu: operation                  (**r [rd = high part of r1 * r2, unsigned] *)
  | Odivl: operation                    (**r [rd = r1 / r2] (signed) *)
  | Odivlu: operation                   (**r [rd = r1 / r2] (unsigned) *)
  | Oandl: operation                    (**r [rd = r1 & r2] *)
  | Oandlimm: int64 -> operation        (**r [rd = r1 & n] *)
  | Oorl: operation                     (**r [rd = r1 | r2] *)
  | Oorlimm: int64 -> operation         (**r [rd = r1 | n] *)
  | Oxorl: operation                    (**r [rd = r1 ^ r2] *)
  | Oxorlimm: int64 -> operation        (**r [rd = r1 ^ n] *)
  | Onotl: operation                    (**r [rd = ~r1] *)
  | Oshll: operation                    (**r [rd = r1 << r2] *)
  | Oshrl: operation                    (**r [rd = r1 >> r2] (signed) *)
  | Oshrlimm: int -> operation          (**r [rd = r1 >> n] (signed) *)
  | Oshrxlimm: int -> operation         (**r [rd = r1 / 2^n] (signed) *)
  | Oshrlu: operation                   (**r [rd = r1 >> r2] (unsigned) *)
  | Orolml: int -> int64 -> operation   (**r rotate left and mask *)
  | Olongoffloat: operation             (**r [rd = signed_int64_of_float(r1)] *)
  | Ofloatoflong: operation             (**r [rd = float_of_signed_int64(r1)] *)
(*c Floating-point arithmetic: *)
  | Onegf: operation                    (**r [rd = - r1] *)
  | Oabsf: operation                    (**r [rd = abs(r1)] *)
  | Oaddf: operation                    (**r [rd = r1 + r2] *)
  | Osubf: operation                    (**r [rd = r1 - r2] *)
  | Omulf: operation                    (**r [rd = r1 * r2] *)
  | Odivf: operation                    (**r [rd = r1 / r2] *)
  | Onegfs: operation                   (**r [rd = - r1] *)
  | Oabsfs: operation                   (**r [rd = abs(r1)] *)
  | Oaddfs: operation                   (**r [rd = r1 + r2] *)
  | Osubfs: operation                   (**r [rd = r1 - r2] *)
  | Omulfs: operation                   (**r [rd = r1 * r2] *)
  | Odivfs: operation                   (**r [rd = r1 / r2] *)
  | Osingleoffloat: operation           (**r [rd] is [r1] truncated to single-precision float *)
  | Ofloatofsingle: operation           (**r [rd] is [r1] extended to double-precision float *)
(*c Conversions between int and float: *)
  | Ointoffloat: operation              (**r [rd = signed_int_of_float(r1)] *)
  | Ofloatofwords: operation            (**r [rd = float_of_words(r1,r2)] *)
(*c Manipulating 64-bit integers: *)
  | Omakelong: operation                (**r [rd = r1 << 32 | r2] *)
  | Olowlong: operation                 (**r [rd = low-word(r1)] *)
  | Ohighlong: operation                (**r [rd = high-word(r1)] *)
(*c Boolean tests: *)
  | Ocmp: condition -> operation        (**r [rd = 1] if condition holds, [rd = 0] otherwise. *)
  | Osel: condition -> typ -> operation.
                                        (**r [rd = rs1] if condition holds, [rd = rs2] otherwise. *)

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

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

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

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

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

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

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

Global Opaque eq_condition eq_addressing eq_operation.

(** * Evaluation functions *)

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

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

Definition eval_operation
             (F V: Type) (genv: Genv.t F V) (sp: val)
             (op: operation) (vl: list val) (m: mem): option val :=
  match op, vl with
  | Omove, v1::nil => Some v1
  | Ointconst n, nil => Some (Vint n)
  | Ofloatconst n, nil => Some (Vfloat n)
  | Osingleconst n, nil => Some (Vsingle n)
  | Oaddrsymbol s ofs, nil => Some (Genv.symbol_address genv s ofs)
  | Oaddrstack ofs, nil => Some (Val.offset_ptr sp ofs)
  | Ocast8signed, v1::nil => Some (Val.sign_ext 8 v1)
  | Ocast16signed, v1::nil => Some (Val.sign_ext 16 v1)
  | Oadd, v1::v2::nil => Some (Val.add v1 v2)
  | Oaddimm n, v1::nil => Some (Val.add v1 (Vint n))
  | Oaddsymbol s ofs, v1::nil => Some (Val.add (Genv.symbol_address genv s ofs) v1)
  | Osub, v1::v2::nil => Some (Val.sub v1 v2)
  | Osubimm n, v1::nil => Some (Val.sub (Vint n) v1)
  | Omul, v1::v2::nil => Some (Val.mul v1 v2)
  | Omulimm n, v1::nil => Some (Val.mul v1 (Vint n))
  | Omulhs, v1::v2::nil => Some (Val.mulhs v1 v2)
  | Omulhu, v1::v2::nil => Some (Val.mulhu v1 v2)
  | Odiv, v1::v2::nil => Val.divs v1 v2
  | Odivu, v1::v2::nil => Val.divu v1 v2
  | Oand, v1::v2::nil => Some(Val.and v1 v2)
  | Oandimm n, v1::nil => Some (Val.and v1 (Vint n))
  | Oor, v1::v2::nil => Some(Val.or v1 v2)
  | Oorimm n, v1::nil => Some (Val.or v1 (Vint n))
  | Oxor, v1::v2::nil => Some(Val.xor v1 v2)
  | Oxorimm n, v1::nil => Some (Val.xor v1 (Vint n))
  | Onot, v1::nil => Some(Val.notint v1)
  | Onand, v1::v2::nil => Some (Val.notint (Val.and v1 v2))
  | Onor, v1::v2::nil => Some (Val.notint (Val.or v1 v2))
  | Onxor, v1::v2::nil => Some (Val.notint (Val.xor v1 v2))
  | Oandc, v1::v2::nil => Some (Val.and v1 (Val.notint v2))
  | Oorc, v1::v2::nil => Some (Val.or v1 (Val.notint v2))
  | Oshl, v1::v2::nil => Some (Val.shl v1 v2)
  | Oshr, v1::v2::nil => Some (Val.shr v1 v2)
  | Oshrimm n, v1::nil => Some (Val.shr v1 (Vint n))
  | Oshrximm n, v1::nil => Val.shrx v1 (Vint n)
  | Oshru, v1::v2::nil => Some (Val.shru v1 v2)
  | Orolm amount mask, v1::nil => Some (Val.rolm v1 amount mask)
  | Oroli amount mask, v1::v2::nil =>
      Some(Val.or (Val.and v1 (Vint (Int.not mask))) (Val.rolm v2 amount mask))
  | Olongconst n, nil => Some (Vlong n)
  | Ocast32signed, v1::nil => Some (Val.longofint v1)
  | Ocast32unsigned, v1::nil => Some (Val.longofintu v1)
  | Oaddl, v1::v2::nil => Some (Val.addl v1 v2)
  | Oaddlimm n, v1::nil => Some (Val.addl v1 (Vlong n))
  | Osubl, v1::v2::nil => Some (Val.subl v1 v2)
  | Onegl, v1::nil => Some (Val.negl v1)
  | Omull, v1::v2::nil => Some (Val.mull v1 v2)
  | Omullhs, v1::v2::nil => Some (Val.mullhs v1 v2)
  | Omullhu, v1::v2::nil => Some (Val.mullhu v1 v2)
  | Odivl, v1::v2::nil => Val.divls v1 v2
  | Odivlu, v1::v2::nil => Val.divlu v1 v2
  | Oandl, v1::v2::nil => Some(Val.andl v1 v2)
  | Oandlimm n, v1::nil => Some (Val.andl v1 (Vlong n))
  | Oorl, v1::v2::nil => Some(Val.orl v1 v2)
  | Oorlimm n, v1::nil => Some (Val.orl v1 (Vlong n))
  | Oxorl, v1::v2::nil => Some(Val.xorl v1 v2)
  | Oxorlimm n, v1::nil => Some (Val.xorl v1 (Vlong n))
  | Onotl, v1::nil => Some(Val.notl v1)
  | Oshll, v1::v2::nil => Some (Val.shll v1 v2)
  | Oshrl, v1::v2::nil => Some (Val.shrl v1 v2)
  | Oshrlimm n, v1::nil => Some (Val.shrl v1 (Vint n))
  | Oshrxlimm n, v1::nil => Val.shrxl v1 (Vint n)
  | Oshrlu, v1::v2::nil => Some (Val.shrlu v1 v2)
  | Orolml amount mask, v1::nil => Some (Val.rolml v1 amount mask)
  | Olongoffloat, v1::nil => Val.longoffloat v1
  | Ofloatoflong, v1::nil => Val.floatoflong v1
  | Onegf, v1::nil => Some(Val.negf v1)
  | Oabsf, v1::nil => Some(Val.absf v1)
  | Oaddf, v1::v2::nil => Some(Val.addf v1 v2)
  | Osubf, v1::v2::nil => Some(Val.subf v1 v2)
  | Omulf, v1::v2::nil => Some(Val.mulf v1 v2)
  | Odivf, v1::v2::nil => Some(Val.divf v1 v2)
  | Onegfs, v1::nil => Some(Val.negfs v1)
  | Oabsfs, v1::nil => Some(Val.absfs v1)
  | Oaddfs, v1::v2::nil => Some(Val.addfs v1 v2)
  | Osubfs, v1::v2::nil => Some(Val.subfs v1 v2)
  | Omulfs, v1::v2::nil => Some(Val.mulfs v1 v2)
  | Odivfs, v1::v2::nil => Some(Val.divfs v1 v2)
  | Osingleoffloat, v1::nil => Some(Val.singleoffloat v1)
  | Ofloatofsingle, v1::nil => Some(Val.floatofsingle v1)
  | Ointoffloat, v1::nil => Val.intoffloat v1
  | Ofloatofwords, v1::v2::nil => Some(Val.floatofwords v1 v2)
  | Omakelong, v1::v2::nil => Some(Val.longofwords v1 v2)
  | Olowlong, v1::nil => Some(Val.loword v1)
  | Ohighlong, v1::nil => Some(Val.hiword v1)
  | Ocmp c, _ => Some(Val.of_optbool (eval_condition c vl m))
  | Osel c ty, v1::v2::vl => Some(Val.select (eval_condition c vl m) v1 v2 ty)
  | _, _ => None
  end.

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

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

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

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

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

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

Definition type_of_operation (op: operation) : list typ * typ :=
  match op with
  | Omove => (nil, Tint)   (* treated specially *)
  | Ointconst _ => (nil, Tint)
  | Ofloatconst f => (nil, Tfloat)
  | Osingleconst f => (nil, Tsingle)
  | Oaddrsymbol _ _ => (nil, Tint)
  | Oaddrstack _ => (nil, Tint)
  | Ocast8signed => (Tint :: nil, Tint)
  | Ocast16signed => (Tint :: nil, Tint)
  | Oadd => (Tint :: Tint :: nil, Tint)
  | Oaddimm _ => (Tint :: nil, Tint)
  | Oaddsymbol _ _ => (Tint :: nil, Tint)
  | Osub => (Tint :: Tint :: nil, Tint)
  | Osubimm _ => (Tint :: nil, Tint)
  | Omul => (Tint :: Tint :: nil, Tint)
  | Omulimm _ => (Tint :: nil, Tint)
  | Omulhs => (Tint :: Tint :: nil, Tint)
  | Omulhu => (Tint :: Tint :: nil, Tint)
  | Odiv => (Tint :: Tint :: nil, Tint)
  | Odivu => (Tint :: Tint :: nil, Tint)
  | Oand => (Tint :: Tint :: nil, Tint)
  | Oandimm _ => (Tint :: nil, Tint)
  | Oor => (Tint :: Tint :: nil, Tint)
  | Oorimm _ => (Tint :: nil, Tint)
  | Oxor => (Tint :: Tint :: nil, Tint)
  | Oxorimm _ => (Tint :: nil, Tint)
  | Onot => (Tint :: nil, Tint)
  | Onand => (Tint :: Tint :: nil, Tint)
  | Onor => (Tint :: Tint :: nil, Tint)
  | Onxor => (Tint :: Tint :: nil, Tint)
  | Oandc => (Tint :: Tint :: nil, Tint)
  | Oorc => (Tint :: Tint :: nil, Tint)
  | Oshl => (Tint :: Tint :: nil, Tint)
  | Oshr => (Tint :: Tint :: nil, Tint)
  | Oshrimm _ => (Tint :: nil, Tint)
  | Oshrximm _ => (Tint :: nil, Tint)
  | Oshru => (Tint :: Tint :: nil, Tint)
  | Orolm _ _ => (Tint :: nil, Tint)
  | Oroli _ _ => (Tint :: Tint :: nil, Tint)
  | Olongconst _ => (nil, Tlong)
  | Ocast32signed => (Tint :: nil, Tlong)
  | Ocast32unsigned => (Tint :: nil, Tlong)
  | Oaddl => (Tlong :: Tlong :: nil, Tlong)
  | Oaddlimm _ => (Tlong :: nil, Tlong)
  | Osubl => (Tlong :: Tlong :: nil, Tlong)
  | Onegl => (Tlong :: nil, Tlong)
  | Omull => (Tlong :: Tlong :: nil, Tlong)
  | Omullhs => (Tlong :: Tlong :: nil, Tlong)
  | Omullhu => (Tlong :: Tlong :: nil, Tlong)
  | Odivl => (Tlong :: Tlong :: nil, Tlong)
  | Odivlu => (Tlong :: Tlong :: nil, Tlong)
  | Oandl => (Tlong :: Tlong :: nil, Tlong)
  | Oandlimm _ => (Tlong :: nil, Tlong)
  | Oorl => (Tlong :: Tlong :: nil, Tlong)
  | Oorlimm _ => (Tlong :: nil, Tlong)
  | Oxorl => (Tlong :: Tlong :: nil, Tlong)
  | Oxorlimm _ => (Tlong :: nil, Tlong)
  | Onotl => (Tlong :: nil, Tlong)
  | Oshll => (Tlong :: Tint :: nil, Tlong)
  | Oshrl => (Tlong :: Tint :: nil, Tlong)
  | Oshrlimm _ => (Tlong :: nil, Tlong)
  | Oshrxlimm _ => (Tlong :: nil, Tlong)
  | Oshrlu => (Tlong :: Tint :: nil, Tlong)
  | Orolml _ _ => (Tlong :: nil, Tlong)
  | Olongoffloat => (Tfloat :: nil, Tlong)
  | Ofloatoflong => (Tlong :: nil, Tfloat)
  | Onegf => (Tfloat :: nil, Tfloat)
  | Oabsf => (Tfloat :: nil, Tfloat)
  | Oaddf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Osubf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Omulf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Odivf => (Tfloat :: Tfloat :: nil, Tfloat)
  | Onegfs => (Tsingle :: nil, Tsingle)
  | Oabsfs => (Tsingle :: nil, Tsingle)
  | Oaddfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Osubfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Omulfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Odivfs => (Tsingle :: Tsingle :: nil, Tsingle)
  | Osingleoffloat => (Tfloat :: nil, Tsingle)
  | Ofloatofsingle => (Tsingle :: nil, Tfloat)
  | Ointoffloat => (Tfloat :: nil, Tint)
  | Ofloatofwords => (Tint :: Tint :: nil, Tfloat)
  | Omakelong => (Tint :: Tint :: nil, Tlong)
  | Olowlong => (Tlong :: nil, Tint)
  | Ohighlong => (Tlong :: nil, Tint)
  | Ocmp c => (type_of_condition c, Tint)
  | Osel c ty => (ty :: ty :: type_of_condition c, ty)
  end.

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

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

Section SOUNDNESS.

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

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

End SOUNDNESS.

(** * Manipulating and transforming operations *)

(** Recognition of move operations. *)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Definition condition_depends_on_memory (c: condition) : bool :=
  match c with
  | Ccompu _ => true
  | Ccompuimm _ _ => true
  | Ccomplu _ => Archi.ppc64
  | Ccompluimm _ _ => Archi.ppc64
  | _ => false
  end.

Definition op_depends_on_memory (op: operation) : bool :=
  match op with
  | Ocmp c => condition_depends_on_memory c
  | Osel c ty => condition_depends_on_memory c
  | _ => false
  end.

Lemma condition_depends_on_memory_correct:
  forall c args m1 m2,
  condition_depends_on_memory c = false ->
  eval_condition c args m1 = eval_condition c args m2.
Proof.
  intros. destruct c; simpl; auto; discriminate.
Qed.

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

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

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

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

(** * Invariance and compatibility properties. *)

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

Section GENV_TRANSF.

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

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

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

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

End GENV_TRANSF.

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

Section EVAL_COMPAT.

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

Variable m1: mem.
Variable m2: mem.

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

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

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

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

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

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

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

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

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

End EVAL_COMPAT.

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

Section EVAL_LESSDEF.

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

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

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

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

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

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

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

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

End EVAL_LESSDEF.

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

Section EVAL_INJECT.

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

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

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

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

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

End EVAL_INJECT.

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

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

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

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

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

Fixpoint is_mask_rec {A: Type} (trans: A -> bool -> A) (accept: A -> bool)
                     (n: nat) (s: A) (x: Z) {struct n} : bool :=
  match n with
  | O =>
      accept s
  | S m =>
      is_mask_rec trans accept m (trans s (Z.odd x)) (Z.div2 x)
  end.

Definition is_rlw_mask (x: int) : bool :=
  is_mask_rec rlw_transition rlw_accepting Int.wordsize RLW_S0 (Int.unsigned x).

(** For the 64-bit [rldicl] and [rldicr] instructions, the acceptable
  masks are (in big endian):
- for [rldicl]: masks that clear the leftmost bits (most significant bits),
  that is, [00000011111], that is, ones in the low bits followed by zeros
  in the high bits;
- for [rldicr]: masks that clear the rightmost bits (least significant bits),
  that is, [11110000000], that is, zeros in the low bits followed by ones
  in the high bits.

  All ones  is OK, but not all zeroes.

  The corresponding automata for [rldicl] is
<<
                 1          0
                / \        / \
                \ /        \ /      (accepting: [1], [2])
     [0] --1--> [1] --0--> [2]
>>
  The automata for [rldicr] is
<<
      0          1
     / \        / \
     \ /        \ /          (accepting: [1])
     [0] --1--> [1]
>>
*)

Inductive rll_state: Type := RLL_S0 | RLL_S1 | RLL_S2 | RLL_Sbad.

Definition rll_transition (s: rll_state) (b: bool) : rll_state :=
  match s, b with
  | RLL_S0, true => RLL_S1
  | RLL_S1, false => RLL_S2
  | RLL_S1, true => RLL_S1
  | RLL_S2, false => RLL_S2
  | _, _ => RLL_Sbad
  end.

Definition rll_accepting (s: rll_state) : bool :=
  match s with
  | RLL_S1 | RLL_S2 => true
  | _ => false
  end.

Inductive rlr_state: Type := RLR_S0 | RLR_S1 | RLR_Sbad.

Definition rlr_transition (s: rlr_state) (b: bool) : rlr_state :=
  match s, b with
  | RLR_S0, false => RLR_S0
  | RLR_S0, true => RLR_S1
  | RLR_S1, true => RLR_S1
  | _, _ => RLR_Sbad
  end.

Definition rlr_accepting (s: rlr_state) : bool :=
  match s with
  | RLR_S1 => true
  | _ => false
  end.

Definition is_rldl_mask (x: int64) : bool :=    (*r 0s in the high bits, 1s in the low bits *)
  is_mask_rec rll_transition rll_accepting Int64.wordsize RLL_S0 (Int64.unsigned x).

Definition is_rldr_mask (x: int64) : bool :=    (*r 1s in the high bits, 0s in the low bits *)
  is_mask_rec rlr_transition rlr_accepting Int64.wordsize RLR_S0 (Int64.unsigned x).

(** * Handling of builtin arguments *)

Definition builtin_arg_ok_1
       (A: Type) (ba: builtin_arg A) (c: builtin_arg_constraint) :=
  match c, ba with
  | OK_all, _ => true
  | OK_const, (BA_int _ | BA_long _ | BA_float _ | BA_single _) => true
  | OK_addrstack, BA_addrstack _ => true
  | OK_addressing, BA_addrstack _ => true
  | OK_addressing, BA_addrglobal _ _ => true
  | OK_addressing, BA_addptr (BA _) (BA_int _) => true
  | OK_addressing, BA_addptr (BA_addrglobal _ _) (BA _) => true
  | OK_addressing, BA_addptr (BA _) (BA _) => true
  | _, _ => false
  end.

Definition builtin_arg_ok
       (A: Type) (ba: builtin_arg A) (c: builtin_arg_constraint) :=
  match ba with
  | (BA _ | BA_splitlong (BA _) (BA _)) => true
  | _ => builtin_arg_ok_1 ba c
  end.