Module Events


Observable events, execution traces, and semantics of external calls.

Require Import Coqlib.
Require Intv.
Require Import AST.
Require Import Integers.
Require Import Floats.
Require Import Values.
Require Import NormaliseSpec.
Require Import Memory.
Require Import Globalenvs.
Require Import Values_symbolic.
Require Import Values_symbolictype.
Require Import IntFacts.
Require Import Equivalences.

Events and traces


The observable behaviour of programs is stated in terms of input/output events, which represent the actions of the program that the external world can observe. CompCert leaves much flexibility as to the exact content of events: the only requirement is that they do not expose memory states nor pointer values (other than pointers to global variables), because these are not preserved literally during compilation. For concreteness, we use the following type for events. Each event represents either: The values attached to these events are of the following form. As mentioned above, we do not expose pointer values directly. Pointers relative to a global variable are shown with the name of the variable instead of the block identifier.

Inductive eventval: Type :=
  | EVint: int -> eventval
  | EVlong: int64 -> eventval
  | EVfloat: float -> eventval
  | EVsingle: float32 -> eventval
  | EVptr_global: ident -> int -> eventval.

Inductive event: Type :=
  | Event_syscall: ident -> list eventval -> eventval -> event
  | Event_vload: memory_chunk -> ident -> int -> eventval -> event
  | Event_vstore: memory_chunk -> ident -> int -> eventval -> event
.
 
The dynamic semantics for programs collect traces of events. Traces are of two kinds: finite (type trace) or infinite (type traceinf).

Definition trace := list event.

Definition E0 : trace := nil.

Definition Eapp (t1 t2: trace) : trace := t1 ++ t2.

CoInductive traceinf : Type :=
  | Econsinf: event -> traceinf -> traceinf.

Fixpoint Eappinf (t: trace) (T: traceinf) {struct t} : traceinf :=
  match t with
  | nil => T
  | ev :: t' => Econsinf ev (Eappinf t' T)
  end.

Concatenation of traces is written ** in the finite case or *** in the infinite case.

Infix "**" := Eapp (at level 60, right associativity).
Infix "***" := Eappinf (at level 60, right associativity).

Lemma E0_left: forall t, E0 ** t = t.
Proof.
auto. Qed.

Lemma E0_right: forall t, t ** E0 = t.
Proof.
intros. unfold E0, Eapp. rewrite <- app_nil_end. auto. Qed.

Lemma Eapp_assoc: forall t1 t2 t3, (t1 ** t2) ** t3 = t1 ** (t2 ** t3).
Proof.
intros. unfold Eapp, trace. apply app_ass. Qed.

Lemma Eapp_E0_inv: forall t1 t2, t1 ** t2 = E0 -> t1 = E0 /\ t2 = E0.
Proof (@app_eq_nil event).
  
Lemma E0_left_inf: forall T, E0 *** T = T.
Proof.
auto. Qed.

Lemma Eappinf_assoc: forall t1 t2 T, (t1 ** t2) *** T = t1 *** (t2 *** T).
Proof.
  induction t1; intros; simpl. auto. decEq; auto.
Qed.

Hint Rewrite E0_left E0_right Eapp_assoc
             E0_left_inf Eappinf_assoc: trace_rewrite.

Opaque trace E0 Eapp Eappinf.

The following traceEq tactic proves equalities between traces or infinite traces.

Ltac substTraceHyp :=
  match goal with
  | [ H: (@eq trace ?x ?y) |- _ ] =>
       subst x || clear H
  end.

Ltac decomposeTraceEq :=
  match goal with
  | [ |- (_ ** _) = (_ ** _) ] =>
      apply (f_equal2 Eapp); auto; decomposeTraceEq
  | _ =>
      auto
  end.

Ltac traceEq :=
  repeat substTraceHyp; autorewrite with trace_rewrite; decomposeTraceEq.

Bisimilarity between infinite traces.

CoInductive traceinf_sim: traceinf -> traceinf -> Prop :=
  | traceinf_sim_cons: forall e T1 T2,
      traceinf_sim T1 T2 ->
      traceinf_sim (Econsinf e T1) (Econsinf e T2).

Lemma traceinf_sim_refl:
  forall T, traceinf_sim T T.
Proof.
  cofix COINDHYP; intros.
  destruct T. constructor. apply COINDHYP.
Qed.
 
Lemma traceinf_sim_sym:
  forall T1 T2, traceinf_sim T1 T2 -> traceinf_sim T2 T1.
Proof.
  cofix COINDHYP; intros. inv H; constructor; auto.
Qed.

Lemma traceinf_sim_trans:
  forall T1 T2 T3,
  traceinf_sim T1 T2 -> traceinf_sim T2 T3 -> traceinf_sim T1 T3.
Proof.
  cofix COINDHYP;intros. inv H; inv H0; constructor; eauto.
Qed.

CoInductive traceinf_sim': traceinf -> traceinf -> Prop :=
  | traceinf_sim'_cons: forall t T1 T2,
      t <> E0 -> traceinf_sim' T1 T2 -> traceinf_sim' (t *** T1) (t *** T2).

Lemma traceinf_sim'_sim:
  forall T1 T2, traceinf_sim' T1 T2 -> traceinf_sim T1 T2.
Proof.
  cofix COINDHYP; intros. inv H.
  destruct t. elim H0; auto.
Transparent Eappinf.
Transparent E0.
  simpl.
  destruct t. simpl. constructor. apply COINDHYP; auto.
  constructor. apply COINDHYP.
  constructor. unfold E0; congruence. auto.
Qed.

An alternate presentation of infinite traces as infinite concatenations of nonempty finite traces.

CoInductive traceinf': Type :=
  | Econsinf': forall (t: trace) (T: traceinf'), t <> E0 -> traceinf'.

Program Definition split_traceinf' (t: trace) (T: traceinf') (NE: t <> E0): event * traceinf' :=
  match t with
  | nil => _
  | e :: nil => (e, T)
  | e :: t' => (e, Econsinf' t' T _)
  end.
Next Obligation.
  elimtype False. elim NE. auto.
Qed.
Next Obligation.
  red; intro. elim (H e). rewrite H0. auto.
Qed.

CoFixpoint traceinf_of_traceinf' (T': traceinf') : traceinf :=
  match T' with
  | Econsinf' t T'' NOTEMPTY =>
      let (e, tl) := split_traceinf' t T'' NOTEMPTY in
      Econsinf e (traceinf_of_traceinf' tl)
  end.

Remark unroll_traceinf':
  forall T, T = match T with Econsinf' t T' NE => Econsinf' t T' NE end.
Proof.
  intros. destruct T; auto.
Qed.

Remark unroll_traceinf:
  forall T, T = match T with Econsinf t T' => Econsinf t T' end.
Proof.
  intros. destruct T; auto.
Qed.

Lemma traceinf_traceinf'_app:
  forall t T NE,
  traceinf_of_traceinf' (Econsinf' t T NE) = t *** traceinf_of_traceinf' T.
Proof.
  induction t.
  intros. elim NE. auto.
  intros. simpl.
  rewrite (unroll_traceinf (traceinf_of_traceinf' (Econsinf' (a :: t) T NE))).
  simpl. destruct t. auto.
Transparent Eappinf.
  simpl. f_equal. apply IHt.
Qed.

Prefixes of traces.

Definition trace_prefix (t1 t2: trace) :=
  exists t3, t2 = t1 ** t3.

Definition traceinf_prefix (t1: trace) (T2: traceinf) :=
  exists T3, T2 = t1 *** T3.

Lemma trace_prefix_app:
  forall t1 t2 t,
  trace_prefix t1 t2 ->
  trace_prefix (t ** t1) (t ** t2).
Proof.
  intros. destruct H as [t3 EQ]. exists t3. traceEq.
Qed.

Lemma traceinf_prefix_app:
  forall t1 T2 t,
  traceinf_prefix t1 T2 ->
  traceinf_prefix (t ** t1) (t *** T2).
Proof.
  intros. destruct H as [T3 EQ]. exists T3. subst T2. traceEq.
Qed.

Relating values and event values


Set Implicit Arguments.

Section EVENTVAL.

Global environment used to translate between global variable names and their block identifiers.
Variables F V: Type.
Variable ge: Genv.t F V.

Translation between values and event values.

Inductive eventval_match: eventval -> typ -> expr_sym -> Prop :=
| ev_match_int: forall i,
                  eventval_match (EVint i) AST.Tint (Eval (Eint i))
| ev_match_long: forall i,
                   eventval_match (EVlong i) AST.Tlong (Eval (Elong i))
| ev_match_float: forall f,
                    eventval_match (EVfloat f) AST.Tfloat (Eval (Efloat f))
| ev_match_single: forall f,
                     eventval_match (EVsingle f) AST.Tsingle (Eval (Esingle f))
| ev_match_ptr: forall id b ofs,
                  Genv.find_symbol ge id = Some b ->
                  eventval_match (EVptr_global id ofs) AST.Tint (Eval (Eptr b ofs)).

Inductive eventval_list_match: list eventval -> list typ -> list expr_sym -> Prop :=
  | evl_match_nil:
      eventval_list_match nil nil nil
  | evl_match_cons:
      forall ev1 evl ty1 tyl v1 vl,
      eventval_match ev1 ty1 v1 ->
      eventval_list_match evl tyl vl ->
      eventval_list_match (ev1::evl) (ty1::tyl) (v1::vl).

Some properties of these translation predicates.

Lemma eventval_match_type:
  forall ev ty v,
  eventval_match ev ty v -> Val.has_type v (Normalise.styp_of_typ ty).
Proof.
  intros.
  unfold Val.has_type.
  apply tcheck_expr_correct.
  inv H; simpl; auto.
Qed.

Lemma eventval_list_match_length:
  forall evl tyl vl, eventval_list_match evl tyl vl -> List.length vl = List.length tyl.
Proof.
  induction 1; simpl; eauto.
Qed.

Lemma eventval_match_lessdef:
  forall ev ty v1 v2 p,
  eventval_match ev ty v1 -> Val.lessdef p v1 v2 -> eventval_match ev ty v2.
Proof.
  intros. inv H0. rewrite Val.apply_inj_id in inj_ok.
  inv inj_ok.
  inv H; econstructor; simpl; eauto;
  apply same_eval_subst; intros; try congruence.
Qed.

Lemma eventval_list_match_lessdef:
  forall p evl tyl vl1, eventval_list_match evl tyl vl1 ->
  forall vl2, Val.lessdef_list p vl1 vl2 -> eventval_list_match evl tyl vl2.
Proof.
  induction 1; intros. inv H; constructor.
  inv H1. constructor. eapply eventval_match_lessdef; eauto. eauto.
Qed.

Compatibility with memory injections

Variable f: block -> option (block * Z).
Variable p: Val.partial_undef_allocation.

Definition meminj_preserves_globals : Prop :=
     (forall id b, Genv.find_symbol ge id = Some b -> f b = Some(b, 0))
  /\ (forall b gv, Genv.find_var_info ge b = Some gv -> f b = Some(b, 0))
  /\ (forall b1 b2 delta gv, Genv.find_var_info ge b2 = Some gv -> f b1 = Some(b2, delta) -> b2 = b1).

Hypothesis glob_pres: meminj_preserves_globals.

Lemma eventval_match_inject:
  forall ev ty v1 v2,
  eventval_match ev ty v1 -> Val.expr_inject p f v1 v2 -> eventval_match ev ty v2.
Proof.
  intros. inv H; inv H0; simpl in *; inv inj_ok; try econstructor; eauto.
  destruct glob_pres as [A [B C]].
  exploit A; eauto. unfold Val.inj_ptr in H0.
  intro EQ; rewrite EQ in H0. inv H0.
  rewrite Int.add_zero. econstructor; eauto.
Qed.

Lemma eventval_match_inject_2:
  forall ev ty v,
  eventval_match ev ty v -> Val.expr_inject p f v v.
Proof.
  induction 1; auto; try (constructor; simpl; eauto).
  unfold Val.inj_ptr.
  destruct glob_pres as [A [B C]].
  erewrite A; eauto. rewrite Int.add_zero; auto.
Qed.

Lemma eventval_list_match_inject:
  forall evl tyl vl1, eventval_list_match evl tyl vl1 ->
  forall vl2, Val.expr_list_inject p f vl1 vl2 -> eventval_list_match evl tyl vl2.
Proof.
  induction 1; intros. inv H; constructor.
  inv H1. constructor. eapply eventval_match_inject; eauto. eauto.
Qed.

Determinism

Lemma eventval_match_determ_1:
  forall ev ty v1 v2, eventval_match ev ty v1 -> eventval_match ev ty v2 -> v1 = v2.
Proof.
  intros. inv H; inv H0; auto. congruence.
Qed.

Lemma eventval_match_determ_2:
  forall ev1 ev2 ty v, eventval_match ev1 ty v -> eventval_match ev2 ty v -> ev1 = ev2.
Proof.
  intros. inv H; inv H0; auto.
  decEq. eapply Genv.genv_vars_inj; eauto.
Qed.

Lemma eventval_list_match_determ_2:
  forall evl1 tyl vl, eventval_list_match evl1 tyl vl ->
  forall evl2, eventval_list_match evl2 tyl vl -> evl1 = evl2.
Proof.
  induction 1; intros. inv H. auto. inv H1. f_equal; eauto.
  eapply eventval_match_determ_2; eauto.
Qed.

Validity

Definition eventval_valid (ev: eventval) : Prop :=
  match ev with
  | EVint _ => True
  | EVlong _ => True
  | EVfloat _ => True
  | EVsingle _ => True
  | EVptr_global id ofs => exists b, Genv.find_symbol ge id = Some b
  end.

Definition eventval_type (ev: eventval) : typ :=
  match ev with
  | EVint _ => AST.Tint
  | EVlong _ => AST.Tlong
  | EVfloat _ => AST.Tfloat
  | EVsingle _ => AST.Tsingle
  | EVptr_global id ofs => AST.Tint
  end.

Lemma eventval_match_receptive:
  forall ev1 ty v1 ev2,
  eventval_match ev1 ty v1 ->
  eventval_valid ev1 -> eventval_valid ev2 -> eventval_type ev1 = eventval_type ev2 ->
  exists v2, eventval_match ev2 ty v2.
Proof.
  intros. inv H; destruct ev2; simpl in H2; try discriminate;
          try solve [ eexists; constructor].
  destruct H1 as [b EQ]. eexists; constructor; eauto.
  destruct H1 as [b' EQ]. eexists; constructor; eauto.
Qed.

Lemma eventval_match_valid:
  forall ev ty v, eventval_match ev ty v -> eventval_valid ev.
Proof.
  destruct 1; simpl; auto. exists b; auto.
Qed.

Lemma eventval_match_same_type:
  forall ev1 ty v1 ev2 v2,
  eventval_match ev1 ty v1 -> eventval_match ev2 ty v2 -> eventval_type ev1 = eventval_type ev2.
Proof.
  destruct 1; intros EV; inv EV; auto.
Qed.

End EVENTVAL.

Invariance under changes to the global environment

Section EVENTVAL_INV.

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

Hypothesis symbols_preserved:
  forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id.

Lemma eventval_match_preserved:
  forall ev ty v,
  eventval_match ge1 ev ty v -> eventval_match ge2 ev ty v.
Proof.
  induction 1; constructor; auto. rewrite symbols_preserved; auto.
Qed.

Lemma eventval_list_match_preserved:
  forall evl tyl vl,
  eventval_list_match ge1 evl tyl vl -> eventval_list_match ge2 evl tyl vl.
Proof.
  induction 1; constructor; auto. eapply eventval_match_preserved; eauto.
Qed.

Lemma eventval_valid_preserved:
  forall ev, eventval_valid ge1 ev -> eventval_valid ge2 ev.
Proof.
  unfold eventval_valid; destruct ev; auto.
  intros [b A]. exists b; rewrite symbols_preserved; auto.
Qed.

End EVENTVAL_INV.

Matching traces.


Section MATCH_TRACES.

Variables F V: Type.
Variable ge: Genv.t F V.

Matching between traces corresponding to single transitions. Arguments (provided by the program) must be equal. Results (provided by the outside world) can vary as long as they can be converted safely to values.

Inductive match_traces: trace -> trace -> Prop :=
  | match_traces_E0:
      match_traces nil nil
  | match_traces_syscall: forall id args res1 res2,
      eventval_valid ge res1 -> eventval_valid ge res2 -> eventval_type res1 = eventval_type res2 ->
      match_traces (Event_syscall id args res1 :: nil) (Event_syscall id args res2 :: nil)
  | match_traces_vload: forall chunk id ofs res1 res2,
      eventval_valid ge res1 -> eventval_valid ge res2 -> eventval_type res1 = eventval_type res2 ->
      match_traces (Event_vload chunk id ofs res1 :: nil) (Event_vload chunk id ofs res2 :: nil)
  | match_traces_vstore: forall chunk id ofs arg,
      match_traces (Event_vstore chunk id ofs arg :: nil) (Event_vstore chunk id ofs arg :: nil)
.

End MATCH_TRACES.

Invariance by change of global environment

Section MATCH_TRACES_INV.

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

Hypothesis symbols_preserved:
  forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id.

Lemma match_traces_preserved:
  forall t1 t2, match_traces ge1 t1 t2 -> match_traces ge2 t1 t2.
Proof.
  induction 1; constructor; auto; eapply eventval_valid_preserved; eauto.
Qed.

End MATCH_TRACES_INV.

An output trace is a trace composed only of output events, that is, events that do not take any result from the outside world.

Definition output_event (ev: event) : Prop :=
  match ev with
  | Event_syscall _ _ _ => False
  | Event_vload _ _ _ _ => False
  | Event_vstore _ _ _ _ => True
  end.
  
Fixpoint output_trace (t: trace) : Prop :=
  match t with
  | nil => True
  | ev :: t' => output_event ev /\ output_trace t'
  end.

Semantics of volatile memory accesses


Definition block_is_volatile (F V: Type) (ge: Genv.t F V) (b: block) : bool :=
  match Genv.find_var_info ge b with
  | None => false
  | Some gv => gv.(gvar_volatile)
  end.

Inductive volatile_load (F V: Type) (ge: Genv.t F V):
                   memory_chunk -> mem -> expr_sym -> trace -> expr_sym -> Prop :=
| volatile_load_vol: forall addr chunk m b ofs id ev v,
                       Mem.mem_norm m addr Ptr = Vptr b ofs ->
                       block_is_volatile ge b = true ->
                       Genv.find_symbol ge id = Some b ->
                       eventval_match ge ev (AST.type_of_chunk chunk) v ->
                       volatile_load ge chunk m addr
                                     (Event_vload chunk id ofs ev :: nil)
                                     (Val.load_result chunk v)
| volatile_load_nonvol: forall addr chunk m b ofs v,
                          Mem.mem_norm m addr Ptr = Vptr b ofs ->
                          block_is_volatile ge b = false ->
                          Mem.load chunk m b (Int.unsigned ofs) = Some v ->
                          volatile_load ge chunk m addr E0 v.


Definition result_of_styp (s: styp) : result :=
  match s with
      Tint => Int
    | Tlong => Long
    | Tfloat => Float
    | Tsingle => Single
  end.


Inductive volatile_store (F V: Type) (ge: Genv.t F V):
                  memory_chunk -> mem -> expr_sym -> expr_sym -> trace -> mem -> Prop :=
| volatile_store_vol: forall addr chunk m b ofs id ev v nv,
                        Mem.mem_norm m addr Ptr = Vptr b ofs ->
                        block_is_volatile ge b = true ->
                        Genv.find_symbol ge id = Some b ->
                        Mem.mem_norm m (Val.load_result chunk v) (result_of_styp (type_of_chunk chunk)) = nv ->
                        eventval_match ge ev (AST.type_of_chunk chunk)
                                       (Eval (NormaliseSpec.sval_of_val nv)) ->
                        volatile_store ge chunk m addr v
                                       (Event_vstore chunk id ofs ev :: nil)
                                       m
| volatile_store_nonvol: forall addr chunk m b ofs v m',
                           Mem.mem_norm m addr Ptr = Vptr b ofs ->
                           block_is_volatile ge b = false ->
                           Mem.store chunk m b (Int.unsigned ofs) v = Some m' ->
                           volatile_store ge chunk m addr v E0 m'.

Semantics of external functions


For each external function, its behavior is defined by a predicate relating:

Definition extcall_sem : Type :=
  forall (F V: Type), Genv.t F V -> list expr_sym -> mem -> trace -> expr_sym -> mem -> Prop.

We now specify the expected properties of this predicate.

Definition loc_out_of_bounds (m: mem) (b: block) (ofs: Z) : Prop :=
  ~Mem.perm m b ofs Max Nonempty.

Definition loc_not_writable (m: mem) (b: block) (ofs: Z) : Prop :=
  ~Mem.perm m b ofs Max Writable.

Definition loc_unmapped (f: meminj) (b: block) (ofs: Z): Prop :=
  f b = None.

Definition loc_out_of_reach (f: meminj) (m: mem) (b: block) (ofs: Z): Prop :=
  forall b0 delta,
  f b0 = Some(b, delta) -> ~Mem.perm m b0 (ofs - delta) Max Nonempty.

Definition inject_separated (f f': meminj) (m1 m2: mem): Prop :=
  forall b1 b2 delta,
  f b1 = None -> f' b1 = Some(b2, delta) ->
  ~Mem.valid_block m1 b1 /\ ~Mem.valid_block m2 b2.

Record extcall_properties (sem: extcall_sem)
                          (sg: signature) : Prop := mk_extcall_properties {

The return value of an external call must agree with its signature.
  ec_well_typed:
    forall F V (ge: Genv.t F V) vargs m1 t vres m2,
    sem F V ge vargs m1 t vres m2 ->
    Val.has_type vres (Normalise.styp_of_typ (proj_sig_res sg));

The semantics is invariant under change of global environment that preserves symbols.
  ec_symbols_preserved:
    forall F1 V1 (ge1: Genv.t F1 V1) F2 V2 (ge2: Genv.t F2 V2) vargs m1 t vres m2,
    (forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id) ->
    (forall b, block_is_volatile ge2 b = block_is_volatile ge1 b) ->
    sem F1 V1 ge1 vargs m1 t vres m2 ->
    sem F2 V2 ge2 vargs m1 t vres m2;

External calls cannot invalidate memory blocks. (Remember that freeing a block does not invalidate its block identifier.)
  ec_valid_block:
     forall F V (ge: Genv.t F V) vargs m1 t vres m2 b,
    sem F V ge vargs m1 t vres m2 ->
    Mem.valid_block m1 b -> Mem.valid_block m2 b;

External calls cannot increase the max permissions of a valid block. They can decrease the max permissions, e.g. by freeing.
  ec_max_perm:
    forall F V (ge: Genv.t F V) vargs m1 t vres m2 b ofs p,
    sem F V ge vargs m1 t vres m2 ->
    Mem.valid_block m1 b -> Mem.perm m2 b ofs Max p -> Mem.perm m1 b ofs Max p;

External call cannot modify memory unless they have Max, Writable permissions.
  ec_readonly:
    forall F V (ge: Genv.t F V) vargs m1 t vres m2,
    sem F V ge vargs m1 t vres m2 ->
    Mem.unchanged_on (loc_not_writable m1) m1 m2;

External calls must commute with memory extensions, in the following sense.

External calls must commute with memory injections, in the following sense.
  ec_mem_inject:
    forall p F V (ge: Genv.t F V) vargs m1 t vres m2 f m1' vargs'
           (ABI: Mem.all_blocks_injected f m1),
    meminj_preserves_globals ge f ->
    sem F V ge vargs m1 t vres m2 ->
    Mem.inject p f m1 m1' ->
    Val.expr_list_inject p f vargs vargs' ->
exists vres', exists m2',
       sem F V ge vargs' m1' t vres' m2'
       /\ Mem.all_blocks_injected f m2
    /\ Val.expr_inject p f vres vres'
    /\ Mem.inject p f m2 m2'
    /\ Mem.unchanged_on (loc_unmapped f) m1 m2
    /\ Mem.unchanged_on (loc_out_of_reach f m1) m1' m2'
;

External calls produce at most one event.
  ec_trace_length:
    forall F V ge vargs m t vres m',
    sem F V ge vargs m t vres m' -> (length t <= 1)%nat;

External calls must be receptive to changes of traces by another, matching trace.
  ec_receptive:
    forall F V ge vargs m t1 vres1 m1 t2,
    sem F V ge vargs m t1 vres1 m1 -> match_traces ge t1 t2 ->
    exists vres2, exists m2, sem F V ge vargs m t2 vres2 m2;

External calls must be deterministic up to matching between traces.
  ec_determ:
    forall F V ge vargs m t1 vres1 m1 t2 vres2 m2,
    sem F V ge vargs m t1 vres1 m1 -> sem F V ge vargs m t2 vres2 m2 ->
    match_traces ge t1 t2 /\ (t1 = t2 -> vres1 = vres2 /\ m1 = m2)
}.

Semantics of volatile loads


Inductive volatile_load_sem (chunk: memory_chunk) (F V: Type) (ge: Genv.t F V):
              list expr_sym -> mem -> trace -> expr_sym -> mem -> Prop :=
  | volatile_load_sem_intro: forall addr m t v ,
      volatile_load ge chunk m addr t v ->
      volatile_load_sem chunk ge (addr :: nil) m t v m.


Lemma volatile_load_preserved:
  forall F1 V1 (ge1: Genv.t F1 V1) F2 V2 (ge2: Genv.t F2 V2) chunk m addr b ofs t v
         (MN: Mem.mem_norm m addr Ptr = Vptr b ofs)
         (GFS: forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id)
         (IV: forall b, block_is_volatile ge2 b = block_is_volatile ge1 b),
    volatile_load ge1 chunk m addr t v ->
    volatile_load ge2 chunk m addr t v.
Proof.
  intros. inv H; econstructor; eauto.
  rewrite GFS; auto.
  eapply eventval_match_preserved; eauto.
Qed.


Remark meminj_preserves_block_is_volatile:
  forall F V (ge: Genv.t F V) f b1 b2 delta,
  meminj_preserves_globals ge f ->
  f b1 = Some (b2, delta) ->
  block_is_volatile ge b2 = block_is_volatile ge b1.
Proof.
  intros. destruct H as [A [B C]]. unfold block_is_volatile.
  case_eq (Genv.find_var_info ge b1); intros.
  exploit B; eauto. intro EQ; rewrite H0 in EQ; inv EQ. rewrite H; auto.
  case_eq (Genv.find_var_info ge b2); intros.
  exploit C; eauto. intro EQ. congruence.
  auto.
Qed.

Lemma volatile_load_inject:
  forall p F V (ge: Genv.t F V) f chunk m addr addr' t v m'
         (ABI: Mem.all_blocks_injected f m),
    meminj_preserves_globals ge f ->
    volatile_load ge chunk m addr t v ->
    Val.expr_inject p f addr addr' ->
    Mem.inject p f m m' ->
    exists v', volatile_load ge chunk m' addr' t v' /\ Val.expr_inject p f v v'.
Proof.
  intros. inv H0.
  -
    exploit (proj1 H); eauto. intros EQ.
    exists (Val.load_result chunk v0); split.
    + econstructor; eauto.
      generalize (Mem.norm_inject _ _ _ _ _ (Vptr b ofs) _ ABI
                                  H2 H1).
      intro A; destruct A with (r:=Ptr); eauto. congruence.
      destruct (Mem.mem_norm m' addr' Ptr) eqn:?; simpl in *; try congruence;
      inv H7; simpl in inj_ok; unfold Val.inj_ptr in inj_ok; simpl in inj_ok;
      rewrite EQ in inj_ok; inv inj_ok.
      rewrite Int.add_zero. eauto.
    + apply Val.expr_load_result_inject'.
      inv H6; try (simpl; econstructor; simpl; eauto; simpl; tauto; fail).
      simpl. econstructor. simpl.
      unfold Val.inj_ptr. exploit (proj1 H). eauto. intro EQ'; rewrite EQ'.
      rewrite Int.add_zero; auto.
  -
      generalize (Mem.norm_inject _ _ _ _ _ (Vptr b ofs) _ ABI
                                  H2 H1).
      intro A; destruct A with (r:=Ptr); eauto. congruence.
      destruct (Mem.mem_norm m' addr' Ptr) eqn:?; simpl in *; try congruence;
      inv H6; simpl in inj_ok; unfold Val.inj_ptr in inj_ok; simpl in inj_ok;
      destruct (f b) as [[bb oo]|] eqn:?; inv inj_ok.
      generalize (Mem.load_inject p f m m' chunk b (Int.unsigned ofs) b0 oo v H2 H5 Heqo); eauto.
      simpl; intros [v' [C D]]. exists v'; split; auto.
      econstructor; eauto. rewrite <- H4. eapply meminj_preserves_block_is_volatile; eauto.
      rewrite <- C. f_equal.
      rewrite <- (Int.repr_unsigned ofs) at 1.
      rewrite Val.int_add_repr.
      apply Int.unsigned_repr.
      inv H2.
      refine ( (Mem.mi_representable _ _ _ _ mi_inj _ _ _ ofs Heqo (or_introl _)) _).
      apply Mem.load_valid_access in H5.
      eapply Mem.valid_access_perm in H5; eauto.
      eapply Mem.perm_implies; eauto. constructor.
      eapply mi_delta_pos; eauto.
Qed.

Lemma volatile_load_receptive:
  forall F V (ge: Genv.t F V) chunk m addr t1 t2 v1,
  volatile_load ge chunk m addr t1 v1 -> match_traces ge t1 t2 ->
  exists v2, volatile_load ge chunk m addr t2 v2.
Proof.
  intros. inv H; inv H0.
  exploit eventval_match_receptive; eauto. intros [v' EM].
  exists (Val.load_result chunk v'). econstructor; eauto.
  exists v1; econstructor; eauto.
Qed.

Lemma volatile_load_ok:
  forall chunk,
  extcall_properties (volatile_load_sem chunk)
                     (mksignature (AST.Tint :: nil) (Some (AST.type_of_chunk chunk)) cc_default).
Proof.
  intros; constructor; intros.
-
  unfold proj_sig_res; simpl. inv H. inv H0.
  + apply Val.load_result_type.
    inv H3; simpl; auto.
  + exploit Mem.load_type; eauto. destruct chunk; simpl; auto.
-
  inv H1. inv H2; econstructor; econstructor; eauto.
  rewrite H; auto.
  inv H5; constructor.
  rewrite H; auto.
-
  inv H; auto.
-
  inv H; auto.
-
  inv H. apply Mem.unchanged_on_refl.
-
  inv H0. inv H2. inv H7.
  exploit volatile_load_inject; eauto.
  intros [v'0 [A B]].
  exists v'0; exists m1'; intuition. constructor; auto.
-
  inv H; inv H0; simpl; omega.
-
  inv H. exploit volatile_load_receptive; eauto. intros [v3 A].
  exists v3; exists m1; econstructor; eauto.
-
  inv H; inv H0. inv H1; inv H2; try congruence.
  rewrite H in H1; inv H1.
  assert (id = id0) by (eapply Genv.genv_vars_inj; eauto). subst id0.
  split. constructor.
  eapply eventval_match_valid; eauto.
  eapply eventval_match_valid; eauto.
  eapply eventval_match_same_type; eauto.
  intros EQ; inv EQ.
  assert (v = v0) by (eapply eventval_match_determ_1; eauto). subst v0.
  auto.
  split. constructor. intuition congruence.
Qed.

Inductive volatile_load_global_sem (chunk: memory_chunk) (id: ident) (ofs: int)
                                   (F V: Type) (ge: Genv.t F V):
              list expr_sym -> mem -> trace -> expr_sym -> mem -> Prop :=
  | volatile_load_global_sem_intro: forall b t v m,
      Genv.find_symbol ge id = Some b ->
      volatile_load ge chunk m (Eval (Eptr b ofs)) t v ->
      volatile_load_global_sem chunk id ofs ge nil m t v m.

Remark volatile_load_global_charact:
  forall chunk id ofs (F V: Type) (ge: Genv.t F V) vargs m t vres m',
  volatile_load_global_sem chunk id ofs ge vargs m t vres m' <->
  exists b,
    Genv.find_symbol ge id = Some b /\ volatile_load_sem chunk ge (Eval (Eptr b ofs) :: vargs) m t vres m'.
Proof.
  intros; split.
  intros. inv H. exists b. split; auto.
  econstructor; eauto.
  intros [b [sv P]]. inv P. econstructor; eauto.
Qed.

Lemma volatile_load_global_ok:
  forall chunk id ofs,
  extcall_properties (volatile_load_global_sem chunk id ofs)
                     (mksignature nil (Some (AST.type_of_chunk chunk)) cc_default).
Proof.
  intros; constructor; intros.
-
  unfold proj_sig_res; simpl. inv H. inv H1.
  + apply Val.load_result_type.
    inv H4; simpl; auto.
  + exploit Mem.load_type; eauto.
    destruct chunk; auto.
-
  inv H1. inv H3; econstructor; eauto; try econstructor; eauto; try rewrite H; eauto.
  inv H6; constructor.
  rewrite H; auto.
-
  inv H; auto.
-
  inv H; auto.
-
  inv H. apply Mem.unchanged_on_refl.
-
  inv H0. inv H2.
  assert (Val.expr_inject p f (Eval (Eptr b ofs)) (Eval (Eptr b ofs))).
  {
    constructor. simpl.
    unfold Val.inj_ptr.
    erewrite (proj1 H); eauto.
    rewrite Int.add_zero. auto.
  }
  generalize (volatile_load_inject ABI H H4 H0 H1).
  intros [v' [A B]].
  exists v'; exists m1'; intuition. econstructor; eauto.
-
  inv H; inv H1; simpl; omega.
-
  inv H. exploit volatile_load_receptive; eauto. intros [v2 A].
  exists v2; exists m1; econstructor; eauto.
-
  inv H; inv H0.
  rewrite H in H1; inv H1.
  eapply ec_determ. eapply volatile_load_ok; eauto.
  econstructor; eauto.
  econstructor; eauto.
Qed.

Semantics of volatile stores


Inductive volatile_store_sem (chunk: memory_chunk) (F V: Type) (ge: Genv.t F V):
              list expr_sym -> mem -> trace -> expr_sym -> mem -> Prop :=
  | volatile_store_sem_intro: forall addr m1 v t m2 ,
      volatile_store ge chunk m1 addr v t m2 ->
      volatile_store_sem chunk ge (addr :: v :: nil) m1 t (Eval (Eint Int.zero)) m2.

Lemma volatile_store_preserved:
  forall F1 V1 (ge1: Genv.t F1 V1) F2 V2 (ge2: Genv.t F2 V2) chunk m1 addr b ofs v t m2
         (MN: Mem.mem_norm m1 addr Ptr = Vptr b ofs)
         (GFS: forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id)
         (IV: forall b, block_is_volatile ge2 b = block_is_volatile ge1 b)
         (VS: volatile_store ge1 chunk m1 addr v t m2),
    volatile_store ge2 chunk m1 addr v t m2.
Proof.
  intros. inv VS; econstructor; eauto.
  rewrite GFS; auto.
  eapply eventval_match_preserved; eauto.
Qed.

Lemma volatile_store_readonly:
  forall F V (ge: Genv.t F V) chunk1 m1 addr v t m2,
  volatile_store ge chunk1 m1 addr v t m2 ->
  Mem.unchanged_on (loc_not_writable m1) m1 m2.
Proof.
  intros. inv H.
  apply Mem.unchanged_on_refl.
  eapply Mem.store_unchanged_on; eauto.
  exploit Mem.store_valid_access_3; eauto. intros [P Q].
  intros. unfold loc_not_writable. red; intros. elim H3.
  apply Mem.perm_cur_max. apply P. auto.
Qed.


Lemma volatile_store_inject:
  forall p F V (ge: Genv.t F V) f chunk m1 bofs v t m2 m1' bofs' v'
    (ABI:Mem.all_blocks_injected f m1),
  meminj_preserves_globals ge f ->
  volatile_store ge chunk m1 bofs v t m2 ->
  Val.expr_inject p f bofs bofs' ->
  Val.expr_inject p f v v' ->
  Mem.inject p f m1 m1' ->
  exists m2',
       volatile_store ge chunk m1' bofs' v' t m2'
    /\ Mem.inject p f m2 m2'
    /\ Mem.unchanged_on (loc_unmapped f) m1 m2
    /\ Mem.unchanged_on (loc_out_of_reach f m1) m1' m2'.
Proof.
  intros. inv H0.
  - generalize (Mem.norm_inject_val' _ _ _ _ _ _ Ptr ABI H3 H1).
    rewrite H4. intro A; inv A.
      erewrite (proj1 H) in H10; eauto. inv H10. rewrite Int.add_zero in H9.
      exists m1'. intuition.
      econstructor; eauto.
      generalize (Mem.norm_inject_val' _ _ _ _ _ _ (result_of_styp (type_of_chunk chunk)) ABI H3
                                       (Val.expr_load_result_inject' _ _ chunk _ _ H2)).
      intro A; inv A;
      unfold Val.load_result in *;
      try (rewrite <- H7 in H8; rewrite <- H10; inv H8; constructor).
      rewrite <- H0 in H8. rewrite <- H7. simpl in *. inv H8.
      
      erewrite (proj1 H) in H10; eauto. inv H10.
      rewrite Int.add_zero.
      simpl. econstructor; eauto.
      rewrite <- H7 in H8. simpl in H8; inv H8.
  - generalize (Mem.norm_inject _ _ _ _ _ (Vptr b ofs) _ ABI
                                H3 H1).
      intro A; destruct A with (r:=Ptr); eauto. congruence.
      destruct (Mem.mem_norm m1' bofs' Ptr) eqn:?; simpl in *; try congruence;
      inv H7; simpl in inj_ok; unfold Val.inj_ptr in inj_ok; simpl in inj_ok;
      destruct (f b) as [[bb oo]|] eqn:?; inv inj_ok.
      destruct (Mem.store_mapped_inject
                  _ _ _ _ _ _ _ _ _ _ _ _
                  H3 H6 Heqo H2)
      as [m2' [B C]]; eauto.
    exists m2'; intuition.
    + econstructor; eauto.
      * rewrite <- H5. eapply meminj_preserves_block_is_volatile; eauto.
      * rewrite <- B. f_equal.
        inv H3.
        generalize (Mem.mi_representable _ _ _ _ mi_inj
                                         _ _ _ ofs Heqo).
        intro D. Alloc.trim D.
        left.
        apply Mem.store_valid_access_3 in H6.
        destruct H6 as [H6 _].
        apply Mem.perm_cur_max.
        eapply Mem.perm_implies.
        apply H6. destruct chunk; simpl; omega.
        constructor.
        Alloc.trim D.
        eapply mi_delta_pos; eauto.
        unfold Int.add.
        rewrite (Int.unsigned_repr oo).
        rewrite Int.unsigned_repr. auto. auto.
        apply mi_delta_pos in Heqo. generalize (Int.unsigned_range_2 ofs). omega.
    + eapply Mem.store_unchanged_on; eauto.
      unfold loc_unmapped; intros. congruence.
    + eapply Mem.store_unchanged_on; eauto.
      unfold loc_out_of_reach; intros. red; intros.
      assert (EQ: Int.unsigned (Int.add ofs (Int.repr oo)) = Int.unsigned ofs + oo)
        by (eapply Mem.address_inject; eauto with mem).
      eelim H8; eauto.
      exploit Mem.store_valid_access_3. eexact H6. intros [P Q].
      apply Mem.perm_cur_max. apply Mem.perm_implies with Writable; auto with mem.
      apply P. omega.
Qed.


Lemma volatile_store_receptive:
  forall F V (ge: Genv.t F V) chunk m addr v t1 m1 t2,
  volatile_store ge chunk m addr v t1 m1 -> match_traces ge t1 t2 -> t1 = t2.
Proof.
  intros. inv H; inv H0; auto.
Qed.

Lemma sval_of_val_inj:
  forall v v0, sval_of_val v = sval_of_val v0 -> v = v0.
Proof.
  intros; destruct v; destruct v0; simpl in *; intuition try congruence.
Qed.

Lemma volatile_store_ok:
  forall chunk,
  extcall_properties (volatile_store_sem chunk)
                     (mksignature (AST.Tint :: AST.type_of_chunk chunk :: nil) None cc_default).
Proof.
  intros; constructor; intros.
-
  unfold proj_sig_res; simpl. inv H; constructor.
-
  inv H1. inv H2; econstructor; eauto; econstructor; eauto.
  rewrite H; auto.
  inv H6; simpl; try rewrite <- H8; try constructor.
  rewrite H; auto.
-
  inv H. inv H1. auto. eauto with mem.
-
  inv H. inv H2. auto. eauto with mem.
-
  inv H. eapply volatile_store_readonly; eauto.
-
  inv H0. inv H2. inv H7. inv H8.
  exploit volatile_store_inject; eauto. intros [m2' [A [B [C D]]]].
  exists (Eval (Eint Int.zero)); exists m2'; intuition.
  constructor; auto.
  + red; intros.
    eapply ABI; eauto.
    rewrite <- H0.
    inv H3. auto.
    eapply Mem.bounds_of_block_store; eauto.
  + constructor; simpl; auto.
-
  inv H; inv H0; simpl; omega.
-
  assert (t1 = t2). inv H. eapply volatile_store_receptive; eauto.
  subst t2; exists vres1; exists m1; auto.
-
  inv H; inv H0. inv H1; inv H7; try congruence.
  + rewrite H1 in H; inv H.
    assert (id = id0) by (eapply Genv.genv_vars_inj; eauto). subst id0.
    assert (ev = ev0).
    {
      inv H4; inv H8; try congruence.
      rewrite <- H7 in H10. inv H10; auto.
      apply Genv.find_invert_symbol in H11.
      apply Genv.find_invert_symbol in H9.
      congruence.
    }
    subst ev0.
    split. constructor. auto.
  + split. constructor. intuition congruence.
Qed.

Inductive volatile_store_global_sem (chunk: memory_chunk) (id: ident) (ofs: int)
                                   (F V: Type) (ge: Genv.t F V):
              list expr_sym -> mem -> trace -> expr_sym -> mem -> Prop :=
  | volatile_store_global_sem_intro: forall b m1 v t m2,
      Genv.find_symbol ge id = Some b ->
      volatile_store ge chunk m1 (Eval (Eptr b ofs)) v t m2 ->
      volatile_store_global_sem chunk id ofs ge (v :: nil) m1 t (Eval (Eint Int.zero)) m2.

Remark volatile_store_global_charact:
  forall chunk id ofs (F V: Type) (ge: Genv.t F V) vargs m t vres m',
  volatile_store_global_sem chunk id ofs ge vargs m t vres m' <->
  exists b, Genv.find_symbol ge id = Some b /\ volatile_store_sem chunk ge (Eval (Eptr b ofs) :: vargs) m t vres m'.
Proof.
  intros; split.
  intros. inv H; exists b. split; auto. econstructor; eauto.
  intros [b [P Q]]. inv Q. econstructor; eauto.
Qed.

Lemma volatile_store_global_ok:
  forall chunk id ofs,
  extcall_properties (volatile_store_global_sem chunk id ofs)
                     (mksignature (AST.type_of_chunk chunk :: nil) None cc_default).
Proof.
  intros; constructor; intros.
-
  unfold proj_sig_res; simpl. inv H; constructor.
-
  inv H1. econstructor. rewrite H; eauto.
  inv H3; eapply volatile_store_preserved; eauto;
  econstructor; eauto.
-
  inv H. inv H2. auto. eauto with mem.
-
  inv H. inv H3. auto. eauto with mem.
-
  inv H. eapply volatile_store_readonly; eauto.
-
  rewrite volatile_store_global_charact in H0. destruct H0 as [b [P Q]].
  exploit (proj1 H). eauto. intros EQ.
  assert (Val.expr_inject p f (Eval (Eptr b ofs)) (Eval (Eptr b ofs))).
  {
    econstructor; eauto. simpl.
    unfold Val.inj_ptr. rewrite EQ. rewrite Int.add_zero; auto.
  }
  exploit ec_mem_inject. eapply volatile_store_ok. eauto. eauto.
  eexact Q. eauto. constructor; eauto.
  intros [vres' [m2' [A [B [C [D [E G]]]]]]].
  exists vres'; exists m2'; intuition.
  rewrite volatile_store_global_charact. exists b; auto.
-
  inv H. inv H1; simpl; omega.
-
  assert (t1 = t2). inv H. eapply volatile_store_receptive; eauto. subst t2.
  exists vres1; exists m1; congruence.
-
  inv H; inv H0. rewrite H1 in H3; inv H3.
  eapply ec_determ. eapply volatile_store_ok.
  econstructor; eauto. econstructor; eauto.
Qed.

Semantics of dynamic memory allocation (malloc)


Semantics of memcpy operations.


Inductive extcall_memcpy_sem (sz al: Z) (F V: Type) (ge: Genv.t F V): list expr_sym -> mem -> trace -> expr_sym -> mem -> Prop :=
  | extcall_memcpy_sem_intro: forall bdst odst bsrc osrc m bytes m',
      al = 1 \/ al = 2 \/ al = 4 \/ al = 8 -> sz >= 0 -> (al | sz) ->
      (sz > 0 -> (al | Int.unsigned osrc)) ->
      (sz > 0 -> (al | Int.unsigned odst)) ->
      bsrc <> bdst \/ Int.unsigned osrc = Int.unsigned odst
                   \/ Int.unsigned osrc + sz <= Int.unsigned odst
                   \/ Int.unsigned odst + sz <= Int.unsigned osrc ->
      Mem.loadbytes m bsrc (Int.unsigned osrc) sz = Some bytes ->
      Mem.storebytes m bdst (Int.unsigned odst) bytes = Some m' ->
      forall v' v,
        Mem.mem_norm m v' Ptr = Vptr bdst odst ->
        Mem.mem_norm m v Ptr = Vptr bsrc osrc ->
        extcall_memcpy_sem sz al ge (v' :: v :: nil)
                           m E0 (Eval (Eint Int.zero)) m'.



Lemma extcall_memcpy_ok:
  forall sz al,
  extcall_properties (extcall_memcpy_sem sz al) (mksignature (AST.Tint :: AST.Tint :: nil) None cc_default).
Proof.
  intros. constructor.
-
  intros. inv H. constructor.
-
  intros. inv H1.
  eapply extcall_memcpy_sem_intro with (odst:=odst) (osrc:=osrc); eauto.
-
  intros. inv H. eauto with mem.
-
  intros. inv H. eapply Mem.perm_storebytes_2; eauto.
-
  intros. inv H. eapply Mem.storebytes_unchanged_on; eauto.
  intros; red; intros. elim H10.
  apply Mem.perm_cur_max. eapply Mem.storebytes_range_perm; eauto.
-
  intros. inv H0. inv H2. inv H16. inv H17.

  generalize (Mem.norm_inject _ _ _ _ _ (Vptr bsrc osrc) _ ABI
                              H1 H13).
  intro A; destruct A with (r:=Ptr); eauto. congruence.
  destruct (Mem.mem_norm m1' v'1 Ptr) eqn:?; simpl in *; try congruence;
  inv H2; simpl in inj_ok; unfold Val.inj_ptr in inj_ok; simpl in inj_ok;
  destruct (f bsrc) as [[bbsrc oosrc]|] eqn:?; inv inj_ok.
  clear A.
  generalize (Mem.norm_inject _ _ _ _ _ (Vptr bdst odst) _ ABI
                              H1 H14).
  intro A; destruct A with (r:=Ptr); eauto. congruence.
  destruct (Mem.mem_norm m1' v'0 Ptr) eqn:?; simpl in *; try congruence;
  inv H15; simpl in inj_ok; unfold Val.inj_ptr in inj_ok; simpl in inj_ok;
  destruct (f bdst) as [[bbdst oodst]|] eqn:?; inv inj_ok.
  clear A. clear H0 H2.
  destruct (zeq sz 0).
+
  assert (bytes = nil).
  { exploit (Mem.loadbytes_empty m1 bsrc (Int.unsigned osrc) sz). omega. congruence. }
  subst.
  destruct (Mem.range_perm_storebytes m1' b0 (Int.unsigned (Int.add odst (Int.repr oodst))) nil)
  as [m2' SB].
  * simpl. red; intros; omegaContradiction.
  * simpl. auto.
  * exists (Eval (Eint Int.zero)), m2'.
  split. revert Heqv1 Heqv0. eapply extcall_memcpy_sem_intro; auto.
  intros; omegaContradiction.
  intros; omegaContradiction.
  right; omega.
  apply Mem.loadbytes_empty. omega.
  auto.
  split. red; intros; eapply ABI; eauto.
  erewrite Mem.bounds_of_block_storebytes; eauto.
  split. constructor; simpl; auto.
  split. eapply Mem.storebytes_empty_inject; eauto.
  split. eapply Mem.storebytes_unchanged_on; eauto. unfold loc_unmapped; intros.
  congruence.
  eapply Mem.storebytes_unchanged_on; eauto.
  simpl; intros; omegaContradiction.
+
  exploit Mem.loadbytes_length; eauto. intros LEN.
  assert (RPSRC: Mem.range_perm m1 bsrc (Int.unsigned osrc) (Int.unsigned osrc + sz) Cur Nonempty).
    eapply Mem.range_perm_implies. eapply Mem.loadbytes_range_perm; eauto. auto with mem.
  assert (RPDST: Mem.range_perm m1 bdst (Int.unsigned odst) (Int.unsigned odst + sz) Cur Nonempty).
    replace sz with (Z_of_nat (length bytes)).
    eapply Mem.range_perm_implies. eapply Mem.storebytes_range_perm; eauto. auto with mem.
    rewrite LEN. apply nat_of_Z_eq. omega.
  assert (PSRC: Mem.perm m1 bsrc (Int.unsigned osrc) Cur Nonempty).
    apply RPSRC. omega.
  assert (PDST: Mem.perm m1 bdst (Int.unsigned odst) Cur Nonempty).
    apply RPDST. omega.
  exploit Mem.address_inject. eauto. eexact PSRC. eauto. intros EQ1.
  exploit Mem.address_inject. eauto. eexact PDST. eauto. intros EQ2.
  exploit Mem.loadbytes_inject; eauto. intros [bytes2 [A B]].
  exploit Mem.storebytes_mapped_inject; eauto.
  eapply Mem.loadbytes_wt_memval; eauto.
  intros [m2' [C D]].
  exists (Eval (Eint Int.zero)); exists m2'.
  split. revert Heqv1 Heqv0. eapply extcall_memcpy_sem_intro; try rewrite EQ1; try rewrite EQ2; auto.
  intros; eapply Mem.aligned_area_inject with (m := m1); eauto.
  intros; eapply Mem.aligned_area_inject with (m := m1); eauto.
  eapply Mem.disjoint_or_equal_inject with (m := m1); eauto.
  apply Mem.range_perm_max with Cur; auto.
  apply Mem.range_perm_max with Cur; auto. omega.
  eauto. eauto.
  split.
  red; intros; eapply ABI; eauto.
  erewrite Mem.bounds_of_block_storebytes; eauto.
  split. constructor. simpl; auto.
  split. auto.
  split. eapply Mem.storebytes_unchanged_on; eauto. unfold loc_unmapped; intros.
  congruence.
  eapply Mem.storebytes_unchanged_on; eauto. unfold loc_out_of_reach; intros. red; intros.
  eelim H2; eauto.
  apply Mem.perm_cur_max. apply Mem.perm_implies with Writable; auto with mem.
  eapply Mem.storebytes_range_perm; eauto.
  erewrite list_forall2_length; eauto.
  omega.
  
-
  intros; inv H. simpl; omega.
-
  intros.
  assert (t1 = t2). inv H; inv H0; auto. subst t2.
  exists vres1; exists m1; auto.
-
  intros; inv H; inv H0. split. constructor.

  intros; split; congruence.
Qed.

Semantics of annotations.



Lemma map_inj:
  forall {A B: Type} (f: A -> B)
         (f_inj: forall a0 a1, f a0 = f a1 -> a0 = a1) l0 l1,
    map f l0 = map f l1 ->
    l0 = l1.
Proof.
  induction l0; simpl; intros.
  - destruct l1; simpl in *; intuition try congruence.
  - destruct l1; simpl in *; intuition try congruence.
    inv H.
    f_equal.
    apply f_inj; auto.
    apply IHl0; auto.
Qed.

Semantics of external functions.


For functions defined outside the program (EF_external and EF_builtin), we do not define their semantics, but only assume that it satisfies extcall_properties.

Parameter external_functions_sem: ident -> signature -> extcall_sem.

Axiom external_functions_properties:
  forall id sg, extcall_properties (external_functions_sem id sg) sg.

We treat inline assembly similarly.

Parameter inline_assembly_sem: ident -> extcall_sem.

Axiom inline_assembly_properties:
  forall id, extcall_properties (inline_assembly_sem id) (mksignature nil None cc_default).


Axiom external_call_not_taken_into_account:
  forall name sg (F V: Type) (ge: Genv.t F V) args m t vres m2,
    external_functions_sem name sg ge args m t vres m2 ->
    forall P : Prop, P.

Axiom inline_assembly_not_taken_into_account:
  forall name (F V: Type) (ge: Genv.t F V) args m t vres m2,
    inline_assembly_sem name ge args m t vres m2 ->
    forall P : Prop, P.


Combined semantics of external calls


Combining the semantics given above for the various kinds of external calls, we define the predicate external_call that relates: This predicate is used in the semantics of all CompCert languages.

Definition external_call (ef: external_function): extcall_sem :=
  match ef with
  | EF_external name sg => external_functions_sem name sg
  | EF_builtin name sg => external_functions_sem name sg
  | EF_vload chunk => volatile_load_sem chunk
  | EF_vstore chunk => volatile_store_sem chunk
  | EF_vload_global chunk id ofs => volatile_load_global_sem chunk id ofs
  | EF_vstore_global chunk id ofs => volatile_store_global_sem chunk id ofs
  | EF_memcpy sz al => extcall_memcpy_sem sz al
  | EF_inline_asm txt => inline_assembly_sem txt
  end.

Theorem external_call_spec:
  forall ef,
  extcall_properties (external_call ef) (ef_sig ef).
Proof.
  intros. unfold external_call, ef_sig. destruct ef.
  apply external_functions_properties.
  apply external_functions_properties.
  apply volatile_load_ok.
  apply volatile_store_ok.
  apply volatile_load_global_ok.
  apply volatile_store_global_ok.
  apply extcall_memcpy_ok.
  apply inline_assembly_properties.
Qed.

Definition external_call_well_typed ef := ec_well_typed (external_call_spec ef).
Definition external_call_symbols_preserved_gen ef := ec_symbols_preserved (external_call_spec ef).
Definition external_call_valid_block ef := ec_valid_block (external_call_spec ef).
Definition external_call_max_perm ef := ec_max_perm (external_call_spec ef).
Definition external_call_readonly ef := ec_readonly (external_call_spec ef).
Definition external_call_mem_inject ef := ec_mem_inject (external_call_spec ef).
Definition external_call_trace_length ef := ec_trace_length (external_call_spec ef).
Definition external_call_receptive ef := ec_receptive (external_call_spec ef).
Definition external_call_determ ef := ec_determ (external_call_spec ef).

Special cases of external_call_symbols_preserved_gen.

Lemma external_call_symbols_preserved:
  forall ef F1 F2 V (ge1: Genv.t F1 V) (ge2: Genv.t F2 V) vargs m1 t vres m2,
  external_call ef ge1 vargs m1 t vres m2 ->
  (forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id) ->
  (forall b, Genv.find_var_info ge2 b = Genv.find_var_info ge1 b) ->
  external_call ef ge2 vargs m1 t vres m2.
Proof.
  intros. eapply external_call_symbols_preserved_gen; eauto.
  intros. unfold block_is_volatile. rewrite H1. auto.
Qed.

Require Import Errors.

Lemma external_call_symbols_preserved_2:
  forall ef F1 V1 F2 V2 (tvar: V1 -> res V2)
         (ge1: Genv.t F1 V1) (ge2: Genv.t F2 V2) vargs m1 t vres m2,
  external_call ef ge1 vargs m1 t vres m2 ->
  (forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id) ->
  (forall b gv1, Genv.find_var_info ge1 b = Some gv1 ->
     exists gv2, Genv.find_var_info ge2 b = Some gv2 /\ transf_globvar tvar gv1 = OK gv2) ->
  (forall b gv2, Genv.find_var_info ge2 b = Some gv2 ->
     exists gv1, Genv.find_var_info ge1 b = Some gv1 /\ transf_globvar tvar gv1 = OK gv2) ->
  external_call ef ge2 vargs m1 t vres m2.
Proof.
  intros. eapply external_call_symbols_preserved_gen; eauto.
  intros. unfold block_is_volatile.
  case_eq (Genv.find_var_info ge1 b); intros.
  exploit H1; eauto. intros [g2 [A B]]. rewrite A. monadInv B. destruct g; auto.
  case_eq (Genv.find_var_info ge2 b); intros.
  exploit H2; eauto. intros [g1 [A B]]. congruence.
  auto.
Qed.

Corollary of external_call_valid_block.

Lemma external_call_nextblock:
  forall ef (F V : Type) (ge : Genv.t F V) vargs m1 t vres m2,
  external_call ef ge vargs m1 t vres m2 ->
  Ple (Mem.nextblock m1) (Mem.nextblock m2).
Proof.
  intros. destruct (plt (Mem.nextblock m2) (Mem.nextblock m1)).
  exploit external_call_valid_block; eauto. intros.
  eelim Plt_strict; eauto.
  unfold Plt, Ple in *; zify; omega.
Qed.

Corollaries of external_call_determ.

Lemma external_call_match_traces:
  forall ef (F V : Type) (ge : Genv.t F V) vargs m t1 vres1 m1 t2 vres2 m2,
  external_call ef ge vargs m t1 vres1 m1 ->
  external_call ef ge vargs m t2 vres2 m2 ->
  match_traces ge t1 t2.
Proof.
  intros. exploit external_call_determ. eexact H. eexact H0. tauto.
Qed.

Lemma external_call_deterministic:
  forall ef (F V : Type) (ge : Genv.t F V) vargs m t vres1 m1 vres2 m2,
  external_call ef ge vargs m t vres1 m1 ->
  external_call ef ge vargs m t vres2 m2 ->
  vres1 = vres2 /\ m1 = m2.
Proof.
  intros. exploit external_call_determ. eexact H. eexact H0. intuition.
Qed.

Late in the back-end, calling conventions for external calls change: arguments and results of type Tlong are passed as two integers. We now wrap external_call to adapt to this convention.

Fixpoint decode_longs (tyl: list typ) (vl: list expr_sym) : list expr_sym :=
  match tyl with
  | nil => nil
  | AST.Tlong :: tys =>
      match vl with
      | v1 :: v2 :: vs => Val.longofwords v1 v2 :: decode_longs tys vs
      | _ => nil
      end
  | ty :: tys =>
      match vl with
      | v1 :: vs => v1 :: decode_longs tys vs
      | _ => nil
      end
  end.

Definition encode_long (oty: option typ) (v: expr_sym) : list expr_sym :=
  match oty with
  | Some AST.Tlong => Val.hiword v :: Val.loword v :: nil
  | _ => v :: nil
  end.

Definition proj_sig_res' (s: signature) : list typ :=
  match s.(sig_res) with
  | Some AST.Tlong => AST.Tint :: AST.Tint :: nil
  | Some ty => ty :: nil
  | None => AST.Tint :: nil
  end.

Inductive external_call'
      (ef: external_function) (F V: Type) (ge: Genv.t F V)
      (vargs: list expr_sym) (m1: mem) (t: trace) (vres: list expr_sym) (m2: mem) : Prop :=
  external_call'_intro: forall v,
    external_call ef ge (decode_longs (sig_args (ef_sig ef)) vargs) m1 t v m2 ->
    vres = encode_long (sig_res (ef_sig ef)) v ->
    external_call' ef ge vargs m1 t vres m2.

Lemma decode_longs_lessdef:
  forall p tyl vl1 vl2, Val.lessdef_list p vl1 vl2 -> Val.lessdef_list p (decode_longs tyl vl1) (decode_longs tyl vl2).
Proof.
  induction tyl; simpl; intros.
  auto.
  destruct a; inv H; auto. inv H1; auto. constructor; auto. apply Val.longofwords_lessdef; auto.
Qed.

Lemma decode_longs_inject:
  forall p f tyl vl1 vl2, Val.expr_list_inject p f vl1 vl2 -> Val.expr_list_inject p f (decode_longs tyl vl1) (decode_longs tyl vl2).
Proof.
  induction tyl; simpl; intros.
  auto.
  destruct a; inv H; auto. inv H1; auto. constructor; auto. apply Val.expr_longofwords_inject; auto.
Qed.

Lemma encode_long_lessdef:
  forall p oty v1 v2, Val.lessdef p v1 v2 -> Val.lessdef_list p (encode_long oty v1) (encode_long oty v2).
Proof.
  intros. destruct oty as [[]|]; simpl; auto.
  constructor. apply Val.hiword_lessdef; auto. constructor. apply Val.loword_lessdef; auto. auto.
Qed.

Lemma encode_long_inject:
  forall p f oty v1 v2, Val.expr_inject p f v1 v2 -> Val.expr_list_inject p f (encode_long oty v1) (encode_long oty v2).
Proof.
  intros. destruct oty as [[]|]; simpl; auto.
  constructor. apply Val.expr_hiword_inject; auto. constructor. apply Val.expr_loword_inject; auto. auto.
Qed.

Lemma encode_long_has_type:
  forall v sg,
  Val.has_type v (styp_of_ast (proj_sig_res sg)) ->
  Val.has_type_list (encode_long (sig_res sg) v) (map styp_of_ast (proj_sig_res' sg)).
Proof.
  unfold proj_sig_res, proj_sig_res', encode_long; intros.
  destruct (sig_res sg) as [[] | ]; simpl; auto.
Qed.

Lemma external_call_well_typed':
  forall ef (F V : Type) (ge : Genv.t F V) vargs m1 t vres m2,
  external_call' ef ge vargs m1 t vres m2 ->
  Val.has_type_list vres (map styp_of_ast (proj_sig_res' (ef_sig ef))).
Proof.
  intros. inv H. apply encode_long_has_type.
  eapply external_call_well_typed; eauto.
Qed.

Lemma external_call_symbols_preserved':
  forall ef F1 F2 V (ge1: Genv.t F1 V) (ge2: Genv.t F2 V) vargs m1 t vres m2,
  external_call' ef ge1 vargs m1 t vres m2 ->
  (forall id, Genv.find_symbol ge2 id = Genv.find_symbol ge1 id) ->
  (forall b, Genv.find_var_info ge2 b = Genv.find_var_info ge1 b) ->
  external_call' ef ge2 vargs m1 t vres m2.
Proof.
  intros. inv H. exists v; auto. eapply external_call_symbols_preserved; eauto.
Qed.

Lemma external_call_valid_block':
  forall ef (F V : Type) (ge : Genv.t F V) vargs m1 t vres m2 b,
  external_call' ef ge vargs m1 t vres m2 ->
  Mem.valid_block m1 b -> Mem.valid_block m2 b.
Proof.
  intros. inv H. eapply external_call_valid_block; eauto.
Qed.

Lemma external_call_nextblock':
  forall ef (F V : Type) (ge : Genv.t F V) vargs m1 t vres m2,
  external_call' ef ge vargs m1 t vres m2 ->
  Ple (Mem.nextblock m1) (Mem.nextblock m2).
Proof.
  intros. inv H. eapply external_call_nextblock; eauto.
Qed.


Lemma same_eval_load_result:
  forall chunk v v',
    same_eval v v' ->
    same_eval (Val.load_result chunk v) (Val.load_result chunk v').
Proof.
  destruct chunk; intros; simpl; auto; apply unop_same_eval; auto.
Qed.

Lemma external_call_se:
  forall (F V: Type) m m' args args' ef (ge: Genv.t F V) t vres m2,
    mem_equiv m m' ->
    list_forall2 same_eval args args' ->
    external_call ef ge args m t vres m2 ->
    exists vres' m2',
      external_call ef ge args' m' t vres' m2' /\
      same_eval vres vres' /\
      mem_equiv m2 m2'.
Proof.
  intros F V m m' args args' ef ge t vres m2 ME SE EC.
  destruct ef; simpl in *.
  - eapply external_call_not_taken_into_account; eauto.
  - eapply external_call_not_taken_into_account; eauto.
  - inv EC. inv SE. inv H4. inv H.
    + eexists; eexists; split; eauto.
      econstructor; eauto.
      econstructor; eauto.
      rewrite <- H0.
      symmetry.
      erewrite (same_eval_eqm); eauto.
      apply mem_equiv_norm; auto.
      split. reflexivity. auto.
    + eapply mem_equiv_load in H3; eauto.
      destruct H3 as [v' [A B]].
      exists v'; exists m'.
      split. econstructor; eauto. econstructor; eauto.
      rewrite <- H0.
      symmetry.
      erewrite (same_eval_eqm); eauto.
      apply mem_equiv_norm; auto. split; auto.
  - inv EC. inv SE. inv H4. inv H6. inv H.
    + eexists; eexists; split; eauto.
      econstructor; eauto.
      econstructor; eauto.
      rewrite <- H0.
      symmetry.
      erewrite (same_eval_eqm); eauto.
      apply mem_equiv_norm; auto.
      erewrite <- mem_equiv_norm; eauto.
      erewrite <- same_eval_eqm; eauto.
      apply same_eval_load_result; auto.
      split. reflexivity. auto.
    + eapply store_mem_equiv in H4; eauto.
      destruct H4 as [m0 [A B]].
      eapply store_val_equiv in A; eauto.
      destruct A as [m1 [A C]].
      eexists; eexists.
      split. econstructor; eauto. econstructor; eauto.
      rewrite <- H0.
      symmetry.
      erewrite (same_eval_eqm); eauto.
      apply mem_equiv_norm; auto. split; auto.
      reflexivity. rewrite B; auto.
  - inv EC. inv SE. inv H0.
    + eexists; eexists; split; eauto.
      econstructor; eauto.
      econstructor; eauto.
      rewrite <- H1.
      symmetry.
      apply mem_equiv_norm; auto.
      split. reflexivity. auto.
    + eapply mem_equiv_load in H3; eauto.
      destruct H3 as [v' [A B]].
      eexists; eexists.
      split. econstructor; eauto. econstructor; eauto.
      rewrite <- H1.
      symmetry.
      apply mem_equiv_norm; auto. split; auto.
  - inv EC. inv SE. inv H5. inv H0.
    + eexists; eexists; split; eauto.
      econstructor; eauto.
      econstructor; eauto.
      rewrite <- H1.
      symmetry.
      apply mem_equiv_norm; auto.
      erewrite <- mem_equiv_norm; eauto.
      erewrite <- same_eval_eqm; eauto.
      apply same_eval_load_result; auto.
      split. reflexivity. auto.
    + eapply store_mem_equiv in H4; eauto.
      destruct H4 as [m0 [A B]].
      eapply store_val_equiv in A; eauto.
      destruct A as [m1 [A C]].
      eexists; eexists.
      split. econstructor; eauto. econstructor; eauto.
      rewrite <- H1.
      symmetry.
      apply mem_equiv_norm; auto. split; auto.
      reflexivity. rewrite B; auto.
  - inv EC. inv SE. inv H13. inv H15.
    erewrite (mem_equiv_norm) in H7; eauto.
    erewrite (same_eval_eqm) in H7; eauto.
    erewrite (mem_equiv_norm) in H8; eauto.
    erewrite (same_eval_eqm) in H8; eauto.
    eapply mem_equiv_loadbytes in H5; eauto.
    destruct H5 as [v'0 [LB LF]].
    eapply storebytes_mem_equiv in H6; eauto.
    destruct H6 as [m0 [A B]].
    eapply storebytes_val_equiv in A; eauto.
    destruct A as [m1 [A C]].
    eexists; eexists; split; eauto.
    eapply extcall_memcpy_sem_intro with (osrc:=osrc) (odst:=odst); eauto.
    split. reflexivity. rewrite B; auto.
  - eapply inline_assembly_not_taken_into_account; eauto.
Qed.



Lemma external_call_mem_inject':
  forall ef p F V (ge: Genv.t F V) vargs m1 t vres m2 f m1' vargs'
  (ABI: Mem.all_blocks_injected f m1),
  meminj_preserves_globals ge f ->
  external_call' ef ge vargs m1 t vres m2 ->
  Mem.inject p f m1 m1' ->
  Val.expr_list_inject p f vargs vargs' ->
  exists vres' m2',
     external_call' ef ge vargs' m1' t vres' m2'
  /\ Val.expr_list_inject p f vres vres'
  /\ Mem.inject p f m2 m2'
  /\ Mem.unchanged_on (loc_unmapped f) m1 m2
  /\ Mem.unchanged_on (loc_out_of_reach f m1) m1' m2'
.
Proof.
  intros. inv H0.
  exploit external_call_mem_inject; eauto.
  eapply decode_longs_inject; eauto.
  intros (v' & m2' & A & B & C & D & E & P ).
  exists (encode_long (sig_res (ef_sig ef)) v'); exists m2'; intuition.
  econstructor; eauto.
  apply encode_long_inject; auto.
Qed.


Lemma external_call_determ':
  forall ef (F V : Type) (ge : Genv.t F V) vargs m t1 vres1 m1 t2 vres2 m2,
  external_call' ef ge vargs m t1 vres1 m1 ->
  external_call' ef ge vargs m t2 vres2 m2 ->
  match_traces ge t1 t2 /\ (t1 = t2 -> vres1 = vres2 /\ m1 = m2).
Proof.
  intros. inv H; inv H0. exploit external_call_determ. eexact H1. eexact H.
  intros [A B]. split. auto. intros. destruct B as [C D]; auto. subst. auto.
Qed.

Lemma external_call_match_traces':
  forall ef (F V : Type) (ge : Genv.t F V) vargs m t1 vres1 m1 t2 vres2 m2,
  external_call' ef ge vargs m t1 vres1 m1 ->
  external_call' ef ge vargs m t2 vres2 m2 ->
  match_traces ge t1 t2.
Proof.
  intros. inv H; inv H0. eapply external_call_match_traces; eauto.
Qed.

Lemma external_call_deterministic':
  forall ef (F V : Type) (ge : Genv.t F V) vargs m t vres1 m1 vres2 m2,
  external_call' ef ge vargs m t vres1 m1 ->
  external_call' ef ge vargs m t vres2 m2 ->
  vres1 = vres2 /\ m1 = m2.
Proof.
  intros. inv H; inv H0.
  exploit external_call_deterministic. eexact H1. eexact H. intros [A B].
  split; congruence.
Qed.